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