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

build-npm-launcher.test.ts

495 lines21.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* (
51 root: string,
52 executable = `#!/bin/sh
53if [ -n "$T3CODE_TEST_CALLS" ]; then echo "$*|$T3CODE_NPM_LAUNCHER_PATH" >> "$T3CODE_TEST_CALLS"; fi
54if [ "$1" = "--version" ]; then echo "${VERSION}"; exit 0; fi
55echo "stub $* launcher=$T3CODE_NPM_LAUNCHER_PATH"
56exit 7
57`,
58) {
59 const fs = yield* FileSystem.FileSystem;
60 const path = yield* Path.Path;
61 const key = `${yield* HostProcess.Platform}-${yield* HostProcess.Architecture}`;
62 const stem = `t3-${VERSION}-${key}`;
63 const archiveName = `${stem}.tar.gz`;
64 yield* fs.makeDirectory(path.join(root, "release", stem, "node_modules/native"), {
65 recursive: true,
66 });
67 yield* fs.writeFileString(path.join(root, "release", stem, "t3"), executable);
68 yield* fs.chmod(path.join(root, "release", stem, "t3"), 0o755);
69 const tar = yield* run("tar", ["-czf", archiveName, stem], {
70 cwd: path.join(root, "release"),
71 env: { PATH: (yield* HostProcess.Environment).PATH },
72 });
73 assert.equal(tar.exitCode, 0, tar.stderr);
74 const archive = yield* fs.readFile(path.join(root, "release", archiveName));
75 let checksum = NodeCrypto.createHash("sha256").update(archive).digest("hex");
76 const requests: Array<string> = [];
77 const failures: Array<number> = [];
78 const server = NodeHttp.createServer((request, response) => {
79 requests.push(request.url ?? "");
80 const failure = failures.shift();
81 if (failure !== undefined) {
82 response.writeHead(failure).end("upstream timed out");
83 } else if (request.url === `/v${VERSION}/SHA256SUMS`) {
84 response.end(`${checksum} ${archiveName}\n`);
85 } else if (request.url === `/v${VERSION}/${archiveName}`) {
86 response.writeHead(200, { "Content-Length": archive.length }).end(archive);
87 } else {
88 response.writeHead(404).end();
89 }
90 });
91 yield* Effect.acquireRelease(
92 Effect.callback<void>((resume) => {
93 server.listen(0, "127.0.0.1", () => resume(Effect.void));
94 }),
95 () =>
96 Effect.callback<void>((resume) => {
97 server.close(() => resume(Effect.void));
98 }),
99 );
100 const address = server.address();
101 if (address === null || typeof address === "string") return yield* Effect.die("no TCP address");
102 return {
103 baseUrl: `http://127.0.0.1:${address.port}`,
104 requests,
105 corruptChecksum: () => {
106 checksum = "0".repeat(64);
107 },
108 failNextRequests: (...statuses: Array<number>) => {
109 failures.push(...statuses);
110 },
111 };
112});
113​
114it.layer(NodeServices.layer)("build-npm-launcher", (it) => {
115 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
116 "publishes a launcher that downloads, verifies, caches, and runs the release executable",
117 () =>
118 Effect.gen(function* () {
119 const fs = yield* FileSystem.FileSystem;
120 const path = yield* Path.Path;
121 // macOS temp directories sit under /var, a link to /private/var, and the launcher
122 // reports the resolved path it runs from.
123 const root = yield* fs.realPath(
124 yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" }),
125 );
126 const output = yield* buildNpmLauncher({
127 version: VERSION,
128 outputDir: path.join(root, "out"),
129 });
130​
131 const manifest = yield* decodeManifest(
132 yield* fs.readFileString(path.join(output.packageDir, "package.json")),
133 );
134 assert.equal(manifest.name, "t3");
135 assert.equal(manifest.version, VERSION);
136 assert.deepStrictEqual(manifest.bin, { t3: "./bin/t3.mjs" });
137 assert.isUndefined(manifest.dependencies);
138 assert.isUndefined(manifest.optionalDependencies);
139 assert.isAbove(npmReleaseDatabaseMigration(manifest) ?? 0, 0);
140​
141 const installed = path.join(root, "installed");
142 yield* fs.makeDirectory(installed);
143 const unpack = yield* run("tar", ["-xzf", output.tarball, "-C", installed], {
144 cwd: root,
145 env: { PATH: (yield* HostProcess.Environment).PATH },
146 });
147 assert.equal(unpack.exitCode, 0, unpack.stderr);
148 const packageDir = path.join(installed, "package");
149​
150 const release = yield* serveFakeRelease(root);
151 // regression: #32897
152 release.failNextRequests(504, 524);
153 const home = path.join(root, "home");
154 const env = {
155 PATH: (yield* HostProcess.Environment).PATH,
156 T3CODE_HOME: home,
157 T3CODE_TEST_CALLS: path.join(root, "calls"),
158 T3CODE_RELEASE_BASE_URL: release.baseUrl,
159 };
160 const launcher = path.join(packageDir, "bin/t3.mjs");
161 const first = yield* run(process.execPath, [launcher, "serve", "a b"], {
162 cwd: root,
163 env,
164 });
165 assert.equal(first.stdout.trim(), `stub serve a b launcher=${launcher}`, first.stderr);
166 assert.equal(first.exitCode, 7);
167 assert.deepStrictEqual(
168 (yield* fs.readFileString(env.T3CODE_TEST_CALLS)).trim().split("\n"),
169 ["--version|", `serve a b|${launcher}`],
170 );
171 const versionDir = path.join(home, "runtime/versions", VERSION);
172 assert.equal(
173 (yield* fs.readFileString(path.join(versionDir, ".install-complete"))).trim(),
174 VERSION,
175 );
176 assert.isTrue(yield* fs.exists(path.join(versionDir, "node_modules/native")));
177 assert.deepStrictEqual(
178 (yield* fs.readDirectory(path.join(home, "runtime/versions"))).sort(),
179 [VERSION],
180 );
181​
182 const requestsAfterFirst = release.requests.length;
183 const second = yield* run(process.execPath, [launcher, "--version"], { cwd: root, env });
184 assert.equal(second.exitCode, 0);
185 assert.equal(release.requests.length, requestsAfterFirst);
186 assert.deepStrictEqual(
187 (yield* fs.readFileString(env.T3CODE_TEST_CALLS)).trim().split("\n"),
188 ["--version|", `serve a b|${launcher}`, `--version|${launcher}`],
189 );
190​
191 yield* fs.writeFileString(path.join(versionDir, "t3"), "#!/t3-test-missing-loader\n");
192 for (const _attempt of [1, 2]) {
193 const cached = yield* run(process.execPath, [launcher, "serve"], { cwd: root, env });
194 assert.equal(cached.exitCode, 1, cached.stderr);
195 assert.include(cached.stderr, "could not run");
196 assert.equal(release.requests.length, requestsAfterFirst);
197 assert.equal(
198 yield* fs.readFileString(path.join(versionDir, ".install-complete")),
199 `${VERSION}\n`,
200 );
201 }
202​
203 const ipcServer = path.join(home, "runtime/versions", VERSION, "t3");
204 yield* fs.writeFileString(
205 ipcServer,
206 `#!${process.execPath}\nprocess.on("SIGTERM", () => process.exit(23));\nprocess.on("message", (m) => process.send({ reply: m }));\nprocess.send({ args: process.argv.slice(2) });\n`,
207 );
208 const legacy = NodeChildProcess.fork(
209 path.join(packageDir, "dist/bin.mjs"),
210 ["__service-preflight", "a b"],
211 { env, silent: true },
212 );
213 yield* Effect.promise(async () => {
214 assert.deepStrictEqual((await NodeEvents.EventEmitter.once(legacy, "message"))[0], {
215 args: ["__service-preflight", "a b"],
216 });
217 const reply = NodeEvents.EventEmitter.once(legacy, "message");
218 legacy.send({ type: "trial-accepted" });
219 assert.deepStrictEqual((await reply)[0], { reply: { type: "trial-accepted" } });
220 const exit = NodeEvents.EventEmitter.once(legacy, "exit");
221 legacy.kill("SIGTERM");
222 assert.deepStrictEqual(await exit, [23, null]);
223 });
224​
225 const raceHome = path.join(root, "race-home");
226 const launch = run(process.execPath, [launcher, "--version"], {
227 cwd: root,
228 env: { ...env, T3CODE_HOME: raceHome },
229 });
230 const [one, two] = yield* Effect.all([launch, launch], { concurrency: "unbounded" });
231 assert.equal(one.exitCode, 0, one.stderr);
232 assert.equal(two.exitCode, 0, two.stderr);
233 assert.deepStrictEqual(yield* fs.readDirectory(path.join(raceHome, "runtime/versions")), [
234 VERSION,
235 ]);
236​
237 // A peer's executable and sidecar stay available after every later rename or removal,
238 // even when it publishes after our missing-marker read.
239 const staleHome = path.join(root, "stale-home");
240 const staleDir = path.join(staleHome, "runtime/versions", VERSION);
241 const peerDir = path.join(root, "peer-runtime");
242 yield* fs.makeDirectory(staleDir, { recursive: true });
243 yield* fs.writeFileString(path.join(staleDir, "t3"), "");
244 yield* fs.makeDirectory(peerDir);
245 yield* fs.writeFileString(path.join(peerDir, "t3"), '#!/bin/sh\necho "peer $*"\nexit 7\n');
246 yield* fs.chmod(path.join(peerDir, "t3"), 0o755);
247 yield* fs.writeFileString(path.join(peerDir, ".install-complete"), `${VERSION}\n`);
248 yield* fs.writeFileString(path.join(peerDir, "sidecar"), "peer sidecar");
249 const peerChecks = path.join(root, "peer-checks.txt");
250 // The peer publishes after the launcher's rename fails and it reads the marker.
251 const peerHook = path.join(root, "peer-publishes.mjs");
252 yield* fs.writeFileString(
253 peerHook,
254 `import fs from "node:fs";
255import { spawnSync } from "node:child_process";
256const dir = ${JSON.stringify(staleDir)};
257const { readFileSync, renameSync, rmSync } = fs;
258let checking = false;
259let published = false;
260const checkPeer = () => {
261 const child = spawnSync(dir + "/t3", ["--version"], { encoding: "utf8" });
262 let sidecar;
263 try {
264 sidecar = readFileSync(dir + "/sidecar", "utf8");
265 } catch (error) {
266 sidecar = error.code;
267 }
268 fs.appendFileSync(${JSON.stringify(peerChecks)},
269 [child.status, child.error?.code ?? child.stdout.trim(), sidecar].join("|") + "\\n");
270};
271fs.renameSync = (from, to) => {
272 try {
273 return renameSync(from, to);
274 } catch (error) {
275 checking ||= to === dir;
276 throw error;
277 } finally {
278 if (published) checkPeer();
279 }
280};
281fs.rmSync = (...args) => {
282 try {
283 return rmSync(...args);
284 } finally {
285 if (published) checkPeer();
286 }
287};
288fs.readFileSync = (file, ...rest) => {
289 try {
290 return readFileSync(file, ...rest);
291 } finally {
292 if (checking && file === dir + "/.install-complete") {
293 checking = false;
294 rmSync(dir, { recursive: true });
295 renameSync(${JSON.stringify(peerDir)}, dir);
296 published = true;
297 checkPeer();
298 }
299 }
300};
301`,
302 );
303 const recovered = yield* run(
304 process.execPath,
305 ["--import", peerHook, launcher, "--version"],
306 { cwd: root, env: { ...env, T3CODE_HOME: staleHome } },
307 );
308 const checks = (yield* fs.readFileString(peerChecks)).trim().split("\n");
309 assert.isAtLeast(checks.length, 2);
310 assert.deepStrictEqual([...new Set(checks)], ["7|peer --version|peer sidecar"]);
311 assert.equal(recovered.stdout.trim(), "peer --version", recovered.stderr);
312 assert.equal(recovered.exitCode, 7);
313 assert.deepStrictEqual(yield* fs.readDirectory(path.join(staleHome, "runtime/versions")), [
314 VERSION,
315 ]);
316​
317 // While another launch holds the lock, a stale folder is left alone and the error says
318 // how to clear a lock left by a crash.
319 const staleOnlyHome = path.join(root, "stale-only-home");
320 const staleOnlyDir = path.join(staleOnlyHome, "runtime/versions", VERSION);
321 yield* fs.makeDirectory(staleOnlyDir, { recursive: true });
322 yield* fs.writeFileString(path.join(staleOnlyDir, "t3"), "incomplete");
323 yield* fs.makeDirectory(`${staleOnlyDir}.lock`);
324 const locked = yield* run(process.execPath, [launcher, "--version"], {
325 cwd: root,
326 env: { ...env, T3CODE_HOME: staleOnlyHome },
327 });
328 assert.equal(locked.exitCode, 1);
329 assert.include(locked.stderr, `delete ${staleOnlyDir}.lock`);
330 assert.equal(yield* fs.readFileString(path.join(staleOnlyDir, "t3")), "incomplete");
331​
332 // Without a peer, the stale folder is replaced by our own download.
333 yield* fs.remove(`${staleOnlyDir}.lock`, { recursive: true });
334 const replaced = yield* run(process.execPath, [launcher, "--version"], {
335 cwd: root,
336 env: { ...env, T3CODE_HOME: staleOnlyHome },
337 });
338 assert.equal(replaced.stdout.trim(), VERSION, replaced.stderr);
339 assert.equal(replaced.exitCode, 0);
340 assert.deepStrictEqual(
341 yield* fs.readDirectory(path.join(staleOnlyHome, "runtime/versions")),
342 [VERSION],
343 );
344​
345 release.corruptChecksum();
346 const corrupt = yield* run(process.execPath, [launcher, "--version"], {
347 cwd: root,
348 env: { ...env, T3CODE_HOME: path.join(root, "other-home") },
349 });
350 assert.equal(corrupt.exitCode, 1);
351 assert.include(corrupt.stderr, "checksum mismatch");
352 assert.deepStrictEqual(
353 yield* fs.readDirectory(path.join(root, "other-home/runtime/versions")),
354 [],
355 );
356 }),
357 );
358 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
359 "does not publish an unusable release",
360 () =>
361 Effect.gen(function* () {
362 const fs = yield* FileSystem.FileSystem;
363 const path = yield* Path.Path;
364 for (const executable of [
365 "#!/t3-test-missing-loader\n",
366 '#!/bin/sh\necho "runtime loader failed" >&2\nexit 42\n',
367 "#!/bin/sh\nkill -TERM $$\n",
368 '#!/bin/sh\ntrap \'echo caught > "$T3CODE_TEST_TERM"; exit 42\' TERM\necho ready > "$T3CODE_TEST_READY"\nwhile :; do :; done\n',
369 ]) {
370 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-validation-test-" });
371 const output = yield* buildNpmLauncher({
372 version: VERSION,
373 outputDir: path.join(root, "out"),
374 });
375 const release = yield* serveFakeRelease(root, executable);
376 const home = path.join(root, "home");
377 const dir = path.join(home, "runtime/versions", VERSION);
378 const probeTimeoutHook = path.join(root, "probe-timeout.mjs");
379 yield* fs.writeFileString(
380 probeTimeoutHook,
381 `import childProcess from "node:child_process";
382import { syncBuiltinESMExports } from "node:module";
383const { spawnSync } = childProcess;
384childProcess.spawnSync = (command, args, options) => spawnSync(command, args,
385 options?.timeout === undefined ? options : { ...options, timeout: 500 });
386syncBuiltinESMExports();
387`,
388 );
389 const env = {
390 PATH: (yield* HostProcess.Environment).PATH,
391 T3CODE_HOME: home,
392 T3CODE_RELEASE_BASE_URL: release.baseUrl,
393 T3CODE_TEST_READY: path.join(root, "probe-ready"),
394 T3CODE_TEST_TERM: path.join(root, "probe-term"),
395 };
396 const launcher = path.join(output.packageDir, "bin/t3.mjs");
397 const failed = yield* run(
398 process.execPath,
399 ["--import", probeTimeoutHook, launcher, "serve"],
400 { cwd: root, env },
401 );
402 assert.equal(failed.exitCode, 1, failed.stderr);
403 assert.deepStrictEqual(yield* fs.readDirectory(path.dirname(dir)), [], failed.stderr);
404 assert.include(failed.stderr, "could not run");
405 if (executable.includes("runtime loader failed")) {
406 assert.include(failed.stderr, "runtime loader failed");
407 }
408 if (executable.includes("trap")) {
409 assert.isTrue(yield* fs.exists(env.T3CODE_TEST_READY));
410 assert.isFalse(yield* fs.exists(env.T3CODE_TEST_TERM));
411 }
412 if ((yield* HostProcess.Platform) === "linux") {
413 assert.include(failed.stderr, "glibc");
414 assert.include(failed.stderr, "musl");
415 }
416 }
417 }),
418 );
419​
420 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
421 "kills a runtime that ignores the forwarded SIGTERM, and its providers, so the launcher exits",
422 () =>
423 Effect.gen(function* () {
424 const fs = yield* FileSystem.FileSystem;
425 const path = yield* Path.Path;
426 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" });
427 const output = yield* buildNpmLauncher({
428 version: VERSION,
429 outputDir: path.join(root, "out"),
430 });
431 const hostPath = (yield* HostProcess.Environment).PATH;
432 const installed = path.join(root, "installed");
433 yield* fs.makeDirectory(installed);
434 const unpack = yield* run("tar", ["-xzf", output.tarball, "-C", installed], {
435 cwd: root,
436 env: { PATH: hostPath },
437 });
438 assert.equal(unpack.exitCode, 0, unpack.stderr);
439​
440 const home = path.join(root, "home");
441 const versionDir = path.join(home, "runtime/versions", VERSION);
442 yield* fs.makeDirectory(versionDir, { recursive: true });
443 yield* fs.writeFileString(path.join(versionDir, ".install-complete"), `${VERSION}\n`);
444 // Stands in for a runtime whose exit is stuck behind blocked filesystem calls, with a
445 // provider it never gets to stop. Both give up on their own well inside the project
446 // timeout so an unescalated stop fails descriptively.
447 const stuck = "runtime ignored SIGTERM and was still running 30s later";
448 const orphaned = "provider outlived the runtime by 30s";
449 const provider = `process.on("SIGTERM", () => {}); setTimeout(() => { console.log(${JSON.stringify(orphaned)}); process.exit(0); }, 30_000);`;
450 yield* fs.writeFileString(
451 path.join(versionDir, "t3"),
452 `#!${process.execPath}
453const provider = require("node:child_process").spawn(process.execPath, ["-e", ${JSON.stringify(provider)}], { stdio: "inherit" });
454process.on("SIGTERM", () => setTimeout(() => { console.log(${JSON.stringify(stuck)}); process.exit(0); }, 30_000));
455setInterval(() => {}, 1 << 30);
456console.log(process.pid, provider.pid);
457`,
458 );
459 yield* fs.chmod(path.join(versionDir, "t3"), 0o755);
460​
461 const launcher = NodeChildProcess.spawn(
462 process.execPath,
463 [path.join(installed, "package/bin/t3.mjs"), "serve"],
464 { cwd: root, env: { PATH: hostPath, T3CODE_HOME: home }, stdio: "pipe" },
465 );
466 let pids: Array<number> = [];
467 yield* Effect.addFinalizer(() =>
468 Effect.sync(() => {
469 for (const pid of [...pids, launcher.pid]) {
470 try {
471 if (pid !== undefined) process.kill(pid, "SIGKILL");
472 } catch {}
473 }
474 }),
475 );
476 let stdout = "";
477 const started = Promise.withResolvers<void>();
478 launcher.stdout.setEncoding("utf8");
479 launcher.stdout.on("data", (chunk: string) => {
480 stdout += chunk;
481 if (stdout.includes("\n")) started.resolve();
482 });
483 // The runtime and provider inherit this pipe, so it closes only once all three are gone.
484 const closed = NodeEvents.EventEmitter.once(launcher.stdout, "close");
485 yield* Effect.promise(() => started.promise);
486 pids = stdout.trim().split(" ").map(Number);
487 assert.isTrue(pids.length === 2 && pids.every(Number.isInteger), stdout);
488​
489 launcher.kill("SIGTERM");
490 yield* Effect.promise(() => closed);
491 assert.notInclude(stdout, stuck, "the launcher waited on a runtime that ignored SIGTERM");
492 assert.notInclude(stdout, orphaned, "the runtime's provider outlived the launcher");
493 }),
494 );
495});