Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import * as HostProcess from "@t3tools/shared/HostProcess";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as FileSystem from "effect/FileSystem";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as TestClock from "effect/testing/TestClock";
11import { HttpClient, HttpClientResponse } from "effect/http";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13import { afterEach, vi } from "vite-plus/test";
14
15import { prunePinnedRuntimes } from "../cloud/pinnedRuntime.ts";
16import * as ProcessRunner from "../processRunner.ts";
17import { repointLauncher, resolveLauncherPath, resolveNewestVersion } from "./update.ts";
18
19// lsof listing one process, so prune sees a process list in which no runtime is running.
20const unrelatedLsof = ProcessRunner.ProcessRunner.of({
21 run: () =>
22 Effect.succeed({
23 stdout: "p1\nftxt\nn/usr/bin/true\n",
24 stderr: "",
25 code: ChildProcessSpawner.ExitCode(0),
26 timedOut: false,
27 stdoutTruncated: false,
28 stderrTruncated: false,
29 stdoutInvalidUtf8: false,
30 stderrInvalidUtf8: false,
31 }),
32});
33
34afterEach(() => vi.restoreAllMocks());
35
36it.effect("authenticates each release page until the requested channel is found", () =>
37 Effect.gen(function* () {
38 const pages: string[] = [];
39 const httpClient = HttpClient.make((request) => {
40 const url = new URL(request.url);
41 assert.equal(url.origin, "https://api.github.com");
42 assert.equal(url.pathname, "/repos/pingdotgg/t3code/releases");
43 assert.equal(request.headers.accept, "application/vnd.github+json");
44 assert.equal(request.headers.authorization, "Bearer gh-token");
45 const page = url.searchParams.get("page") ?? "";
46 pages.push(page);
47 const tag_name = page === "1" ? "v1.2.4-preview.20260101.1" : "v1.2.3";
48 return Effect.succeed(HttpClientResponse.fromWeb(request, Response.json([{ tag_name }])));
49 });
50 const version = yield* resolveNewestVersion("stable").pipe(
51 Effect.provideService(HostProcess.Environment, { GH_TOKEN: "gh-token" }),
52 Effect.provideService(HttpClient.HttpClient, httpClient),
53 );
54 assert.equal(version, "1.2.3");
55 assert.deepStrictEqual(pages, ["1", "2"]);
56 }),
57);
58
59it.layer(NodeServices.layer)("t3 update launcher", (it) => {
60 it.effect("repoints a symlink that lives in a runtime versions tree", () =>
61 Effect.gen(function* () {
62 const fs = yield* FileSystem.FileSystem;
63 const path = yield* Path.Path;
64 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
65 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
66 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
67 const launcher = path.join(root, "bin/t3");
68 for (const file of [oldExe, newExe]) {
69 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
70 yield* fs.writeFileString(file, "");
71 }
72 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
73 yield* fs.symlink(oldExe, launcher);
74
75 const repointed = yield* repointLauncher({
76 launchedAs: launcher,
77 baseDir: root,
78 targetEntryPath: newExe,
79 });
80
81 assert.deepStrictEqual(Option.getOrUndefined(repointed), launcher);
82 assert.equal(yield* fs.readLink(launcher), newExe);
83 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
84 );
85
86 it.effect.each([
87 { name: "no launcher records", recorded: undefined },
88 { name: "an empty launcher record", recorded: "" },
89 { name: "whole launcher records", recorded: "/opt/t3\n" },
90 { name: "Windows launcher records", recorded: "C:\\t3.cmd\r\n" },
91 // An interrupted append cut this record short.
92 { name: "an unterminated launcher record", recorded: "/opt/t" },
93 // Another process's append is cut short after t3 update reads the records.
94 { name: "a record cut short after the read", recorded: "/opt/t3\n", cut: "/opt/t" },
95 ])("keeps the runtime a repointed launcher off PATH points at with $name", ({ recorded, cut }) =>
96 Effect.gen(function* () {
97 const fs = yield* FileSystem.FileSystem;
98 const path = yield* Path.Path;
99 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
100 yield* TestClock.setTime(Duration.toMillis(Duration.days(1)));
101 for (const version of ["1.0.0", "2.0.0"]) {
102 const directory = path.join(root, "runtime/versions", version);
103 yield* fs.makeDirectory(directory, { recursive: true });
104 yield* fs.writeFileString(path.join(directory, "t3"), "");
105 yield* fs.writeFileString(path.join(directory, ".install-complete"), `${version}\n`);
106 yield* fs.utimes(path.join(directory, ".install-complete"), 0, 0);
107 }
108 if (recorded !== undefined) {
109 yield* fs.writeFileString(path.join(root, "runtime/launchers"), recorded);
110 }
111 // A launcher in the T3 home itself, which neither PATH nor the default bin dir reaches.
112 const launcher = path.join(root, "t3");
113 yield* fs.symlink(path.join(root, "runtime/versions/1.0.0/t3"), launcher);
114
115 const launchersFile = path.join(root, "runtime/launchers");
116 yield* repointLauncher({
117 launchedAs: launcher,
118 baseDir: root,
119 targetEntryPath: path.join(root, "runtime/versions/2.0.0/t3"),
120 }).pipe(
121 Effect.provideService(FileSystem.FileSystem, {
122 ...fs,
123 readFileString: (file, encoding) =>
124 fs
125 .readFileString(file, encoding)
126 .pipe(
127 Effect.tap(() =>
128 cut === undefined || file !== launchersFile
129 ? Effect.void
130 : fs.writeFileString(file, cut, { flag: "a" }),
131 ),
132 ),
133 }),
134 );
135 // A later server start prunes with no idea how this machine launches t3.
136 const removed = yield* prunePinnedRuntimes({ baseDir: root, keep: [] }).pipe(
137 Effect.provideService(ProcessRunner.ProcessRunner, unrelatedLsof),
138 Effect.provideService(HostProcess.Platform, "darwin"),
139 Effect.provideService(HostProcess.Environment, { PATH: "" }),
140 Effect.provideService(HostProcess.HomeDirectory, root),
141 );
142
143 assert.deepStrictEqual(removed, ["1.0.0"]);
144 // macOS temp dirs sit behind the /var -> /private/var symlink, so compare canonical paths.
145 assert.equal(
146 yield* fs.realPath(launcher),
147 yield* fs.realPath(path.join(root, "runtime/versions/2.0.0/t3")),
148 );
149 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
150 );
151
152 const launcherFixture = Effect.fnUntraced(function* () {
153 const fs = yield* FileSystem.FileSystem;
154 const path = yield* Path.Path;
155 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
156 const oldExe = path.join(root, "runtime/versions/1.0.0/t3");
157 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
158 const launcher = path.join(root, "t3");
159 for (const file of [oldExe, newExe]) {
160 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
161 yield* fs.writeFileString(file, "");
162 }
163 yield* fs.symlink(oldExe, launcher);
164 return { root, oldExe, newExe, launcher, launchersFile: path.join(root, "runtime/launchers") };
165 });
166
167 it.effect("records a relative launcher path as absolute", () =>
168 Effect.gen(function* () {
169 const fs = yield* FileSystem.FileSystem;
170 const path = yield* Path.Path;
171 const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
172
173 yield* repointLauncher({
174 launchedAs: path.relative(path.resolve("."), launcher),
175 baseDir: root,
176 targetEntryPath: newExe,
177 });
178
179 assert.equal(yield* fs.readFileString(launchersFile), `\n${launcher}\n`);
180 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
181 );
182
183 it.effect("fails instead of repointing a launcher it cannot record", () =>
184 Effect.gen(function* () {
185 const fs = yield* FileSystem.FileSystem;
186 const { root, oldExe, newExe, launcher, launchersFile } = yield* launcherFixture();
187 // Appending to a directory fails the way a read-only or full disk would.
188 yield* fs.makeDirectory(launchersFile);
189
190 const result = yield* repointLauncher({
191 launchedAs: launcher,
192 baseDir: root,
193 targetEntryPath: newExe,
194 }).pipe(Effect.exit);
195
196 assert.isTrue(Exit.isFailure(result));
197 assert.equal(yield* fs.readLink(launcher), oldExe);
198 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
199 );
200
201 it.effect.each(["recording", "repointing"] as const)(
202 "never leaves a repointed launcher unrecorded when t3 update dies while %s",
203 (step) =>
204 Effect.gen(function* () {
205 const fs = yield* FileSystem.FileSystem;
206 const { root, newExe, launcher, launchersFile } = yield* launcherFixture();
207
208 yield* repointLauncher({
209 launchedAs: launcher,
210 baseDir: root,
211 targetEntryPath: newExe,
212 }).pipe(
213 Effect.provideService(FileSystem.FileSystem, {
214 ...fs,
215 writeFileString: (path, data, options) =>
216 step === "recording" && path === launchersFile
217 ? Effect.die("t3 update was killed")
218 : fs.writeFileString(path, data, options),
219 rename: (from, to) =>
220 step === "repointing" && to === launcher
221 ? Effect.die("t3 update was killed")
222 : fs.rename(from, to),
223 }),
224 Effect.exit,
225 );
226
227 const repointed = (yield* fs.readLink(launcher)) === newExe;
228 const recorded = (yield* fs
229 .readFileString(launchersFile)
230 .pipe(Effect.orElseSucceed(() => "")))
231 .split("\n")
232 .includes(launcher);
233 assert.isFalse(repointed && !recorded);
234 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
235 );
236
237 it.effect("leaves a plain copy or a foreign symlink alone", () =>
238 Effect.gen(function* () {
239 const fs = yield* FileSystem.FileSystem;
240 const path = yield* Path.Path;
241 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
242 const newExe = path.join(root, "runtime/versions/2.0.0/t3");
243 const copy = path.join(root, "copy/t3");
244 const foreign = path.join(root, "foreign/t3");
245 const elsewhere = path.join(root, "elsewhere/t3");
246 const otherHome = path.join(root, "other/runtime/versions/1.0.0/t3");
247 const otherLauncher = path.join(root, "other/bin/t3");
248 for (const file of [newExe, copy, elsewhere, otherHome]) {
249 yield* fs.makeDirectory(path.dirname(file), { recursive: true });
250 yield* fs.writeFileString(file, "");
251 }
252 yield* fs.makeDirectory(path.dirname(foreign), { recursive: true });
253 yield* fs.symlink(elsewhere, foreign);
254 yield* fs.makeDirectory(path.dirname(otherLauncher), { recursive: true });
255 yield* fs.symlink(otherHome, otherLauncher);
256
257 for (const launchedAs of [copy, foreign, otherLauncher, undefined]) {
258 const repointed = yield* repointLauncher({
259 launchedAs,
260 baseDir: root,
261 targetEntryPath: newExe,
262 });
263 assert.equal(repointed._tag, "None", launchedAs ?? "undefined");
264 }
265 assert.equal(yield* fs.readLink(foreign), elsewhere);
266 assert.equal(yield* fs.readLink(otherLauncher), otherHome);
267 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
268 );
269
270 it.effect("finds the launcher a bare command name resolved to on PATH", () =>
271 Effect.gen(function* () {
272 const fs = yield* FileSystem.FileSystem;
273 const path = yield* Path.Path;
274 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
275 const launcher = path.join(root, "bin/t3");
276 yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
277 yield* fs.writeFileString(launcher, "");
278
279 const bare = yield* resolveLauncherPath.pipe(
280 Effect.provideService(HostProcess.InvokedAs, "t3"),
281 Effect.provideService(HostProcess.Environment, {
282 PATH: `${path.join(root, "missing")}:${path.join(root, "bin")}`,
283 }),
284 Effect.provideService(HostProcess.WorkingDirectory, root),
285 );
286 const relative = yield* resolveLauncherPath.pipe(
287 Effect.provideService(HostProcess.InvokedAs, "./bin/t3"),
288 Effect.provideService(HostProcess.Environment, { PATH: "" }),
289 Effect.provideService(HostProcess.WorkingDirectory, root),
290 );
291 const absent = yield* resolveLauncherPath.pipe(
292 Effect.provideService(HostProcess.InvokedAs, "t3"),
293 Effect.provideService(HostProcess.Environment, { PATH: path.join(root, "missing") }),
294 Effect.provideService(HostProcess.WorkingDirectory, root),
295 );
296
297 assert.equal(bare, launcher);
298 assert.equal(relative, launcher);
299 assert.equal(absent, undefined);
300 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),
301 );
302});