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 "./lib/windows-tar.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 // Isolate system Node and inherited launcher context from the archive smoke check.
50 env: { PATH: "", HOME: cwd, USERPROFILE: cwd, TMPDIR: cwd, TEMP: cwd },
51 extendEnv: false,
52 }),
53 );
54 const [stdout, stderr, exitCode] = yield* Effect.all(
55 [collect(child.stdout), collect(child.stderr), child.exitCode.pipe(Effect.map(Number))],
56 { concurrency: "unbounded" },
57 );
58 return { stdout, stderr, exitCode };
59});
60
61const smokeCliArchive = Effect.fn("smokeCliArchive")(function* (input: {
62 readonly archive: string;
63 readonly expectVersion: string;
64}) {
65 const fs = yield* FileSystem.FileSystem;
66 const path = yield* Path.Path;
67 const platform = yield* HostProcess.Platform;
68 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
69 const scratch = yield* fs.makeTempDirectory({ prefix: "t3-cli-smoke-" });
70 // Windows can briefly retain executable locks; cleanup retries but must not fail a successful smoke check.
71 yield* Effect.addFinalizer(() =>
72 fs.remove(scratch, { recursive: true }).pipe(
73 Effect.retry({ times: 10, schedule: Schedule.spaced("500 millis") }),
74 Effect.catch((error) =>
75 Effect.logWarning(`[cli-smoke] could not remove ${scratch}: ${error.message}`),
76 ),
77 ),
78 );
79
80 // Windows bsdtar reads zip; Git Bash's GNU tar does not.
81 const tar = platform === "win32" ? windowsSystemTar() : "tar";
82 const extract = yield* spawner
83 .spawn(ChildProcess.make(tar, ["-xf", input.archive, "-C", scratch]))
84 .pipe(Effect.flatMap((child) => child.exitCode));
85 if (Number(extract) !== 0) {
86 return yield* new CliArchiveSmokeError({
87 step: "extracting the archive",
88 detail: `tar exited with ${String(extract)}`,
89 });
90 }
91 const [root] = yield* fs.readDirectory(scratch);
92 if (root === undefined) {
93 return yield* new CliArchiveSmokeError({
94 step: "extracting the archive",
95 detail: "the archive was empty",
96 });
97 }
98 const contentDir = path.join(scratch, root);
99 const executable = path.join(contentDir, platform === "win32" ? "t3.exe" : "t3");
100 for (const required of [executable, path.join(contentDir, "client/index.html")]) {
101 if (!(yield* fs.exists(required))) {
102 return yield* new CliArchiveSmokeError({
103 step: "checking the archive layout",
104 detail: `missing ${path.relative(contentDir, required)}`,
105 });
106 }
107 }
108
109 const version = yield* runExecutable(executable, ["--version"], contentDir);
110 if (version.exitCode !== 0 || !version.stdout.includes(input.expectVersion)) {
111 return yield* new CliArchiveSmokeError({
112 step: "running --version",
113 detail: `exit ${String(version.exitCode)}\n${version.stdout}${version.stderr}`,
114 });
115 }
116
117 const net = yield* NetService.NetService;
118 const port = yield* net.findAvailablePort(47700);
119 const home = path.join(scratch, "home");
120 const server = yield* spawner.spawn(
121 ChildProcess.make(
122 executable,
123 ["serve", "--host", "127.0.0.1", "--port", String(port), "--no-browser"],
124 {
125 cwd: contentDir,
126 env: {
127 PATH: "",
128 HOME: home,
129 USERPROFILE: home,
130 TMPDIR: scratch,
131 TEMP: scratch,
132 T3CODE_HOME: home,
133 // The archive has a release channel built in, so its events would
134 // look like a real new install.
135 T3CODE_TELEMETRY_ENABLED: "false",
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 // Probes can hang during server initialization; bound each request as SSH readiness does.
146 const probe = httpClient.execute(HttpClientRequest.get(`http://127.0.0.1:${String(port)}/`)).pipe(
147 Effect.map((response) => response.status === 200),
148 Effect.timeout(Duration.seconds(2)),
149 Effect.orElseSucceed(() => false),
150 );
151 const pollUntilReady = Effect.gen(function* () {
152 while (!(yield* probe)) {
153 yield* Effect.sleep(Duration.millis(250));
154 }
155 return true;
156 });
157 const ready = yield* pollUntilReady.pipe(
158 Effect.timeout(Duration.seconds(30)),
159 Effect.orElseSucceed(() => false),
160 );
161 yield* server.kill({ killSignal: "SIGTERM" }).pipe(Effect.ignore);
162 yield* server.exitCode.pipe(Effect.timeout(Duration.seconds(10)), Effect.ignore);
163 const [stdout, stderr] = yield* Fiber.join(output).pipe(
164 Effect.timeout(Duration.seconds(5)),
165 Effect.orElseSucceed(() => ["", ""] as const),
166 );
167 if (!ready) {
168 return yield* new CliArchiveSmokeError({
169 step: "serving from the extracted archive",
170 detail: `no 200 from / within 30s\n${stdout}${stderr}`,
171 });
172 }
173 yield* Effect.log(`[cli-smoke] ${root}: --version passed and serve answered on ${String(port)}.`);
174});
175
176const command = Command.make(
177 "smoke-cli-archive",
178 {
179 archive: Flag.String("archive"),
180 expectVersion: Flag.String("expect-version"),
181 },
182 (input) => smokeCliArchive(input).pipe(Effect.scoped),
183).pipe(Command.withDescription("Extract a CLI archive and run its executable."));
184
185if (import.meta.main) {
186 Command.run(command, { version: "0.0.0" }).pipe(
187 Effect.provide(
188 Layer.mergeAll(
189 Logger.layer([Logger.consolePretty()]),
190 NodeServices.layer,
191 NetService.layer,
192 FetchHttpClient.layer,
193 ),
194 ),
195 NodeRuntime.runMain,
196 );
197}