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

pinnedRuntime.test.ts

729 lines29.1 KB

1// @effect-diagnostics nodeBuiltinImport:off - node:path.win32 stands in for a Windows host in one test.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import * as Deferred from "effect/Deferred";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as Fiber from "effect/Fiber";
9import * as Path from "effect/Path";
10import * as NodePath from "node:path";
11import * as TestClock from "effect/testing/TestClock";
12import { HttpClient, HttpClientResponse } from "effect/http";
13import * as ChildProcess from "effect/process/ChildProcess";
14import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15​
16import * as HostProcess from "@t3tools/shared/HostProcess";
17​
18import * as ProcessRunner from "../processRunner.ts";
19import {
20 isVersionExecutable,
21 ensurePinnedRuntimeInstalled,
22 isUnpublishedRelease,
23 pinnedRuntimeCommand,
24 pinnedRuntimePaths,
25 PinnedRuntimeInstallError,
26 type PinnedRuntimeProgress,
27 prunePinnedRuntimes,
28} from "./pinnedRuntime.ts";
29import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
30​
31const version = "1.2.3";
32const archiveName = `t3-${version}-linux-x64.tar.gz`;
33const archiveBytes = new TextEncoder().encode("not really a tarball");
34const archiveHex = (bytes: Uint8Array) =>
35 Effect.promise(() => crypto.subtle.digest("SHA-256", bytes)).pipe(
36 Effect.map((digest) =>
37 Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""),
38 ),
39 );
40const validChecksums = archiveHex(archiveBytes).pipe(
41 Effect.map((hex) => `${hex} ${archiveName}\n`),
42);
43const releaseHttpClient = (checksums: string, requests: string[] = []) =>
44 HttpClient.make((request) => {
45 requests.push(request.url);
46 const body = new URL(request.url).pathname.endsWith("/SHA256SUMS") ? checksums : archiveBytes;
47 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body)));
48 });
49const extractingRunner = (fs: FileSystem.FileSystem, path: Path.Path, commands: string[] = []) =>
50 ProcessRunner.ProcessRunner.of({
51 run: (input) =>
52 Effect.gen(function* () {
53 commands.push(input.command);
54 const targetIndex = input.args.indexOf("-C");
55 const stagingDir = input.args[targetIndex + 1];
56 if (input.command !== "tar" || stagingDir === undefined) {
57 return yield* Effect.die(`unexpected command ${input.command}`);
58 }
59 yield* fs.writeFileString(path.join(stagingDir, "t3"), "#!/bin/sh\n").pipe(Effect.orDie);
60 return {
61 stdout: "",
62 stderr: "",
63 code: ChildProcessSpawner.ExitCode(0),
64 timedOut: false,
65 stdoutTruncated: false,
66 stderrTruncated: false,
67 stdoutInvalidUtf8: false,
68 stderrInvalidUtf8: false,
69 };
70 }),
71 });
72​
73it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
74 it.effect("installs the verified release archive as the runtime executable", () =>
75 Effect.gen(function* () {
76 const fs = yield* FileSystem.FileSystem;
77 const path = yield* Path.Path;
78 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-" });
79 const requests: string[] = [];
80 const commands: string[] = [];
81 const paths = yield* ensurePinnedRuntimeInstalled({
82 baseDir,
83 version,
84 fs,
85 path,
86 platform: "linux",
87 arch: "x64",
88 httpClient: releaseHttpClient(yield* validChecksums, requests),
89 releaseBaseUrl: "https://releases.example/download",
90 runner: extractingRunner(fs, path, commands),
91 validate: (staging) =>
92 fs.exists(staging.entryPath).pipe(
93 Effect.flatMap((exists) => (exists ? Effect.void : Effect.die("missing runtime"))),
94 Effect.orDie,
95 ),
96 });
97 assert.equal(paths.entryPath, path.join(paths.versionDir, "t3"));
98 assert.deepEqual(pinnedRuntimeCommand(paths), { command: paths.entryPath, args: [] });
99 assert.deepEqual(requests, [
100 `https://releases.example/download/v${version}/SHA256SUMS`,
101 `https://releases.example/download/v${version}/${archiveName}`,
102 ]);
103 assert.deepEqual(commands, ["tar"]);
104 assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`);
105 assert.isFalse(yield* fs.exists(path.join(paths.versionDir, "t3-runtime-archive")));
106 }),
107 );
108​
109 it.effect("cleans up an interrupted download without reporting verification or extraction", () =>
110 Effect.gen(function* () {
111 const fs = yield* FileSystem.FileSystem;
112 const path = yield* Path.Path;
113 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-progress-failed-" });
114 const checksums = yield* validChecksums;
115 const progress: PinnedRuntimeProgress[] = [];
116 let cancelled = false;
117 const client = HttpClient.make((request) =>
118 Effect.succeed(
119 HttpClientResponse.fromWeb(
120 request,
121 request.url.endsWith("/SHA256SUMS")
122 ? new Response(checksums)
123 : new Response(
124 new ReadableStream({
125 start(controller) {
126 controller.enqueue(archiveBytes.slice(0, 4));
127 },
128 cancel() {
129 cancelled = true;
130 },
131 }),
132 ),
133 ),
134 ),
135 );
136 const firstChunk = yield* Deferred.make<void>();
137 const install = yield* ensurePinnedRuntimeInstalled({
138 baseDir,
139 version,
140 fs,
141 path,
142 platform: "linux",
143 arch: "x64",
144 httpClient: client,
145 runner: extractingRunner(fs, path),
146 validate: () => Effect.die("must not validate an interrupted archive"),
147 onProgress: (event) => {
148 progress.push(event);
149 if (event.stage === "download" && event.received === 4)
150 Deferred.doneUnsafe(firstChunk, Effect.void);
151 },
152 }).pipe(Effect.forkScoped);
153 yield* Deferred.await(firstChunk);
154 yield* Fiber.interrupt(install);
155 assert.deepEqual(progress.at(-1), { stage: "download", received: 4, total: undefined });
156 assert.isTrue(progress.every((event) => event.stage === "download"));
157 assert.isTrue(cancelled);
158 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
159 }),
160 );
161​
162 it.effect("reports a release that lists an archive it does not serve as unpublished", () =>
163 Effect.gen(function* () {
164 const fs = yield* FileSystem.FileSystem;
165 const path = yield* Path.Path;
166 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-missing-" });
167 const checksums = yield* validChecksums;
168 const failsWith = (status: number) =>
169 ensurePinnedRuntimeInstalled({
170 baseDir,
171 version,
172 fs,
173 path,
174 platform: "linux",
175 arch: "x64",
176 httpClient: HttpClient.make((request) =>
177 Effect.succeed(
178 HttpClientResponse.fromWeb(
179 request,
180 request.url.endsWith("/SHA256SUMS")
181 ? new Response(checksums)
182 : new Response("", { status }),
183 ),
184 ),
185 ),
186 // "404" in the mirror's path must not read a server error as a missing release.
187 releaseBaseUrl: "https://updates.example.com/404/t3code",
188 runner: extractingRunner(fs, path),
189 validate: () => Effect.die("must not validate a missing archive"),
190 }).pipe(Effect.flip);
191 assert.isTrue(isUnpublishedRelease(yield* failsWith(404)));
192 assert.isFalse(isUnpublishedRelease(yield* failsWith(500)));
193 }),
194 );
195​
196 it.effect("refuses an archive whose checksum does not match the release", () =>
197 Effect.gen(function* () {
198 const fs = yield* FileSystem.FileSystem;
199 const path = yield* Path.Path;
200 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-bad-" });
201 const commands: string[] = [];
202 const error = yield* ensurePinnedRuntimeInstalled({
203 baseDir,
204 version,
205 fs,
206 path,
207 platform: "linux",
208 arch: "x64",
209 httpClient: releaseHttpClient(`${"0".repeat(64)} ${archiveName}\n`),
210 runner: extractingRunner(fs, path, commands),
211 validate: () => Effect.die("must not validate an unverified archive"),
212 }).pipe(Effect.flip);
213 assert.instanceOf(error, PinnedRuntimeInstallError);
214 assert.equal(error.step, "verifying the t3 release archive checksum");
215 assert.deepEqual(commands, []);
216 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
217 }),
218 );
219​
220 it.effect("validates a staging tree before atomically publishing it", () =>
221 Effect.gen(function* () {
222 const fs = yield* FileSystem.FileSystem;
223 const path = yield* Path.Path;
224 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
225 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
226 let validatedDirectory = "";
227​
228 const installed = yield* ensurePinnedRuntimeInstalled({
229 baseDir,
230 version,
231 fs,
232 path,
233 platform: "linux",
234 arch: "x64",
235 httpClient: releaseHttpClient(yield* validChecksums),
236 runner: extractingRunner(fs, path),
237 validate: (staging) =>
238 Effect.gen(function* () {
239 validatedDirectory = staging.versionDir;
240 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
241 assert.isTrue(yield* fs.exists(staging.entryPath));
242 }).pipe(Effect.orDie),
243 });
244​
245 assert.notEqual(validatedDirectory, finalPaths.versionDir);
246 assert.deepEqual(installed, finalPaths);
247 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
248 assert.equal(yield* fs.readFileString(finalPaths.sentinelPath), `${version}\n`);
249 }),
250 );
251​
252 it.effect("removes staging and leaves no final runtime when validation fails", () =>
253 Effect.gen(function* () {
254 const fs = yield* FileSystem.FileSystem;
255 const path = yield* Path.Path;
256 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
257 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
258​
259 yield* ensurePinnedRuntimeInstalled({
260 baseDir,
261 version,
262 fs,
263 path,
264 platform: "linux",
265 arch: "x64",
266 httpClient: releaseHttpClient(yield* validChecksums),
267 runner: extractingRunner(fs, path),
268 validate: () =>
269 Effect.fail(new PinnedRuntimeInstallError({ step: "validating the staged runtime" })),
270 }).pipe(Effect.flip);
271​
272 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
273 assert.deepEqual(
274 (yield* fs.readDirectory(path.dirname(finalPaths.versionDir))).filter((entry) =>
275 entry.startsWith(".staging-"),
276 ),
277 [],
278 );
279 }),
280 );
281​
282 it.effect("replaces an incomplete pinned runtime", () =>
283 Effect.gen(function* () {
284 const fs = yield* FileSystem.FileSystem;
285 const path = yield* Path.Path;
286 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
287 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
288 yield* fs.makeDirectory(finalPaths.versionDir, { recursive: true });
289 yield* fs.writeFileString(path.join(finalPaths.versionDir, "partial"), "incomplete\n");
290​
291 yield* ensurePinnedRuntimeInstalled({
292 baseDir,
293 version,
294 fs,
295 path,
296 platform: "linux",
297 arch: "x64",
298 httpClient: releaseHttpClient(yield* validChecksums),
299 runner: extractingRunner(fs, path),
300 validate: () => Effect.void,
301 });
302​
303 assert.isFalse(yield* fs.exists(path.join(finalPaths.versionDir, "partial")));
304 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
305 }),
306 );
307​
308 it.effect("reuses a cached runtime under a mirror only while the mirror lists it", () =>
309 Effect.gen(function* () {
310 const fs = yield* FileSystem.FileSystem;
311 const path = yield* Path.Path;
312 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-mirror-" });
313 const cached = pinnedRuntimePaths(path, baseDir, version, "linux");
314 yield* fs.makeDirectory(path.dirname(cached.entryPath), { recursive: true });
315 yield* fs.writeFileString(cached.entryPath, "#!/bin/sh\n");
316 yield* fs.writeFileString(cached.sentinelPath, `${version}\n`);
317 const install = (checksums: string, requests: string[]) =>
318 ensurePinnedRuntimeInstalled({
319 baseDir,
320 version,
321 fs,
322 path,
323 platform: "linux",
324 arch: "x64",
325 httpClient: releaseHttpClient(checksums, requests),
326 // A signed mirror URL keeps its query on every file it serves.
327 releaseBaseUrl: "https://updates.example.com/t3code/?token=abc",
328 requirePublishedRelease: true,
329 runner: extractingRunner(fs, path),
330 validate: () => Effect.void,
331 });
332​
333 const withdrawn = yield* install("", []).pipe(Effect.flip);
334 assert.include(withdrawn.message, `finding ${archiveName} in the t3 release checksums`);
335 const requests: string[] = [];
336 assert.equal((yield* install(yield* validChecksums, requests)).entryPath, cached.entryPath);
337 // Listed, so the cached runtime is used without downloading it again.
338 assert.deepEqual(requests, [
339 `https://updates.example.com/t3code/v${version}/SHA256SUMS?token=abc`,
340 ]);
341 }),
342 );
343​
344 it.effect("preserves a completed runtime when validation fails", () =>
345 Effect.gen(function* () {
346 const fs = yield* FileSystem.FileSystem;
347 const path = yield* Path.Path;
348 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
349 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
350 yield* fs.makeDirectory(path.dirname(finalPaths.entryPath), { recursive: true });
351 yield* fs.writeFileString(finalPaths.entryPath, "broken\n");
352 yield* fs.writeFileString(finalPaths.sentinelPath, `${version}\n`);
353​
354 let validations = 0;
355 const requests: string[] = [];
356 yield* ensurePinnedRuntimeInstalled({
357 baseDir,
358 version,
359 fs,
360 path,
361 platform: "linux",
362 arch: "x64",
363 httpClient: releaseHttpClient(yield* validChecksums, requests),
364 runner: extractingRunner(fs, path),
365 validate: (paths) =>
366 Effect.gen(function* () {
367 validations += 1;
368 const source = yield* fs.readFileString(paths.entryPath).pipe(Effect.orDie);
369 if (source === "broken\n") {
370 return yield* new PinnedRuntimeInstallError({ step: "validating the runtime" });
371 }
372 }),
373 }).pipe(Effect.flip);
374​
375 assert.equal(validations, 1);
376 assert.deepEqual(requests, []);
377 assert.equal(yield* fs.readFileString(finalPaths.entryPath), "broken\n");
378 }),
379 );
380});
381​
382it("isVersionExecutable accepts only <version>/t3, never another drive or program", () => {
383 const win32 = NodePath.win32 as unknown as Path.Path;
384 assert.isTrue(isVersionExecutable(win32, "C:\\t3\\versions", "C:\\t3\\versions\\1.0.0\\t3.exe"));
385 assert.isFalse(isVersionExecutable(win32, "C:\\t3\\versions", "D:\\t3.exe"));
386 assert.isFalse(
387 isVersionExecutable(win32, "C:\\t3\\versions", "C:\\t3\\versions\\1.0.0\\node.exe"),
388 );
389});
390​
391it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => {
392 const lsofRunner = (stdout: string) =>
393 ProcessRunner.ProcessRunner.of({
394 run: () =>
395 Effect.succeed({
396 stdout,
397 stderr: "",
398 code: ChildProcessSpawner.ExitCode(0),
399 timedOut: false,
400 stdoutTruncated: false,
401 stderrTruncated: false,
402 stdoutInvalidUtf8: false,
403 stderrInvalidUtf8: false,
404 }),
405 });
406​
407 const setup = Effect.fn(function* (versions: ReadonlyArray<string>) {
408 const fs = yield* FileSystem.FileSystem;
409 const path = yield* Path.Path;
410 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-prune-" });
411 const versionsDir = path.join(baseDir, "runtime", "versions");
412 const now = Duration.toMillis(Duration.days(1));
413 yield* TestClock.setTime(now);
414 const install = Effect.fn(function* (
415 version: string,
416 completed: "long ago" | "just now" | "never" = "long ago",
417 ) {
418 const directory = path.join(versionsDir, version);
419 yield* fs.makeDirectory(directory, { recursive: true });
420 yield* fs.writeFileString(path.join(directory, "t3"), "");
421 if (completed === "never") return;
422 const sentinel = path.join(directory, ".install-complete");
423 yield* fs.writeFileString(sentinel, `${version}\n`);
424 const at = completed === "just now" ? now : 0;
425 yield* fs.utimes(sentinel, at, at);
426 });
427 for (const version of versions) yield* install(version);
428 return { baseDir, versionsDir, install };
429 });
430​
431 it.effect("removes only completed runtimes nothing references", () =>
432 Effect.gen(function* () {
433 const fs = yield* FileSystem.FileSystem;
434 const path = yield* Path.Path;
435 const { baseDir, versionsDir, install } = yield* setup([
436 "1.0.0",
437 "1.1.0",
438 "1.2.0",
439 "1.2.5",
440 "1.3.0",
441 "1.3.5",
442 "1.4.0",
443 "1.5.0",
444 "2.0.0",
445 "2.1.0",
446 ]);
447 // A downgrade another process installed but has not pointed anything at yet.
448 yield* install("0.5.0", "just now");
449 yield* install("1.0.1", "never");
450 yield* install(".staging-abc", "never");
451 yield* install(".pruned-0.8.0");
452 yield* install("other", "never");
453 yield* fs.symlink(path.join(versionsDir, "other"), path.join(versionsDir, "0.9.0"));
454 const binDir = path.join(baseDir, "bin");
455 const customBinDir = path.join(baseDir, "custom-bin");
456 yield* fs.makeDirectory(binDir);
457 yield* fs.makeDirectory(customBinDir);
458 // Chained: the launcher reaches its runtime through a second link.
459 yield* fs.symlink(path.join(versionsDir, "1.2.0", "t3"), path.join(baseDir, "alias-t3"));
460 yield* fs.symlink(path.join(baseDir, "alias-t3"), path.join(binDir, "t3"));
461 yield* fs.symlink(path.join(versionsDir, "1.2.5", "t3"), path.join(customBinDir, "t3"));
462 yield* fs.writeFileString(
463 path.join(baseDir, "runtime", "launchers"),
464 `${path.join(customBinDir, "t3")}\n`,
465 );
466 yield* fs.writeFileString(
467 path.join(baseDir, "runtime", "service-state.json"),
468 JSON.stringify({
469 protocol: SERVICE_LAUNCHER_PROTOCOL,
470 activeVersion: "1.4.0",
471 update: { id: "u", fromVersion: "1.4.0", targetVersion: "1.5.0", status: "rolled-back" },
472 }),
473 );
474​
475 const removed = yield* prunePinnedRuntimes({
476 baseDir,
477 keep: ["2.0.0"],
478 references: [`ExecStart=${path.join(versionsDir, "1.3.5", "t3")} __service-launcher`],
479 }).pipe(
480 Effect.provideService(
481 ProcessRunner.ProcessRunner,
482 lsofRunner(`p42\nftxt\nn${path.join(versionsDir, "1.3.0", "t3")}\n`),
483 ),
484 Effect.provideService(HostProcess.Platform, "darwin"),
485 Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: binDir }),
486 );
487​
488 // 1.2.0 is the default launcher, 1.2.5 a recorded one, 1.3.0 running, 1.3.5 in the unit,
489 // 1.4.0 active, 1.5.0 the rolled-back target, 2.0.0 the caller's, 0.5.0 just installed.
490 // Being newer than the caller's version does not keep 2.1.0.
491 assert.deepEqual(removed.toSorted(), ["0.8.0", "1.0.0", "1.1.0", "2.1.0"]);
492 // The launcher found on PATH is remembered for a service that cannot see it.
493 assert.equal(
494 yield* fs.readFileString(path.join(baseDir, "runtime", "launchers")),
495 `${path.join(customBinDir, "t3")}\n\n${path.join(binDir, "t3")}\n`,
496 );
497 assert.deepEqual((yield* fs.readDirectory(versionsDir)).toSorted(), [
498 ".staging-abc",
499 "0.5.0",
500 "0.9.0",
501 "1.0.1",
502 "1.2.0",
503 "1.2.5",
504 "1.3.0",
505 "1.3.5",
506 "1.4.0",
507 "1.5.0",
508 "2.0.0",
509 "other",
510 ]);
511 }),
512 );
513​
514 it.effect.each([
515 { name: "its directory is on PATH", onPath: true, recorded: false, linkedHome: false },
516 {
517 name: "an earlier prune recorded its entry as a launcher",
518 onPath: false,
519 recorded: true,
520 linkedHome: false,
521 },
522 {
523 name: "its real directory in a symlinked home is on PATH",
524 onPath: true,
525 recorded: false,
526 linkedHome: true,
527 },
528 ])("removes a runtime only its own entry names when $name", ({ onPath, recorded, linkedHome }) =>
529 Effect.gen(function* () {
530 const fs = yield* FileSystem.FileSystem;
531 const path = yield* Path.Path;
532 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
533 const binDir = path.join(baseDir, "bin");
534 yield* fs.makeDirectory(binDir);
535 yield* fs.symlink(path.join(versionsDir, "1.1.0", "t3"), path.join(binDir, "t3"));
536 const ownDir = path.join(versionsDir, "1.0.0");
537 if (recorded) {
538 yield* fs.writeFileString(
539 path.join(baseDir, "runtime", "launchers"),
540 `${path.join(ownDir, "t3")}\n`,
541 );
542 }
543​
544 const home = linkedHome
545 ? path.join(yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-link-" }), "home")
546 : baseDir;
547 if (linkedHome) yield* fs.symlink(baseDir, home);
548​
549 // The launch agent puts the running runtime's own directory on PATH.
550 const removed = yield* prunePinnedRuntimes({ baseDir: home, keep: ["2.0.0"] }).pipe(
551 Effect.provideService(
552 ProcessRunner.ProcessRunner,
553 lsofRunner("p1\nftxt\nn/sbin/launchd\n"),
554 ),
555 Effect.provideService(HostProcess.Platform, "darwin"),
556 Effect.provideService(HostProcess.Environment, {
557 T3CODE_INSTALL_BIN_DIR: binDir,
558 PATH: onPath ? `${ownDir}:/usr/bin:/bin` : "/usr/bin:/bin",
559 }),
560 );
561 assert.deepEqual(removed, ["1.0.0"]);
562 }),
563 );
564​
565 it.effect.each([
566 { name: "a launcher inside the versions directory", via: "bin" as const },
567 { name: "a PATH directory linked to its version directory", via: "linked dir" as const },
568 {
569 name: "a PATH directory in the versions directory linked to its version directory",
570 via: "linked versions dir" as const,
571 },
572 ])("keeps a runtime $name names", ({ via }) =>
573 Effect.gen(function* () {
574 const fs = yield* FileSystem.FileSystem;
575 const path = yield* Path.Path;
576 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
577 let pathDirs = "/usr/bin:/bin";
578 if (via === "bin") {
579 // The installer accepts any bin directory, including one under the versions directory.
580 const binDir = path.join(versionsDir, "bin");
581 yield* fs.makeDirectory(binDir);
582 yield* fs.symlink(path.join(versionsDir, "1.0.0", "t3"), path.join(binDir, "t3"));
583 yield* fs.writeFileString(
584 path.join(baseDir, "runtime", "launchers"),
585 `${path.join(binDir, "t3")}\n`,
586 );
587 } else {
588 const linkedDir = path.join(via === "linked dir" ? baseDir : versionsDir, "current");
589 yield* fs.symlink(path.join(versionsDir, "1.0.0"), linkedDir);
590 pathDirs = `${linkedDir}:${pathDirs}`;
591 }
592​
593 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
594 Effect.provideService(
595 ProcessRunner.ProcessRunner,
596 lsofRunner("p1\nftxt\nn/sbin/launchd\n"),
597 ),
598 Effect.provideService(HostProcess.Platform, "darwin"),
599 Effect.provideService(HostProcess.Environment, { PATH: pathDirs }),
600 );
601 assert.deepEqual(removed, ["1.1.0"]);
602 }),
603 );
604​
605 it.effect.each([
606 // An interrupted append cut this record short.
607 { name: "an unterminated launcher record", recorded: "/opt/t", cut: "" },
608 // Another process's append is cut short after prune reads the records.
609 { name: "a record cut short after the read", recorded: "/opt/t3\n", cut: "/opt/t" },
610 ])("remembers a launcher found on PATH after $name", ({ recorded, cut }) =>
611 Effect.gen(function* () {
612 const fs = yield* FileSystem.FileSystem;
613 const path = yield* Path.Path;
614 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
615 const binDir = path.join(baseDir, "custom-bin");
616 yield* fs.makeDirectory(binDir);
617 yield* fs.symlink(path.join(versionsDir, "1.0.0", "t3"), path.join(binDir, "t3"));
618 const launchersFile = path.join(baseDir, "runtime", "launchers");
619 yield* fs.writeFileString(launchersFile, recorded);
620 const prune = (environment: Record<string, string>) =>
621 prunePinnedRuntimes({ baseDir, keep: [] }).pipe(
622 Effect.provideService(ProcessRunner.ProcessRunner, lsofRunner("p1\nftxt\nn/bin/sh\n")),
623 Effect.provideService(HostProcess.Platform, "darwin"),
624 Effect.provideService(HostProcess.Environment, environment),
625 Effect.provideService(HostProcess.HomeDirectory, baseDir),
626 );
627​
628 yield* prune({ PATH: binDir }).pipe(
629 Effect.provideService(FileSystem.FileSystem, {
630 ...fs,
631 readFileString: (file, encoding) =>
632 fs
633 .readFileString(file, encoding)
634 .pipe(
635 Effect.tap(() =>
636 file === launchersFile
637 ? fs.writeFileString(file, cut, { flag: "a" })
638 : Effect.void,
639 ),
640 ),
641 }),
642 );
643 // A service that cannot see the interactive PATH.
644 const removed = yield* prune({});
645​
646 assert.deepEqual(removed, []);
647 assert.isTrue(yield* fs.exists(path.join(versionsDir, "1.0.0", "t3")));
648 }),
649 );
650​
651 it.effect("matches a Windows shim whatever its casing", () =>
652 Effect.gen(function* () {
653 const fs = yield* FileSystem.FileSystem;
654 const path = yield* Path.Path;
655 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
656 const shim = path.join(baseDir, "t3.cmd");
657 yield* fs.writeFileString(
658 shim,
659 `@echo off\r\n"${path.join(versionsDir, "1.0.0", "t3.exe").toUpperCase()}" %*`,
660 );
661 yield* fs.writeFileString(path.join(baseDir, "runtime", "launchers"), `${shim}\n`);
662​
663 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
664 Effect.provideService(
665 ProcessRunner.ProcessRunner,
666 lsofRunner("C:\\Windows\\explorer.exe\n"),
667 ),
668 Effect.provideService(HostProcess.Platform, "win32"),
669 Effect.provideService(HostProcess.Environment, {}),
670 );
671 assert.deepEqual(removed, ["1.1.0"]);
672 }),
673 );
674​
675 it.effect.each([
676 { name: "the process list is unavailable", state: undefined, lsof: "" },
677 { name: "the service state is unparseable", state: "{", lsof: "p1\nftxt\nn/sbin/launchd\n" },
678 {
679 name: "the service state cannot be read",
680 state: null,
681 lsof: "p1\nftxt\nn/sbin/launchd\n",
682 },
683 ])("keeps everything when $name", ({ state, lsof }) =>
684 Effect.gen(function* () {
685 const fs = yield* FileSystem.FileSystem;
686 const path = yield* Path.Path;
687 const { baseDir, versionsDir } = yield* setup(["1.0.0"]);
688 const statePath = path.join(baseDir, "runtime", "service-state.json");
689 if (state === null) yield* fs.makeDirectory(statePath);
690 else if (state !== undefined) yield* fs.writeFileString(statePath, state);
691​
692 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
693 Effect.provideService(ProcessRunner.ProcessRunner, lsofRunner(lsof)),
694 Effect.provideService(HostProcess.Platform, "darwin"),
695 Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: baseDir }),
696 );
697 assert.deepEqual(removed, []);
698 assert.deepEqual(yield* fs.readDirectory(versionsDir), ["1.0.0"]);
699 }),
700 );
701​
702 it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
703 "keeps a runtime a process runs through a symlink",
704 () =>
705 Effect.gen(function* () {
706 const fs = yield* FileSystem.FileSystem;
707 const path = yield* Path.Path;
708 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
709 const entry = path.join(versionsDir, "1.0.0", "t3");
710 // Multicall coreutils (Ubuntu's uutils) refuse to run renamed, so copy Node instead.
711 yield* fs.copyFile(process.execPath, entry);
712 yield* fs.chmod(entry, 0o755);
713 const link = path.join(baseDir, "t3");
714 yield* fs.symlink(entry, link);
715 // Its argv names only the link, as with `t3 serve` run from PATH. Removing the link after
716 // spawning leaves the process's executable as the only reference.
717 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
718 yield* spawner.spawn(ChildProcess.make(link, ["-e", "setTimeout(() => {}, 30_000)"]));
719 yield* fs.remove(link);
720​
721 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
722 Effect.provideService(HostProcess.Platform, "linux"),
723 Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: baseDir }),
724 Effect.provide(ProcessRunner.layer),
725 );
726 assert.deepEqual(removed, ["1.1.0"]);
727 }),
728 );
729});