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

pinnedRuntime.test.ts

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