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