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

pinnedRuntime.test.ts

989 lines40.0 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 Stream from "effect/Stream";
11import * as NodePath from "node:path";
12import * as TestClock from "effect/testing/TestClock";
13import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
14import * as ChildProcess from "effect/process/ChildProcess";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16​
17import * as HostProcess from "@t3tools/shared/HostProcess";
18​
19import * as ProcessRunner from "../processRunner.ts";
20import {
21 isVersionExecutable,
22 ensurePinnedRuntimeInstalled,
23 isUnpublishedRelease,
24 pinnedRuntimeCommand,
25 pinnedRuntimePaths,
26 PinnedRuntimeInstallError,
27 type PinnedRuntimeProgress,
28 prunePinnedRuntimes,
29} from "./pinnedRuntime.ts";
30import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
31​
32const version = "1.2.3";
33const archiveName = `t3-${version}-linux-x64.tar.gz`;
34const archiveBytes = new TextEncoder().encode("not really a tarball");
35const archiveHex = (bytes: Uint8Array) =>
36 Effect.promise(() => crypto.subtle.digest("SHA-256", bytes)).pipe(
37 Effect.map((digest) =>
38 Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""),
39 ),
40 );
41const validChecksums = archiveHex(archiveBytes).pipe(
42 Effect.map((hex) => `${hex} ${archiveName}\n`),
43);
44const releaseHttpClient = (checksums: string, requests: string[] = []) =>
45 HttpClient.make((request) => {
46 requests.push(request.url);
47 const body = new URL(request.url).pathname.endsWith("/SHA256SUMS") ? checksums : archiveBytes;
48 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body)));
49 });
50const extractingRunner = (fs: FileSystem.FileSystem, path: Path.Path, commands: string[] = []) =>
51 ProcessRunner.ProcessRunner.of({
52 run: (input) =>
53 Effect.gen(function* () {
54 commands.push(input.command);
55 const targetIndex = input.args.indexOf("-C");
56 const stagingDir = input.args[targetIndex + 1];
57 if (input.command !== "tar" || stagingDir === undefined) {
58 return yield* Effect.die(`unexpected command ${input.command}`);
59 }
60 yield* fs.writeFileString(path.join(stagingDir, "t3"), "#!/bin/sh\n").pipe(Effect.orDie);
61 return {
62 stdout: "",
63 stderr: "",
64 code: ChildProcessSpawner.ExitCode(0),
65 timedOut: false,
66 stdoutTruncated: false,
67 stderrTruncated: false,
68 stdoutInvalidUtf8: false,
69 stderrInvalidUtf8: false,
70 };
71 }),
72 });
73​
74it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
75 it.effect("installs the verified release archive as the runtime executable", () =>
76 Effect.gen(function* () {
77 const fs = yield* FileSystem.FileSystem;
78 const path = yield* Path.Path;
79 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-" });
80 const requests: string[] = [];
81 const commands: string[] = [];
82 const paths = yield* ensurePinnedRuntimeInstalled({
83 baseDir,
84 version,
85 fs,
86 path,
87 platform: "linux",
88 arch: "x64",
89 httpClient: releaseHttpClient(yield* validChecksums, requests),
90 releaseBaseUrl: "https://releases.example/download",
91 runner: extractingRunner(fs, path, commands),
92 validate: (staging) =>
93 fs.exists(staging.entryPath).pipe(
94 Effect.flatMap((exists) => (exists ? Effect.void : Effect.die("missing runtime"))),
95 Effect.orDie,
96 ),
97 });
98 assert.equal(paths.entryPath, path.join(paths.versionDir, "t3"));
99 assert.deepEqual(pinnedRuntimeCommand(paths), { command: paths.entryPath, args: [] });
100 assert.deepEqual(requests, [
101 `https://releases.example/download/v${version}/SHA256SUMS`,
102 `https://releases.example/download/v${version}/${archiveName}`,
103 ]);
104 assert.deepEqual(commands, ["tar"]);
105 assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`);
106 assert.isFalse(yield* fs.exists(path.join(paths.versionDir, "t3-runtime-archive")));
107 }),
108 );
109​
110 it.effect("cleans up an interrupted download without reporting verification or extraction", () =>
111 Effect.gen(function* () {
112 const fs = yield* FileSystem.FileSystem;
113 const path = yield* Path.Path;
114 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-progress-failed-" });
115 const checksums = yield* validChecksums;
116 const progress: PinnedRuntimeProgress[] = [];
117 let cancelled = false;
118 const client = HttpClient.make((request) =>
119 Effect.succeed(
120 HttpClientResponse.fromWeb(
121 request,
122 request.url.endsWith("/SHA256SUMS")
123 ? new Response(checksums)
124 : new Response(
125 new ReadableStream({
126 start(controller) {
127 controller.enqueue(archiveBytes.slice(0, 4));
128 },
129 cancel() {
130 cancelled = true;
131 },
132 }),
133 ),
134 ),
135 ),
136 );
137 const firstChunk = yield* Deferred.make<void>();
138 const install = yield* ensurePinnedRuntimeInstalled({
139 baseDir,
140 version,
141 fs,
142 path,
143 platform: "linux",
144 arch: "x64",
145 httpClient: client,
146 runner: extractingRunner(fs, path),
147 validate: () => Effect.die("must not validate an interrupted archive"),
148 onProgress: (event) => {
149 progress.push(event);
150 if (event.stage === "download" && event.received === 4)
151 Deferred.doneUnsafe(firstChunk, Effect.void);
152 },
153 }).pipe(Effect.forkScoped);
154 yield* Deferred.await(firstChunk);
155 // Nothing is staged mid-download, so an age-based prune elsewhere cannot remove it.
156 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
157 yield* Fiber.interrupt(install);
158 assert.deepEqual(progress.at(-1), { stage: "download", received: 4, total: undefined });
159 assert.isTrue(progress.every((event) => event.stage === "download"));
160 assert.isTrue(cancelled);
161 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
162 }),
163 );
164​
165 it.effect("reports a release that lists an archive it does not serve as unpublished", () =>
166 Effect.gen(function* () {
167 const fs = yield* FileSystem.FileSystem;
168 const path = yield* Path.Path;
169 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-missing-" });
170 const checksums = yield* validChecksums;
171 const failsWith = (status: number) =>
172 ensurePinnedRuntimeInstalled({
173 baseDir,
174 version,
175 fs,
176 path,
177 platform: "linux",
178 arch: "x64",
179 httpClient: HttpClient.make((request) =>
180 Effect.succeed(
181 HttpClientResponse.fromWeb(
182 request,
183 request.url.endsWith("/SHA256SUMS")
184 ? new Response(checksums)
185 : new Response("", { status }),
186 ),
187 ),
188 ),
189 // "404" in the mirror's path must not read a server error as a missing release.
190 releaseBaseUrl: "https://updates.example.com/404/t3code",
191 runner: extractingRunner(fs, path),
192 validate: () => Effect.die("must not validate a missing archive"),
193 }).pipe(Effect.flip);
194 assert.isTrue(isUnpublishedRelease(yield* failsWith(404)));
195 assert.isFalse(isUnpublishedRelease(yield* failsWith(403)));
196 }),
197 );
198​
199 it.effect("retries a release download that GitHub answers with a gateway timeout", () =>
200 Effect.gen(function* () {
201 const fs = yield* FileSystem.FileSystem;
202 const path = yield* Path.Path;
203 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-retry-" });
204 const checksums = yield* validChecksums;
205 const requests: string[] = [];
206 const gatewayTimeoutServed = yield* Deferred.make<void>();
207 const install = yield* ensurePinnedRuntimeInstalled({
208 baseDir,
209 version,
210 fs,
211 path,
212 platform: "linux",
213 arch: "x64",
214 httpClient: HttpClient.make((request) => {
215 requests.push(request.url);
216 const isChecksums = request.url.endsWith("/SHA256SUMS");
217 if (requests.length === 1) {
218 Deferred.doneUnsafe(gatewayTimeoutServed, Effect.void);
219 return Effect.succeed(
220 HttpClientResponse.fromWeb(request, new Response("", { status: 504 })),
221 );
222 }
223 return Effect.succeed(
224 HttpClientResponse.fromWeb(
225 request,
226 new Response(isChecksums ? checksums : archiveBytes),
227 ),
228 );
229 }),
230 runner: extractingRunner(fs, path),
231 validate: () => Effect.void,
232 }).pipe(Effect.forkScoped);
233 yield* Deferred.await(gatewayTimeoutServed);
234 yield* TestClock.adjust(Duration.seconds(2));
235 const paths = yield* Fiber.join(install);
236 assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`);
237 assert.equal(requests.filter((url) => url.endsWith("/SHA256SUMS")).length, 2);
238 }),
239 );
240​
241 it.effect.each([
242 { name: "body fails after the host answered", first: "body fails", honorsRange: true },
243 {
244 name: "body stalls and its resume ends early",
245 first: "body stalls",
246 honorsRange: true,
247 shortResume: true,
248 },
249 { name: "body stalls on a host that ignores Range", first: "body stalls", honorsRange: false },
250 { name: "response headers stall", first: "headers stall", honorsRange: true },
251 {
252 name: "whole body arrives and then stalls",
253 first: "body stalls",
254 honorsRange: true,
255 wholeArchive: true,
256 },
257 ] as const)("resumes a release archive download when its $name", (row) =>
258 Effect.gen(function* () {
259 const { first, honorsRange } = row;
260 const shortResume = "shortResume" in row;
261 const fs = yield* FileSystem.FileSystem;
262 const path = yield* Path.Path;
263 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-retry-body-" });
264 const checksums = yield* validChecksums;
265 const ranges: Array<string | undefined> = [];
266 const checksumRanges: Array<string | undefined> = [];
267 const progress: PinnedRuntimeProgress[] = [];
268 const checksumsRequested = yield* Deferred.make<void>();
269 const archiveRequested = yield* Deferred.make<void>();
270 const shortResumeRequested = yield* Deferred.make<void>();
271 const total = archiveBytes.length;
272 const heldBytes = "wholeArchive" in row ? archiveBytes : archiveBytes.slice(0, 4);
273 const install = yield* ensurePinnedRuntimeInstalled({
274 baseDir,
275 version,
276 fs,
277 path,
278 platform: "linux",
279 arch: "x64",
280 httpClient: HttpClient.make((request) => {
281 if (request.url.endsWith("/SHA256SUMS")) {
282 checksumRanges.push(request.headers["range"]);
283 const response = HttpClientResponse.fromWeb(request, new Response(checksums));
284 if (checksumRanges.length > 1) return Effect.succeed(response);
285 Deferred.doneUnsafe(checksumsRequested, Effect.void);
286 // The checksums fail once after a prefix, which their retry must not resume from.
287 const failingBody = Stream.concat(
288 Stream.make(new TextEncoder().encode(checksums).slice(0, 8)),
289 Stream.fail(
290 new HttpClientError.HttpClientError({
291 reason: new HttpClientError.DecodeError({ request, response }),
292 }),
293 ),
294 );
295 return Effect.sleep("1 second").pipe(
296 Effect.as<HttpClientResponse.HttpClientResponse>(
297 Object.create(response, { stream: { value: failingBody } }),
298 ),
299 );
300 }
301 const range = request.headers["range"];
302 ranges.push(range);
303 if (ranges.length > 1) {
304 const start = honorsRange ? Number(/^bytes=(\d+)-$/.exec(range ?? "")?.[1] ?? 0) : 0;
305 // A short resume stops one byte early; the next retry asks for that byte.
306 const end = shortResume && ranges.length === 2 ? total - 1 : total;
307 const response = HttpClientResponse.fromWeb(
308 request,
309 start >= total
310 ? new Response("", {
311 status: 416,
312 headers: { "content-range": `bytes */${total}` },
313 })
314 : start > 0
315 ? new Response(archiveBytes.slice(start, end), {
316 status: 206,
317 headers: { "content-range": `bytes ${start}-${end - 1}/${total}` },
318 })
319 : new Response(archiveBytes, { headers: { "content-length": `${total}` } }),
320 );
321 if (end === total) return Effect.succeed(response);
322 Deferred.doneUnsafe(shortResumeRequested, Effect.void);
323 // An Effect stream keeps the body, and so the retry wait after it, on the test clock.
324 const body = Stream.make(archiveBytes.slice(start, end));
325 return Effect.sleep("1 second").pipe(
326 Effect.as<HttpClientResponse.HttpClientResponse>(
327 Object.create(response, { stream: { value: body } }),
328 ),
329 );
330 }
331 Deferred.doneUnsafe(archiveRequested, Effect.void);
332 if (first === "headers stall") return Effect.never;
333 const response = HttpClientResponse.fromWeb(
334 request,
335 new Response(archiveBytes, { headers: { "content-length": `${total}` } }),
336 );
337 const failingBody = Stream.concat(
338 Stream.make(heldBytes),
339 first === "body stalls"
340 ? Stream.never
341 : Stream.fail(
342 new HttpClientError.HttpClientError({
343 reason: new HttpClientError.DecodeError({ request, response }),
344 }),
345 ),
346 );
347 // TestClock follows the work a woken sleep starts, so one adjust reaches the retry wait.
348 return Effect.sleep("1 second").pipe(
349 Effect.as<HttpClientResponse.HttpClientResponse>(
350 Object.create(response, { stream: { value: failingBody } }),
351 ),
352 );
353 }),
354 runner: extractingRunner(fs, path),
355 validate: () => Effect.void,
356 onProgress: (event) => progress.push(event),
357 }).pipe(Effect.forkScoped);
358 yield* Deferred.await(checksumsRequested);
359 yield* TestClock.adjust(Duration.seconds(3));
360 yield* Deferred.await(archiveRequested);
361 // The one-minute stall bound, then the first two-second retry backoff.
362 yield* TestClock.adjust(Duration.seconds(first === "body fails" ? 3 : 63));
363 if (shortResume) {
364 yield* Deferred.await(shortResumeRequested);
365 // Its one-second delay, then the second, four-second backoff.
366 yield* TestClock.adjust(Duration.seconds(5));
367 }
368 const paths = yield* Fiber.join(install);
369 assert.deepEqual(checksumRanges, [undefined, undefined]);
370 assert.deepEqual(ranges, [
371 undefined,
372 first === "headers stall" ? undefined : `bytes=${heldBytes.length}-`,
373 ...(shortResume ? [`bytes=${total - 1}-`] : []),
374 ]);
375 assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`);
376 assert.deepEqual(
377 progress.findLast((event) => event.stage === "download"),
378 {
379 stage: "download",
380 received: total,
381 total,
382 },
383 );
384 }),
385 );
386​
387 it.effect("fails at once when the release host cannot be reached", () =>
388 Effect.gen(function* () {
389 const fs = yield* FileSystem.FileSystem;
390 const path = yield* Path.Path;
391 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-offline-" });
392 let requests = 0;
393 const error = yield* ensurePinnedRuntimeInstalled({
394 baseDir,
395 version,
396 fs,
397 path,
398 platform: "linux",
399 arch: "x64",
400 httpClient: HttpClient.make((request) => {
401 requests += 1;
402 return Effect.fail(
403 new HttpClientError.HttpClientError({
404 reason: new HttpClientError.TransportError({ request }),
405 }),
406 );
407 }),
408 runner: extractingRunner(fs, path),
409 validate: () => Effect.die("must not validate without a download"),
410 }).pipe(Effect.flip);
411 assert.instanceOf(error, PinnedRuntimeInstallError);
412 assert.equal(requests, 1);
413 }),
414 );
415​
416 it.effect("refuses an archive whose checksum does not match the release", () =>
417 Effect.gen(function* () {
418 const fs = yield* FileSystem.FileSystem;
419 const path = yield* Path.Path;
420 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-bad-" });
421 const commands: string[] = [];
422 const error = yield* ensurePinnedRuntimeInstalled({
423 baseDir,
424 version,
425 fs,
426 path,
427 platform: "linux",
428 arch: "x64",
429 httpClient: releaseHttpClient(`${"0".repeat(64)} ${archiveName}\n`),
430 runner: extractingRunner(fs, path, commands),
431 validate: () => Effect.die("must not validate an unverified archive"),
432 }).pipe(Effect.flip);
433 assert.instanceOf(error, PinnedRuntimeInstallError);
434 assert.equal(error.step, "verifying the t3 release archive checksum");
435 assert.deepEqual(commands, []);
436 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
437 }),
438 );
439​
440 it.effect("validates a staging tree before atomically publishing it", () =>
441 Effect.gen(function* () {
442 const fs = yield* FileSystem.FileSystem;
443 const path = yield* Path.Path;
444 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
445 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
446 let validatedDirectory = "";
447​
448 const installed = yield* ensurePinnedRuntimeInstalled({
449 baseDir,
450 version,
451 fs,
452 path,
453 platform: "linux",
454 arch: "x64",
455 httpClient: releaseHttpClient(yield* validChecksums),
456 runner: extractingRunner(fs, path),
457 validate: (staging) =>
458 Effect.gen(function* () {
459 validatedDirectory = staging.versionDir;
460 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
461 assert.isTrue(yield* fs.exists(staging.entryPath));
462 }).pipe(Effect.orDie),
463 });
464​
465 assert.notEqual(validatedDirectory, finalPaths.versionDir);
466 assert.deepEqual(installed, finalPaths);
467 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
468 assert.equal(yield* fs.readFileString(finalPaths.sentinelPath), `${version}\n`);
469 }),
470 );
471​
472 it.effect("removes staging and leaves no final runtime when validation fails", () =>
473 Effect.gen(function* () {
474 const fs = yield* FileSystem.FileSystem;
475 const path = yield* Path.Path;
476 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
477 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
478​
479 yield* ensurePinnedRuntimeInstalled({
480 baseDir,
481 version,
482 fs,
483 path,
484 platform: "linux",
485 arch: "x64",
486 httpClient: releaseHttpClient(yield* validChecksums),
487 runner: extractingRunner(fs, path),
488 validate: () =>
489 Effect.fail(new PinnedRuntimeInstallError({ step: "validating the staged runtime" })),
490 }).pipe(Effect.flip);
491​
492 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
493 assert.deepEqual(
494 (yield* fs.readDirectory(path.dirname(finalPaths.versionDir))).filter((entry) =>
495 entry.startsWith(".staging-"),
496 ),
497 [],
498 );
499 }),
500 );
501​
502 it.effect("replaces an incomplete pinned runtime", () =>
503 Effect.gen(function* () {
504 const fs = yield* FileSystem.FileSystem;
505 const path = yield* Path.Path;
506 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
507 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
508 yield* fs.makeDirectory(finalPaths.versionDir, { recursive: true });
509 yield* fs.writeFileString(path.join(finalPaths.versionDir, "partial"), "incomplete\n");
510​
511 yield* ensurePinnedRuntimeInstalled({
512 baseDir,
513 version,
514 fs,
515 path,
516 platform: "linux",
517 arch: "x64",
518 httpClient: releaseHttpClient(yield* validChecksums),
519 runner: extractingRunner(fs, path),
520 validate: () => Effect.void,
521 });
522​
523 assert.isFalse(yield* fs.exists(path.join(finalPaths.versionDir, "partial")));
524 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
525 }),
526 );
527​
528 it.effect("reuses a cached runtime under a mirror only while the mirror lists it", () =>
529 Effect.gen(function* () {
530 const fs = yield* FileSystem.FileSystem;
531 const path = yield* Path.Path;
532 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-mirror-" });
533 const cached = pinnedRuntimePaths(path, baseDir, version, "linux");
534 yield* fs.makeDirectory(path.dirname(cached.entryPath), { recursive: true });
535 yield* fs.writeFileString(cached.entryPath, "#!/bin/sh\n");
536 yield* fs.writeFileString(cached.sentinelPath, `${version}\n`);
537 const install = (checksums: string, requests: string[]) =>
538 ensurePinnedRuntimeInstalled({
539 baseDir,
540 version,
541 fs,
542 path,
543 platform: "linux",
544 arch: "x64",
545 httpClient: releaseHttpClient(checksums, requests),
546 // A signed mirror URL keeps its query on every file it serves.
547 releaseBaseUrl: "https://updates.example.com/t3code/?token=abc",
548 requirePublishedRelease: true,
549 runner: extractingRunner(fs, path),
550 validate: () => Effect.void,
551 });
552​
553 const withdrawn = yield* install("", []).pipe(Effect.flip);
554 assert.include(withdrawn.message, `finding ${archiveName} in the t3 release checksums`);
555 const requests: string[] = [];
556 assert.equal((yield* install(yield* validChecksums, requests)).entryPath, cached.entryPath);
557 // Listed, so the cached runtime is used without downloading it again.
558 assert.deepEqual(requests, [
559 `https://updates.example.com/t3code/v${version}/SHA256SUMS?token=abc`,
560 ]);
561 }),
562 );
563​
564 it.effect("preserves a completed runtime when validation fails", () =>
565 Effect.gen(function* () {
566 const fs = yield* FileSystem.FileSystem;
567 const path = yield* Path.Path;
568 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
569 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
570 yield* fs.makeDirectory(path.dirname(finalPaths.entryPath), { recursive: true });
571 yield* fs.writeFileString(finalPaths.entryPath, "broken\n");
572 yield* fs.writeFileString(finalPaths.sentinelPath, `${version}\n`);
573​
574 let validations = 0;
575 const requests: string[] = [];
576 yield* ensurePinnedRuntimeInstalled({
577 baseDir,
578 version,
579 fs,
580 path,
581 platform: "linux",
582 arch: "x64",
583 httpClient: releaseHttpClient(yield* validChecksums, requests),
584 runner: extractingRunner(fs, path),
585 validate: (paths) =>
586 Effect.gen(function* () {
587 validations += 1;
588 const source = yield* fs.readFileString(paths.entryPath).pipe(Effect.orDie);
589 if (source === "broken\n") {
590 return yield* new PinnedRuntimeInstallError({ step: "validating the runtime" });
591 }
592 }),
593 }).pipe(Effect.flip);
594​
595 assert.equal(validations, 1);
596 assert.deepEqual(requests, []);
597 assert.equal(yield* fs.readFileString(finalPaths.entryPath), "broken\n");
598 }),
599 );
600});
601​
602it("isVersionExecutable accepts only <version>/t3, never another drive or program", () => {
603 const win32 = NodePath.win32 as unknown as Path.Path;
604 assert.isTrue(isVersionExecutable(win32, "C:\\t3\\versions", "C:\\t3\\versions\\1.0.0\\t3.exe"));
605 assert.isFalse(isVersionExecutable(win32, "C:\\t3\\versions", "D:\\t3.exe"));
606 assert.isFalse(
607 isVersionExecutable(win32, "C:\\t3\\versions", "C:\\t3\\versions\\1.0.0\\node.exe"),
608 );
609});
610​
611it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => {
612 const lsofRunner = (stdout: string) =>
613 ProcessRunner.ProcessRunner.of({
614 run: () =>
615 Effect.succeed({
616 stdout,
617 stderr: "",
618 code: ChildProcessSpawner.ExitCode(0),
619 timedOut: false,
620 stdoutTruncated: false,
621 stderrTruncated: false,
622 stdoutInvalidUtf8: false,
623 stderrInvalidUtf8: false,
624 }),
625 });
626​
627 const setup = Effect.fn(function* (versions: ReadonlyArray<string>) {
628 const fs = yield* FileSystem.FileSystem;
629 const path = yield* Path.Path;
630 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-prune-" });
631 const versionsDir = path.join(baseDir, "runtime", "versions");
632 const now = Duration.toMillis(Duration.days(1));
633 yield* TestClock.setTime(now);
634 const install = Effect.fn(function* (
635 version: string,
636 completed: "long ago" | "just now" | "never" = "long ago",
637 ) {
638 const directory = path.join(versionsDir, version);
639 yield* fs.makeDirectory(directory, { recursive: true });
640 yield* fs.writeFileString(path.join(directory, "t3"), "");
641 if (completed === "never") return;
642 const sentinel = path.join(directory, ".install-complete");
643 yield* fs.writeFileString(sentinel, `${version}\n`);
644 const at = completed === "just now" ? now : 0;
645 yield* fs.utimes(sentinel, at, at);
646 });
647 for (const version of versions) yield* install(version);
648 return { baseDir, versionsDir, install };
649 });
650​
651 it.effect("removes only completed runtimes nothing references", () =>
652 Effect.gen(function* () {
653 const fs = yield* FileSystem.FileSystem;
654 const path = yield* Path.Path;
655 const { baseDir, versionsDir, install } = yield* setup([
656 "1.0.0",
657 "1.1.0",
658 "1.2.0",
659 "1.2.5",
660 "1.3.0",
661 "1.3.5",
662 "1.4.0",
663 "1.5.0",
664 "2.0.0",
665 "2.1.0",
666 ]);
667 // A downgrade another process installed but has not pointed anything at yet.
668 yield* install("0.5.0", "just now");
669 yield* install("1.0.1", "never");
670 yield* install(".staging-abc", "never");
671 yield* install(".pruned-0.8.0");
672 yield* install("other", "never");
673 yield* fs.symlink(path.join(versionsDir, "other"), path.join(versionsDir, "0.9.0"));
674 const binDir = path.join(baseDir, "bin");
675 const customBinDir = path.join(baseDir, "custom-bin");
676 yield* fs.makeDirectory(binDir);
677 yield* fs.makeDirectory(customBinDir);
678 // Chained: the launcher reaches its runtime through a second link.
679 yield* fs.symlink(path.join(versionsDir, "1.2.0", "t3"), path.join(baseDir, "alias-t3"));
680 yield* fs.symlink(path.join(baseDir, "alias-t3"), path.join(binDir, "t3"));
681 yield* fs.symlink(path.join(versionsDir, "1.2.5", "t3"), path.join(customBinDir, "t3"));
682 yield* fs.writeFileString(
683 path.join(baseDir, "runtime", "launchers"),
684 `${path.join(customBinDir, "t3")}\n`,
685 );
686 yield* fs.writeFileString(
687 path.join(baseDir, "runtime", "service-state.json"),
688 JSON.stringify({
689 protocol: SERVICE_LAUNCHER_PROTOCOL,
690 activeVersion: "1.4.0",
691 update: { id: "u", fromVersion: "1.4.0", targetVersion: "1.5.0", status: "rolled-back" },
692 }),
693 );
694​
695 const removed = yield* prunePinnedRuntimes({
696 baseDir,
697 keep: ["2.0.0"],
698 references: [`ExecStart=${path.join(versionsDir, "1.3.5", "t3")} __service-launcher`],
699 }).pipe(
700 Effect.provideService(
701 ProcessRunner.ProcessRunner,
702 lsofRunner(`p42\nftxt\nn${path.join(versionsDir, "1.3.0", "t3")}\n`),
703 ),
704 Effect.provideService(HostProcess.Platform, "darwin"),
705 Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: binDir }),
706 );
707​
708 // 1.2.0 is the default launcher, 1.2.5 a recorded one, 1.3.0 running, 1.3.5 in the unit,
709 // 1.4.0 active, 1.5.0 the rolled-back target, 2.0.0 the caller's, 0.5.0 just installed.
710 // Being newer than the caller's version does not keep 2.1.0.
711 assert.deepEqual(removed.toSorted(), ["0.8.0", "1.0.0", "1.1.0", "2.1.0"]);
712 // The launcher found on PATH is remembered for a service that cannot see it.
713 assert.equal(
714 yield* fs.readFileString(path.join(baseDir, "runtime", "launchers")),
715 `${path.join(customBinDir, "t3")}\n\n${path.join(binDir, "t3")}\n`,
716 );
717 assert.deepEqual((yield* fs.readDirectory(versionsDir)).toSorted(), [
718 ".staging-abc",
719 "0.5.0",
720 "0.9.0",
721 "1.0.1",
722 "1.2.0",
723 "1.2.5",
724 "1.3.0",
725 "1.3.5",
726 "1.4.0",
727 "1.5.0",
728 "2.0.0",
729 "other",
730 ]);
731 }),
732 );
733​
734 it.effect("removes the runtime a committed update replaced", () =>
735 Effect.gen(function* () {
736 const fs = yield* FileSystem.FileSystem;
737 const path = yield* Path.Path;
738 const { baseDir } = yield* setup(["1.0.0", "1.1.0"]);
739 yield* fs.writeFileString(
740 path.join(baseDir, "runtime", "service-state.json"),
741 JSON.stringify({
742 protocol: SERVICE_LAUNCHER_PROTOCOL,
743 activeVersion: "1.1.0",
744 update: { id: "u", fromVersion: "1.0.0", targetVersion: "1.1.0", status: "committed" },
745 }),
746 );
747​
748 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["1.1.0"] }).pipe(
749 Effect.provideService(ProcessRunner.ProcessRunner, lsofRunner("p1\nftxt\nn/bin/sh\n")),
750 Effect.provideService(HostProcess.Platform, "darwin"),
751 Effect.provideService(HostProcess.Environment, {}),
752 );
753 assert.deepEqual(removed, ["1.0.0"]);
754 }),
755 );
756​
757 it.effect("removes a staging directory an interrupted install abandoned long ago", () =>
758 Effect.gen(function* () {
759 const fs = yield* FileSystem.FileSystem;
760 const path = yield* Path.Path;
761 const { baseDir, versionsDir, install } = yield* setup(["1.0.0"]);
762 yield* install(".staging-abc", "never");
763 yield* fs.utimes(path.join(versionsDir, ".staging-abc"), 0, 0);
764​
765 yield* prunePinnedRuntimes({ baseDir, keep: ["1.0.0"] }).pipe(
766 Effect.provideService(ProcessRunner.ProcessRunner, lsofRunner("p1\nftxt\nn/bin/sh\n")),
767 Effect.provideService(HostProcess.Platform, "darwin"),
768 Effect.provideService(HostProcess.Environment, {}),
769 );
770 assert.deepEqual(yield* fs.readDirectory(versionsDir), ["1.0.0"]);
771 }),
772 );
773​
774 it.effect.each([
775 { name: "its directory is on PATH", onPath: true, recorded: false, linkedHome: false },
776 {
777 name: "an earlier prune recorded its entry as a launcher",
778 onPath: false,
779 recorded: true,
780 linkedHome: false,
781 },
782 {
783 name: "its real directory in a symlinked home is on PATH",
784 onPath: true,
785 recorded: false,
786 linkedHome: true,
787 },
788 ])("removes a runtime only its own entry names when $name", ({ onPath, recorded, linkedHome }) =>
789 Effect.gen(function* () {
790 const fs = yield* FileSystem.FileSystem;
791 const path = yield* Path.Path;
792 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
793 const binDir = path.join(baseDir, "bin");
794 yield* fs.makeDirectory(binDir);
795 yield* fs.symlink(path.join(versionsDir, "1.1.0", "t3"), path.join(binDir, "t3"));
796 const ownDir = path.join(versionsDir, "1.0.0");
797 if (recorded) {
798 yield* fs.writeFileString(
799 path.join(baseDir, "runtime", "launchers"),
800 `${path.join(ownDir, "t3")}\n`,
801 );
802 }
803​
804 const home = linkedHome
805 ? path.join(yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-link-" }), "home")
806 : baseDir;
807 if (linkedHome) yield* fs.symlink(baseDir, home);
808​
809 // The launch agent puts the running runtime's own directory on PATH.
810 const removed = yield* prunePinnedRuntimes({ baseDir: home, keep: ["2.0.0"] }).pipe(
811 Effect.provideService(
812 ProcessRunner.ProcessRunner,
813 lsofRunner("p1\nftxt\nn/sbin/launchd\n"),
814 ),
815 Effect.provideService(HostProcess.Platform, "darwin"),
816 Effect.provideService(HostProcess.Environment, {
817 T3CODE_INSTALL_BIN_DIR: binDir,
818 PATH: onPath ? `${ownDir}:/usr/bin:/bin` : "/usr/bin:/bin",
819 }),
820 );
821 assert.deepEqual(removed, ["1.0.0"]);
822 }),
823 );
824​
825 it.effect.each([
826 { name: "a launcher inside the versions directory", via: "bin" as const },
827 { name: "a PATH directory linked to its version directory", via: "linked dir" as const },
828 {
829 name: "a PATH directory in the versions directory linked to its version directory",
830 via: "linked versions dir" as const,
831 },
832 ])("keeps a runtime $name names", ({ via }) =>
833 Effect.gen(function* () {
834 const fs = yield* FileSystem.FileSystem;
835 const path = yield* Path.Path;
836 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
837 let pathDirs = "/usr/bin:/bin";
838 if (via === "bin") {
839 // The installer accepts any bin directory, including one under the versions directory.
840 const binDir = path.join(versionsDir, "bin");
841 yield* fs.makeDirectory(binDir);
842 yield* fs.symlink(path.join(versionsDir, "1.0.0", "t3"), path.join(binDir, "t3"));
843 yield* fs.writeFileString(
844 path.join(baseDir, "runtime", "launchers"),
845 `${path.join(binDir, "t3")}\n`,
846 );
847 } else {
848 const linkedDir = path.join(via === "linked dir" ? baseDir : versionsDir, "current");
849 yield* fs.symlink(path.join(versionsDir, "1.0.0"), linkedDir);
850 pathDirs = `${linkedDir}:${pathDirs}`;
851 }
852​
853 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
854 Effect.provideService(
855 ProcessRunner.ProcessRunner,
856 lsofRunner("p1\nftxt\nn/sbin/launchd\n"),
857 ),
858 Effect.provideService(HostProcess.Platform, "darwin"),
859 Effect.provideService(HostProcess.Environment, { PATH: pathDirs }),
860 );
861 assert.deepEqual(removed, ["1.1.0"]);
862 }),
863 );
864​
865 it.effect.each([
866 // An interrupted append cut this record short.
867 { name: "an unterminated launcher record", recorded: "/opt/t", cut: "" },
868 // Another process's append is cut short after prune reads the records.
869 { name: "a record cut short after the read", recorded: "/opt/t3\n", cut: "/opt/t" },
870 ])("remembers a launcher found on PATH after $name", ({ recorded, cut }) =>
871 Effect.gen(function* () {
872 const fs = yield* FileSystem.FileSystem;
873 const path = yield* Path.Path;
874 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
875 const binDir = path.join(baseDir, "custom-bin");
876 yield* fs.makeDirectory(binDir);
877 yield* fs.symlink(path.join(versionsDir, "1.0.0", "t3"), path.join(binDir, "t3"));
878 const launchersFile = path.join(baseDir, "runtime", "launchers");
879 yield* fs.writeFileString(launchersFile, recorded);
880 const prune = (environment: Record<string, string>) =>
881 prunePinnedRuntimes({ baseDir, keep: [] }).pipe(
882 Effect.provideService(ProcessRunner.ProcessRunner, lsofRunner("p1\nftxt\nn/bin/sh\n")),
883 Effect.provideService(HostProcess.Platform, "darwin"),
884 Effect.provideService(HostProcess.Environment, environment),
885 Effect.provideService(HostProcess.HomeDirectory, baseDir),
886 );
887​
888 yield* prune({ PATH: binDir }).pipe(
889 Effect.provideService(FileSystem.FileSystem, {
890 ...fs,
891 readFileString: (file, encoding) =>
892 fs
893 .readFileString(file, encoding)
894 .pipe(
895 Effect.tap(() =>
896 file === launchersFile
897 ? fs.writeFileString(file, cut, { flag: "a" })
898 : Effect.void,
899 ),
900 ),
901 }),
902 );
903 // A service that cannot see the interactive PATH.
904 const removed = yield* prune({});
905​
906 assert.deepEqual(removed, []);
907 assert.isTrue(yield* fs.exists(path.join(versionsDir, "1.0.0", "t3")));
908 }),
909 );
910​
911 it.effect("matches a Windows shim whatever its casing", () =>
912 Effect.gen(function* () {
913 const fs = yield* FileSystem.FileSystem;
914 const path = yield* Path.Path;
915 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
916 const shim = path.join(baseDir, "t3.cmd");
917 yield* fs.writeFileString(
918 shim,
919 `@echo off\r\n"${path.join(versionsDir, "1.0.0", "t3.exe").toUpperCase()}" %*`,
920 );
921 yield* fs.writeFileString(path.join(baseDir, "runtime", "launchers"), `${shim}\n`);
922​
923 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
924 Effect.provideService(
925 ProcessRunner.ProcessRunner,
926 lsofRunner("C:\\Windows\\explorer.exe\n"),
927 ),
928 Effect.provideService(HostProcess.Platform, "win32"),
929 Effect.provideService(HostProcess.Environment, {}),
930 );
931 assert.deepEqual(removed, ["1.1.0"]);
932 }),
933 );
934​
935 it.effect.each([
936 { name: "the process list is unavailable", state: undefined, lsof: "" },
937 { name: "the service state is unparseable", state: "{", lsof: "p1\nftxt\nn/sbin/launchd\n" },
938 {
939 name: "the service state cannot be read",
940 state: null,
941 lsof: "p1\nftxt\nn/sbin/launchd\n",
942 },
943 ])("keeps everything when $name", ({ state, lsof }) =>
944 Effect.gen(function* () {
945 const fs = yield* FileSystem.FileSystem;
946 const path = yield* Path.Path;
947 const { baseDir, versionsDir } = yield* setup(["1.0.0"]);
948 const statePath = path.join(baseDir, "runtime", "service-state.json");
949 if (state === null) yield* fs.makeDirectory(statePath);
950 else if (state !== undefined) yield* fs.writeFileString(statePath, state);
951​
952 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
953 Effect.provideService(ProcessRunner.ProcessRunner, lsofRunner(lsof)),
954 Effect.provideService(HostProcess.Platform, "darwin"),
955 Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: baseDir }),
956 );
957 assert.deepEqual(removed, []);
958 assert.deepEqual(yield* fs.readDirectory(versionsDir), ["1.0.0"]);
959 }),
960 );
961​
962 it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
963 "keeps a runtime a process runs through a symlink",
964 () =>
965 Effect.gen(function* () {
966 const fs = yield* FileSystem.FileSystem;
967 const path = yield* Path.Path;
968 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
969 const entry = path.join(versionsDir, "1.0.0", "t3");
970 // Multicall coreutils (Ubuntu's uutils) refuse to run renamed, so copy Node instead.
971 yield* fs.copyFile(process.execPath, entry);
972 yield* fs.chmod(entry, 0o755);
973 const link = path.join(baseDir, "t3");
974 yield* fs.symlink(entry, link);
975 // Its argv names only the link, as with `t3 serve` run from PATH. Removing the link after
976 // spawning leaves the process's executable as the only reference.
977 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
978 yield* spawner.spawn(ChildProcess.make(link, ["-e", "setTimeout(() => {}, 30_000)"]));
979 yield* fs.remove(link);
980​
981 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
982 Effect.provideService(HostProcess.Platform, "linux"),
983 Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: baseDir }),
984 Effect.provide(ProcessRunner.layer),
985 );
986 assert.deepEqual(removed, ["1.1.0"]);
987 }),
988 );
989});