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 Effect from "effect/Effect";
5import * as FileSystem from "effect/FileSystem";
6import * as Fiber from "effect/Fiber";
7import * as Path from "effect/Path";
8import { HttpClient, HttpClientResponse } from "effect/http";
9import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
10
11import * as ProcessRunner from "../processRunner.ts";
12import {
13 ensurePinnedRuntimeInstalled,
14 pinnedRuntimeCommand,
15 pinnedRuntimePaths,
16 PinnedRuntimeInstallError,
17 type PinnedRuntimeProgress,
18} from "./pinnedRuntime.ts";
19
20const version = "1.2.3";
21const archiveName = `t3-${version}-linux-x64.tar.gz`;
22const archiveBytes = new TextEncoder().encode("not really a tarball");
23const archiveHex = (bytes: Uint8Array) =>
24 Effect.promise(() => crypto.subtle.digest("SHA-256", bytes)).pipe(
25 Effect.map((digest) =>
26 Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""),
27 ),
28 );
29const validChecksums = archiveHex(archiveBytes).pipe(
30 Effect.map((hex) => `${hex} ${archiveName}\n`),
31);
32const releaseHttpClient = (checksums: string, requests: string[] = []) =>
33 HttpClient.make((request) => {
34 requests.push(request.url);
35 const body = request.url.endsWith("/SHA256SUMS") ? checksums : archiveBytes;
36 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body)));
37 });
38const extractingRunner = (fs: FileSystem.FileSystem, path: Path.Path, commands: string[] = []) =>
39 ProcessRunner.ProcessRunner.of({
40 run: (input) =>
41 Effect.gen(function* () {
42 commands.push(input.command);
43 const targetIndex = input.args.indexOf("-C");
44 const stagingDir = input.args[targetIndex + 1];
45 if (input.command !== "tar" || stagingDir === undefined) {
46 return yield* Effect.die(`unexpected command ${input.command}`);
47 }
48 yield* fs.writeFileString(path.join(stagingDir, "t3"), "#!/bin/sh\n").pipe(Effect.orDie);
49 return {
50 stdout: "",
51 stderr: "",
52 code: ChildProcessSpawner.ExitCode(0),
53 timedOut: false,
54 stdoutTruncated: false,
55 stderrTruncated: false,
56 stdoutInvalidUtf8: false,
57 stderrInvalidUtf8: false,
58 };
59 }),
60 });
61
62it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
63 it.effect("installs the verified release archive as the runtime executable", () =>
64 Effect.gen(function* () {
65 const fs = yield* FileSystem.FileSystem;
66 const path = yield* Path.Path;
67 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-" });
68 const requests: string[] = [];
69 const commands: string[] = [];
70 const paths = yield* ensurePinnedRuntimeInstalled({
71 baseDir,
72 version,
73 fs,
74 path,
75 platform: "linux",
76 arch: "x64",
77 httpClient: releaseHttpClient(yield* validChecksums, requests),
78 releaseBaseUrl: "https://releases.example/download",
79 runner: extractingRunner(fs, path, commands),
80 validate: (staging) =>
81 fs.exists(staging.entryPath).pipe(
82 Effect.flatMap((exists) => (exists ? Effect.void : Effect.die("missing runtime"))),
83 Effect.orDie,
84 ),
85 });
86 assert.equal(paths.entryPath, path.join(paths.versionDir, "t3"));
87 assert.deepEqual(pinnedRuntimeCommand(paths), { command: paths.entryPath, args: [] });
88 assert.deepEqual(requests, [
89 `https://releases.example/download/v${version}/SHA256SUMS`,
90 `https://releases.example/download/v${version}/${archiveName}`,
91 ]);
92 assert.deepEqual(commands, ["tar"]);
93 assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`);
94 assert.isFalse(yield* fs.exists(path.join(paths.versionDir, "t3-runtime-archive")));
95 }),
96 );
97
98 it.effect.each([true, false])(
99 "reports bytes before completion, then verifies and extracts (known size: %s)",
100 (knownSize) =>
101 Effect.gen(function* () {
102 const fs = yield* FileSystem.FileSystem;
103 const path = yield* Path.Path;
104 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-progress-" });
105 const firstChunk = yield* Deferred.make<void>();
106 let archiveController: ReadableStreamDefaultController<Uint8Array> | undefined;
107 const checksums = yield* validChecksums;
108 const progress: PinnedRuntimeProgress[] = [];
109 const client = HttpClient.make((request) =>
110 Effect.succeed(
111 HttpClientResponse.fromWeb(
112 request,
113 request.url.endsWith("/SHA256SUMS")
114 ? new Response(checksums)
115 : new Response(
116 new ReadableStream({
117 start(controller) {
118 archiveController = controller;
119 controller.enqueue(archiveBytes.slice(0, 4));
120 },
121 }),
122 { headers: knownSize ? { "content-length": String(archiveBytes.length) } : {} },
123 ),
124 ),
125 ),
126 );
127 const install = yield* ensurePinnedRuntimeInstalled({
128 baseDir,
129 version,
130 fs,
131 path,
132 platform: "linux",
133 arch: "x64",
134 httpClient: client,
135 runner: extractingRunner(fs, path),
136 validate: () => Effect.void,
137 onProgress: (event) => {
138 progress.push(event);
139 if (event.stage === "download" && event.received === 4) {
140 Deferred.doneUnsafe(firstChunk, Effect.void);
141 }
142 },
143 }).pipe(Effect.forkScoped);
144 yield* Deferred.await(firstChunk);
145 assert.deepEqual(progress.at(-1), {
146 stage: "download",
147 received: 4,
148 total: knownSize ? archiveBytes.length : undefined,
149 });
150 assert.isFalse(progress.some((event) => event.stage === "extract"));
151 assert.isDefined(archiveController);
152 archiveController!.enqueue(archiveBytes.slice(4));
153 archiveController!.close();
154 const installed = yield* Fiber.join(install);
155 assert.deepEqual(progress.slice(-4), [
156 { stage: "download", received: archiveBytes.length, total: archiveBytes.length },
157 { stage: "verify" },
158 { stage: "extract" },
159 { stage: "validate" },
160 ]);
161 assert.equal(yield* fs.readFileString(installed.sentinelPath), `${version}\n`);
162 }),
163 );
164
165 it.effect("cleans up an interrupted download without reporting verification or extraction", () =>
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-progress-failed-" });
170 const checksums = yield* validChecksums;
171 const progress: PinnedRuntimeProgress[] = [];
172 let cancelled = false;
173 const client = HttpClient.make((request) =>
174 Effect.succeed(
175 HttpClientResponse.fromWeb(
176 request,
177 request.url.endsWith("/SHA256SUMS")
178 ? new Response(checksums)
179 : new Response(
180 new ReadableStream({
181 start(controller) {
182 controller.enqueue(archiveBytes.slice(0, 4));
183 },
184 cancel() {
185 cancelled = true;
186 },
187 }),
188 ),
189 ),
190 ),
191 );
192 const firstChunk = yield* Deferred.make<void>();
193 const install = yield* ensurePinnedRuntimeInstalled({
194 baseDir,
195 version,
196 fs,
197 path,
198 platform: "linux",
199 arch: "x64",
200 httpClient: client,
201 runner: extractingRunner(fs, path),
202 validate: () => Effect.die("must not validate an interrupted archive"),
203 onProgress: (event) => {
204 progress.push(event);
205 if (event.stage === "download" && event.received === 4)
206 Deferred.doneUnsafe(firstChunk, Effect.void);
207 },
208 }).pipe(Effect.forkScoped);
209 yield* Deferred.await(firstChunk);
210 yield* Fiber.interrupt(install);
211 assert.deepEqual(progress.at(-1), { stage: "download", received: 4, total: undefined });
212 assert.isTrue(progress.every((event) => event.stage === "download"));
213 assert.isTrue(cancelled);
214 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
215 }),
216 );
217
218 it.effect("refuses an archive whose checksum does not match the release", () =>
219 Effect.gen(function* () {
220 const fs = yield* FileSystem.FileSystem;
221 const path = yield* Path.Path;
222 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-bad-" });
223 const commands: string[] = [];
224 const error = yield* ensurePinnedRuntimeInstalled({
225 baseDir,
226 version,
227 fs,
228 path,
229 platform: "linux",
230 arch: "x64",
231 httpClient: releaseHttpClient(`${"0".repeat(64)} ${archiveName}\n`),
232 runner: extractingRunner(fs, path, commands),
233 validate: () => Effect.die("must not validate an unverified archive"),
234 }).pipe(Effect.flip);
235 assert.instanceOf(error, PinnedRuntimeInstallError);
236 assert.equal(error.step, "verifying the t3 release archive checksum");
237 assert.deepEqual(commands, []);
238 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
239 }),
240 );
241
242 it.effect("validates a staging tree before atomically publishing it", () =>
243 Effect.gen(function* () {
244 const fs = yield* FileSystem.FileSystem;
245 const path = yield* Path.Path;
246 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
247 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
248 let validatedDirectory = "";
249
250 const installed = yield* ensurePinnedRuntimeInstalled({
251 baseDir,
252 version,
253 fs,
254 path,
255 platform: "linux",
256 arch: "x64",
257 httpClient: releaseHttpClient(yield* validChecksums),
258 runner: extractingRunner(fs, path),
259 validate: (staging) =>
260 Effect.gen(function* () {
261 validatedDirectory = staging.versionDir;
262 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
263 assert.isTrue(yield* fs.exists(staging.entryPath));
264 }).pipe(Effect.orDie),
265 });
266
267 assert.notEqual(validatedDirectory, finalPaths.versionDir);
268 assert.deepEqual(installed, finalPaths);
269 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
270 assert.equal(yield* fs.readFileString(finalPaths.sentinelPath), `${version}\n`);
271 }),
272 );
273
274 it.effect("removes staging and leaves no final runtime when validation fails", () =>
275 Effect.gen(function* () {
276 const fs = yield* FileSystem.FileSystem;
277 const path = yield* Path.Path;
278 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
279 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
280
281 yield* ensurePinnedRuntimeInstalled({
282 baseDir,
283 version,
284 fs,
285 path,
286 platform: "linux",
287 arch: "x64",
288 httpClient: releaseHttpClient(yield* validChecksums),
289 runner: extractingRunner(fs, path),
290 validate: () =>
291 Effect.fail(new PinnedRuntimeInstallError({ step: "validating the staged runtime" })),
292 }).pipe(Effect.flip);
293
294 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
295 assert.deepEqual(
296 (yield* fs.readDirectory(path.dirname(finalPaths.versionDir))).filter((entry) =>
297 entry.startsWith(".staging-"),
298 ),
299 [],
300 );
301 }),
302 );
303
304 it.effect("replaces an incomplete pinned runtime", () =>
305 Effect.gen(function* () {
306 const fs = yield* FileSystem.FileSystem;
307 const path = yield* Path.Path;
308 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
309 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
310 yield* fs.makeDirectory(finalPaths.versionDir, { recursive: true });
311 yield* fs.writeFileString(path.join(finalPaths.versionDir, "partial"), "incomplete\n");
312
313 yield* ensurePinnedRuntimeInstalled({
314 baseDir,
315 version,
316 fs,
317 path,
318 platform: "linux",
319 arch: "x64",
320 httpClient: releaseHttpClient(yield* validChecksums),
321 runner: extractingRunner(fs, path),
322 validate: () => Effect.void,
323 });
324
325 assert.isFalse(yield* fs.exists(path.join(finalPaths.versionDir, "partial")));
326 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
327 }),
328 );
329
330 it.effect("preserves a completed runtime when validation fails", () =>
331 Effect.gen(function* () {
332 const fs = yield* FileSystem.FileSystem;
333 const path = yield* Path.Path;
334 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
335 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
336 yield* fs.makeDirectory(path.dirname(finalPaths.entryPath), { recursive: true });
337 yield* fs.writeFileString(finalPaths.entryPath, "broken\n");
338 yield* fs.writeFileString(finalPaths.sentinelPath, `${version}\n`);
339
340 let validations = 0;
341 const requests: string[] = [];
342 yield* ensurePinnedRuntimeInstalled({
343 baseDir,
344 version,
345 fs,
346 path,
347 platform: "linux",
348 arch: "x64",
349 httpClient: releaseHttpClient(yield* validChecksums, requests),
350 runner: extractingRunner(fs, path),
351 validate: (paths) =>
352 Effect.gen(function* () {
353 validations += 1;
354 const source = yield* fs.readFileString(paths.entryPath).pipe(Effect.orDie);
355 if (source === "broken\n") {
356 return yield* new PinnedRuntimeInstallError({ step: "validating the runtime" });
357 }
358 }),
359 }).pipe(Effect.flip);
360
361 assert.equal(validations, 1);
362 assert.deepEqual(requests, []);
363 assert.equal(yield* fs.readFileString(finalPaths.entryPath), "broken\n");
364 }),
365 );
366
367 it.effect("removes staging when installation is interrupted", () =>
368 Effect.gen(function* () {
369 const fs = yield* FileSystem.FileSystem;
370 const path = yield* Path.Path;
371 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-interrupt-" });
372 const started = yield* Deferred.make<void>();
373 const runner = ProcessRunner.ProcessRunner.of({
374 run: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)),
375 });
376 const install = yield* ensurePinnedRuntimeInstalled({
377 baseDir,
378 version,
379 fs,
380 path,
381 platform: "linux",
382 arch: "x64",
383 httpClient: releaseHttpClient(yield* validChecksums),
384 runner,
385 validate: () => Effect.void,
386 }).pipe(Effect.forkScoped);
387
388 yield* Deferred.await(started);
389 yield* Fiber.interrupt(install);
390 const versionsDir = path.join(baseDir, "runtime", "versions");
391 assert.deepEqual(yield* fs.readDirectory(versionsDir), []);
392 }),
393 );
394});