Open History to see the last commit
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 // An interrupted append cut this record short.
516 { name: "an unterminated launcher record", recorded: "/opt/t", cut: "" },
517 // Another process's append is cut short after prune reads the records.
518 { name: "a record cut short after the read", recorded: "/opt/t3\n", cut: "/opt/t" },
519 ])("remembers a launcher found on PATH after $name", ({ recorded, cut }) =>
520 Effect.gen(function* () {
521 const fs = yield* FileSystem.FileSystem;
522 const path = yield* Path.Path;
523 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
524 const binDir = path.join(baseDir, "custom-bin");
525 yield* fs.makeDirectory(binDir);
526 yield* fs.symlink(path.join(versionsDir, "1.0.0", "t3"), path.join(binDir, "t3"));
527 const launchersFile = path.join(baseDir, "runtime", "launchers");
528 yield* fs.writeFileString(launchersFile, recorded);
529 const prune = (environment: Record<string, string>) =>
530 prunePinnedRuntimes({ baseDir, keep: [] }).pipe(
531 Effect.provideService(ProcessRunner.ProcessRunner, lsofRunner("p1\nftxt\nn/bin/sh\n")),
532 Effect.provideService(HostProcess.Platform, "darwin"),
533 Effect.provideService(HostProcess.Environment, environment),
534 Effect.provideService(HostProcess.HomeDirectory, baseDir),
535 );
536
537 yield* prune({ PATH: binDir }).pipe(
538 Effect.provideService(FileSystem.FileSystem, {
539 ...fs,
540 readFileString: (file, encoding) =>
541 fs
542 .readFileString(file, encoding)
543 .pipe(
544 Effect.tap(() =>
545 file === launchersFile
546 ? fs.writeFileString(file, cut, { flag: "a" })
547 : Effect.void,
548 ),
549 ),
550 }),
551 );
552 // A service that cannot see the interactive PATH.
553 const removed = yield* prune({});
554
555 assert.deepEqual(removed, []);
556 assert.isTrue(yield* fs.exists(path.join(versionsDir, "1.0.0", "t3")));
557 }),
558 );
559
560 it.effect("matches a Windows shim whatever its casing", () =>
561 Effect.gen(function* () {
562 const fs = yield* FileSystem.FileSystem;
563 const path = yield* Path.Path;
564 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
565 const shim = path.join(baseDir, "t3.cmd");
566 yield* fs.writeFileString(
567 shim,
568 `@echo off\r\n"${path.join(versionsDir, "1.0.0", "t3.exe").toUpperCase()}" %*`,
569 );
570 yield* fs.writeFileString(path.join(baseDir, "runtime", "launchers"), `${shim}\n`);
571
572 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
573 Effect.provideService(
574 ProcessRunner.ProcessRunner,
575 lsofRunner("C:\\Windows\\explorer.exe\n"),
576 ),
577 Effect.provideService(HostProcess.Platform, "win32"),
578 Effect.provideService(HostProcess.Environment, {}),
579 );
580 assert.deepEqual(removed, ["1.1.0"]);
581 }),
582 );
583
584 it.effect.each([
585 { name: "the process list is unavailable", state: undefined, lsof: "" },
586 { name: "the service state is unparseable", state: "{", lsof: "p1\nftxt\nn/sbin/launchd\n" },
587 {
588 name: "the service state cannot be read",
589 state: null,
590 lsof: "p1\nftxt\nn/sbin/launchd\n",
591 },
592 ])("keeps everything when $name", ({ state, lsof }) =>
593 Effect.gen(function* () {
594 const fs = yield* FileSystem.FileSystem;
595 const path = yield* Path.Path;
596 const { baseDir, versionsDir } = yield* setup(["1.0.0"]);
597 const statePath = path.join(baseDir, "runtime", "service-state.json");
598 if (state === null) yield* fs.makeDirectory(statePath);
599 else if (state !== undefined) yield* fs.writeFileString(statePath, state);
600
601 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
602 Effect.provideService(ProcessRunner.ProcessRunner, lsofRunner(lsof)),
603 Effect.provideService(HostProcess.Platform, "darwin"),
604 Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: baseDir }),
605 );
606 assert.deepEqual(removed, []);
607 assert.deepEqual(yield* fs.readDirectory(versionsDir), ["1.0.0"]);
608 }),
609 );
610
611 it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
612 "keeps a runtime a process runs through a symlink",
613 () =>
614 Effect.gen(function* () {
615 const fs = yield* FileSystem.FileSystem;
616 const path = yield* Path.Path;
617 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
618 const entry = path.join(versionsDir, "1.0.0", "t3");
619 // Multicall coreutils (Ubuntu's uutils) refuse to run renamed, so copy Node instead.
620 yield* fs.copyFile(process.execPath, entry);
621 yield* fs.chmod(entry, 0o755);
622 const link = path.join(baseDir, "t3");
623 yield* fs.symlink(entry, link);
624 // Its argv names only the link, as with `t3 serve` run from PATH. Removing the link after
625 // spawning leaves the process's executable as the only reference.
626 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
627 yield* spawner.spawn(ChildProcess.make(link, ["-e", "setTimeout(() => {}, 30_000)"]));
628 yield* fs.remove(link);
629
630 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
631 Effect.provideService(HostProcess.Platform, "linux"),
632 Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: baseDir }),
633 Effect.provide(ProcessRunner.layer),
634 );
635 assert.deepEqual(removed, ["1.1.0"]);
636 }),
637 );
638});