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

update.test.ts

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