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

pinnedRuntime.test.ts

509 lines20.0 KB

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 ChildProcess from "effect/process/ChildProcess";
12import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13​
14import * as HostProcess from "@t3tools/shared/HostProcess";
15​
16import * as ProcessRunner from "../processRunner.ts";
17import {
18 ensurePinnedRuntimeInstalled,
19 pinnedRuntimeCommand,
20 pinnedRuntimePaths,
21 PinnedRuntimeInstallError,
22 type PinnedRuntimeProgress,
23 prunePinnedRuntimes,
24} from "./pinnedRuntime.ts";
25import { SERVICE_LAUNCHER_PROTOCOL } from "./serviceProtocol.ts";
26​
27const version = "1.2.3";
28const archiveName = `t3-${version}-linux-x64.tar.gz`;
29const archiveBytes = new TextEncoder().encode("not really a tarball");
30const archiveHex = (bytes: Uint8Array) =>
31 Effect.promise(() => crypto.subtle.digest("SHA-256", bytes)).pipe(
32 Effect.map((digest) =>
33 Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""),
34 ),
35 );
36const validChecksums = archiveHex(archiveBytes).pipe(
37 Effect.map((hex) => `${hex} ${archiveName}\n`),
38);
39const releaseHttpClient = (checksums: string, requests: string[] = []) =>
40 HttpClient.make((request) => {
41 requests.push(request.url);
42 const body = request.url.endsWith("/SHA256SUMS") ? checksums : archiveBytes;
43 return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(body)));
44 });
45const extractingRunner = (fs: FileSystem.FileSystem, path: Path.Path, commands: string[] = []) =>
46 ProcessRunner.ProcessRunner.of({
47 run: (input) =>
48 Effect.gen(function* () {
49 commands.push(input.command);
50 const targetIndex = input.args.indexOf("-C");
51 const stagingDir = input.args[targetIndex + 1];
52 if (input.command !== "tar" || stagingDir === undefined) {
53 return yield* Effect.die(`unexpected command ${input.command}`);
54 }
55 yield* fs.writeFileString(path.join(stagingDir, "t3"), "#!/bin/sh\n").pipe(Effect.orDie);
56 return {
57 stdout: "",
58 stderr: "",
59 code: ChildProcessSpawner.ExitCode(0),
60 timedOut: false,
61 stdoutTruncated: false,
62 stderrTruncated: false,
63 stdoutInvalidUtf8: false,
64 stderrInvalidUtf8: false,
65 };
66 }),
67 });
68​
69it.layer(NodeServices.layer)("ensurePinnedRuntimeInstalled", (it) => {
70 it.effect("installs the verified release archive as the runtime executable", () =>
71 Effect.gen(function* () {
72 const fs = yield* FileSystem.FileSystem;
73 const path = yield* Path.Path;
74 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-" });
75 const requests: string[] = [];
76 const commands: string[] = [];
77 const paths = yield* ensurePinnedRuntimeInstalled({
78 baseDir,
79 version,
80 fs,
81 path,
82 platform: "linux",
83 arch: "x64",
84 httpClient: releaseHttpClient(yield* validChecksums, requests),
85 releaseBaseUrl: "https://releases.example/download",
86 runner: extractingRunner(fs, path, commands),
87 validate: (staging) =>
88 fs.exists(staging.entryPath).pipe(
89 Effect.flatMap((exists) => (exists ? Effect.void : Effect.die("missing runtime"))),
90 Effect.orDie,
91 ),
92 });
93 assert.equal(paths.entryPath, path.join(paths.versionDir, "t3"));
94 assert.deepEqual(pinnedRuntimeCommand(paths), { command: paths.entryPath, args: [] });
95 assert.deepEqual(requests, [
96 `https://releases.example/download/v${version}/SHA256SUMS`,
97 `https://releases.example/download/v${version}/${archiveName}`,
98 ]);
99 assert.deepEqual(commands, ["tar"]);
100 assert.equal(yield* fs.readFileString(paths.sentinelPath), `${version}\n`);
101 assert.isFalse(yield* fs.exists(path.join(paths.versionDir, "t3-runtime-archive")));
102 }),
103 );
104​
105 it.effect("cleans up an interrupted download without reporting verification or extraction", () =>
106 Effect.gen(function* () {
107 const fs = yield* FileSystem.FileSystem;
108 const path = yield* Path.Path;
109 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-progress-failed-" });
110 const checksums = yield* validChecksums;
111 const progress: PinnedRuntimeProgress[] = [];
112 let cancelled = false;
113 const client = HttpClient.make((request) =>
114 Effect.succeed(
115 HttpClientResponse.fromWeb(
116 request,
117 request.url.endsWith("/SHA256SUMS")
118 ? new Response(checksums)
119 : new Response(
120 new ReadableStream({
121 start(controller) {
122 controller.enqueue(archiveBytes.slice(0, 4));
123 },
124 cancel() {
125 cancelled = true;
126 },
127 }),
128 ),
129 ),
130 ),
131 );
132 const firstChunk = yield* Deferred.make<void>();
133 const install = yield* ensurePinnedRuntimeInstalled({
134 baseDir,
135 version,
136 fs,
137 path,
138 platform: "linux",
139 arch: "x64",
140 httpClient: client,
141 runner: extractingRunner(fs, path),
142 validate: () => Effect.die("must not validate an interrupted archive"),
143 onProgress: (event) => {
144 progress.push(event);
145 if (event.stage === "download" && event.received === 4)
146 Deferred.doneUnsafe(firstChunk, Effect.void);
147 },
148 }).pipe(Effect.forkScoped);
149 yield* Deferred.await(firstChunk);
150 yield* Fiber.interrupt(install);
151 assert.deepEqual(progress.at(-1), { stage: "download", received: 4, total: undefined });
152 assert.isTrue(progress.every((event) => event.stage === "download"));
153 assert.isTrue(cancelled);
154 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
155 }),
156 );
157​
158 it.effect("refuses an archive whose checksum does not match the release", () =>
159 Effect.gen(function* () {
160 const fs = yield* FileSystem.FileSystem;
161 const path = yield* Path.Path;
162 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-archive-bad-" });
163 const commands: string[] = [];
164 const error = yield* ensurePinnedRuntimeInstalled({
165 baseDir,
166 version,
167 fs,
168 path,
169 platform: "linux",
170 arch: "x64",
171 httpClient: releaseHttpClient(`${"0".repeat(64)} ${archiveName}\n`),
172 runner: extractingRunner(fs, path, commands),
173 validate: () => Effect.die("must not validate an unverified archive"),
174 }).pipe(Effect.flip);
175 assert.instanceOf(error, PinnedRuntimeInstallError);
176 assert.equal(error.step, "verifying the t3 release archive checksum");
177 assert.deepEqual(commands, []);
178 assert.deepEqual(yield* fs.readDirectory(path.join(baseDir, "runtime", "versions")), []);
179 }),
180 );
181​
182 it.effect("validates a staging tree before atomically publishing it", () =>
183 Effect.gen(function* () {
184 const fs = yield* FileSystem.FileSystem;
185 const path = yield* Path.Path;
186 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
187 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
188 let validatedDirectory = "";
189​
190 const installed = yield* ensurePinnedRuntimeInstalled({
191 baseDir,
192 version,
193 fs,
194 path,
195 platform: "linux",
196 arch: "x64",
197 httpClient: releaseHttpClient(yield* validChecksums),
198 runner: extractingRunner(fs, path),
199 validate: (staging) =>
200 Effect.gen(function* () {
201 validatedDirectory = staging.versionDir;
202 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
203 assert.isTrue(yield* fs.exists(staging.entryPath));
204 }).pipe(Effect.orDie),
205 });
206​
207 assert.notEqual(validatedDirectory, finalPaths.versionDir);
208 assert.deepEqual(installed, finalPaths);
209 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
210 assert.equal(yield* fs.readFileString(finalPaths.sentinelPath), `${version}\n`);
211 }),
212 );
213​
214 it.effect("removes staging and leaves no final runtime when validation fails", () =>
215 Effect.gen(function* () {
216 const fs = yield* FileSystem.FileSystem;
217 const path = yield* Path.Path;
218 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-test-" });
219 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
220​
221 yield* ensurePinnedRuntimeInstalled({
222 baseDir,
223 version,
224 fs,
225 path,
226 platform: "linux",
227 arch: "x64",
228 httpClient: releaseHttpClient(yield* validChecksums),
229 runner: extractingRunner(fs, path),
230 validate: () =>
231 Effect.fail(new PinnedRuntimeInstallError({ step: "validating the staged runtime" })),
232 }).pipe(Effect.flip);
233​
234 assert.isFalse(yield* fs.exists(finalPaths.versionDir));
235 assert.deepEqual(
236 (yield* fs.readDirectory(path.dirname(finalPaths.versionDir))).filter((entry) =>
237 entry.startsWith(".staging-"),
238 ),
239 [],
240 );
241 }),
242 );
243​
244 it.effect("replaces an incomplete pinned runtime", () =>
245 Effect.gen(function* () {
246 const fs = yield* FileSystem.FileSystem;
247 const path = yield* Path.Path;
248 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
249 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
250 yield* fs.makeDirectory(finalPaths.versionDir, { recursive: true });
251 yield* fs.writeFileString(path.join(finalPaths.versionDir, "partial"), "incomplete\n");
252​
253 yield* ensurePinnedRuntimeInstalled({
254 baseDir,
255 version,
256 fs,
257 path,
258 platform: "linux",
259 arch: "x64",
260 httpClient: releaseHttpClient(yield* validChecksums),
261 runner: extractingRunner(fs, path),
262 validate: () => Effect.void,
263 });
264​
265 assert.isFalse(yield* fs.exists(path.join(finalPaths.versionDir, "partial")));
266 assert.isTrue(yield* fs.exists(finalPaths.entryPath));
267 }),
268 );
269​
270 it.effect("preserves a completed runtime when validation fails", () =>
271 Effect.gen(function* () {
272 const fs = yield* FileSystem.FileSystem;
273 const path = yield* Path.Path;
274 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-runtime-repair-" });
275 const finalPaths = pinnedRuntimePaths(path, baseDir, version, "linux");
276 yield* fs.makeDirectory(path.dirname(finalPaths.entryPath), { recursive: true });
277 yield* fs.writeFileString(finalPaths.entryPath, "broken\n");
278 yield* fs.writeFileString(finalPaths.sentinelPath, `${version}\n`);
279​
280 let validations = 0;
281 const requests: string[] = [];
282 yield* ensurePinnedRuntimeInstalled({
283 baseDir,
284 version,
285 fs,
286 path,
287 platform: "linux",
288 arch: "x64",
289 httpClient: releaseHttpClient(yield* validChecksums, requests),
290 runner: extractingRunner(fs, path),
291 validate: (paths) =>
292 Effect.gen(function* () {
293 validations += 1;
294 const source = yield* fs.readFileString(paths.entryPath).pipe(Effect.orDie);
295 if (source === "broken\n") {
296 return yield* new PinnedRuntimeInstallError({ step: "validating the runtime" });
297 }
298 }),
299 }).pipe(Effect.flip);
300​
301 assert.equal(validations, 1);
302 assert.deepEqual(requests, []);
303 assert.equal(yield* fs.readFileString(finalPaths.entryPath), "broken\n");
304 }),
305 );
306});
307​
308it.layer(NodeServices.layer)("prunePinnedRuntimes", (it) => {
309 const lsofRunner = (stdout: string) =>
310 ProcessRunner.ProcessRunner.of({
311 run: () =>
312 Effect.succeed({
313 stdout,
314 stderr: "",
315 code: ChildProcessSpawner.ExitCode(0),
316 timedOut: false,
317 stdoutTruncated: false,
318 stderrTruncated: false,
319 stdoutInvalidUtf8: false,
320 stderrInvalidUtf8: false,
321 }),
322 });
323​
324 const setup = Effect.fn(function* (versions: ReadonlyArray<string>) {
325 const fs = yield* FileSystem.FileSystem;
326 const path = yield* Path.Path;
327 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-pinned-prune-" });
328 const versionsDir = path.join(baseDir, "runtime", "versions");
329 const now = Duration.toMillis(Duration.days(1));
330 yield* TestClock.setTime(now);
331 const install = Effect.fn(function* (
332 version: string,
333 completed: "long ago" | "just now" | "never" = "long ago",
334 ) {
335 const directory = path.join(versionsDir, version);
336 yield* fs.makeDirectory(directory, { recursive: true });
337 yield* fs.writeFileString(path.join(directory, "t3"), "");
338 if (completed === "never") return;
339 const sentinel = path.join(directory, ".install-complete");
340 yield* fs.writeFileString(sentinel, `${version}\n`);
341 const at = completed === "just now" ? now : 0;
342 yield* fs.utimes(sentinel, at, at);
343 });
344 for (const version of versions) yield* install(version);
345 return { baseDir, versionsDir, install };
346 });
347​
348 it.effect("removes only completed runtimes nothing references", () =>
349 Effect.gen(function* () {
350 const fs = yield* FileSystem.FileSystem;
351 const path = yield* Path.Path;
352 const { baseDir, versionsDir, install } = yield* setup([
353 "1.0.0",
354 "1.1.0",
355 "1.2.0",
356 "1.2.5",
357 "1.3.0",
358 "1.3.5",
359 "1.4.0",
360 "1.5.0",
361 "2.0.0",
362 "2.1.0",
363 ]);
364 // A downgrade another process installed but has not pointed anything at yet.
365 yield* install("0.5.0", "just now");
366 yield* install("1.0.1", "never");
367 yield* install(".staging-abc", "never");
368 yield* install(".pruned-0.8.0");
369 yield* install("other", "never");
370 yield* fs.symlink(path.join(versionsDir, "other"), path.join(versionsDir, "0.9.0"));
371 const binDir = path.join(baseDir, "bin");
372 const customBinDir = path.join(baseDir, "custom-bin");
373 yield* fs.makeDirectory(binDir);
374 yield* fs.makeDirectory(customBinDir);
375 // Chained: the launcher reaches its runtime through a second link.
376 yield* fs.symlink(path.join(versionsDir, "1.2.0", "t3"), path.join(baseDir, "alias-t3"));
377 yield* fs.symlink(path.join(baseDir, "alias-t3"), path.join(binDir, "t3"));
378 yield* fs.symlink(path.join(versionsDir, "1.2.5", "t3"), path.join(customBinDir, "t3"));
379 yield* fs.writeFileString(
380 path.join(baseDir, "runtime", "launchers"),
381 `${path.join(customBinDir, "t3")}\n`,
382 );
383 yield* fs.writeFileString(
384 path.join(baseDir, "runtime", "service-state.json"),
385 JSON.stringify({
386 protocol: SERVICE_LAUNCHER_PROTOCOL,
387 activeVersion: "1.4.0",
388 update: { id: "u", fromVersion: "1.4.0", targetVersion: "1.5.0", status: "rolled-back" },
389 }),
390 );
391​
392 const removed = yield* prunePinnedRuntimes({
393 baseDir,
394 keep: ["2.0.0"],
395 references: [`ExecStart=${path.join(versionsDir, "1.3.5", "t3")} __service-launcher`],
396 }).pipe(
397 Effect.provideService(
398 ProcessRunner.ProcessRunner,
399 lsofRunner(`p42\nftxt\nn${path.join(versionsDir, "1.3.0", "t3")}\n`),
400 ),
401 Effect.provideService(HostProcess.Platform, "darwin"),
402 Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: binDir }),
403 );
404​
405 // 1.2.0 is the default launcher, 1.2.5 a recorded one, 1.3.0 running, 1.3.5 in the unit,
406 // 1.4.0 active, 1.5.0 the rolled-back target, 2.0.0 the caller's, 0.5.0 just installed.
407 // Being newer than the caller's version does not keep 2.1.0.
408 assert.deepEqual(removed.toSorted(), ["0.8.0", "1.0.0", "1.1.0", "2.1.0"]);
409 // The launcher found on PATH is remembered for a service that cannot see it.
410 assert.equal(
411 yield* fs.readFileString(path.join(baseDir, "runtime", "launchers")),
412 `${path.join(customBinDir, "t3")}\n${path.join(binDir, "t3")}\n`,
413 );
414 assert.deepEqual((yield* fs.readDirectory(versionsDir)).toSorted(), [
415 ".staging-abc",
416 "0.5.0",
417 "0.9.0",
418 "1.0.1",
419 "1.2.0",
420 "1.2.5",
421 "1.3.0",
422 "1.3.5",
423 "1.4.0",
424 "1.5.0",
425 "2.0.0",
426 "other",
427 ]);
428 }),
429 );
430​
431 it.effect("matches a Windows shim whatever its casing", () =>
432 Effect.gen(function* () {
433 const fs = yield* FileSystem.FileSystem;
434 const path = yield* Path.Path;
435 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
436 const shim = path.join(baseDir, "t3.cmd");
437 yield* fs.writeFileString(
438 shim,
439 `@echo off\r\n"${path.join(versionsDir, "1.0.0", "t3.exe").toUpperCase()}" %*`,
440 );
441 yield* fs.writeFileString(path.join(baseDir, "runtime", "launchers"), `${shim}\n`);
442​
443 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
444 Effect.provideService(
445 ProcessRunner.ProcessRunner,
446 lsofRunner("C:\\Windows\\explorer.exe\n"),
447 ),
448 Effect.provideService(HostProcess.Platform, "win32"),
449 Effect.provideService(HostProcess.Environment, {}),
450 );
451 assert.deepEqual(removed, ["1.1.0"]);
452 }),
453 );
454​
455 it.effect.each([
456 { name: "the process list is unavailable", state: undefined, lsof: "" },
457 { name: "the service state is unparseable", state: "{", lsof: "p1\nftxt\nn/sbin/launchd\n" },
458 {
459 name: "the service state cannot be read",
460 state: null,
461 lsof: "p1\nftxt\nn/sbin/launchd\n",
462 },
463 ])("keeps everything when $name", ({ state, lsof }) =>
464 Effect.gen(function* () {
465 const fs = yield* FileSystem.FileSystem;
466 const path = yield* Path.Path;
467 const { baseDir, versionsDir } = yield* setup(["1.0.0"]);
468 const statePath = path.join(baseDir, "runtime", "service-state.json");
469 if (state === null) yield* fs.makeDirectory(statePath);
470 else if (state !== undefined) yield* fs.writeFileString(statePath, state);
471​
472 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
473 Effect.provideService(ProcessRunner.ProcessRunner, lsofRunner(lsof)),
474 Effect.provideService(HostProcess.Platform, "darwin"),
475 Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: baseDir }),
476 );
477 assert.deepEqual(removed, []);
478 assert.deepEqual(yield* fs.readDirectory(versionsDir), ["1.0.0"]);
479 }),
480 );
481​
482 it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
483 "keeps a runtime a process runs through a symlink",
484 () =>
485 Effect.gen(function* () {
486 const fs = yield* FileSystem.FileSystem;
487 const path = yield* Path.Path;
488 const { baseDir, versionsDir } = yield* setup(["1.0.0", "1.1.0"]);
489 const entry = path.join(versionsDir, "1.0.0", "t3");
490 // Multicall coreutils (Ubuntu's uutils) refuse to run renamed, so copy Node instead.
491 yield* fs.copyFile(process.execPath, entry);
492 yield* fs.chmod(entry, 0o755);
493 const link = path.join(baseDir, "t3");
494 yield* fs.symlink(entry, link);
495 // Its argv names only the link, as with `t3 serve` run from PATH. Removing the link after
496 // spawning leaves the process's executable as the only reference.
497 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
498 yield* spawner.spawn(ChildProcess.make(link, ["-e", "setTimeout(() => {}, 30_000)"]));
499 yield* fs.remove(link);
500​
501 const removed = yield* prunePinnedRuntimes({ baseDir, keep: ["2.0.0"] }).pipe(
502 Effect.provideService(HostProcess.Platform, "linux"),
503 Effect.provideService(HostProcess.Environment, { T3CODE_INSTALL_BIN_DIR: baseDir }),
504 Effect.provide(ProcessRunner.layer),
505 );
506 assert.deepEqual(removed, ["1.1.0"]);
507 }),
508 );
509});