Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

selfUpdate.test.ts

495 lines19.7 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { expect, it } from "@effect/vitest";
3import type { ManagedPolicyDocument } from "@t3tools/contracts";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Deferred from "effect/Deferred";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Fiber from "effect/Fiber";
10import * as Layer from "effect/Layer";
11import * as Path from "effect/Path";
12import * as Stream from "effect/Stream";
13import * as TestClock from "effect/testing/TestClock";
14import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16​
17import packageJson from "../../package.json" with { type: "json" };
18import * as ServerConfig from "../config.ts";
19import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
20import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
21import * as ProcessRunner from "../processRunner.ts";
22import * as ServiceLauncherClient from "./serviceLauncherClient.ts";
23import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
24import * as ServerSelfUpdate from "./selfUpdate.ts";
25​
26interface HarnessOptions {
27 readonly mode?: "web" | "desktop";
28 readonly managed?: boolean;
29 readonly preflight?: "ready" | "blocked";
30 readonly preflightDuration?: Duration.Input;
31 readonly preflightStarted?: Deferred.Deferred<void>;
32 readonly beforeDownload?: Effect.Effect<void>;
33 readonly httpClient?: HttpClient.HttpClient;
34 readonly requestUpdate?: ServiceLauncherClient.ServiceLauncherClient["Service"]["requestUpdate"];
35 readonly desktopAppUpdate?: DesktopAppUpdate.DesktopAppUpdate["Service"];
36 readonly policy?: ManagedPolicyDocument;
38​
39const archiveBytes = new TextEncoder().encode("not really a tarball");
40const releaseHttpClient = (order: string[], urls: string[], beforeDownload?: Effect.Effect<void>) =>
41 HttpClient.make((request) =>
42 Effect.gen(function* () {
43 urls.push(request.url);
44 if (request.url.endsWith("/SHA256SUMS")) {
45 const digest = yield* Effect.promise(() => crypto.subtle.digest("SHA-256", archiveBytes));
46 const hex = Array.from(new Uint8Array(digest), (byte) =>
47 byte.toString(16).padStart(2, "0"),
48 ).join("");
49 return HttpClientResponse.fromWeb(
50 request,
51 new Response(`${hex} t3-1.1.0-linux-x64.tar.gz\n`),
52 );
53 }
54 if (beforeDownload) yield* beforeDownload;
55 order.push("download");
56 return HttpClientResponse.fromWeb(request, new Response(archiveBytes));
57 }),
58 );
59​
60const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
61 options: HarnessOptions = {},
62) {
63 const fs = yield* FileSystem.FileSystem;
64 const path = yield* Path.Path;
65 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-self-update-test-" });
66 const order: string[] = [];
67 const urls: string[] = [];
68 const runner = ProcessRunner.ProcessRunner.of({
69 run: (input) =>
70 Effect.gen(function* () {
71 if (input.command === "tar") {
72 order.push("extract");
73 const stagingDir = input.args[input.args.indexOf("-C") + 1];
74 if (stagingDir === undefined) return yield* Effect.die("missing tar target");
75 yield* fs.writeFileString(path.join(stagingDir, "t3"), "#!/bin/sh\n").pipe(Effect.orDie);
76 return {
77 stdout: "",
78 stderr: "",
79 code: ChildProcessSpawner.ExitCode(0),
80 timedOut: false,
81 stdoutTruncated: false,
82 stderrTruncated: false,
83 stdoutInvalidUtf8: false,
84 stderrInvalidUtf8: false,
85 };
86 }
87 if (options.preflightStarted) yield* Deferred.succeed(options.preflightStarted, undefined);
88 if (options.preflightDuration !== undefined) {
89 // Like the real runner, fail once the caller's timeout elapses.
90 const timeout = Duration.fromInputUnsafe(input.timeout ?? "60 seconds");
91 const finished = yield* Effect.sleep(options.preflightDuration).pipe(
92 Effect.timeoutOption(timeout),
93 );
94 if (finished._tag === "None") {
95 return yield* new ProcessRunner.ProcessTimeoutError({
96 command: input.command,
97 argumentCount: input.args.length,
98 timeoutMs: Duration.toMillis(timeout),
99 });
100 }
101 }
102 order.push("preflight");
103 const result =
104 options.preflight === "blocked"
105 ? { status: "blocked", version: "1.1.0", reason: "local update required" }
106 : {
107 status: "ready",
108 version: "1.1.0",
109 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
110 };
111 return {
112 stdout: JSON.stringify(result),
113 stderr: "",
114 code: ChildProcessSpawner.ExitCode(0),
115 timedOut: false,
116 stdoutTruncated: false,
117 stderrTruncated: false,
118 stdoutInvalidUtf8: false,
119 stderrInvalidUtf8: false,
120 };
121 }),
122 });
123 const launcher = ServiceLauncherClient.ServiceLauncherClient.of({
124 managed: options.managed ?? true,
125 requestUpdate:
126 options.requestUpdate ??
127 (() =>
128 Effect.sync(() => {
129 order.push("accept");
130 return "launcher-id";
131 })),
132 prepareTrial: Effect.undefined,
133 });
134 const config = yield* ServerConfig.ServerConfig.pipe(
135 Effect.provide(ServerConfig.layerTest(process.cwd(), baseDir)),
136 );
137 const selfUpdate = yield* ServerSelfUpdate.make().pipe(
138 Effect.provideService(ProcessRunner.ProcessRunner, runner),
139 Effect.provideService(ServiceLauncherClient.ServiceLauncherClient, launcher),
140 Effect.provideService(
141 DesktopAppUpdate.DesktopAppUpdate,
142 options.desktopAppUpdate ?? {
143 available: false,
144 run: () => Effect.die("unexpected desktop app update run"),
145 },
146 ),
147 Effect.provideService(
148 HttpClient.HttpClient,
149 options.httpClient ?? releaseHttpClient(order, urls, options.beforeDownload),
150 ),
151 Effect.provideService(HostProcess.Platform, "linux"),
152 Effect.provideService(HostProcess.Architecture, "x64"),
153 Effect.provide(
154 Layer.merge(
155 ServerConfig.layer({ ...config, mode: options.mode ?? "web" }),
156 ManagedPolicy.layerTest(options.policy),
157 ),
158 ),
159 );
160 return { selfUpdate, order, urls, baseDir };
161});
162​
163it.layer(NodeServices.layer)("server self update", (it) => {
164 it.effect.each([
165 { asset: "checksums", status: 504 },
166 { asset: "archive", status: 503 },
167 { asset: "checksums", status: 403 },
168 ])("reports an HTTP $status downloading $asset and allows retry", ({ asset, status }) =>
169 Effect.gen(function* () {
170 let failDownload = true;
171 const { selfUpdate, order, baseDir } = yield* makeHarness({
172 httpClient: releaseHttpClient([], []).pipe(
173 HttpClient.transform((response, request) =>
174 failDownload && request.url.endsWith("/SHA256SUMS") === (asset === "checksums")
175 ? Effect.succeed(
176 HttpClientResponse.fromWeb(
177 HttpClientRequest.get("https://user:password@cdn.example/private?token=secret"),
178 new Response("private response body", { status }),
179 ),
180 )
181 : response,
182 ),
183 ),
184 });
185 const error = yield* selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip);
186 expect(error.reason).toBe(
187 `Could not prepare t3@1.1.0 while downloading the t3 release ${asset} (HTTP ${status} from cdn.example).`,
188 );
189 expect(order).toEqual([]);
190 const fs = yield* FileSystem.FileSystem;
191 const path = yield* Path.Path;
192 expect(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions"))).toEqual([]);
193 failDownload = false;
194 expect((yield* selfUpdate.update({ targetVersion: "1.1.0" })).updateId).toBe("launcher-id");
195 expect(order).toEqual(["extract", "preflight", "accept"]);
196 }),
197 );
198​
199 // regression: #5181 make remote updates rollback-safe
200 it.effect("rejects invalid versions and desktop-managed servers before staging", () =>
201 Effect.gen(function* () {
202 const web = yield* makeHarness();
203 expect(
204 (yield* web.selfUpdate.update({ targetVersion: "latest" }).pipe(Effect.flip)).reason,
205 ).toBe("'latest' is not an exact t3 version.");
206 const desktop = yield* makeHarness({ mode: "desktop" });
207 expect(
208 (yield* desktop.selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason,
209 ).toContain("desktop app");
210 expect([...web.order, ...desktop.order]).toEqual([]);
211 }),
212 );
213​
214 it.effect("refuses every update when the managed policy turns updates off", () =>
215 Effect.gen(function* () {
216 const policy: ManagedPolicyDocument = {
217 schemaVersion: 1,
218 organization: "Example Corp",
219 limits: { updates: { mode: "off" } },
220 };
221 const service = yield* makeHarness({ policy });
222 const desktop = yield* makeHarness({
223 mode: "desktop",
224 policy,
225 desktopAppUpdate: {
226 available: true,
227 run: () => Effect.die("unexpected desktop app update run"),
228 commit: () => Effect.never,
229 },
230 });
231 for (const harness of [service, desktop]) {
232 expect(
233 (yield* harness.selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason,
234 ).toBe("Example Corp manages T3 Code updates.");
235 }
236 expect([...service.order, ...desktop.order]).toEqual([]);
237 }),
238 );
239​
240 it.effect("lets a user start an update, but only to stable without nightly", () =>
241 Effect.gen(function* () {
242 const { selfUpdate, order, urls } = yield* makeHarness({
243 policy: {
244 schemaVersion: 1,
245 organization: "Example Corp",
246 limits: {
247 updates: {
248 mode: "auto",
249 allowNightly: false,
250 feedUrl: "https://updates.example.com/t3code/",
251 },
252 },
253 },
254 });
255 expect(
256 (yield* selfUpdate.update({ targetVersion: "1.2.0-nightly.20261028.1" }).pipe(Effect.flip))
257 .reason,
258 ).toBe("Example Corp manages T3 Code updates. Only stable releases can be installed.");
259 expect(order).toEqual([]);
260 // The mirror lists only 1.1.0's archive.
261 expect((yield* selfUpdate.update({ targetVersion: "1.2.0" }).pipe(Effect.flip)).reason).toBe(
262 "Example Corp's update mirror has no t3@1.2.0 for this machine.",
263 );
264 expect((yield* selfUpdate.update({ targetVersion: "1.1.0" })).updateId).toBe("launcher-id");
265 // The release comes from the policy's mirror, not GitHub.
266 expect(urls.length).toBeGreaterThan(0);
267 for (const url of urls)
268 expect(url).toMatch(/^https:\/\/updates\.example\.com\/t3code\/v1\.[12]\.0\//);
269 }),
270 );
271​
272 it.effect("delegates desktop-managed updates to the desktop app when available", () =>
273 Effect.gen(function* () {
274 const stages: string[] = [];
275 const { selfUpdate, order } = yield* makeHarness({
276 mode: "desktop",
277 desktopAppUpdate: {
278 available: true,
279 run: (reportProgress) =>
280 reportProgress("downloading").pipe(
281 Effect.andThen(reportProgress("installing")),
282 Effect.as({ targetVersion: "1.2.0", method: "desktop-app" as const }),
283 ),
284 commit: () => Effect.never,
285 },
286 });
287 const result = yield* selfUpdate.update({ targetVersion: "1.1.0" }, (stage) =>
288 Effect.sync(() => void stages.push(stage)),
289 );
290 expect(result).toEqual({ targetVersion: "1.2.0", method: "desktop-app" });
291 expect(stages).toEqual(["downloading", "installing"]);
292 expect(order).toEqual([]);
293 }),
294 );
295​
296 it.effect("allows only one update at a time", () =>
297 Effect.gen(function* () {
298 const requested = yield* Deferred.make<void>();
299 const accepted = yield* Deferred.make<string>();
300 const { selfUpdate } = yield* makeHarness({
301 requestUpdate: () =>
302 Deferred.succeed(requested, undefined).pipe(Effect.andThen(Deferred.await(accepted))),
303 });
304 const first = yield* Effect.forkChild(selfUpdate.update({ targetVersion: "1.1.0" }), {
305 startImmediately: true,
306 });
307 yield* Deferred.await(requested);
308 expect((yield* selfUpdate.update({ targetVersion: "1.1.1" }).pipe(Effect.flip)).reason).toBe(
309 "A server update is already in progress.",
310 );
311 yield* Deferred.succeed(accepted, "launcher-id");
312 expect((yield* Fiber.join(first)).updateId).toBe("launcher-id");
313 }),
314 );
315​
316 // regression: #28198 a slow staged preflight on a loaded host no longer fails the update
317 it.effect("waits for a staged preflight that takes a minute on a loaded host", () =>
318 Effect.gen(function* () {
319 const preflightStarted = yield* Deferred.make<void>();
320 const { selfUpdate, order } = yield* makeHarness({
321 preflightDuration: "60 seconds",
322 preflightStarted,
323 });
324 const update = yield* Effect.forkChild(selfUpdate.update({ targetVersion: "1.1.0" }), {
325 startImmediately: true,
326 });
327 yield* Deferred.await(preflightStarted);
328 yield* TestClock.adjust("60 seconds");
329 const exit = yield* Fiber.await(update);
330 expect(exit._tag === "Failure" ? String(exit.cause) : "launcher handoff").toBe(
331 "launcher handoff",
332 );
333 expect(order).toEqual(["download", "extract", "preflight", "accept"]);
334 }),
335 );
336​
337 it.effect("keeps preparing after the progress stream closes", () =>
338 Effect.gen(function* () {
339 const releaseDownload = yield* Deferred.make<void>();
340 const sawDownloading = yield* Deferred.make<void>();
341 const accepted = yield* Deferred.make<void>();
342 const { selfUpdate, order } = yield* makeHarness({
343 beforeDownload: Deferred.await(releaseDownload),
344 requestUpdate: () =>
345 Effect.sync(() => {
346 order.push("accept");
347 }).pipe(Effect.andThen(Deferred.succeed(accepted, undefined)), Effect.as("launcher-id")),
348 });
349​
350 const consumed = yield* ServerSelfUpdate.updateProgressStream(selfUpdate, {
351 targetVersion: "1.1.0",
352 }).pipe(
353 Stream.tap((event) =>
354 event.type === "progress" && event.stage === "downloading"
355 ? Deferred.succeed(sawDownloading, undefined)
356 : Effect.void,
357 ),
358 Stream.runDrain,
359 Effect.forkChild,
360 );
361​
362 yield* Deferred.await(sawDownloading);
363 yield* Fiber.interrupt(consumed);
364 expect((yield* selfUpdate.update({ targetVersion: "1.2.0" }).pipe(Effect.flip)).reason).toBe(
365 "A server update is already in progress.",
366 );
367​
368 yield* Deferred.succeed(releaseDownload, undefined);
369 yield* Deferred.await(accepted);
370 expect(order).toEqual(["download", "extract", "preflight", "accept"]);
371 expect((yield* selfUpdate.update({ targetVersion: "1.1.0" }).pipe(Effect.flip)).reason).toBe(
372 "A server update is already in progress.",
373 );
374 }),
375 );
376});
377​
378it.layer(NodeServices.layer)("pruning runtimes on start", (it) => {
379 const staleVersion = "0.0.1";
380 const otherProcesses = ProcessRunner.ProcessRunner.of({
381 run: () =>
382 Effect.succeed({
383 stdout: "p42\nftxt\nn/bin/sh\n",
384 stderr: "",
385 code: ChildProcessSpawner.ExitCode(0),
386 timedOut: false,
387 stdoutTruncated: false,
388 stderrTruncated: false,
389 stdoutInvalidUtf8: false,
390 stderrInvalidUtf8: false,
391 }),
392 });
393​
394 const pruneOnStart = Effect.fn("test.prune_on_start")(function* (input: {
395 readonly executable: "own runtime" | "elsewhere";
396 readonly managed?: boolean;
397 readonly symlinkedHome?: boolean;
398 }) {
399 const fs = yield* FileSystem.FileSystem;
400 const path = yield* Path.Path;
401 const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-prune-on-start-" });
402 const realHome = path.join(tempDir, "home");
403 const baseDir = input.symlinkedHome ? path.join(tempDir, "linked-home") : realHome;
404 const versionsDir = path.join(baseDir, "runtime", "versions");
405 yield* TestClock.setTime(24 * 60 * 60 * 1000);
406 for (const version of [staleVersion, packageJson.version]) {
407 const directory = path.join(realHome, "runtime", "versions", version);
408 yield* fs.makeDirectory(directory, { recursive: true });
409 yield* fs.writeFileString(path.join(directory, "t3"), "");
410 const sentinel = path.join(directory, ".install-complete");
411 yield* fs.writeFileString(sentinel, `${version}\n`);
412 yield* fs.utimes(sentinel, 0, 0);
413 }
414 if (input.symlinkedHome) yield* fs.symlink(realHome, baseDir);
415 // Like `process.execPath`, the running runtime is reported by its real path.
416 const executablePath =
417 input.executable === "own runtime"
418 ? yield* fs.realPath(path.join(versionsDir, packageJson.version, "t3"))
419 : "/usr/local/bin/node";
420 const removed = yield* ServerSelfUpdate.pruneRuntimesOnStart({
421 baseDir,
422 managed: input.managed ?? false,
423 }).pipe(
424 Effect.provideService(HostProcess.ExecutablePath, executablePath),
425 Effect.provideService(HostProcess.Platform, "darwin"),
426 Effect.provideService(HostProcess.Environment, {}),
427 Effect.provideService(ProcessRunner.ProcessRunner, otherProcesses),
428 );
429 return { removed, remaining: (yield* fs.readDirectory(versionsDir)).toSorted() };
430 });
431​
432 // The SSH launcher runs `t3 serve` straight from the pinned runtime, with no boot service.
433 it.effect("prunes for a server started from its home's pinned runtime", () =>
434 Effect.gen(function* () {
435 const { removed, remaining } = yield* pruneOnStart({ executable: "own runtime" });
436 expect(removed).toEqual([staleVersion]);
437 expect(remaining).toEqual([packageJson.version]);
438 }),
439 );
440​
441 it.effect("recognizes its runtime through a symlinked T3 home", () =>
442 Effect.gen(function* () {
443 const { removed } = yield* pruneOnStart({ executable: "own runtime", symlinkedHome: true });
444 expect(removed).toEqual([staleVersion]);
445 }),
446 );
447​
448 it.effect("prunes for a boot-service server wherever it runs from", () =>
449 Effect.gen(function* () {
450 const { removed } = yield* pruneOnStart({ executable: "elsewhere", managed: true });
451 expect(removed).toEqual([staleVersion]);
452 }),
453 );
454​
455 it.effect("leaves runtimes alone for an unmanaged server started elsewhere", () =>
456 Effect.gen(function* () {
457 const { removed, remaining } = yield* pruneOnStart({ executable: "elsewhere" });
458 expect(removed).toEqual([]);
459 expect(remaining).toEqual([staleVersion, packageJson.version].toSorted());
460 }),
461 );
462});
463​
464it("a host crosses tracks only to a release that knows its whole database", () => {
465 const cross = (
466 serverVersion: string,
467 targetVersion: string,
468 targetDatabaseMigration: number | undefined,
469 databaseMigration = 72,
470 ) =>
471 ServerSelfUpdate.trackSwitchBlockReason({
472 serverVersion,
473 targetVersion,
474 targetDatabaseMigration,
475 databaseMigration: () => databaseMigration,
476 });
477 const nightly = "0.1.4-nightly.20261027.3796";
478​
479 expect(cross(nightly, "0.1.4", 72)).toBeNull();
480 // Another client moved this host to a newer Nightly after the switch was planned.
481 expect(cross(nightly, "0.1.4", 72, 73)).toContain("does not support yet");
482 expect(cross(nightly, "0.1.4", undefined)).toContain("Cannot confirm");
483 // A Stable tag can carry a migration the latest Nightly lacks.
484 expect(cross("0.1.4", nightly, 72, 73)).toContain("does not support yet");
485 expect(cross("0.1.3", "0.1.4", undefined)).toBeNull();
486 // A database that exists but cannot be read proves nothing.
487 expect(
488 ServerSelfUpdate.trackSwitchBlockReason({
489 serverVersion: nightly,
490 targetVersion: "0.1.4",
491 targetDatabaseMigration: 72,
492 databaseMigration: () => undefined,
493 }),
494 ).toContain("Cannot confirm");
495});