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

build-npm-launcher.test.ts

208 lines8.4 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 { buildNpmLauncher } from "./build-npm-launcher.ts";
17​
18const VERSION = "1.2.3";
19const decodeManifest = Schema.decodeEffect(
20 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown)),
21);
22​
23const collect = <E>(stream: Stream.Stream<Uint8Array, E>) =>
24 stream.pipe(
25 Stream.decodeText(),
26 Stream.runFold(
27 () => "",
28 (acc, chunk) => acc + chunk,
29 ),
30 );
31​
32const run = Effect.fn("test.run")(function* (
33 command: string,
34 args: ReadonlyArray<string>,
35 options: { readonly cwd: string; readonly env: Record<string, string | undefined> },
36) {
37 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
38 const child = yield* spawner.spawn(
39 ChildProcess.make(command, args, { cwd: options.cwd, env: options.env, extendEnv: false }),
40 );
41 const [stdout, stderr, exitCode] = yield* Effect.all(
42 [collect(child.stdout), collect(child.stderr), child.exitCode.pipe(Effect.map(Number))],
43 { concurrency: "unbounded" },
44 );
45 return { stdout, stderr, exitCode };
46}, Effect.scoped);
47​
48const serveFakeRelease = Effect.fn("test.serveFakeRelease")(function* (root: string) {
49 const fs = yield* FileSystem.FileSystem;
50 const path = yield* Path.Path;
51 const key = `${yield* HostProcess.Platform}-${yield* HostProcess.Architecture}`;
52 const stem = `t3-${VERSION}-${key}`;
53 const archiveName = `${stem}.tar.gz`;
54 yield* fs.makeDirectory(path.join(root, "release", stem, "node_modules/native"), {
55 recursive: true,
56 });
57 yield* fs.writeFileString(
58 path.join(root, "release", stem, "t3"),
59 '#!/bin/sh\necho "stub $* launcher=$T3CODE_NPM_LAUNCHER_PATH"\nexit 7\n',
60 );
61 yield* fs.chmod(path.join(root, "release", stem, "t3"), 0o755);
62 const tar = yield* run("tar", ["-czf", archiveName, stem], {
63 cwd: path.join(root, "release"),
64 env: { PATH: process.env.PATH },
65 });
66 assert.equal(tar.exitCode, 0, tar.stderr);
67 const archive = yield* fs.readFile(path.join(root, "release", archiveName));
68 let checksum = NodeCrypto.createHash("sha256").update(archive).digest("hex");
69 const requests: Array<string> = [];
70 const server = NodeHttp.createServer((request, response) => {
71 requests.push(request.url ?? "");
72 if (request.url === `/v${VERSION}/SHA256SUMS`) {
73 response.end(`${checksum} ${archiveName}\n`);
74 } else if (request.url === `/v${VERSION}/${archiveName}`) {
75 response.writeHead(200, { "Content-Length": archive.length }).end(archive);
76 } else {
77 response.writeHead(404).end();
78 }
79 });
80 yield* Effect.acquireRelease(
81 Effect.callback<void>((resume) => {
82 server.listen(0, "127.0.0.1", () => resume(Effect.void));
83 }),
84 () =>
85 Effect.callback<void>((resume) => {
86 server.close(() => resume(Effect.void));
87 }),
88 );
89 const address = server.address();
90 if (address === null || typeof address === "string") return yield* Effect.die("no TCP address");
91 return {
92 baseUrl: `http://127.0.0.1:${address.port}`,
93 requests,
94 corruptChecksum: () => {
95 checksum = "0".repeat(64);
96 },
97 };
98});
99​
100it.layer(NodeServices.layer)("build-npm-launcher", (it) => {
101 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
102 "publishes a launcher that downloads, verifies, caches, and runs the release executable",
103 () =>
104 Effect.gen(function* () {
105 const fs = yield* FileSystem.FileSystem;
106 const path = yield* Path.Path;
107 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" });
108 const output = yield* buildNpmLauncher({
109 version: VERSION,
110 outputDir: path.join(root, "out"),
111 });
112​
113 const manifest = yield* decodeManifest(
114 yield* fs.readFileString(path.join(output.packageDir, "package.json")),
115 );
116 assert.equal(manifest.name, "t3");
117 assert.equal(manifest.version, VERSION);
118 assert.deepStrictEqual(manifest.bin, { t3: "./bin/t3.mjs" });
119 assert.isUndefined(manifest.dependencies);
120 assert.isUndefined(manifest.optionalDependencies);
121​
122 const installed = path.join(root, "installed");
123 yield* fs.makeDirectory(installed);
124 const unpack = yield* run("tar", ["-xzf", output.tarball, "-C", installed], {
125 cwd: root,
126 env: { PATH: process.env.PATH },
127 });
128 assert.equal(unpack.exitCode, 0, unpack.stderr);
129 const packageDir = path.join(installed, "package");
130​
131 const release = yield* serveFakeRelease(root);
132 const home = path.join(root, "home");
133 const env = {
134 PATH: process.env.PATH,
135 T3CODE_HOME: home,
136 T3CODE_RELEASE_BASE_URL: release.baseUrl,
137 };
138 const launcher = path.join(packageDir, "bin/t3.mjs");
139 const first = yield* run(process.execPath, [launcher, "serve", "a b"], {
140 cwd: root,
141 env,
142 });
143 assert.equal(first.stdout.trim(), `stub serve a b launcher=${launcher}`, first.stderr);
144 assert.equal(first.exitCode, 7);
145 const versionDir = path.join(home, "runtime/versions", VERSION);
146 assert.equal(
147 (yield* fs.readFileString(path.join(versionDir, ".install-complete"))).trim(),
148 VERSION,
149 );
150 assert.isTrue(yield* fs.exists(path.join(versionDir, "node_modules/native")));
151 assert.deepStrictEqual(
152 (yield* fs.readDirectory(path.join(home, "runtime/versions"))).sort(),
153 [VERSION],
154 );
155​
156 const requestsAfterFirst = release.requests.length;
157 const second = yield* run(process.execPath, [launcher, "--version"], { cwd: root, env });
158 assert.equal(second.exitCode, 7);
159 assert.equal(release.requests.length, requestsAfterFirst);
160​
161 const ipcServer = path.join(home, "runtime/versions", VERSION, "t3");
162 yield* fs.writeFileString(
163 ipcServer,
164 `#!${process.execPath}\nprocess.on("SIGTERM", () => process.exit(23));\nprocess.on("message", (m) => process.send({ reply: m }));\nprocess.send({ args: process.argv.slice(2) });\n`,
165 );
166 const legacy = NodeChildProcess.fork(
167 path.join(packageDir, "dist/bin.mjs"),
168 ["__service-preflight", "a b"],
169 { env, silent: true },
170 );
171 yield* Effect.promise(async () => {
172 assert.deepStrictEqual((await NodeEvents.EventEmitter.once(legacy, "message"))[0], {
173 args: ["__service-preflight", "a b"],
174 });
175 const reply = NodeEvents.EventEmitter.once(legacy, "message");
176 legacy.send({ type: "trial-accepted" });
177 assert.deepStrictEqual((await reply)[0], { reply: { type: "trial-accepted" } });
178 const exit = NodeEvents.EventEmitter.once(legacy, "exit");
179 legacy.kill("SIGTERM");
180 assert.deepStrictEqual(await exit, [23, null]);
181 });
182​
183 const raceHome = path.join(root, "race-home");
184 const launch = run(process.execPath, [launcher, "--version"], {
185 cwd: root,
186 env: { ...env, T3CODE_HOME: raceHome },
187 });
188 const [one, two] = yield* Effect.all([launch, launch], { concurrency: "unbounded" });
189 assert.equal(one.exitCode, 7, one.stderr);
190 assert.equal(two.exitCode, 7, two.stderr);
191 assert.deepStrictEqual(yield* fs.readDirectory(path.join(raceHome, "runtime/versions")), [
192 VERSION,
193 ]);
194​
195 release.corruptChecksum();
196 const corrupt = yield* run(process.execPath, [launcher, "--version"], {
197 cwd: root,
198 env: { ...env, T3CODE_HOME: path.join(root, "other-home") },
199 });
200 assert.equal(corrupt.exitCode, 1);
201 assert.include(corrupt.stderr, "checksum mismatch");
202 assert.deepStrictEqual(
203 yield* fs.readDirectory(path.join(root, "other-home/runtime/versions")),
204 [],
205 );
206 }),
207 );
208});