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/unstable/http";
9import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
10
11import * as ProcessRunner from "../processRunner.ts";
12import {
13 ensurePinnedRuntimeInstalled,
14 pinnedRuntimeCommand,
15 pinnedRuntimePaths,
16 PinnedRuntimeInstallError,
17} from "./pinnedRuntime.ts";
18
19// Every install fetches the release archive, checks it against SHA256SUMS,
20// and unpacks it with tar. The fake client serves both files; the fake runner
21// stands in for tar and drops the executable where extraction would.
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("refuses an archive whose checksum does not match the release", () =>
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-archive-bad-" });
105 const commands: string[] = [];
106 const error = yield* ensurePinnedRuntimeInstalled({
107 baseDir,
108 version,
109 fs,
110 path,
111 platform: "linux",
112 arch: "x64",
113 httpClient: releaseHttpClient(`${"0".repeat(64)} ${archiveName}\n`),
114 runner: extractingRunner(fs, path, commands),
115 validate: () => Effect.die("must not validate an unverified archive"),
116 }).pipe(Effect.flip);
117 assert.instanceOf(error, PinnedRuntimeInstallError);
118 assert.equal(error.step, "verifying the t3 release archive checksum");
119 assert.deepEqual(commands, []);
120 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
121 }),
122 );
123
124 it.effect("validates a staging tree before atomically publishing it", () =>
125 Effect.gen(function* () {
126 const fs = yield* FileSystem.FileSystem;
127 const path = yield* Path.Path;
128 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
129 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
130 let validatedDirectory = "";
131
132 const installed = yield* ensurePinnedRuntimeInstalled({
133 baseDir,
134 version,
135 fs,
136 path,
137 platform: "linux",
138 arch: "x64",
139 httpClient: releaseHttpClient(yield* validChecksums),
140 runner: extractingRunner(fs, path),
141 validate: (staging) =>
142 Effect.gen(function* () {
143 validatedDirectory = staging.versionDir;
144 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
145 assert.isTrue(yield* fs.exists(staging.entryPath));
146 }).pipe(Effect.orDie),
147 });
148
149 assert.notEqual(validatedDirectory, finalPaths.versionDir);
150 assert.deepEqual(installed, finalPaths);
151 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
152 assert.equal(yield* fs.readFileString(finalPaths.sentinelPath), `${version}\n`);
153 }),
154 );
155
156 it.effect("removes staging and leaves no final runtime when validation fails", () =>
157 Effect.gen(function* () {
158 const fs = yield* FileSystem.FileSystem;
159 const path = yield* Path.Path;
160 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
161 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
162
163 yield* ensurePinnedRuntimeInstalled({
164 baseDir,
165 version,
166 fs,
167 path,
168 platform: "linux",
169 arch: "x64",
170 httpClient: releaseHttpClient(yield* validChecksums),
171 runner: extractingRunner(fs, path),
172 validate: () =>
173 Effect.fail(new PinnedRuntimeInstallError({ step: "validating the staged runtime" })),
174 }).pipe(Effect.flip);
175
176 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
177 assert.deepEqual(
178 (yield* fs.readDirectory(path.dirname(finalPaths.versionDir))).filter((entry) =>
179 entry.startsWith(".staging-"),
180 ),
181 [],
182 );
183 }),
184 );
185
186 it.effect("replaces an incomplete pinned runtime", () =>
187 Effect.gen(function* () {
188 const fs = yield* FileSystem.FileSystem;
189 const path = yield* Path.Path;
190 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
191 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
192 yield* fs.makeDirectory(finalPaths.versionDir, { recursive: true });
193 yield* fs.writeFileString(path.join(finalPaths.versionDir, "partial"), "incomplete\n");
194
195 yield* ensurePinnedRuntimeInstalled({
196 baseDir,
197 version,
198 fs,
199 path,
200 platform: "linux",
201 arch: "x64",
202 httpClient: releaseHttpClient(yield* validChecksums),
203 runner: extractingRunner(fs, path),
204 validate: () => Effect.void,
205 });
206
207 assert.isFalse(yield* fs.exists(path.join(finalPaths.versionDir, "partial")));
208 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
209 }),
210 );
211
212 it.effect("preserves a completed runtime when validation fails", () =>
213 Effect.gen(function* () {
214 const fs = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
217 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
218 yield* fs.makeDirectory(path.dirname(finalPaths.entryPath), { recursive: true });
219 yield* fs.writeFileString(finalPaths.entryPath, "broken\n");
220 yield* fs.writeFileString(finalPaths.sentinelPath, `${version}\n`);
221
222 let validations = 0;
223 const requests: string[] = [];
224 yield* ensurePinnedRuntimeInstalled({
225 baseDir,
226 version,
227 fs,
228 path,
229 platform: "linux",
230 arch: "x64",
231 httpClient: releaseHttpClient(yield* validChecksums, requests),
232 runner: extractingRunner(fs, path),
233 validate: (paths) =>
234 Effect.gen(function* () {
235 validations += 1;
236 const source = yield* fs.readFileString(paths.entryPath).pipe(Effect.orDie);
237 if (source === "broken\n") {
238 return yield* new PinnedRuntimeInstallError({ step: "validating the runtime" });
239 }
240 }),
241 }).pipe(Effect.flip);
242
243 assert.equal(validations, 1);
244 assert.deepEqual(requests, []);
245 assert.equal(yield* fs.readFileString(finalPaths.entryPath), "broken\n");
246 }),
247 );
248
249 it.effect("removes staging when installation is interrupted", () =>
250 Effect.gen(function* () {
251 const fs = yield* FileSystem.FileSystem;
252 const path = yield* Path.Path;
253 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-interrupt-" });
254 const started = yield* Deferred.make<void>();
255 const runner = ProcessRunner.ProcessRunner.of({
256 run: () => Deferred.succeed(started, undefined).pipe(Effect.andThen(Effect.never)),
257 });
258 const install = yield* ensurePinnedRuntimeInstalled({
259 baseDir,
260 version,
261 fs,
262 path,
263 platform: "linux",
264 arch: "x64",
265 httpClient: releaseHttpClient(yield* validChecksums),
266 runner,
267 validate: () => Effect.void,
268 }).pipe(Effect.forkScoped);
269
270 yield* Deferred.await(started);
271 yield* Fiber.interrupt(install);
272 const versionsDir = path.join(baseDir, "runtime", "versions");
273 assert.deepEqual(yield* fs.readDirectory(versionsDir), []);
274 }),
275 );
276});