Open History to see the last commit
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
48/** A release archive for this host with a stub `t3` that echoes its args and launcher. */
49const serveFakeRelease = Effect.fn("test.serveFakeRelease")(function* (root: string) {
50 const fs = yield* FileSystem.FileSystem;
51 const path = yield* Path.Path;
52 const key = `${yield* HostProcess.Platform}-${yield* HostProcess.Architecture}`;
53 const stem = `t3-${VERSION}-${key}`;
54 const archiveName = `${stem}.tar.gz`;
55 yield* fs.makeDirectory(path.join(root, "release", stem, "node_modules/native"), {
56 recursive: true,
57 });
58 yield* fs.writeFileString(
59 path.join(root, "release", stem, "t3"),
60 '#!/bin/sh\necho "stub $* launcher=$T3CODE_NPM_LAUNCHER_PATH"\nexit 7\n',
61 );
62 yield* fs.chmod(path.join(root, "release", stem, "t3"), 0o755);
63 const tar = yield* run("tar", ["-czf", archiveName, stem], {
64 cwd: path.join(root, "release"),
65 env: { PATH: process.env.PATH },
66 });
67 assert.equal(tar.exitCode, 0, tar.stderr);
68 const archive = yield* fs.readFile(path.join(root, "release", archiveName));
69 let checksum = NodeCrypto.createHash("sha256").update(archive).digest("hex");
70 const requests: Array<string> = [];
71 const server = NodeHttp.createServer((request, response) => {
72 requests.push(request.url ?? "");
73 if (request.url === `/v${VERSION}/SHA256SUMS`) {
74 response.end(`${checksum} ${archiveName}\n`);
75 } else if (request.url === `/v${VERSION}/${archiveName}`) {
76 response.writeHead(200, { "Content-Length": archive.length }).end(archive);
77 } else {
78 response.writeHead(404).end();
79 }
80 });
81 yield* Effect.acquireRelease(
82 Effect.callback<void>((resume) => {
83 server.listen(0, "127.0.0.1", () => resume(Effect.void));
84 }),
85 () =>
86 Effect.callback<void>((resume) => {
87 server.close(() => resume(Effect.void));
88 }),
89 );
90 const address = server.address();
91 if (address === null || typeof address === "string") return yield* Effect.die("no TCP address");
92 return {
93 baseUrl: `http://127.0.0.1:${address.port}`,
94 requests,
95 corruptChecksum: () => {
96 checksum = "0".repeat(64);
97 },
98 };
99});
100
101it.layer(NodeServices.layer)("build-npm-launcher", (it) => {
102 it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")(
103 "publishes a launcher that downloads, verifies, caches, and runs the release executable",
104 () =>
105 Effect.gen(function* () {
106 const fs = yield* FileSystem.FileSystem;
107 const path = yield* Path.Path;
108 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-launcher-test-" });
109 const output = yield* buildNpmLauncher({
110 version: VERSION,
111 outputDir: path.join(root, "out"),
112 });
113
114 const manifest = yield* decodeManifest(
115 yield* fs.readFileString(path.join(output.packageDir, "package.json")),
116 );
117 assert.equal(manifest.name, "t3");
118 assert.equal(manifest.version, VERSION);
119 assert.deepStrictEqual(manifest.bin, { t3: "./bin/t3.mjs" });
120 // Nothing for npm to resolve, so nothing that can lag behind the launcher.
121 assert.isUndefined(manifest.dependencies);
122 assert.isUndefined(manifest.optionalDependencies);
123
124 // Run what npm would install: the published tarball, unpacked.
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 // The same layout the install scripts and `t3 update` use.
149 const versionDir = path.join(home, "runtime/versions", VERSION);
150 assert.equal(
151 (yield* fs.readFileString(path.join(versionDir, ".install-complete"))).trim(),
152 VERSION,
153 );
154 assert.isTrue(yield* fs.exists(path.join(versionDir, "node_modules/native")));
155 assert.deepStrictEqual(
156 (yield* fs.readDirectory(path.join(home, "runtime/versions"))).sort(),
157 [VERSION],
158 );
159
160 // A second run reuses the download.
161 const requestsAfterFirst = release.requests.length;
162 const second = yield* run(process.execPath, [launcher, "--version"], { cwd: root, env });
163 assert.equal(second.exitCode, 7);
164 assert.equal(release.requests.length, requestsAfterFirst);
165
166 // Services installed before 0.0.41 fork dist/bin.mjs and talk to the
167 // server over IPC; the channel and SIGTERM must reach the executable.
168 const ipcServer = path.join(home, "runtime/versions", VERSION, "t3");
169 yield* fs.writeFileString(
170 ipcServer,
171 `#!${process.execPath}\nprocess.on("SIGTERM", () => process.exit(23));\nprocess.on("message", (m) => process.send({ reply: m }));\nprocess.send({ args: process.argv.slice(2) });\n`,
172 );
173 const legacy = NodeChildProcess.fork(
174 path.join(packageDir, "dist/bin.mjs"),
175 ["__service-preflight", "a b"],
176 { env, silent: true },
177 );
178 yield* Effect.promise(async () => {
179 assert.deepStrictEqual((await NodeEvents.EventEmitter.once(legacy, "message"))[0], {
180 args: ["__service-preflight", "a b"],
181 });
182 const reply = NodeEvents.EventEmitter.once(legacy, "message");
183 legacy.send({ type: "trial-accepted" });
184 assert.deepStrictEqual((await reply)[0], { reply: { type: "trial-accepted" } });
185 const exit = NodeEvents.EventEmitter.once(legacy, "exit");
186 legacy.kill("SIGTERM");
187 assert.deepStrictEqual(await exit, [23, null]);
188 });
189
190 // Two first runs at once both start, and neither removes the other's install.
191 const raceHome = path.join(root, "race-home");
192 const launch = run(process.execPath, [launcher, "--version"], {
193 cwd: root,
194 env: { ...env, T3CODE_HOME: raceHome },
195 });
196 const [one, two] = yield* Effect.all([launch, launch], { concurrency: "unbounded" });
197 assert.equal(one.exitCode, 7, one.stderr);
198 assert.equal(two.exitCode, 7, two.stderr);
199 assert.deepStrictEqual(yield* fs.readDirectory(path.join(raceHome, "runtime/versions")), [
200 VERSION,
201 ]);
202
203 // A download that does not match the release checksums is never installed.
204 release.corruptChecksum();
205 const corrupt = yield* run(process.execPath, [launcher, "--version"], {
206 cwd: root,
207 env: { ...env, T3CODE_HOME: path.join(root, "other-home") },
208 });
209 assert.equal(corrupt.exitCode, 1);
210 assert.include(corrupt.stderr, "checksum mismatch");
211 assert.deepStrictEqual(
212 yield* fs.readDirectory(path.join(root, "other-home/runtime/versions")),
213 [],
214 );
215 }),
216 );
217});