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

update.test.ts

532 lines21.5 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 ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16import { afterEach, vi } from "vite-plus/test";
17​
18import packageJson from "../../package.json" with { type: "json" };
19import * as BootService from "../cloud/bootService.ts";
20import { pinnedRuntimePaths, prunePinnedRuntimes } from "../cloud/pinnedRuntime.ts";
21import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
22import * as ProcessRunner from "../processRunner.ts";
23import {
24 repointLauncher,
25 resolveLauncherPath,
26 resolveMirrorVersion,
27 resolveNewestVersion,
28 runUpdate,
29} from "./update.ts";
30​
31// lsof listing one process, so prune sees a process list in which no runtime is running.
32const unrelatedLsof = ProcessRunner.ProcessRunner.of({
33 run: () =>
34 Effect.succeed({
35 stdout: "p1\nftxt\nn/usr/bin/true\n",
36 stderr: "",
37 code: ChildProcessSpawner.ExitCode(0),
38 timedOut: false,
39 stdoutTruncated: false,
40 stderrTruncated: false,
41 stdoutInvalidUtf8: false,
42 stderrInvalidUtf8: false,
43 }),
44});
45​
46afterEach(() => vi.restoreAllMocks());
47​
48it.effect("authenticates each release page until the requested channel is found", () =>
49 Effect.gen(function* () {
50 const pages: string[] = [];
51 const httpClient = HttpClient.make((request) => {
52 const url = new URL(request.url);
53 assert.equal(url.origin, "https://api.github.com");
54 assert.equal(url.pathname, "/repos/pingdotgg/t3code/releases");
55 assert.equal(request.headers.accept, "application/vnd.github+json");
56 assert.equal(request.headers.authorization, "Bearer gh-token");
57 const page = url.searchParams.get("page") ?? "";
58 pages.push(page);
59 const tag_name = page === "1" ? "v1.2.4-preview.20260101.1" : "v1.2.3";
60 return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json([{ tag_name }])));
61 });
62 const version = yield* resolveNewestVersion("stable").pipe(
63 Effect.provideService(HostProcess.Environment, { GH_TOKEN: "gh-token" }),
64 Effect.provideService(HttpClient.HttpClient, httpClient),
65 );
66 assert.equal(version, "1.2.3");
67 assert.deepStrictEqual(pages, ["1", "2"]);
68 }),
69);
70​
71it.effect("reads the newest version from the update feed file a mirror publishes", () =>
72 Effect.gen(function* () {
73 const requested: string[] = [];
74 const mirror = {
75 organization: "Example Corp",
76 feedUrl: "https://updates.example.com/t3code/?token=abc",
77 };
78 const resolve = (
79 channel: "stable" | "nightly" | "preview",
80 platform: NodeJS.Platform,
81 arch: string,
82 feed: string,
83 ) =>
84 resolveMirrorVersion(mirror, channel).pipe(
85 Effect.map((version): string => version),
86 Effect.catchTags({ CliUpdateError: (error) => Effect.succeed(`error: ${error.reason}`) }),
87 Effect.provideService(HostProcess.Platform, platform),
88 Effect.provideService(HostProcess.Architecture, arch),
89 Effect.provideService(
90 HttpClient.HttpClient,
91 HttpClient.make((request) => {
92 requested.push(request.url);
93 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(feed)));
94 }),
95 ),
96 );
97​
98 assert.equal(
99 yield* resolve("stable", "darwin", "arm64", "version: 1.4.0\nfiles: []\n"),
100 "1.4.0",
101 );
102 assert.equal(
103 yield* resolve("nightly", "linux", "arm64", "version: '1.5.0-nightly.20261101.2'\n"),
104 "1.5.0-nightly.20261101.2",
105 );
106 assert.deepStrictEqual(requested, [
107 "https://updates.example.com/t3code/latest-mac.yml?token=abc",
108 "https://updates.example.com/t3code/nightly-linux-arm64.yml?token=abc",
109 ]);
110 // A feed for the wrong track is not trusted to mean the requested one.
111 assert.include(
112 yield* resolve("stable", "win32", "x64", "version: 1.5.0-nightly.20261101.2\n"),
113 "Could not read latest.yml from Example Corp's update mirror.",
114 );
115 assert.include(yield* resolve("preview", "win32", "x64", ""), "has no preview builds");
116 }),
117);
118​
119it.layer(NodeServices.layer)("t3 update under a managed policy", (it) => {
120 const runWithPolicy = (
121 updates: ManagedUpdatesPolicy,
122 input: { readonly channel?: "stable" | "nightly"; readonly requestedVersion?: string } = {},
123 httpClient = HttpClient.make(() => Effect.die("unexpected release lookup")),
124 ) =>
125 runUpdate({
126 baseDir: "/unused",
127 logsDir: "/unused",
128 serverRuntimeStatePath: "/unused",
129 channel: input.channel,
130 requestedVersion: input.requestedVersion,
131 allowDowngrade: false,
132 assumeYes: true,
133 }).pipe(
134 Effect.flip,
135 Effect.provide(
136 Layer.mergeAll(
137 ManagedPolicy.layerTest({
138 schemaVersion: 1,
139 organization: "Example Corp",
140 limits: { updates },
141 }),
142 // Refusals happen before the update touches the network, the service, or a process.
143 Layer.mock(BootService.BootService, {}),
144 Layer.mock(ProcessRunner.ProcessRunner, {}),
145 Layer.succeed(HttpClient.HttpClient, httpClient),
146 ),
147 ),
148 );
149​
150 it.effect("refuses to update when updates are off", () =>
151 Effect.gen(function* () {
152 const error = yield* runWithPolicy({ mode: "off" });
153 assert.equal(error.message, "Example Corp manages T3 Code updates.");
154 }),
155 );
156​
157 it.effect("refuses nightly releases when the policy disallows them", () =>
158 Effect.gen(function* () {
159 const byChannel = yield* runWithPolicy(
160 { mode: "auto", allowNightly: false },
161 { channel: "nightly" },
162 );
163 const byVersion = yield* runWithPolicy(
164 { mode: "auto", allowNightly: false },
165 { channel: "stable", requestedVersion: "1.2.0-nightly.20261028.1" },
166 );
167 for (const error of [byChannel, byVersion]) {
168 assert.equal(
169 error.message,
170 "Example Corp manages T3 Code updates. Only stable releases can be installed.",
171 );
172 }
173 }),
174 );
175​
176 it.effect("looks for updates on the policy's mirror, never the public releases", () =>
177 Effect.gen(function* () {
178 const requested: string[] = [];
179 const error = yield* runWithPolicy(
180 { mode: "auto", feedUrl: "https://updates.example.com/t3code" },
181 { channel: "stable" },
182 HttpClient.make((request) => {
183 requested.push(new URL(request.url).origin);
184 return Effect.succeed(
185 HttpClientResponse.fromWeb(request, new Response("", { status: 404 })),
186 );
187 }),
188 );
189 assert.include(error.message, "from Example Corp's update mirror");
190 assert.deepStrictEqual(requested, ["https://updates.example.com"]);
191 }),
192 );
193});
194​
195it.layer(NodeServices.layer)("t3 update launcher", (it) => {
196 it.effect("repoints a symlink that lives in a runtime versions tree", () =>
197 Effect.gen(function* () {
198 const fs = yield* FileSystem.FileSystem;
199 const path = yield* Path.Path;
200 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
201 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
202 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
203 const launcher = path.join(root, "bin/t3");
204 for (const file of [oldExe, newExe]) {
205 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
206 yield* fs.writeFileString(file, "");
207 }
208 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
209 yield* fs.symlink(oldExe, launcher);
210​
211 const repointed = yield* repointLauncher({
212 launchedAs: launcher,
213 baseDir: root,
214 targetEntryPath: newExe,
215 });
216​
217 assert.deepStrictEqual(Option.getOrUndefined(repointed), launcher);
218 assert.equal(yield* fs.readLink(launcher), newExe);
219 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
220 );
221​
222 it.effect.each([
223 { name: "no launcher records", recorded: undefined },
224 { name: "an empty launcher record", recorded: "" },
225 { name: "whole launcher records", recorded: "/opt/t3\n" },
226 { name: "Windows launcher records", recorded: "C:\\t3.cmd\r\n" },
227 // An interrupted append cut this record short.
228 { name: "an unterminated launcher record", recorded: "/opt/t" },
229 // Another process's append is cut short after t3 update reads the records.
230 { name: "a record cut short after the read", recorded: "/opt/t3\n", cut: "/opt/t" },
231 ])("keeps the runtime a repointed launcher off PATH points at with $name", ({ recorded, cut }) =>
232 Effect.gen(function* () {
233 const fs = yield* FileSystem.FileSystem;
234 const path = yield* Path.Path;
235 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
236 yield* TestClock.setTime(Duration.toMillis(Duration.days(1)));
237 for (const version of ["1.0.0", "2.0.0"]) {
238 const directory = path.join(root, "runtime/versions", version);
239 yield* fs.makeDirectory(directory, { recursive: true });
240 yield* fs.writeFileString(path.join(directory, "t3"), "");
241 yield* fs.writeFileString(path.join(directory, ".install-complete"), `${version}\n`);
242 yield* fs.utimes(path.join(directory, ".install-complete"), 0, 0);
243 }
244 if (recorded !== undefined) {
245 yield* fs.writeFileString(path.join(root, "runtime/launchers"), recorded);
246 }
247 // A launcher in the T3 home itself, which neither PATH nor the default bin dir reaches.
248 const launcher = path.join(root, "t3");
249 yield* fs.symlink(path.join(root, "runtime/versions/1.0.0/t3"), launcher);
250​
251 const launchersFile = path.join(root, "runtime/launchers");
252 yield* repointLauncher({
253 launchedAs: launcher,
254 baseDir: root,
255 targetEntryPath: path.join(root, "runtime/versions/2.0.0/t3"),
256 }).pipe(
257 Effect.provideService(FileSystem.FileSystem, {
258 ...fs,
259 readFileString: (file, encoding) =>
260 fs
261 .readFileString(file, encoding)
262 .pipe(
263 Effect.tap(() =>
264 cut === undefined || file !== launchersFile
265 ? Effect.void
266 : fs.writeFileString(file, cut, { flag: "a" }),
267 ),
268 ),
269 }),
270 );
271 // A later server start prunes with no idea how this machine launches t3.
272 const removed = yield* prunePinnedRuntimes({ baseDir: root, keep: [] }).pipe(
273 Effect.provideService(ProcessRunner.ProcessRunner, unrelatedLsof),
274 Effect.provideService(HostProcess.Platform, "darwin"),
275 Effect.provideService(HostProcess.Environment, { PATH: "" }),
276 Effect.provideService(HostProcess.HomeDirectory, root),
277 );
278​
279 assert.deepStrictEqual(removed, ["1.0.0"]);
280 // macOS temp dirs sit behind the /var -> /private/var symlink, so compare canonical paths.
281 assert.equal(
282 yield* fs.realPath(launcher),
283 yield* fs.realPath(path.join(root, "runtime/versions/2.0.0/t3")),
284 );
285 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
286 );
287​
288 const launcherFixture = Effect.fnUntraced(function* () {
289 const fs = yield* FileSystem.FileSystem;
290 const path = yield* Path.Path;
291 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
292 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
293 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
294 const launcher = path.join(root, "t3");
295 for (const file of [oldExe, newExe]) {
296 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
297 yield* fs.writeFileString(file, "");
298 }
299 yield* fs.symlink(oldExe, launcher);
300 return { root, oldExe, newExe, launcher, launchersFile: path.join(root, "runtime/launchers") };
301 });
302​
303 it.effect("records a relative launcher path as absolute", () =>
304 Effect.gen(function* () {
305 const fs = yield* FileSystem.FileSystem;
306 const path = yield* Path.Path;
307 const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
308​
309 yield* repointLauncher({
310 launchedAs: path.relative(path.resolve("."), launcher),
311 baseDir: root,
312 targetEntryPath: newExe,
313 });
314​
315 assert.equal(yield* fs.readFileString(launchersFile), `\n${launcher}\n`);
316 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
317 );
318​
319 it.effect("fails instead of repointing a launcher it cannot record", () =>
320 Effect.gen(function* () {
321 const fs = yield* FileSystem.FileSystem;
322 const { root, oldExe, newExe, launcher, launchersFile } = yield* launcherFixture();
323 // Appending to a directory fails the way a read-only or full disk would.
324 yield* fs.makeDirectory(launchersFile);
325​
326 const result = yield* repointLauncher({
327 launchedAs: launcher,
328 baseDir: root,
329 targetEntryPath: newExe,
330 }).pipe(Effect.exit);
331​
332 assert.isTrue(Exit.isFailure(result));
333 assert.equal(yield* fs.readLink(launcher), oldExe);
334 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
335 );
336​
337 it.effect.each(["recording", "repointing"] as const)(
338 "never leaves a repointed launcher unrecorded when t3 update dies while %s",
339 (step) =>
340 Effect.gen(function* () {
341 const fs = yield* FileSystem.FileSystem;
342 const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
343​
344 yield* repointLauncher({
345 launchedAs: launcher,
346 baseDir: root,
347 targetEntryPath: newExe,
348 }).pipe(
349 Effect.provideService(FileSystem.FileSystem, {
350 ...fs,
351 writeFileString: (path, data, options) =>
352 step === "recording" && path === launchersFile
353 ? Effect.die("t3 update was killed")
354 : fs.writeFileString(path, data, options),
355 rename: (from, to) =>
356 step === "repointing" && to === launcher
357 ? Effect.die("t3 update was killed")
358 : fs.rename(from, to),
359 }),
360 Effect.exit,
361 );
362​
363 const repointed = (yield* fs.readLink(launcher)) === newExe;
364 const recorded = (yield* fs
365 .readFileString(launchersFile)
366 .pipe(Effect.orElseSucceed(() => "")))
367 .split("\n")
368 .includes(launcher);
369 assert.isFalse(repointed && !recorded);
370 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
371 );
372​
373 it.effect("leaves a plain copy or a foreign symlink alone", () =>
374 Effect.gen(function* () {
375 const fs = yield* FileSystem.FileSystem;
376 const path = yield* Path.Path;
377 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
378 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
379 const copy = path.join(root, "copy/t3");
380 const foreign = path.join(root, "foreign/t3");
381 const elsewhere = path.join(root, "elsewhere/t3");
382 const otherHome = path.join(root, "other/runtime/versions/1.0.0/t3");
383 const otherLauncher = path.join(root, "other/bin/t3");
384 for (const file of [newExe, copy, elsewhere, otherHome]) {
385 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
386 yield* fs.writeFileString(file, "");
387 }
388 yield* fs.makeDirectory(path.dirname(foreign), { recursive: true });
389 yield* fs.symlink(elsewhere, foreign);
390 yield* fs.makeDirectory(path.dirname(otherLauncher), { recursive: true });
391 yield* fs.symlink(otherHome, otherLauncher);
392​
393 for (const launchedAs of [copy, foreign, otherLauncher, undefined]) {
394 const repointed = yield* repointLauncher({
395 launchedAs,
396 baseDir: root,
397 targetEntryPath: newExe,
398 });
399 assert.equal(repointed._tag, "None", launchedAs ?? "undefined");
400 }
401 assert.equal(yield* fs.readLink(foreign), elsewhere);
402 assert.equal(yield* fs.readLink(otherLauncher), otherHome);
403 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
404 );
405​
406 it.effect("finds the launcher a bare command name resolved to on PATH", () =>
407 Effect.gen(function* () {
408 const fs = yield* FileSystem.FileSystem;
409 const path = yield* Path.Path;
410 const delimiter = (yield* HostProcess.Platform) === "win32" ? ";" : ":";
411 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
412 const launcher = path.join(root, "bin/t3");
413 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
414 yield* fs.writeFileString(launcher, "");
415​
416 const bare = yield* resolveLauncherPath.pipe(
417 Effect.provideService(HostProcess.InvokedAs, "t3"),
418 Effect.provideService(HostProcess.Environment, {
419 PATH: [path.join(root, "missing"), path.join(root, "bin")].join(delimiter),
420 }),
421 Effect.provideService(HostProcess.WorkingDirectory, root),
422 );
423 const relative = yield* resolveLauncherPath.pipe(
424 Effect.provideService(HostProcess.InvokedAs, "./bin/t3"),
425 Effect.provideService(HostProcess.Environment, { PATH: "" }),
426 Effect.provideService(HostProcess.WorkingDirectory, root),
427 );
428 const absent = yield* resolveLauncherPath.pipe(
429 Effect.provideService(HostProcess.InvokedAs, "t3"),
430 Effect.provideService(HostProcess.Environment, { PATH: path.join(root, "missing") }),
431 Effect.provideService(HostProcess.WorkingDirectory, root),
432 );
433​
434 assert.equal(bare, launcher);
435 assert.equal(relative, launcher);
436 assert.equal(absent, undefined);
437 }).pipe(Effect.scoped),
438 );
439});
440​
441// Without terminals, update skips its restart prompt whatever runs the test.
442const withoutTerminals = Effect.acquireRelease(
443 Effect.sync(() =>
444 [process.stdin, process.stdout].map((stream) => {
445 const descriptor = Object.getOwnPropertyDescriptor(stream, "isTTY");
446 Object.defineProperty(stream, "isTTY", { configurable: true, value: false });
447 return { stream, descriptor };
448 }),
449 ),
450 (saved) =>
451 Effect.sync(() => {
452 for (const { stream, descriptor } of saved) {
453 if (descriptor === undefined) Reflect.deleteProperty(stream, "isTTY");
454 else Object.defineProperty(stream, "isTTY", descriptor);
455 }
456 }),
457);
458​
459it.layer(NodeServices.layer)("t3 update with a background service", (it) => {
460 it.effect("names the version a service with a pending restart still runs", () =>
461 Effect.gen(function* () {
462 yield* withoutTerminals;
463 const fs = yield* FileSystem.FileSystem;
464 const path = yield* Path.Path;
465 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
466 const version = packageJson.version;
467 const runtime = pinnedRuntimePaths(path, baseDir, version, "linux");
468 yield* fs.makeDirectory(runtime.versionDir, { recursive: true });
469 yield* fs.writeFileString(runtime.entryPath, "");
470 yield* fs.writeFileString(runtime.sentinelPath, `${version}\n`);
471 const unitPath = path.join(baseDir, "t3code.service");
472 const logPath = path.join(baseDir, "boot-service.log");
473 // An earlier `t3 update` pointed the service at this version without restarting it.
474 const service = Layer.mock(BootService.BootService, {
475 status: Effect.succeed<BootService.BootServiceStatus>({
476 supported: true,
477 installed: true,
478 current: false,
479 installedVersion: version,
480 installedBaseDir: baseDir,
481 problems: ["restart-pending"],
482 unitPath,
483 logPath,
484 }),
485 install: () => Effect.succeed({ program: [runtime.entryPath], baseDir, unitPath, logPath }),
486 });
487 vi.spyOn(BootService, "layer").mockReturnValue(service);
488 const runner = ProcessRunner.ProcessRunner.of({
489 run: (input) =>
490 input.args?.includes("--version") === true
491 ? unrelatedLsof
492 .run(input)
493 .pipe(Effect.map((result) => ({ ...result, stdout: `t3 v${version}\n` })))
494 : unrelatedLsof.run(input),
495 });
496​
497 const output = yield* runUpdate({
498 baseDir,
499 logsDir: baseDir,
500 serverRuntimeStatePath: path.join(baseDir, "server-runtime.json"),
501 channel: undefined,
502 requestedVersion: version,
503 allowDowngrade: false,
504 assumeYes: false,
505 }).pipe(
506 Effect.andThen(TestConsole.logLines),
507 Effect.map((lines) => lines.join("\n")),
508 Effect.provide(
509 Layer.mergeAll(
510 service,
511 Layer.succeed(ProcessRunner.ProcessRunner, runner),
512 ManagedPolicy.layerTest(),
513 Layer.succeed(
514 HttpClient.HttpClient,
515 HttpClient.make(() => Effect.die("unexpected release lookup")),
516 ),
517 Layer.fresh(TestConsole.layer),
518 ),
519 ),
520 );
521​
522 assert.include(
523 output,
524 `Background service still running the version before ${version}. Run \`t3 service restart\` when you are ready to switch it to ${version}.`,
525 );
526 }).pipe(
527 Effect.scoped,
528 Effect.provideService(HostProcess.Platform, "linux"),
529 Effect.provideService(HostProcess.Environment, { PATH: "" }),
530 ),
531 );
532});