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

build-npm-launcher.test.ts

406 lines16.9 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 server = NodeHttp.createServer((request, response) => {
78 requests.push(request.url ?? "");
79 if (request.url === `/v${VERSION}/SHA256SUMS`) {
80 response.end(`${checksum} ${archiveName}\n`);
81 } else if (request.url === `/v${VERSION}/${archiveName}`) {
82 response.writeHead(200, { "Content-Length": archive.length }).end(archive);
83 } else {
84 response.writeHead(404).end();
85 }
86 });
87 yield* Effect.acquireRelease(
88 Effect.callback<void>((resume) => {
89 server.listen(0, "127.0.0.1", () => resume(Effect.void));
90 }),
91 () =>
92 Effect.callback<void>((resume) => {
93 server.close(() => resume(Effect.void));
94 }),
95 );
96 const address = server.address();
97 if (address === null || typeof address === "string") return yield* Effect.die("no TCP address");
98 return {
99 baseUrl: `http://127.0.0.1:${address.port}`,
100 requests,
101 corruptChecksum: () => {
102 checksum = "0".repeat(64);
103 },
104 };
105});
106​
107it.layer(NodeServices.layer)("build-npm-launcher", (it) => {
108 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
109 "publishes a launcher that downloads, verifies, caches, and runs the release executable",
110 () =>
111 Effect.gen(function* () {
112 const fs = yield* FileSystem.FileSystem;
113 const path = yield* Path.Path;
114 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" });
115 const output = yield* buildNpmLauncher({
116 version: VERSION,
117 outputDir: path.join(root, "out"),
118 });
119​
120 const manifest = yield* decodeManifest(
121 yield* fs.readFileString(path.join(output.packageDir, "package.json")),
122 );
123 assert.equal(manifest.name, "t3");
124 assert.equal(manifest.version, VERSION);
125 assert.deepStrictEqual(manifest.bin, { t3: "./bin/t3.mjs" });
126 assert.isUndefined(manifest.dependencies);
127 assert.isUndefined(manifest.optionalDependencies);
128 assert.isAbove(npmReleaseDatabaseMigration(manifest) ?? 0, 0);
129​
130 const installed = path.join(root, "installed");
131 yield* fs.makeDirectory(installed);
132 const unpack = yield* run("tar", ["-xzf", output.tarball, "-C", installed], {
133 cwd: root,
134 env: { PATH: (yield* HostProcess.Environment).PATH },
135 });
136 assert.equal(unpack.exitCode, 0, unpack.stderr);
137 const packageDir = path.join(installed, "package");
138​
139 const release = yield* serveFakeRelease(root);
140 const home = path.join(root, "home");
141 const env = {
142 PATH: (yield* HostProcess.Environment).PATH,
143 T3CODE_HOME: home,
144 T3CODE_TEST_CALLS: path.join(root, "calls"),
145 T3CODE_RELEASE_BASE_URL: release.baseUrl,
146 };
147 const launcher = path.join(packageDir, "bin/t3.mjs");
148 const first = yield* run(process.execPath, [launcher, "serve", "a b"], {
149 cwd: root,
150 env,
151 });
152 assert.equal(first.stdout.trim(), `stub serve a b launcher=${launcher}`, first.stderr);
153 assert.equal(first.exitCode, 7);
154 assert.deepStrictEqual(
155 (yield* fs.readFileString(env.T3CODE_TEST_CALLS)).trim().split("\n"),
156 ["--version|", `serve a b|${launcher}`],
157 );
158 const versionDir = path.join(home, "runtime/versions", VERSION);
159 assert.equal(
160 (yield* fs.readFileString(path.join(versionDir, ".install-complete"))).trim(),
161 VERSION,
162 );
163 assert.isTrue(yield* fs.exists(path.join(versionDir, "node_modules/native")));
164 assert.deepStrictEqual(
165 (yield* fs.readDirectory(path.join(home, "runtime/versions"))).sort(),
166 [VERSION],
167 );
168​
169 const requestsAfterFirst = release.requests.length;
170 const second = yield* run(process.execPath, [launcher, "--version"], { cwd: root, env });
171 assert.equal(second.exitCode, 0);
172 assert.equal(release.requests.length, requestsAfterFirst);
173 assert.deepStrictEqual(
174 (yield* fs.readFileString(env.T3CODE_TEST_CALLS)).trim().split("\n"),
175 ["--version|", `serve a b|${launcher}`, `--version|${launcher}`],
176 );
177​
178 yield* fs.writeFileString(path.join(versionDir, "t3"), "#!/t3-test-missing-loader\n");
179 for (const _attempt of [1, 2]) {
180 const cached = yield* run(process.execPath, [launcher, "serve"], { cwd: root, env });
181 assert.equal(cached.exitCode, 1, cached.stderr);
182 assert.include(cached.stderr, "could not run");
183 assert.equal(release.requests.length, requestsAfterFirst);
184 assert.equal(
185 yield* fs.readFileString(path.join(versionDir, ".install-complete")),
186 `${VERSION}\n`,
187 );
188 }
189​
190 const ipcServer = path.join(home, "runtime/versions", VERSION, "t3");
191 yield* fs.writeFileString(
192 ipcServer,
193 `#!${process.execPath}\nprocess.on("SIGTERM", () => process.exit(23));\nprocess.on("message", (m) => process.send({ reply: m }));\nprocess.send({ args: process.argv.slice(2) });\n`,
194 );
195 const legacy = NodeChildProcess.fork(
196 path.join(packageDir, "dist/bin.mjs"),
197 ["__service-preflight", "a b"],
198 { env, silent: true },
199 );
200 yield* Effect.promise(async () => {
201 assert.deepStrictEqual((await NodeEvents.EventEmitter.once(legacy, "message"))[0], {
202 args: ["__service-preflight", "a b"],
203 });
204 const reply = NodeEvents.EventEmitter.once(legacy, "message");
205 legacy.send({ type: "trial-accepted" });
206 assert.deepStrictEqual((await reply)[0], { reply: { type: "trial-accepted" } });
207 const exit = NodeEvents.EventEmitter.once(legacy, "exit");
208 legacy.kill("SIGTERM");
209 assert.deepStrictEqual(await exit, [23, null]);
210 });
211​
212 const raceHome = path.join(root, "race-home");
213 const launch = run(process.execPath, [launcher, "--version"], {
214 cwd: root,
215 env: { ...env, T3CODE_HOME: raceHome },
216 });
217 const [one, two] = yield* Effect.all([launch, launch], { concurrency: "unbounded" });
218 assert.equal(one.exitCode, 0, one.stderr);
219 assert.equal(two.exitCode, 0, two.stderr);
220 assert.deepStrictEqual(yield* fs.readDirectory(path.join(raceHome, "runtime/versions")), [
221 VERSION,
222 ]);
223​
224 // A peer's executable and sidecar stay available after every later rename or removal,
225 // even when it publishes after our missing-marker read.
226 const staleHome = path.join(root, "stale-home");
227 const staleDir = path.join(staleHome, "runtime/versions", VERSION);
228 const peerDir = path.join(root, "peer-runtime");
229 yield* fs.makeDirectory(staleDir, { recursive: true });
230 yield* fs.writeFileString(path.join(staleDir, "t3"), "");
231 yield* fs.makeDirectory(peerDir);
232 yield* fs.writeFileString(path.join(peerDir, "t3"), '#!/bin/sh\necho "peer $*"\nexit 7\n');
233 yield* fs.chmod(path.join(peerDir, "t3"), 0o755);
234 yield* fs.writeFileString(path.join(peerDir, ".install-complete"), `${VERSION}\n`);
235 yield* fs.writeFileString(path.join(peerDir, "sidecar"), "peer sidecar");
236 const peerChecks = path.join(root, "peer-checks.txt");
237 // The peer publishes after the launcher's rename fails and it reads the marker.
238 const peerHook = path.join(root, "peer-publishes.mjs");
239 yield* fs.writeFileString(
240 peerHook,
241 `import fs from "node:fs";
242import { spawnSync } from "node:child_process";
243const dir = ${JSON.stringify(staleDir)};
244const { readFileSync, renameSync, rmSync } = fs;
245let checking = false;
246let published = false;
247const checkPeer = () => {
248 const child = spawnSync(dir + "/t3", ["--version"], { encoding: "utf8" });
249 let sidecar;
250 try {
251 sidecar = readFileSync(dir + "/sidecar", "utf8");
252 } catch (error) {
253 sidecar = error.code;
254 }
255 fs.appendFileSync(${JSON.stringify(peerChecks)},
256 [child.status, child.error?.code ?? child.stdout.trim(), sidecar].join("|") + "\\n");
257};
258fs.renameSync = (from, to) => {
259 try {
260 return renameSync(from, to);
261 } catch (error) {
262 checking ||= to === dir;
263 throw error;
264 } finally {
265 if (published) checkPeer();
266 }
267};
268fs.rmSync = (...args) => {
269 try {
270 return rmSync(...args);
271 } finally {
272 if (published) checkPeer();
273 }
274};
275fs.readFileSync = (file, ...rest) => {
276 try {
277 return readFileSync(file, ...rest);
278 } finally {
279 if (checking && file === dir + "/.install-complete") {
280 checking = false;
281 rmSync(dir, { recursive: true });
282 renameSync(${JSON.stringify(peerDir)}, dir);
283 published = true;
284 checkPeer();
285 }
286 }
287};
288`,
289 );
290 const recovered = yield* run(
291 process.execPath,
292 ["--import", peerHook, launcher, "--version"],
293 { cwd: root, env: { ...env, T3CODE_HOME: staleHome } },
294 );
295 const checks = (yield* fs.readFileString(peerChecks)).trim().split("\n");
296 assert.isAtLeast(checks.length, 2);
297 assert.deepStrictEqual([...new Set(checks)], ["7|peer --version|peer sidecar"]);
298 assert.equal(recovered.stdout.trim(), "peer --version", recovered.stderr);
299 assert.equal(recovered.exitCode, 7);
300 assert.deepStrictEqual(yield* fs.readDirectory(path.join(staleHome, "runtime/versions")), [
301 VERSION,
302 ]);
303​
304 // While another launch holds the lock, a stale folder is left alone and the error says
305 // how to clear a lock left by a crash.
306 const staleOnlyHome = path.join(root, "stale-only-home");
307 const staleOnlyDir = path.join(staleOnlyHome, "runtime/versions", VERSION);
308 yield* fs.makeDirectory(staleOnlyDir, { recursive: true });
309 yield* fs.writeFileString(path.join(staleOnlyDir, "t3"), "incomplete");
310 yield* fs.makeDirectory(`${staleOnlyDir}.lock`);
311 const locked = yield* run(process.execPath, [launcher, "--version"], {
312 cwd: root,
313 env: { ...env, T3CODE_HOME: staleOnlyHome },
314 });
315 assert.equal(locked.exitCode, 1);
316 assert.include(locked.stderr, `delete ${staleOnlyDir}.lock`);
317 assert.equal(yield* fs.readFileString(path.join(staleOnlyDir, "t3")), "incomplete");
318​
319 // Without a peer, the stale folder is replaced by our own download.
320 yield* fs.remove(`${staleOnlyDir}.lock`, { recursive: true });
321 const replaced = yield* run(process.execPath, [launcher, "--version"], {
322 cwd: root,
323 env: { ...env, T3CODE_HOME: staleOnlyHome },
324 });
325 assert.equal(replaced.stdout.trim(), VERSION, replaced.stderr);
326 assert.equal(replaced.exitCode, 0);
327 assert.deepStrictEqual(
328 yield* fs.readDirectory(path.join(staleOnlyHome, "runtime/versions")),
329 [VERSION],
330 );
331​
332 release.corruptChecksum();
333 const corrupt = yield* run(process.execPath, [launcher, "--version"], {
334 cwd: root,
335 env: { ...env, T3CODE_HOME: path.join(root, "other-home") },
336 });
337 assert.equal(corrupt.exitCode, 1);
338 assert.include(corrupt.stderr, "checksum mismatch");
339 assert.deepStrictEqual(
340 yield* fs.readDirectory(path.join(root, "other-home/runtime/versions")),
341 [],
342 );
343 }),
344 );
345 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
346 "does not publish an unusable release",
347 () =>
348 Effect.gen(function* () {
349 const fs = yield* FileSystem.FileSystem;
350 const path = yield* Path.Path;
351 for (const executable of [
352 "#!/t3-test-missing-loader\n",
353 '#!/bin/sh\necho "runtime loader failed" >&2\nexit 42\n',
354 "#!/bin/sh\nkill -TERM $$\n",
355 '#!/bin/sh\ntrap \'echo caught > "$T3CODE_TEST_TERM"; exit 42\' TERM\necho ready > "$T3CODE_TEST_READY"\nwhile :; do :; done\n',
356 ]) {
357 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-validation-test-" });
358 const output = yield* buildNpmLauncher({
359 version: VERSION,
360 outputDir: path.join(root, "out"),
361 });
362 const release = yield* serveFakeRelease(root, executable);
363 const home = path.join(root, "home");
364 const dir = path.join(home, "runtime/versions", VERSION);
365 const probeTimeoutHook = path.join(root, "probe-timeout.mjs");
366 yield* fs.writeFileString(
367 probeTimeoutHook,
368 `import childProcess from "node:child_process";
369import { syncBuiltinESMExports } from "node:module";
370const { spawnSync } = childProcess;
371childProcess.spawnSync = (command, args, options) => spawnSync(command, args,
372 options?.timeout === undefined ? options : { ...options, timeout: 500 });
373syncBuiltinESMExports();
374`,
375 );
376 const env = {
377 PATH: (yield* HostProcess.Environment).PATH,
378 T3CODE_HOME: home,
379 T3CODE_RELEASE_BASE_URL: release.baseUrl,
380 T3CODE_TEST_READY: path.join(root, "probe-ready"),
381 T3CODE_TEST_TERM: path.join(root, "probe-term"),
382 };
383 const launcher = path.join(output.packageDir, "bin/t3.mjs");
384 const failed = yield* run(
385 process.execPath,
386 ["--import", probeTimeoutHook, launcher, "serve"],
387 { cwd: root, env },
388 );
389 assert.equal(failed.exitCode, 1, failed.stderr);
390 assert.deepStrictEqual(yield* fs.readDirectory(path.dirname(dir)), [], failed.stderr);
391 assert.include(failed.stderr, "could not run");
392 if (executable.includes("runtime loader failed")) {
393 assert.include(failed.stderr, "runtime loader failed");
394 }
395 if (executable.includes("trap")) {
396 assert.isTrue(yield* fs.exists(env.T3CODE_TEST_READY));
397 assert.isFalse(yield* fs.exists(env.T3CODE_TEST_TERM));
398 }
399 if ((yield* HostProcess.Platform) === "linux") {
400 assert.include(failed.stderr, "glibc");
401 assert.include(failed.stderr, "musl");
402 }
403 }
404 }),
405 );
406});