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

build-npm-launcher.test.ts

323 lines13.0 KB

1// @effect-diagnostics nodeBuiltinImport:off - Serves a fake GitHub Release over real HTTP to the published launcher.
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { assert, it } from "@effect/vitest";
4import * as HostProcess from "@t3tools/shared/HostProcess";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as Schema from "effect/Schema";
9import * as Stream from "effect/Stream";
10import { ChildProcess, ChildProcessSpawner } from "effect/process";
11import * as NodeChildProcess from "node:child_process";
12import * as NodeCrypto from "node:crypto";
13import * as NodeEvents from "node:events";
14import * as NodeHttp from "node:http";
15​
16import { npmReleaseDatabaseMigration } from "@t3tools/shared/cliRelease";
17​
18import { buildNpmLauncher } from "./build-npm-launcher.ts";
19​
20const VERSION = "1.2.3";
21const decodeManifest = Schema.decodeEffect(
22 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
23);
24​
25const collect = <E>(stream: Stream.Stream<Uint8Array, E>) =>
26 stream.pipe(
27 Stream.decodeText(),
28 Stream.runFold(
29 () => "",
30 (acc, chunk) => acc + chunk,
31 ),
32 );
33​
34const run = Effect.fn("test.run")(function* (
35 command: string,
36 args: ReadonlyArray<string>,
37 options: { readonly cwd: string; readonly env: Record<string, string | undefined> },
38) {
39 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
40 const child = yield* spawner.spawn(
41 ChildProcess.make(command, args, { cwd: options.cwd, env: options.env, extendEnv: false }),
42 );
43 const [stdout, stderr, exitCode] = yield* Effect.all(
44 [collect(child.stdout), collect(child.stderr), child.exitCode.pipe(Effect.map(Number))],
45 { concurrency: "unbounded" },
46 );
47 return { stdout, stderr, exitCode };
48}, Effect.scoped);
49​
50const serveFakeRelease = Effect.fn("test.serveFakeRelease")(function* (root: string) {
51 const fs = yield* FileSystem.FileSystem;
52 const path = yield* Path.Path;
53 const key = `${yield* HostProcess.Platform}-${yield* HostProcess.Architecture}`;
54 const stem = `t3-${VERSION}-${key}`;
55 const archiveName = `${stem}.tar.gz`;
56 yield* fs.makeDirectory(path.join(root, "release", stem, "node_modules/native"), {
57 recursive: true,
58 });
59 yield* fs.writeFileString(
60 path.join(root, "release", stem, "t3"),
61 '#!/bin/sh\necho "stub $* launcher=$T3CODE_NPM_LAUNCHER_PATH"\nexit 7\n',
62 );
63 yield* fs.chmod(path.join(root, "release", stem, "t3"), 0o755);
64 const tar = yield* run("tar", ["-czf", archiveName, stem], {
65 cwd: path.join(root, "release"),
66 env: { PATH: process.env.PATH },
67 });
68 assert.equal(tar.exitCode, 0, tar.stderr);
69 const archive = yield* fs.readFile(path.join(root, "release", archiveName));
70 let checksum = NodeCrypto.createHash("sha256").update(archive).digest("hex");
71 const requests: Array<string> = [];
72 const server = NodeHttp.createServer((request, response) => {
73 requests.push(request.url ?? "");
74 if (request.url === `/v${VERSION}/SHA256SUMS`) {
75 response.end(`${checksum} ${archiveName}\n`);
76 } else if (request.url === `/v${VERSION}/${archiveName}`) {
77 response.writeHead(200, { "Content-Length": archive.length }).end(archive);
78 } else {
79 response.writeHead(404).end();
80 }
81 });
82 yield* Effect.acquireRelease(
83 Effect.callback<void>((resume) => {
84 server.listen(0, "127.0.0.1", () => resume(Effect.void));
85 }),
86 () =>
87 Effect.callback<void>((resume) => {
88 server.close(() => resume(Effect.void));
89 }),
90 );
91 const address = server.address();
92 if (address === null || typeof address === "string") return yield* Effect.die("no TCP address");
93 return {
94 baseUrl: `http://127.0.0.1:${address.port}`,
95 requests,
96 corruptChecksum: () => {
97 checksum = "0".repeat(64);
98 },
99 };
100});
101​
102it.layer(NodeServices.layer)("build-npm-launcher", (it) => {
103 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
104 "publishes a launcher that downloads, verifies, caches, and runs the release executable",
105 () =>
106 Effect.gen(function* () {
107 const fs = yield* FileSystem.FileSystem;
108 const path = yield* Path.Path;
109 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" });
110 const output = yield* buildNpmLauncher({
111 version: VERSION,
112 outputDir: path.join(root, "out"),
113 });
114​
115 const manifest = yield* decodeManifest(
116 yield* fs.readFileString(path.join(output.packageDir, "package.json")),
117 );
118 assert.equal(manifest.name, "t3");
119 assert.equal(manifest.version, VERSION);
120 assert.deepStrictEqual(manifest.bin, { t3: "./bin/t3.mjs" });
121 assert.isUndefined(manifest.dependencies);
122 assert.isUndefined(manifest.optionalDependencies);
123 assert.isAbove(npmReleaseDatabaseMigration(manifest) ?? 0, 0);
124​
125 const installed = path.join(root, "installed");
126 yield* fs.makeDirectory(installed);
127 const unpack = yield* run("tar", ["-xzf", output.tarball, "-C", installed], {
128 cwd: root,
129 env: { PATH: process.env.PATH },
130 });
131 assert.equal(unpack.exitCode, 0, unpack.stderr);
132 const packageDir = path.join(installed, "package");
133​
134 const release = yield* serveFakeRelease(root);
135 const home = path.join(root, "home");
136 const env = {
137 PATH: process.env.PATH,
138 T3CODE_HOME: home,
139 T3CODE_RELEASE_BASE_URL: release.baseUrl,
140 };
141 const launcher = path.join(packageDir, "bin/t3.mjs");
142 const first = yield* run(process.execPath, [launcher, "serve", "a b"], {
143 cwd: root,
144 env,
145 });
146 assert.equal(first.stdout.trim(), `stub serve a b launcher=${launcher}`, first.stderr);
147 assert.equal(first.exitCode, 7);
148 const versionDir = path.join(home, "runtime/versions", VERSION);
149 assert.equal(
150 (yield* fs.readFileString(path.join(versionDir, ".install-complete"))).trim(),
151 VERSION,
152 );
153 assert.isTrue(yield* fs.exists(path.join(versionDir, "node_modules/native")));
154 assert.deepStrictEqual(
155 (yield* fs.readDirectory(path.join(home, "runtime/versions"))).sort(),
156 [VERSION],
157 );
158​
159 const requestsAfterFirst = release.requests.length;
160 const second = yield* run(process.execPath, [launcher, "--version"], { cwd: root, env });
161 assert.equal(second.exitCode, 7);
162 assert.equal(release.requests.length, requestsAfterFirst);
163​
164 const ipcServer = path.join(home, "runtime/versions", VERSION, "t3");
165 yield* fs.writeFileString(
166 ipcServer,
167 `#!${process.execPath}\nprocess.on("SIGTERM", () => process.exit(23));\nprocess.on("message", (m) => process.send({ reply: m }));\nprocess.send({ args: process.argv.slice(2) });\n`,
168 );
169 const legacy = NodeChildProcess.fork(
170 path.join(packageDir, "dist/bin.mjs"),
171 ["__service-preflight", "a b"],
172 { env, silent: true },
173 );
174 yield* Effect.promise(async () => {
175 assert.deepStrictEqual((await NodeEvents.EventEmitter.once(legacy, "message"))[0], {
176 args: ["__service-preflight", "a b"],
177 });
178 const reply = NodeEvents.EventEmitter.once(legacy, "message");
179 legacy.send({ type: "trial-accepted" });
180 assert.deepStrictEqual((await reply)[0], { reply: { type: "trial-accepted" } });
181 const exit = NodeEvents.EventEmitter.once(legacy, "exit");
182 legacy.kill("SIGTERM");
183 assert.deepStrictEqual(await exit, [23, null]);
184 });
185​
186 const raceHome = path.join(root, "race-home");
187 const launch = run(process.execPath, [launcher, "--version"], {
188 cwd: root,
189 env: { ...env, T3CODE_HOME: raceHome },
190 });
191 const [one, two] = yield* Effect.all([launch, launch], { concurrency: "unbounded" });
192 assert.equal(one.exitCode, 7, one.stderr);
193 assert.equal(two.exitCode, 7, two.stderr);
194 assert.deepStrictEqual(yield* fs.readDirectory(path.join(raceHome, "runtime/versions")), [
195 VERSION,
196 ]);
197​
198 // A peer's executable and sidecar stay available after every later rename or removal,
199 // even when it publishes after our missing-marker read.
200 const staleHome = path.join(root, "stale-home");
201 const staleDir = path.join(staleHome, "runtime/versions", VERSION);
202 const peerDir = path.join(root, "peer-runtime");
203 yield* fs.makeDirectory(staleDir, { recursive: true });
204 yield* fs.writeFileString(path.join(staleDir, "t3"), "");
205 yield* fs.makeDirectory(peerDir);
206 yield* fs.writeFileString(path.join(peerDir, "t3"), '#!/bin/sh\necho "peer $*"\nexit 7\n');
207 yield* fs.chmod(path.join(peerDir, "t3"), 0o755);
208 yield* fs.writeFileString(path.join(peerDir, ".install-complete"), `${VERSION}\n`);
209 yield* fs.writeFileString(path.join(peerDir, "sidecar"), "peer sidecar");
210 const peerChecks = path.join(root, "peer-checks.txt");
211 // The peer publishes after the launcher's rename fails and it reads the marker.
212 const peerHook = path.join(root, "peer-publishes.mjs");
213 yield* fs.writeFileString(
214 peerHook,
215 `import fs from "node:fs";
216import { spawnSync } from "node:child_process";
217const dir = ${JSON.stringify(staleDir)};
218const { readFileSync, renameSync, rmSync } = fs;
219let checking = false;
220let published = false;
221const checkPeer = () => {
222 const child = spawnSync(dir + "/t3", ["--version"], { encoding: "utf8" });
223 let sidecar;
224 try {
225 sidecar = readFileSync(dir + "/sidecar", "utf8");
226 } catch (error) {
227 sidecar = error.code;
228 }
229 fs.appendFileSync(${JSON.stringify(peerChecks)},
230 [child.status, child.error?.code ?? child.stdout.trim(), sidecar].join("|") + "\\n");
231};
232fs.renameSync = (from, to) => {
233 try {
234 return renameSync(from, to);
235 } catch (error) {
236 checking ||= to === dir;
237 throw error;
238 } finally {
239 if (published) checkPeer();
240 }
241};
242fs.rmSync = (...args) => {
243 try {
244 return rmSync(...args);
245 } finally {
246 if (published) checkPeer();
247 }
248};
249fs.readFileSync = (file, ...rest) => {
250 try {
251 return readFileSync(file, ...rest);
252 } finally {
253 if (checking && file === dir + "/.install-complete") {
254 checking = false;
255 rmSync(dir, { recursive: true });
256 renameSync(${JSON.stringify(peerDir)}, dir);
257 published = true;
258 checkPeer();
259 }
260 }
261};
262`,
263 );
264 const recovered = yield* run(
265 process.execPath,
266 ["--import", peerHook, launcher, "--version"],
267 { cwd: root, env: { ...env, T3CODE_HOME: staleHome } },
268 );
269 const checks = (yield* fs.readFileString(peerChecks)).trim().split("\n");
270 assert.isAtLeast(checks.length, 2);
271 assert.deepStrictEqual([...new Set(checks)], ["7|peer --version|peer sidecar"]);
272 assert.equal(recovered.stdout.trim(), "peer --version", recovered.stderr);
273 assert.equal(recovered.exitCode, 7);
274 assert.deepStrictEqual(yield* fs.readDirectory(path.join(staleHome, "runtime/versions")), [
275 VERSION,
276 ]);
277​
278 // While another launch holds the lock, a stale folder is left alone and the error says
279 // how to clear a lock left by a crash.
280 const staleOnlyHome = path.join(root, "stale-only-home");
281 const staleOnlyDir = path.join(staleOnlyHome, "runtime/versions", VERSION);
282 yield* fs.makeDirectory(staleOnlyDir, { recursive: true });
283 yield* fs.writeFileString(path.join(staleOnlyDir, "t3"), "incomplete");
284 yield* fs.makeDirectory(`${staleOnlyDir}.lock`);
285 const locked = yield* run(process.execPath, [launcher, "--version"], {
286 cwd: root,
287 env: { ...env, T3CODE_HOME: staleOnlyHome },
288 });
289 assert.equal(locked.exitCode, 1);
290 assert.include(locked.stderr, `delete ${staleOnlyDir}.lock`);
291 assert.equal(yield* fs.readFileString(path.join(staleOnlyDir, "t3")), "incomplete");
292​
293 // Without a peer, the stale folder is replaced by our own download.
294 yield* fs.remove(`${staleOnlyDir}.lock`, { recursive: true });
295 const replaced = yield* run(process.execPath, [launcher, "--version"], {
296 cwd: root,
297 env: { ...env, T3CODE_HOME: staleOnlyHome },
298 });
299 assert.equal(
300 replaced.stdout.trim(),
301 `stub --version launcher=${launcher}`,
302 replaced.stderr,
303 );
304 assert.equal(replaced.exitCode, 7);
305 assert.deepStrictEqual(
306 yield* fs.readDirectory(path.join(staleOnlyHome, "runtime/versions")),
307 [VERSION],
308 );
309​
310 release.corruptChecksum();
311 const corrupt = yield* run(process.execPath, [launcher, "--version"], {
312 cwd: root,
313 env: { ...env, T3CODE_HOME: path.join(root, "other-home") },
314 });
315 assert.equal(corrupt.exitCode, 1);
316 assert.include(corrupt.stderr, "checksum mismatch");
317 assert.deepStrictEqual(
318 yield* fs.readDirectory(path.join(root, "other-home/runtime/versions")),
319 [],
320 );
321 }),
322 );
323});