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