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

update.test.ts

776 lines31.4 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import type { ManagedUpdatesPolicy } from "@t3tools/contracts";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as Exit from "effect/Exit";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as TestClock from "effect/testing/TestClock";
13import * as TestConsole from "effect/testing/TestConsole";
14import { HttpClient, HttpClientResponse } from "effect/http";
15import * as ChildProcess from "effect/process/ChildProcess";
16import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17import { afterEach, vi } from "vite-plus/test";
18​
19import packageJson from "../../package.json" with { type: "json" };
20import * as BootService from "../cloud/bootService.ts";
21import { SERVICE_LAUNCHER_PROTOCOL } from "../cloud/serviceProtocol.ts";
22import {
23 pinnedRuntimePaths,
24 posixLauncherScript,
25 prunePinnedRuntimes,
26 readPosixLauncherTarget,
27 resolveLauncherPath,
28} from "../cloud/pinnedRuntime.ts";
29import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
30import * as ProcessRunner from "../processRunner.ts";
31import {
32 repointLauncher,
33 resolveMirrorVersion,
34 resolveNewestVersion,
35 runUpdate,
36} from "./update.ts";
37​
38// lsof listing one process, so prune sees a process list in which no runtime is running.
39const unrelatedLsof = ProcessRunner.ProcessRunner.of({
40 run: () =>
41 Effect.succeed({
42 stdout: "p1\nftxt\nn/usr/bin/true\n",
43 stderr: "",
44 code: ChildProcessSpawner.ExitCode(0),
45 timedOut: false,
46 stdoutTruncated: false,
47 stderrTruncated: false,
48 stdoutInvalidUtf8: false,
49 stderrInvalidUtf8: false,
50 }),
51});
52​
53afterEach(() => vi.restoreAllMocks());
54​
55it.effect("authenticates each release page until the requested channel is found", () =>
56 Effect.gen(function* () {
57 const pages: string[] = [];
58 const httpClient = HttpClient.make((request) => {
59 const url = new URL(request.url);
60 assert.equal(url.origin, "https://api.github.com");
61 assert.equal(url.pathname, "/repos/pingdotgg/t3code/releases");
62 assert.equal(request.headers.accept, "application/vnd.github+json");
63 assert.equal(request.headers.authorization, "Bearer gh-token");
64 const page = url.searchParams.get("page") ?? "";
65 pages.push(page);
66 const tag_name = page === "1" ? "v1.2.4-preview.20260101.1" : "v1.2.3";
67 return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json([{ tag_name }])));
68 });
69 const version = yield* resolveNewestVersion("stable").pipe(
70 Effect.provideService(HostProcess.Environment, { GH_TOKEN: "gh-token" }),
71 Effect.provideService(HttpClient.HttpClient, httpClient),
72 );
73 assert.equal(version, "1.2.3");
74 assert.deepStrictEqual(pages, ["1", "2"]);
75 }),
76);
77​
78it.effect("reads the newest version from the update feed file a mirror publishes", () =>
79 Effect.gen(function* () {
80 const requested: string[] = [];
81 const mirror = {
82 organization: "Example Corp",
83 feedUrl: "https://updates.example.com/t3code/?token=abc",
84 };
85 const resolve = (
86 channel: "stable" | "nightly" | "preview",
87 platform: NodeJS.Platform,
88 arch: string,
89 feed: string,
90 ) =>
91 resolveMirrorVersion(mirror, channel).pipe(
92 Effect.map((version): string => version),
93 Effect.catchTags({ CliUpdateError: (error) => Effect.succeed(`error: ${error.reason}`) }),
94 Effect.provideService(HostProcess.Platform, platform),
95 Effect.provideService(HostProcess.Architecture, arch),
96 Effect.provideService(
97 HttpClient.HttpClient,
98 HttpClient.make((request) => {
99 requested.push(request.url);
100 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(feed)));
101 }),
102 ),
103 );
104​
105 assert.equal(
106 yield* resolve("stable", "darwin", "arm64", "version: 1.4.0\nfiles: []\n"),
107 "1.4.0",
108 );
109 assert.equal(
110 yield* resolve("nightly", "linux", "arm64", "version: '1.5.0-nightly.20261101.2'\n"),
111 "1.5.0-nightly.20261101.2",
112 );
113 assert.deepStrictEqual(requested, [
114 "https://updates.example.com/t3code/latest-mac.yml?token=abc",
115 "https://updates.example.com/t3code/nightly-linux-arm64.yml?token=abc",
116 ]);
117 // A feed for the wrong track is not trusted to mean the requested one.
118 assert.include(
119 yield* resolve("stable", "win32", "x64", "version: 1.5.0-nightly.20261101.2\n"),
120 "Could not read latest.yml from Example Corp's update mirror.",
121 );
122 assert.include(yield* resolve("preview", "win32", "x64", ""), "has no preview builds");
123 }),
124);
125​
126it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
127 const runWithPolicy = (
128 updates: ManagedUpdatesPolicy,
129 input: { readonly channel?: "stable" | "nightly"; readonly requestedVersion?: string } = {},
130 httpClient = HttpClient.make(() => Effect.die("unexpected release lookup")),
131 ) =>
132 runUpdate({
133 baseDir: "/unused",
134 logsDir: "/unused",
135 databasePath: "/unused",
136 serverRuntimeStatePath: "/unused",
137 channel: input.channel,
138 requestedVersion: input.requestedVersion,
139 allowDowngrade: false,
140 assumeYes: true,
141 }).pipe(
142 Effect.flip,
143 Effect.provide(
144 Layer.mergeAll(
145 ManagedPolicy.layerTest({
146 schemaVersion: 1,
147 organization: "Example Corp",
148 limits: { updates },
149 }),
150 // Refusals happen before the update touches the network, the service, or a process.
151 Layer.mock(BootService.BootService, {}),
152 Layer.mock(ProcessRunner.ProcessRunner, {}),
153 Layer.succeed(HttpClient.HttpClient, httpClient),
154 ),
155 ),
156 );
157​
158 it.effect("refuses to update when updates are off", () =>
159 Effect.gen(function* () {
160 const error = yield* runWithPolicy({ mode: "off" });
161 assert.equal(error.message, "Example Corp manages T3 Code updates.");
162 }),
163 );
164​
165 it.effect("refuses nightly releases when the policy disallows them", () =>
166 Effect.gen(function* () {
167 const byChannel = yield* runWithPolicy(
168 { mode: "auto", allowNightly: false },
169 { channel: "nightly" },
170 );
171 const byVersion = yield* runWithPolicy(
172 { mode: "auto", allowNightly: false },
173 { channel: "stable", requestedVersion: "1.2.0-nightly.20261028.1" },
174 );
175 for (const error of [byChannel, byVersion]) {
176 assert.equal(
177 error.message,
178 "Example Corp manages T3 Code updates. Only stable releases can be installed.",
179 );
180 }
181 }),
182 );
183​
184 it.effect("looks for updates on the policy's mirror, never the public releases", () =>
185 Effect.gen(function* () {
186 const requested: string[] = [];
187 const error = yield* runWithPolicy(
188 { mode: "auto", feedUrl: "https://updates.example.com/t3code" },
189 { channel: "stable" },
190 HttpClient.make((request) => {
191 requested.push(new URL(request.url).origin);
192 return Effect.succeed(
193 HttpClientResponse.fromWeb(request, new Response("", { status: 404 })),
194 );
195 }),
196 );
197 assert.include(error.message, "from Example Corp's update mirror");
198 assert.deepStrictEqual(requested, ["https://updates.example.com"]);
199 }),
200 );
201});
202​
203it.layer(NodeServices.layer)("t3 update launcher", (it) => {
204 it.effect("replaces a legacy symlink with a script that execs the new version", () =>
205 Effect.gen(function* () {
206 const fs = yield* FileSystem.FileSystem;
207 const path = yield* Path.Path;
208 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
209 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
210 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
211 const launcher = path.join(root, "bin/t3");
212 for (const file of [oldExe, newExe]) {
213 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
214 yield* fs.writeFileString(file, "");
215 }
216 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
217 yield* fs.symlink(oldExe, launcher);
218​
219 const repointed = yield* repointLauncher({
220 launchedAs: launcher,
221 baseDir: root,
222 targetEntryPath: newExe,
223 });
224​
225 assert.deepStrictEqual(Option.getOrUndefined(repointed), launcher);
226 assert.equal(yield* fs.readFileString(launcher), posixLauncherScript(newExe));
227 // Replaced, not written through.
228 assert.equal(yield* fs.readFileString(oldExe), "");
229 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
230 );
231​
232 it.effect("repoints a recorded Windows launcher outside PATH", () =>
233 Effect.gen(function* () {
234 const fs = yield* FileSystem.FileSystem;
235 const path = yield* Path.Path;
236 const root = yield* fs.makeTempDirectoryScoped();
237 const baseDir = path.join(root, "home");
238 const runtimeDir = path.join(baseDir, "runtime");
239 const launcher = path.join(root, "custom bin", "t3.cmd");
240 const launchedAs = path.join(runtimeDir, "versions", "1.0.0", "t3.exe");
241 const targetEntryPath = path.join(runtimeDir, "versions", "2.0.0", "t3.exe");
242 yield* fs.makeDirectory(runtimeDir, { recursive: true });
243 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
244 yield* fs.writeFileString(launcher, `@echo off\r\n"${launchedAs}" %*`);
245 yield* fs.writeFileString(path.join(runtimeDir, "launchers"), `${launcher}\r\n`);
246​
247 const repointed = yield* repointLauncher({ launchedAs, baseDir, targetEntryPath });
248​
249 assert.equal(Option.getOrUndefined(repointed), launcher);
250 assert.equal(yield* fs.readFileString(launcher), `@echo off\r\n"${targetEntryPath}" %*`);
251 }).pipe(
252 Effect.scoped,
253 Effect.provideService(HostProcess.Platform, "win32"),
254 Effect.provideService(HostProcess.Environment, { PATH: "" }),
255 ),
256 );
257​
258 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
259 "finds the script that ran this executable and rewrites it, keeping aliases and arguments",
260 () =>
261 Effect.gen(function* () {
262 const fs = yield* FileSystem.FileSystem;
263 const path = yield* Path.Path;
264 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
265 const root = yield* fs.realPath(
266 yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" }),
267 );
268 // A quote and a space in the home path exercise the script's quoting.
269 const home = path.join(root, "it's home");
270 const entry = (version: string) => path.join(home, "runtime/versions", version, "t3");
271 for (const version of ["1.0.0", "2.0.0"]) {
272 yield* fs.makeDirectory(path.dirname(entry(version)), { recursive: true });
273 yield* fs.writeFileString(entry(version), '#!/bin/sh\nprintf \'[%s]\\n\' "$0" "$@"\n', {
274 mode: 0o755,
275 });
276 }
277 const launcher = path.join(root, "bin/t3");
278 const alias = path.join(root, "alias/t3");
279 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
280 yield* fs.makeDirectory(path.dirname(alias), { recursive: true });
281 yield* fs.writeFileString(launcher, posixLauncherScript(entry("1.0.0")), { mode: 0o755 });
282 yield* fs.symlink(launcher, alias);
283 const repoint = (environment: Record<string, string>) =>
284 repointLauncher({
285 // The script execs by absolute path, so argv0 names the executable.
286 launchedAs: entry("1.0.0"),
287 baseDir: home,
288 targetEntryPath: entry("2.0.0"),
289 }).pipe(Effect.provideService(HostProcess.Environment, environment));
290​
291 assert.equal(
292 Option.getOrUndefined(yield* repoint({ PATH: path.dirname(alias) })),
293 launcher,
294 );
295 assert.equal(yield* fs.readLink(alias), launcher);
296 const args = ["two words", "it's quoted", "", "*", "$HOME"];
297 assert.equal(
298 yield* spawner.string(ChildProcess.make(alias, args, { cwd: root })),
299 [entry("2.0.0"), ...args].map((arg) => `[${arg}]\n`).join(""),
300 );
301​
302 // Like the shell, a relative PATH entry resolves from the working directory, and a
303 // script nobody can execute is passed over.
304 const unrunnable = path.join(root, "unrunnable/t3");
305 yield* fs.makeDirectory(path.dirname(unrunnable), { recursive: true });
306 yield* fs.writeFileString(unrunnable, posixLauncherScript(entry("2.0.0")), { mode: 0o644 });
307 yield* fs.writeFileString(launcher, posixLauncherScript(entry("2.0.0")), { mode: 0o755 });
308 const relative = yield* repointLauncher({
309 launchedAs: entry("2.0.0"),
310 baseDir: home,
311 targetEntryPath: entry("1.0.0"),
312 }).pipe(
313 Effect.provideService(HostProcess.Environment, {
314 PATH: `${path.dirname(unrunnable)}:bin`,
315 }),
316 Effect.provideService(HostProcess.WorkingDirectory, root),
317 );
318 assert.equal(Option.getOrUndefined(relative), launcher);
319 assert.equal(yield* fs.readFileString(unrunnable), posixLauncherScript(entry("2.0.0")));
320​
321 // An edited script is the user's own wrapper now.
322 const edited = `${posixLauncherScript(entry("1.0.0"))}# mine\n`;
323 yield* fs.writeFileString(launcher, edited);
324 assert.isTrue(Option.isNone(yield* repoint({ PATH: path.dirname(launcher) })));
325 assert.equal(yield* fs.readFileString(launcher), edited);
326 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
327 );
328​
329 it.effect.each([
330 { name: "no launcher records", recorded: undefined },
331 { name: "an empty launcher record", recorded: "" },
332 { name: "whole launcher records", recorded: "/opt/t3\n" },
333 { name: "Windows launcher records", recorded: "C:\\t3.cmd\r\n" },
334 // An interrupted append cut this record short.
335 { name: "an unterminated launcher record", recorded: "/opt/t" },
336 // Another process's append is cut short after t3 update reads the records.
337 { name: "a record cut short after the read", recorded: "/opt/t3\n", cut: "/opt/t" },
338 ])("keeps the runtime a repointed launcher off PATH points at with $name", ({ recorded, cut }) =>
339 Effect.gen(function* () {
340 const fs = yield* FileSystem.FileSystem;
341 const path = yield* Path.Path;
342 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
343 yield* TestClock.setTime(Duration.toMillis(Duration.days(1)));
344 for (const version of ["1.0.0", "2.0.0"]) {
345 const directory = path.join(root, "runtime/versions", version);
346 yield* fs.makeDirectory(directory, { recursive: true });
347 yield* fs.writeFileString(path.join(directory, "t3"), "");
348 yield* fs.writeFileString(path.join(directory, ".install-complete"), `${version}\n`);
349 yield* fs.utimes(path.join(directory, ".install-complete"), 0, 0);
350 }
351 if (recorded !== undefined) {
352 yield* fs.writeFileString(path.join(root, "runtime/launchers"), recorded);
353 }
354 // A launcher in the T3 home itself, which neither PATH nor the default bin dir reaches.
355 const launcher = path.join(root, "t3");
356 yield* fs.symlink(path.join(root, "runtime/versions/1.0.0/t3"), launcher);
357​
358 const launchersFile = path.join(root, "runtime/launchers");
359 yield* repointLauncher({
360 launchedAs: launcher,
361 baseDir: root,
362 targetEntryPath: path.join(root, "runtime/versions/2.0.0/t3"),
363 }).pipe(
364 Effect.provideService(FileSystem.FileSystem, {
365 ...fs,
366 readFileString: (file, encoding) =>
367 fs
368 .readFileString(file, encoding)
369 .pipe(
370 Effect.tap(() =>
371 cut === undefined || file !== launchersFile
372 ? Effect.void
373 : fs.writeFileString(file, cut, { flag: "a" }),
374 ),
375 ),
376 }),
377 );
378 // A later server start prunes with no idea how this machine launches t3.
379 const removed = yield* prunePinnedRuntimes({ baseDir: root, keep: [] }).pipe(
380 Effect.provideService(ProcessRunner.ProcessRunner, unrelatedLsof),
381 Effect.provideService(HostProcess.Platform, "darwin"),
382 Effect.provideService(HostProcess.Environment, { PATH: "" }),
383 Effect.provideService(HostProcess.HomeDirectory, root),
384 );
385​
386 assert.deepStrictEqual(removed, ["1.0.0"]);
387 assert.equal(
388 yield* readPosixLauncherTarget(launcher),
389 path.join(root, "runtime/versions/2.0.0/t3"),
390 );
391 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
392 );
393​
394 const launcherFixture = Effect.fnUntraced(function* () {
395 const fs = yield* FileSystem.FileSystem;
396 const path = yield* Path.Path;
397 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
398 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
399 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
400 const launcher = path.join(root, "t3");
401 for (const file of [oldExe, newExe]) {
402 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
403 yield* fs.writeFileString(file, "");
404 }
405 yield* fs.symlink(oldExe, launcher);
406 return { root, oldExe, newExe, launcher, launchersFile: path.join(root, "runtime/launchers") };
407 });
408​
409 it.effect("records a relative launcher path as absolute", () =>
410 Effect.gen(function* () {
411 const fs = yield* FileSystem.FileSystem;
412 const path = yield* Path.Path;
413 const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
414​
415 yield* repointLauncher({
416 launchedAs: path.relative(path.resolve("."), launcher),
417 baseDir: root,
418 targetEntryPath: newExe,
419 });
420​
421 assert.equal(yield* fs.readFileString(launchersFile), `\n${launcher}\n`);
422 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
423 );
424​
425 it.effect("fails instead of repointing a launcher it cannot record", () =>
426 Effect.gen(function* () {
427 const fs = yield* FileSystem.FileSystem;
428 const { root, oldExe, newExe, launcher, launchersFile } = yield* launcherFixture();
429 // Appending to a directory fails the way a read-only or full disk would.
430 yield* fs.makeDirectory(launchersFile);
431​
432 const result = yield* repointLauncher({
433 launchedAs: launcher,
434 baseDir: root,
435 targetEntryPath: newExe,
436 }).pipe(Effect.exit);
437​
438 assert.isTrue(Exit.isFailure(result));
439 assert.equal(yield* fs.readLink(launcher), oldExe);
440 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
441 );
442​
443 it.effect.each(["recording", "repointing"] as const)(
444 "never leaves a repointed launcher unrecorded when t3 update dies while %s",
445 (step) =>
446 Effect.gen(function* () {
447 const fs = yield* FileSystem.FileSystem;
448 const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
449​
450 yield* repointLauncher({
451 launchedAs: launcher,
452 baseDir: root,
453 targetEntryPath: newExe,
454 }).pipe(
455 Effect.provideService(FileSystem.FileSystem, {
456 ...fs,
457 writeFileString: (path, data, options) =>
458 step === "recording" && path === launchersFile
459 ? Effect.die("t3 update was killed")
460 : fs.writeFileString(path, data, options),
461 rename: (from, to) =>
462 step === "repointing" && to === launcher
463 ? Effect.die("t3 update was killed")
464 : fs.rename(from, to),
465 }),
466 Effect.exit,
467 );
468​
469 const repointed = (yield* readPosixLauncherTarget(launcher)) === newExe;
470 const recorded = (yield* fs
471 .readFileString(launchersFile)
472 .pipe(Effect.orElseSucceed(() => "")))
473 .split("\n")
474 .includes(launcher);
475 assert.isFalse(repointed && !recorded);
476 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
477 );
478​
479 it.effect("leaves a plain copy or a foreign symlink alone", () =>
480 Effect.gen(function* () {
481 const fs = yield* FileSystem.FileSystem;
482 const path = yield* Path.Path;
483 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
484 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
485 const copy = path.join(root, "copy/t3");
486 const foreign = path.join(root, "foreign/t3");
487 const elsewhere = path.join(root, "elsewhere/t3");
488 const otherHome = path.join(root, "other/runtime/versions/1.0.0/t3");
489 const otherLauncher = path.join(root, "other/bin/t3");
490 for (const file of [newExe, copy, elsewhere, otherHome]) {
491 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
492 yield* fs.writeFileString(file, "");
493 }
494 yield* fs.makeDirectory(path.dirname(foreign), { recursive: true });
495 yield* fs.symlink(elsewhere, foreign);
496 yield* fs.makeDirectory(path.dirname(otherLauncher), { recursive: true });
497 yield* fs.symlink(otherHome, otherLauncher);
498​
499 for (const launchedAs of [copy, foreign, otherLauncher, undefined]) {
500 const repointed = yield* repointLauncher({
501 launchedAs,
502 baseDir: root,
503 targetEntryPath: newExe,
504 });
505 assert.equal(repointed._tag, "None", launchedAs ?? "undefined");
506 }
507 assert.equal(yield* fs.readLink(foreign), elsewhere);
508 assert.equal(yield* fs.readLink(otherLauncher), otherHome);
509 }).pipe(Effect.provideService(HostProcess.Platform, "linux")),
510 );
511​
512 it.effect("finds the launcher a bare command name resolved to on PATH", () =>
513 Effect.gen(function* () {
514 const fs = yield* FileSystem.FileSystem;
515 const path = yield* Path.Path;
516 const delimiter = (yield* HostProcess.Platform) === "win32" ? ";" : ":";
517 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
518 const launcher = path.join(root, "bin/t3");
519 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
520 yield* fs.writeFileString(launcher, "", { mode: 0o755 });
521​
522 const bare = yield* resolveLauncherPath.pipe(
523 Effect.provideService(HostProcess.InvokedAs, "t3"),
524 Effect.provideService(HostProcess.Environment, {
525 PATH: [path.join(root, "missing"), path.join(root, "bin")].join(delimiter),
526 }),
527 Effect.provideService(HostProcess.WorkingDirectory, root),
528 );
529 const relative = yield* resolveLauncherPath.pipe(
530 Effect.provideService(HostProcess.InvokedAs, "./bin/t3"),
531 Effect.provideService(HostProcess.Environment, { PATH: "" }),
532 Effect.provideService(HostProcess.WorkingDirectory, root),
533 );
534 const absent = yield* resolveLauncherPath.pipe(
535 Effect.provideService(HostProcess.InvokedAs, "t3"),
536 Effect.provideService(HostProcess.Environment, { PATH: path.join(root, "missing") }),
537 Effect.provideService(HostProcess.WorkingDirectory, root),
538 );
539​
540 assert.equal(bare, launcher);
541 assert.equal(relative, launcher);
542 assert.equal(absent, undefined);
543 }),
544 );
545});
546​
547// Without terminals, update skips its restart prompt whatever runs the test.
548const withoutTerminals = Effect.acquireRelease(
549 Effect.sync(() =>
550 [process.stdin, process.stdout].map((stream) => {
551 const descriptor = Object.getOwnPropertyDescriptor(stream, "isTTY");
552 Object.defineProperty(stream, "isTTY", { configurable: true, value: false });
553 return { stream, descriptor };
554 }),
555 ),
556 (saved) =>
557 Effect.sync(() => {
558 for (const { stream, descriptor } of saved) {
559 if (descriptor === undefined) Reflect.deleteProperty(stream, "isTTY");
560 else Object.defineProperty(stream, "isTTY", descriptor);
561 }
562 }),
563);
564​
565it.layer(NodeServices.layer)("t3 update with a background service", (it) => {
566 it.effect("names the version a service with a pending restart still runs", () =>
567 Effect.gen(function* () {
568 yield* withoutTerminals;
569 const fs = yield* FileSystem.FileSystem;
570 const path = yield* Path.Path;
571 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
572 const version = packageJson.version;
573 const runtime = pinnedRuntimePaths(path, baseDir, version, "linux");
574 yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
575 yield* fs.writeFileString(runtime.entryPath, "");
576 yield* fs.writeFileString(runtime.sentinelPath, `${version}\n`);
577 const unitPath = path.join(baseDir, "t3code.service");
578 const logPath = path.join(baseDir, "boot-service.log");
579 // An earlier `t3 update` pointed the service at this version without restarting it.
580 const service = Layer.mock(BootService.BootService, {
581 status: Effect.succeed<BootService.BootServiceStatus>({
582 supported: true,
583 installed: true,
584 current: false,
585 installedVersion: version,
586 installedBaseDir: baseDir,
587 problems: ["restart-pending"],
588 unitPath,
589 logPath,
590 }),
591 install: () => Effect.succeed({ program: [runtime.entryPath], baseDir, unitPath, logPath }),
592 });
593 vi.spyOn(BootService, "layer").mockReturnValue(service);
594 const runner = ProcessRunner.ProcessRunner.of({
595 run: (input) =>
596 input.args?.includes("__service-preflight") === true
597 ? unrelatedLsof.run(input).pipe(
598 Effect.map((result) => ({
599 ...result,
600 stdout: JSON.stringify({
601 status: "ready",
602 version,
603 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
604 }),
605 })),
606 )
607 : unrelatedLsof.run(input),
608 });
609​
610 const output = yield* runUpdate({
611 baseDir,
612 logsDir: baseDir,
613 databasePath: path.join(baseDir, "statev2.sqlite"),
614 serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
615 channel: undefined,
616 requestedVersion: version,
617 allowDowngrade: false,
618 assumeYes: false,
619 }).pipe(
620 Effect.andThen(TestConsole.logLines),
621 Effect.map((lines) => lines.join("\n")),
622 Effect.provide(
623 Layer.mergeAll(
624 service,
625 Layer.succeed(ProcessRunner.ProcessRunner, runner),
626 ManagedPolicy.layerTest(),
627 Layer.succeed(
628 HttpClient.HttpClient,
629 HttpClient.make(() => Effect.die("unexpected release lookup")),
630 ),
631 Layer.fresh(TestConsole.layer),
632 ),
633 ),
634 );
635​
636 assert.include(
637 output,
638 `Background service still running the version before ${version}. Run \`t3 service restart\` when you are ready to switch it to ${version}.`,
639 );
640 }).pipe(
641 Effect.provideService(HostProcess.Platform, "linux"),
642 Effect.provideService(HostProcess.Environment, { PATH: "" }),
643 ),
644 );
645});
646​
647it.layer(NodeServices.layer)("t3 update checks the database before switching", (it) => {
648 const preflightOutput = (stdout: string, code = 0) => ({
649 stdout,
650 stderr: code === 0 ? "" : "Unknown command: __service-preflight",
651 code: ChildProcessSpawner.ExitCode(code),
652 timedOut: false,
653 stdoutTruncated: false,
654 stderrTruncated: false,
655 stdoutInvalidUtf8: false,
656 stderrInvalidUtf8: false,
657 });
658 const blockedReason = "This database has migrations that t3@0.1.8 does not know: 79_example.";
659​
660 it.effect.each([
661 {
662 name: "installs an older target that accepts this database",
663 targetVersion: "0.1.8",
664 launcherProtocol: 3,
665 preflight: preflightOutput(
666 JSON.stringify({ status: "ready", version: "0.1.8", launcherProtocol: 3 }),
667 ),
668 failure: undefined,
669 },
670 {
671 name: "refuses an older target the database is too new for",
672 targetVersion: "0.1.8",
673 launcherProtocol: 3,
674 preflight: preflightOutput(
675 JSON.stringify({ status: "blocked", version: "0.1.8", reason: blockedReason }),
676 ),
677 failure: blockedReason,
678 },
679 {
680 name: "refuses an older target too old to check the database",
681 targetVersion: "0.1.8",
682 launcherProtocol: 3,
683 preflight: preflightOutput("", 1),
684 failure:
685 "t3@0.1.8 could not confirm it supports this database (its check exited with code 1), so t3 did not switch to it.",
686 },
687 {
688 // Newer builds keep accepting the current launcher protocol, which may drop 3.
689 name: "checks a newer target with the current launcher protocol",
690 targetVersion: "99.0.0",
691 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
692 preflight: preflightOutput(
693 JSON.stringify({
694 status: "ready",
695 version: "99.0.0",
696 launcherProtocol: SERVICE_LAUNCHER_PROTOCOL,
697 }),
698 ),
699 failure: undefined,
700 },
701 ])("$name", ({ targetVersion, launcherProtocol, preflight, failure }) =>
702 Effect.gen(function* () {
703 const fs = yield* FileSystem.FileSystem;
704 const path = yield* Path.Path;
705 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
706 const databasePath = path.join(baseDir, "userdata", "statev2.sqlite");
707 const runtime = pinnedRuntimePaths(path, baseDir, targetVersion, "linux");
708 yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
709 yield* fs.writeFileString(runtime.entryPath, "");
710 yield* fs.writeFileString(runtime.sentinelPath, `${targetVersion}\n`);
711 const service = Layer.mock(BootService.BootService, {
712 status: Effect.succeed<BootService.BootServiceStatus>({
713 supported: true,
714 installed: false,
715 current: false,
716 unitPath: path.join(baseDir, "t3code.service"),
717 logPath: path.join(baseDir, "boot-service.log"),
718 }),
719 });
720 const preflightArgs: Array<ReadonlyArray<string>> = [];
721 const runner = ProcessRunner.ProcessRunner.of({
722 run: (input) => {
723 if (input.args?.includes("__service-preflight") === true) {
724 preflightArgs.push(input.args);
725 return Effect.succeed(preflight);
726 }
727 // A target's --version always answers, whatever its database support.
728 return input.args?.includes("--version") === true
729 ? Effect.succeed(preflightOutput(`t3 v${targetVersion}\n`))
730 : unrelatedLsof.run(input);
731 },
732 });
733​
734 const exit = yield* runUpdate({
735 baseDir,
736 logsDir: baseDir,
737 databasePath,
738 serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
739 channel: undefined,
740 requestedVersion: targetVersion,
741 allowDowngrade: true,
742 assumeYes: true,
743 }).pipe(
744 Effect.exit,
745 Effect.provide(
746 Layer.mergeAll(
747 service,
748 Layer.succeed(ProcessRunner.ProcessRunner, runner),
749 ManagedPolicy.layerTest(),
750 Layer.succeed(
751 HttpClient.HttpClient,
752 HttpClient.make(() => Effect.die("unexpected release lookup")),
753 ),
754 Layer.fresh(TestConsole.layer),
755 ),
756 ),
757 );
758​
759 const error = Option.getOrUndefined(Exit.findErrorOption(exit));
760 assert.equal(error?.message, failure);
761 assert.equal(Exit.isSuccess(exit), failure === undefined);
762 assert.deepEqual(preflightArgs, [
763 [
764 "__service-preflight",
765 "--database-path",
766 databasePath,
767 "--launcher-protocol",
768 String(launcherProtocol),
769 ],
770 ]);
771 }).pipe(
772 Effect.provideService(HostProcess.Platform, "linux"),
773 Effect.provideService(HostProcess.Environment, { PATH: "" }),
774 ),
775 );
776});