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

smoke-cli-archive.ts

198 lines7.1 KB

1#!/usr/bin/env node
2/**
3 * Unpacks a CLI archive into a scratch directory and runs the executable the
4 * way an installer would: no repo, no node_modules, no Node on PATH. Catches
5 * the failures that only show inside the single-executable, such as an
6 * external package reached through `import` or a native addon the hardened
7 * runtime refuses to load.
8 */
9import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
10import * as NodeServices from "@effect/platform-node/NodeServices";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Fiber from "effect/Fiber";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Logger from "effect/Logger";
17import * as Path from "effect/Path";
18import * as Schema from "effect/Schema";
19import * as Stream from "effect/Stream";
20import { Command, Flag } from "effect/unstable/cli";
21import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
22​
23import * as NetService from "@t3tools/shared/Net";
24import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
25import { windowsSystemTar } from "./build-cli-archive.ts";
26import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
27​
28export class CliArchiveSmokeError extends Schema.TaggedError<CliArchiveSmokeError>()(
29 "CliArchiveSmokeError",
30 { step: Schema.String, detail: Schema.String },
31) {
32 override get message(): string {
33 return `CLI archive smoke test failed while ${this.step}: ${this.detail}`;
34 }
36​
37const collect = <E>(stream: Stream.Stream<Uint8Array, E>) =>
38 stream.pipe(
39 Stream.decodeText(),
40 Stream.runFold(
41 () => "",
42 (acc, chunk) => acc + chunk,
43 ),
44 );
45​
46const runExecutable = Effect.fn("runExecutable")(function* (
47 executable: string,
48 args: ReadonlyArray<string>,
49 cwd: string,
50) {
51 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
52 const child = yield* spawner.spawn(
53 ChildProcess.make(executable, args, {
54 cwd,
55 // Empty PATH: the archive must not reach a system node, and the
56 // launcher context must not leak in from a developer shell.
57 env: { PATH: "", HOME: cwd, USERPROFILE: cwd, TMPDIR: cwd, TEMP: cwd },
58 extendEnv: false,
59 }),
60 );
61 const [stdout, stderr, exitCode] = yield* Effect.all(
62 [collect(child.stdout), collect(child.stderr), child.exitCode.pipe(Effect.map(Number))],
63 { concurrency: "unbounded" },
64 );
65 return { stdout, stderr, exitCode };
66});
67​
68const smokeCliArchive = Effect.fn("smokeCliArchive")(function* (input: {
69 readonly archive: string;
70 readonly expectVersion: string;
71}) {
72 const fs = yield* FileSystem.FileSystem;
73 const path = yield* Path.Path;
74 const platform = yield* HostProcessPlatform;
75 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
76 const scratch = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-smoke-" });
77​
78 // On Windows the archive is a zip and the Git Bash `tar` on PATH is GNU
79 // tar; use the bsdtar Windows ships, which reads both formats.
80 const tar = platform === "win32" ? windowsSystemTar() : "tar";
81 const extract = yield* spawner
82 .spawn(ChildProcess.make(tar, ["-xf", input.archive, "-C", scratch]))
83 .pipe(Effect.flatMap((child) => child.exitCode));
84 if (Number(extract) !== 0) {
85 return yield* new CliArchiveSmokeError({
86 step: "extracting the archive",
87 detail: `tar exited with ${String(extract)}`,
88 });
89 }
90 const [root] = yield* fs.readDirectory(scratch);
91 if (root === undefined) {
92 return yield* new CliArchiveSmokeError({
93 step: "extracting the archive",
94 detail: "the archive was empty",
95 });
96 }
97 const contentDir = path.join(scratch, root);
98 const executable = path.join(contentDir, platform === "win32" ? "t3.exe" : "t3");
99 for (const required of [executable, path.join(contentDir, "client/index.html")]) {
100 if (!(yield* fs.exists(required))) {
101 return yield* new CliArchiveSmokeError({
102 step: "checking the archive layout",
103 detail: `missing ${path.relative(contentDir, required)}`,
104 });
105 }
106 }
107​
108 const version = yield* runExecutable(executable, ["--version"], contentDir);
109 if (version.exitCode !== 0 || !version.stdout.includes(input.expectVersion)) {
110 return yield* new CliArchiveSmokeError({
111 step: "running --version",
112 detail: `exit ${String(version.exitCode)}\n${version.stdout}${version.stderr}`,
113 });
114 }
115​
116 // Starting the server is what actually opens sqlite, loads the terminal
117 // and search stacks (node-pty, fff, msgpackr-extract), and serves the
118 // client, so probe a real `serve` in a scratch home rather than a
119 // command that only reads package metadata.
120 const net = yield* NetService.NetService;
121 const port = yield* net.findAvailablePort(47700);
122 const home = path.join(scratch, "home");
123 const server = yield* spawner.spawn(
124 ChildProcess.make(
125 executable,
126 ["serve", "--host", "127.0.0.1", "--port", String(port), "--no-browser"],
127 {
128 cwd: contentDir,
129 env: {
130 PATH: "",
131 HOME: home,
132 USERPROFILE: home,
133 TMPDIR: scratch,
134 TEMP: scratch,
135 T3CODE_HOME: home,
136 },
137 extendEnv: false,
138 },
139 ),
140 );
141 const output = yield* Effect.forkScoped(
142 Effect.all([collect(server.stdout), collect(server.stderr)]),
143 );
144 const httpClient = yield* HttpClient.HttpClient;
145 // A request that connects while the server is still initializing can hang,
146 // so each probe gets its own deadline, like the SSH readiness probe.
147 const probe = httpClient.execute(HttpClientRequest.get(`http://127.0.0.1:${String(port)}/`)).pipe(
148 Effect.map((response) => response.status === 200),
149 Effect.timeout(Duration.seconds(2)),
150 Effect.orElseSucceed(() => false),
151 );
152 const pollUntilReady = Effect.gen(function* () {
153 while (!(yield* probe)) {
154 yield* Effect.sleep(Duration.millis(250));
155 }
156 return true;
157 });
158 const ready = yield* pollUntilReady.pipe(
159 Effect.timeout(Duration.seconds(30)),
160 Effect.orElseSucceed(() => false),
161 );
162 yield* server.kill({ killSignal: "SIGTERM" }).pipe(Effect.ignore);
163 yield* server.exitCode.pipe(Effect.timeout(Duration.seconds(10)), Effect.ignore);
164 const [stdout, stderr] = yield* Fiber.join(output).pipe(
165 Effect.timeout(Duration.seconds(5)),
166 Effect.orElseSucceed(() => ["", ""] as const),
167 );
168 if (!ready) {
169 return yield* new CliArchiveSmokeError({
170 step: "serving from the extracted archive",
171 detail: `no 200 from / within 30s\n${stdout}${stderr}`,
172 });
173 }
174 yield* Effect.log(`[cli-smoke] ${root}: --version passed and serve answered on ${String(port)}.`);
175});
176​
177const command = Command.make(
178 "smoke-cli-archive",
179 {
180 archive: Flag.string("archive"),
181 expectVersion: Flag.string("expect-version"),
182 },
183 (input) => smokeCliArchive(input).pipe(Effect.scoped),
184).pipe(Command.withDescription("Extract a CLI archive and run its executable."));
185​
186if (import.meta.main) {
187 Command.run(command, { version: "0.0.0" }).pipe(
188 Effect.provide(
189 Layer.mergeAll(
190 Logger.layer([Logger.consolePretty()]),
191 NodeServices.layer,
192 NetService.layer,
193 FetchHttpClient.layer,
194 ),
195 ),
196 NodeRuntime.runMain,
197 );