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 ChildProcessSpawner from "effect/process/ChildProcessSpawner";
12
13import * as ProcessRunner from "../processRunner.ts";
14import {
15 ensurePinnedRuntimeInstalled,
16 pinnedRuntimeCommand,
17 pinnedRuntimePaths,
18 PinnedRuntimeInstallError,
19 type PinnedRuntimeProgress,
20} from "./pinnedRuntime.ts";
21
22const version = "1.2.3";
23const archiveName = `t3-${version}-linux-x64.tar.gz`;
24const archiveBytes = new TextEncoder().encode("not really a tarball");
25const archiveHex = (bytes: Uint8Array) =>
26 Effect.promise(() => crypto.subtle.digest("SHA-256", bytes)).pipe(
27 Effect.map((digest) =>
28 Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""),
29 ),
30 );
31const validChecksums = archiveHex(archiveBytes).pipe(
32 Effect.map((hex) => `${hex} ${archiveName}\n`),
33);
34const releaseHttpClient = (checksums: string, requests: string[] = []) =>
35 HttpClient.make((request) => {
36 requests.push(request.url);
37 const body = request.url.endsWith("/SHA256SUMS") ? checksums : archiveBytes;
38 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body)));
39 });
40const extractingRunner = (fs: FileSystem.FileSystem, path: Path.Path, commands: string[] = []) =>
41 ProcessRunner.ProcessRunner.of({
42 run: (input) =>
43 Effect.gen(function* () {
44 commands.push(input.command);
45 const targetIndex = input.args.indexOf("-C");
46 const stagingDir = input.args[targetIndex + 1];
47 if (input.command !== "tar" || stagingDir === undefined) {
48 return yield* Effect.die(`unexpected command ${input.command}`);
49 }
50 yield* fs.writeFileString(path.join(stagingDir, "t3"), "#!/bin/sh\n").pipe(Effect.orDie);
51 return {
52 stdout: "",
53 stderr: "",
54 code: ChildProcessSpawner.ExitCode(0),
55 timedOut: false,
56 stdoutTruncated: false,
57 stderrTruncated: false,
58 stdoutInvalidUtf8: false,
59 stderrInvalidUtf8: false,
60 };
61 }),
62 });
63
64it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
65 it.effect("installs the verified release archive as the runtime executable", () =>
66 Effect.gen(function* () {
67 const fs = yield* FileSystem.FileSystem;
68 const path = yield* Path.Path;
69 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-" });
70 const requests: string[] = [];
71 const commands: string[] = [];
72 const paths = yield* ensurePinnedRuntimeInstalled({
73 baseDir,
74 version,
75 fs,
76 path,
77 platform: "linux",
78 arch: "x64",
79 httpClient: releaseHttpClient(yield* validChecksums, requests),
80 releaseBaseUrl: "https://releases.example/download",
81 runner: extractingRunner(fs, path, commands),
82 validate: (staging) =>
83 fs.exists(staging.entryPath).pipe(
84 Effect.flatMap((exists) => (exists ? Effect.void : Effect.die("missing runtime"))),
85 Effect.orDie,
86 ),
87 });
88 assert.equal(paths.entryPath, path.join(paths.versionDir, "t3"));
89 assert.deepEqual(pinnedRuntimeCommand(paths), { command: paths.entryPath, args: [] });
90 assert.deepEqual(requests, [
91 `https://releases.example/download/v${version}/SHA256SUMS`,
92 `https://releases.example/download/v${version}/${archiveName}`,
93 ]);
94 assert.deepEqual(commands, ["tar"]);
95 assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`);
96 assert.isFalse(yield* fs.exists(path.join(paths.versionDir, "t3-runtime-archive")));
97 }),
98 );
99
100 it.effect.each([true, false])(
101 "reports bytes before completion, then verifies and extracts (known size: %s)",
102 (knownSize) =>
103 Effect.gen(function* () {
104 const fs = yield* FileSystem.FileSystem;
105 const path = yield* Path.Path;
106 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-progress-" });
107 const firstChunk = yield* Deferred.make<void>();
108 let archiveController: ReadableStreamDefaultController<Uint8Array> | undefined;
109 const checksums = yield* validChecksums;
110 const progress: PinnedRuntimeProgress[] = [];
111 const client = HttpClient.make((request) =>
112 Effect.succeed(
113 HttpClientResponse.fromWeb(
114 request,
115 request.url.endsWith("/SHA256SUMS")
116 ? new Response(checksums)
117 : new Response(
118 new ReadableStream({
119 start(controller) {
120 archiveController = controller;
121 controller.enqueue(archiveBytes.slice(0, 4));
122 },
123 }),
124 { headers: knownSize ? { "content-length": String(archiveBytes.length) } : {} },
125 ),
126 ),
127 ),
128 );
129 const install = yield* ensurePinnedRuntimeInstalled({
130 baseDir,
131 version,
132 fs,
133 path,
134 platform: "linux",
135 arch: "x64",
136 httpClient: client,
137 runner: extractingRunner(fs, path),
138 validate: () => Effect.void,
139 onProgress: (event) => {
140 progress.push(event);
141 if (event.stage === "download" && event.received === 4) {
142 Deferred.doneUnsafe(firstChunk, Effect.void);
143 }
144 },
145 }).pipe(Effect.forkScoped);
146 yield* Deferred.await(firstChunk);
147 assert.deepEqual(progress.at(-1), {
148 stage: "download",
149 received: 4,
150 total: knownSize ? archiveBytes.length : undefined,
151 });
152 assert.isFalse(progress.some((event) => event.stage === "extract"));
153 assert.isDefined(archiveController);
154 archiveController!.enqueue(archiveBytes.slice(4));
155 archiveController!.close();
156 const installed = yield* Fiber.join(install);
157 assert.deepEqual(progress.slice(-4), [
158 { stage: "download", received: archiveBytes.length, total: archiveBytes.length },
159 { stage: "verify" },
160 { stage: "extract" },
161 { stage: "validate" },
162 ]);
163 assert.equal(yield* fs.readFileString(installed.sentinelPath), `${version}\n`);
164 }),
165 );
166
167 it.effect("cleans up an interrupted download without reporting verification or extraction", () =>
168 Effect.gen(function* () {
169 const fs = yield* FileSystem.FileSystem;
170 const path = yield* Path.Path;
171 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-progress-failed-" });
172 const checksums = yield* validChecksums;
173 const progress: PinnedRuntimeProgress[] = [];
174 let cancelled = false;
175 const client = HttpClient.make((request) =>
176 Effect.succeed(
177 HttpClientResponse.fromWeb(
178 request,
179 request.url.endsWith("/SHA256SUMS")
180 ? new Response(checksums)
181 : new Response(
182 new ReadableStream({
183 start(controller) {
184 controller.enqueue(archiveBytes.slice(0, 4));
185 },
186 cancel() {
187 cancelled = true;
188 },
189 }),
190 ),
191 ),
192 ),
193 );
194 const firstChunk = yield* Deferred.make<void>();
195 const install = yield* ensurePinnedRuntimeInstalled({
196 baseDir,
197 version,
198 fs,
199 path,
200 platform: "linux",
201 arch: "x64",
202 httpClient: client,
203 runner: extractingRunner(fs, path),
204 validate: () => Effect.die("must not validate an interrupted archive"),
205 onProgress: (event) => {
206 progress.push(event);
207 if (event.stage === "download" && event.received === 4)
208 Deferred.doneUnsafe(firstChunk, Effect.void);
209 },
210 }).pipe(Effect.forkScoped);
211 yield* Deferred.await(firstChunk);
212 yield* Fiber.interrupt(install);
213 assert.deepEqual(progress.at(-1), { stage: "download", received: 4, total: undefined });
214 assert.isTrue(progress.every((event) => event.stage === "download"));
215 assert.isTrue(cancelled);
216 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
217 }),
218 );
219
220 it.effect.each([true, false])(
221 "installs a download receiving bytes for over ten minutes (progress: %s)",
222 (reportProgress) =>
223 Effect.gen(function* () {
224 const fs = yield* FileSystem.FileSystem;
225 const path = yield* Path.Path;
226 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-slow-" });
227 const checksums = yield* validChecksums;
228 const reads = yield* Effect.forEach(archiveBytes, () => Deferred.make<void>());
229 let controller: ReadableStreamDefaultController<Uint8Array>;
230 let offset = 0;
231 const body = new ReadableStream<Uint8Array>(
232 {
233 start(value) {
234 controller = value;
235 },
236 pull() {
237 Deferred.doneUnsafe(reads[offset++]!, Effect.void);
238 },
239 },
240 { highWaterMark: 0 },
241 );
242 const client = HttpClient.make((request) =>
243 Effect.succeed(
244 HttpClientResponse.fromWeb(
245 request,
246 new Response(request.url.endsWith("/SHA256SUMS") ? checksums : body),
247 ),
248 ),
249 );
250 const progress: PinnedRuntimeProgress[] = [];
251 yield* Effect.gen(function* () {
252 // Each read is demanded by the consumer, with no prefetched chunks.
253 for (let index = 0; index < archiveBytes.length; index++) {
254 yield* Deferred.await(reads[index]!);
255 yield* TestClock.adjust(Duration.seconds(40));
256 controller.enqueue(archiveBytes.slice(index, index + 1));
257 }
258 controller.close();
259 }).pipe(Effect.forkScoped);
260 const installed = yield* ensurePinnedRuntimeInstalled({
261 baseDir,
262 version,
263 fs,
264 path,
265 platform: "linux",
266 arch: "x64",
267 httpClient: client,
268 runner: extractingRunner(fs, path),
269 validate: () => Effect.void,
270 ...(reportProgress
271 ? { onProgress: (event: PinnedRuntimeProgress) => progress.push(event) }
272 : {}),
273 });
274 assert.equal(yield* fs.readFileString(installed.sentinelPath), `${version}\n`);
275 if (reportProgress) {
276 assert.deepEqual(progress.slice(-4), [
277 { stage: "download", received: archiveBytes.length, total: archiveBytes.length },
278 { stage: "verify" },
279 { stage: "extract" },
280 { stage: "validate" },
281 ]);
282 }
283 }),
284 );
285
286 it.effect.each([
287 { stall: "response", reportProgress: false },
288 { stall: "body", reportProgress: false },
289 { stall: "body", reportProgress: true },
290 ])(
291 "fails a one-minute $stall stall, cleans up and releases the lock (progress: $reportProgress)",
292 ({ stall, reportProgress }) =>
293 Effect.gen(function* () {
294 const fs = yield* FileSystem.FileSystem;
295 const path = yield* Path.Path;
296 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-stalled-" });
297 const checksums = yield* validChecksums;
298 const waiting = yield* Deferred.make<void>();
299 let cancelled = false;
300 let sentChunk = false;
301 const client = HttpClient.make((request) => {
302 if (request.url.endsWith("/SHA256SUMS")) {
303 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(checksums)));
304 }
305 if (stall === "response") {
306 return Deferred.succeed(waiting, undefined).pipe(
307 Effect.andThen(Effect.never),
308 Effect.ensuring(
309 Effect.sync(() => {
310 cancelled = true;
311 }),
312 ),
313 );
314 }
315 return Effect.succeed(
316 HttpClientResponse.fromWeb(
317 request,
318 new Response(
319 new ReadableStream<Uint8Array>(
320 {
321 pull(controller) {
322 if (!sentChunk) {
323 sentChunk = true;
324 controller.enqueue(archiveBytes.slice(0, 4));
325 } else {
326 Deferred.doneUnsafe(waiting, Effect.void);
327 }
328 },
329 cancel() {
330 cancelled = true;
331 },
332 },
333 { highWaterMark: 0 },
334 ),
335 ),
336 ),
337 );
338 });
339 const progress: PinnedRuntimeProgress[] = [];
340 const commands: string[] = [];
341 const install = yield* ensurePinnedRuntimeInstalled({
342 baseDir,
343 version,
344 fs,
345 path,
346 platform: "linux",
347 arch: "x64",
348 httpClient: client,
349 runner: extractingRunner(fs, path, commands),
350 validate: () => Effect.die("must not validate a stalled archive"),
351 ...(reportProgress
352 ? { onProgress: (event: PinnedRuntimeProgress) => progress.push(event) }
353 : {}),
354 }).pipe(Effect.forkScoped);
355 yield* Deferred.await(waiting);
356 yield* TestClock.adjust(Duration.minutes(1));
357 assert.isTrue(cancelled, "the stalled transfer must be cancelled after one minute");
358 const error = yield* Fiber.join(install).pipe(Effect.flip);
359 assert.instanceOf(error, PinnedRuntimeInstallError);
360 assert.equal(error.step, "downloading the t3 release archive (timed out)");
361 assert.deepEqual(commands, []);
362 assert.isTrue(progress.every((event) => event.stage === "download"));
363 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
364 const installed = yield* ensurePinnedRuntimeInstalled({
365 baseDir,
366 version,
367 fs,
368 path,
369 platform: "linux",
370 arch: "x64",
371 httpClient: releaseHttpClient(checksums),
372 runner: extractingRunner(fs, path),
373 validate: () => Effect.void,
374 });
375 assert.equal(yield* fs.readFileString(installed.sentinelPath), `${version}\n`);
376 }),
377 );
378
379 it.effect("refuses an archive whose checksum does not match the release", () =>
380 Effect.gen(function* () {
381 const fs = yield* FileSystem.FileSystem;
382 const path = yield* Path.Path;
383 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-bad-" });
384 const commands: string[] = [];
385 const error = yield* ensurePinnedRuntimeInstalled({
386 baseDir,
387 version,
388 fs,
389 path,
390 platform: "linux",
391 arch: "x64",
392 httpClient: releaseHttpClient(`${"0".repeat(64)} ${archiveName}\n`),
393 runner: extractingRunner(fs, path, commands),
394 validate: () => Effect.die("must not validate an unverified archive"),
395 }).pipe(Effect.flip);
396 assert.instanceOf(error, PinnedRuntimeInstallError);
397 assert.equal(error.step, "verifying the t3 release archive checksum");
398 assert.deepEqual(commands, []);
399 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
400 }),
401 );
402
403 it.effect("validates a staging tree before atomically publishing it", () =>
404 Effect.gen(function* () {
405 const fs = yield* FileSystem.FileSystem;
406 const path = yield* Path.Path;
407 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
408 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
409 let validatedDirectory = "";
410
411 const installed = yield* ensurePinnedRuntimeInstalled({
412 baseDir,
413 version,
414 fs,
415 path,
416 platform: "linux",
417 arch: "x64",
418 httpClient: releaseHttpClient(yield* validChecksums),
419 runner: extractingRunner(fs, path),
420 validate: (staging) =>
421 Effect.gen(function* () {
422 validatedDirectory = staging.versionDir;
423 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
424 assert.isTrue(yield* fs.exists(staging.entryPath));
425 }).pipe(Effect.orDie),
426 });
427
428 assert.notEqual(validatedDirectory, finalPaths.versionDir);
429 assert.deepEqual(installed, finalPaths);
430 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
431 assert.equal(yield* fs.readFileString(finalPaths.sentinelPath), `${version}\n`);
432 }),
433 );
434
435 it.effect("removes staging and leaves no final runtime when validation fails", () =>
436 Effect.gen(function* () {
437 const fs = yield* FileSystem.FileSystem;
438 const path = yield* Path.Path;
439 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
440 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
441
442 yield* ensurePinnedRuntimeInstalled({
443 baseDir,
444 version,
445 fs,
446 path,
447 platform: "linux",
448 arch: "x64",
449 httpClient: releaseHttpClient(yield* validChecksums),
450 runner: extractingRunner(fs, path),
451 validate: () =>
452 Effect.fail(new PinnedRuntimeInstallError({ step: "validating the staged runtime" })),
453 }).pipe(Effect.flip);
454
455 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
456 assert.deepEqual(
457 (yield* fs.readDirectory(path.dirname(finalPaths.versionDir))).filter((entry) =>
458 entry.startsWith(".staging-"),
459 ),
460 [],
461 );
462 }),
463 );
464
465 it.effect("replaces an incomplete pinned runtime", () =>
466 Effect.gen(function* () {
467 const fs = yield* FileSystem.FileSystem;
468 const path = yield* Path.Path;
469 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
470 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
471 yield* fs.makeDirectory(finalPaths.versionDir, { recursive: true });
472 yield* fs.writeFileString(path.join(finalPaths.versionDir, "partial"), "incomplete\n");
473
474 yield* ensurePinnedRuntimeInstalled({
475 baseDir,
476 version,
477 fs,
478 path,
479 platform: "linux",
480 arch: "x64",
481 httpClient: releaseHttpClient(yield* validChecksums),
482 runner: extractingRunner(fs, path),
483 validate: () => Effect.void,
484 });
485
486 assert.isFalse(yield* fs.exists(path.join(finalPaths.versionDir, "partial")));
487 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
488 }),
489 );
490
491 it.effect("preserves a completed runtime when validation fails", () =>
492 Effect.gen(function* () {
493 const fs = yield* FileSystem.FileSystem;
494 const path = yield* Path.Path;
495 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
496 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
497 yield* fs.makeDirectory(path.dirname(finalPaths.entryPath), { recursive: true });
498 yield* fs.writeFileString(finalPaths.entryPath, "broken\n");
499 yield* fs.writeFileString(finalPaths.sentinelPath, `${version}\n`);
500
501 let validations = 0;
502 const requests: string[] = [];
503 yield* ensurePinnedRuntimeInstalled({
504 baseDir,
505 version,
506 fs,
507 path,
508 platform: "linux",
509 arch: "x64",
510 httpClient: releaseHttpClient(yield* validChecksums, requests),
511 runner: extractingRunner(fs, path),
512 validate: (paths) =>
513 Effect.gen(function* () {
514 validations += 1;
515 const source = yield* fs.readFileString(paths.entryPath).pipe(Effect.orDie);
516 if (source === "broken\n") {
517 return yield* new PinnedRuntimeInstallError({ step: "validating the runtime" });
518 }
519 }),
520 }).pipe(Effect.flip);
521
522 assert.equal(validations, 1);
523 assert.deepEqual(requests, []);
524 assert.equal(yield* fs.readFileString(finalPaths.entryPath), "broken\n");
525 }),
526 );
527
528 it.effect("removes staging when installation is interrupted", () =>
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-interrupt-" });
533 const started = yield* Deferred.make<void>();
534 const runner = ProcessRunner.ProcessRunner.of({
535 run: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)),
536 });
537 const install = yield* ensurePinnedRuntimeInstalled({
538 baseDir,
539 version,
540 fs,
541 path,
542 platform: "linux",
543 arch: "x64",
544 httpClient: releaseHttpClient(yield* validChecksums),
545 runner,
546 validate: () => Effect.void,
547 }).pipe(Effect.forkScoped);
548
549 yield* Deferred.await(started);
550 yield* Fiber.interrupt(install);
551 const versionsDir = path.join(baseDir, "runtime", "versions");
552 assert.deepEqual(yield* fs.readDirectory(versionsDir), []);
553 }),
554 );
555});