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