Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
4import * as Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Path from "effect/Path";
9import * as Schema from "effect/Schema";
10import * as Stream from "effect/Stream";
11import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
12import * as NodeNet from "node:net";
13
14import { buildRemoteT3RunnerScript } from "./tunnel.ts";
15
16const Started = Schema.Struct({
17 pid: Schema.Number,
18 port: Schema.Number,
19 args: Schema.Array(Schema.String),
20});
21const decodeStarted = Schema.decodeUnknownSync(Schema.fromJsonString(Started));
22
23describe.skipIf(HostProcessPlatform.defaultValue() === "win32")(
24 "remote runner process ownership",
25 () => {
26 it.live.each(["npx", "npm"] as const)(
27 "keeps the server PID and graceful shutdown through the %s fallback",
28 (packageManager) =>
29 Effect.gen(function* () {
30 const fs = yield* FileSystem.FileSystem;
31 const path = yield* Path.Path;
32 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
33 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3-runner-" });
34 const bin = path.join(fixture, "bin");
35 const cliPath = path.join(fixture, "installed cli.mjs");
36 const callsPath = path.join(fixture, "package-manager-calls.jsonl");
37 const packageSpec = "t3@0.0.35";
38 yield* fs.makeDirectory(bin);
39 yield* fs.symlink(process.execPath, path.join(bin, "node"));
40 yield* fs.writeFileString(
41 cliPath,
42 `#!/usr/bin/env node
43import * as net from "node:net";
44const server = net.createServer((socket) => {
45 socket.end();
46 server.close();
47});
48process.on("SIGTERM", () => server.close(() => {
49 process.stdout.write("graceful shutdown\\n");
50}));
51server.listen(Number(process.env.T3_TEST_PORT ?? 0), "127.0.0.1", () => {
52 process.stdout.write(JSON.stringify({
53 pid: process.pid,
54 port: server.address().port,
55 args: process.argv.slice(2),
56 }) + "\\n");
57});
58`,
59 );
60 yield* fs.chmod(cliPath, 0o700);
61 yield* fs.writeFileString(
62 path.join(bin, packageManager),
63 `#!/usr/bin/env node
64const fs = require("node:fs");
65const childProcess = require("node:child_process");
66const args = process.argv.slice(2);
67fs.appendFileSync(process.env.T3_TEST_CALLS, JSON.stringify(args) + "\\n");
68if (args.includes("--package")) {
69 process.stdout.write(process.env.T3_TEST_CLI + "\\n");
70} else {
71 const child = childProcess.spawn(process.execPath, [process.env.T3_TEST_CLI, ...args], { stdio: "inherit" });
72 child.once("exit", (code) => { process.exitCode = code ?? 1; });
73}
74`,
75 );
76 yield* fs.chmod(path.join(bin, packageManager), 0o700);
77
78 const runServer = (port = 0) =>
79 Effect.gen(function* () {
80 const child = yield* spawner.spawn(
81 ChildProcess.make("/bin/sh", ["-s", "--", "serve", "a path with spaces"], {
82 cwd: fixture,
83 env: {
84 PATH: bin,
85 T3_TEST_CLI: cliPath,
86 T3_TEST_CALLS: callsPath,
87 T3_TEST_PORT: String(port),
88 },
89 detached: false,
90 stdin: Stream.make(
91 new TextEncoder().encode(buildRemoteT3RunnerScript({ packageSpec })),
92 ),
93 }),
94 );
95 const ready = yield* Deferred.make<typeof Started.Type>();
96 const stdout: string[] = [];
97 const output = yield* child.stdout.pipe(
98 Stream.decodeText(),
99 Stream.splitLines,
100 Stream.runForEach((line) =>
101 Effect.gen(function* () {
102 stdout.push(line);
103 if (stdout.length === 1) {
104 yield* Deferred.succeed(ready, decodeStarted(line));
105 }
106 }),
107 ),
108 Effect.forkScoped,
109 );
110 const stderr = yield* child.stderr.pipe(
111 Stream.decodeText(),
112 Stream.mkString,
113 Effect.forkScoped,
114 );
115 const receipt = yield* Effect.raceFirst(
116 Deferred.await(ready),
117 Fiber.join(output).pipe(
118 Effect.flatMap(() => Fiber.join(stderr)),
119 Effect.flatMap((message) =>
120 Effect.die(new Error(`Runner exited before listening: ${message}`)),
121 ),
122 ),
123 );
124 // A failed PID assertion must still close the owned fixture server, including an npm child.
125 yield* Effect.addFinalizer(() =>
126 Effect.gen(function* () {
127 if (yield* child.isRunning) {
128 yield* Effect.callback<void>((resume) => {
129 const connection = NodeNet.connect(receipt.port, "127.0.0.1");
130 connection.on("error", () => undefined);
131 connection.once("close", () => resume(Effect.void));
132 return Effect.sync(() => connection.destroy());
133 });
134 yield* child.exitCode;
135 }
136 }).pipe(Effect.orDie),
137 );
138 assert.equal(receipt.pid, child.pid);
139 assert.deepEqual(receipt.args, ["serve", "a path with spaces"]);
140 yield* child.kill({ killSignal: "SIGTERM" });
141 assert.equal(yield* child.exitCode, 0);
142 yield* Fiber.join(output);
143 assert.include(stdout, "graceful shutdown");
144 return receipt.port;
145 }).pipe(Effect.scoped);
146
147 const port = yield* runServer();
148 assert.equal(yield* runServer(port), port);
149 const calls = (yield* fs.readFileString(callsPath))
150 .trim()
151 .split("\n")
152 .map((line) => JSON.parse(line));
153 const expectedCall = [
154 ...(packageManager === "npm" ? ["exec"] : []),
155 "--yes",
156 "--package",
157 packageSpec,
158 "--",
159 "sh",
160 "-c",
161 "command -v t3",
162 ];
163 assert.deepEqual(calls, [expectedCall, expectedCall]);
164 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
165 );
166 },
167);
168
169describe.skipIf(HostProcessPlatform.defaultValue() === "win32")(
170 "remote runner install diagnostics",
171 () => {
172 const decodeArguments = Schema.decodeUnknownSync(
173 Schema.fromJsonString(Schema.Array(Schema.String)),
174 );
175 const cases = (["npx", "npm"] as const).flatMap((packageManager) =>
176 (
177 [
178 "etarget",
179 "network",
180 "empty-success",
181 "success",
182 "failed-with-path",
183 "existing-cli",
184 "node-override",
185 ] as const
186 ).map((mode) => ({ packageManager, mode })),
187 );
188
189 it.live.each(cases)("handles $packageManager/$mode", ({ packageManager, mode }) =>
190 Effect.gen(function* () {
191 const fs = yield* FileSystem.FileSystem;
192 const path = yield* Path.Path;
193 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
194 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3-runner-install-" });
195 const bin = path.join(fixture, "bin");
196 const cliPath = path.join(fixture, "installed cli.mjs");
197 const callsPath = path.join(fixture, "installer-calls.jsonl");
198 const packageSpec = "t3@0.0.39-nightly.20260905.1286";
199 const args = ["serve", "a path with spaces"];
200 yield* fs.makeDirectory(bin);
201 yield* fs.symlink(process.execPath, path.join(bin, "node"));
202 yield* fs.writeFileString(
203 cliPath,
204 `#!/usr/bin/env node
205process.stdout.write(JSON.stringify(process.argv.slice(2)) + "\\n");
206`,
207 );
208 yield* fs.chmod(cliPath, 0o700);
209 yield* fs.writeFileString(callsPath, "");
210 yield* fs.writeFileString(
211 path.join(bin, packageManager),
212 `#!/usr/bin/env node
213const fs = require("node:fs");
214fs.appendFileSync(process.env.T3_TEST_CALLS, JSON.stringify(process.argv.slice(2)) + "\\n");
215const mode = process.env.T3_TEST_MODE;
216if (mode === "success" || mode === "failed-with-path") {
217 process.stdout.write(process.env.T3_TEST_CLI + "\\n");
218}
219if (mode === "etarget" || mode === "failed-with-path") {
220 process.stderr.write("npm error code ETARGET\\nnpm error notarget No matching version found.\\n");
221 process.exitCode = 42;
222} else if (mode === "network") {
223 process.stderr.write("npm error code ENETUNREACH\\n");
224 process.exitCode = 43;
225}
226`,
227 );
228 yield* fs.chmod(path.join(bin, packageManager), 0o700);
229 if (mode === "existing-cli") yield* fs.symlink(cliPath, path.join(bin, "t3"));
230
231 const child = yield* spawner.spawn(
232 ChildProcess.make("/bin/sh", ["-s", "--", ...args], {
233 cwd: fixture,
234 extendEnv: false,
235 env: {
236 PATH: bin,
237 T3_TEST_MODE: mode,
238 T3_TEST_CLI: cliPath,
239 T3_TEST_CALLS: callsPath,
240 },
241 stdin: Stream.make(
242 new TextEncoder().encode(
243 buildRemoteT3RunnerScript({
244 packageSpec,
245 ...(mode === "node-override" ? { nodeScriptPath: cliPath } : {}),
246 }),
247 ),
248 ),
249 }),
250 );
251 const { stdout, stderr, exitCode } = yield* Effect.all(
252 {
253 stdout: child.stdout.pipe(Stream.decodeText(), Stream.mkString),
254 stderr: child.stderr.pipe(Stream.decodeText(), Stream.mkString),
255 exitCode: child.exitCode,
256 },
257 { concurrency: "unbounded" },
258 );
259 const installFailed =
260 mode === "etarget" || mode === "network" || mode === "failed-with-path";
261 const missingExecutable = mode === "empty-success";
262 assert.equal(exitCode, installFailed || missingExecutable ? 1 : 0);
263 if (installFailed || missingExecutable) {
264 assert.equal(stdout, "");
265 } else {
266 assert.deepEqual(decodeArguments(stdout), args);
267 }
268 if (installFailed) {
269 const npmError = mode === "network" ? "ENETUNREACH" : "ETARGET";
270 assert.include(stderr, `npm error code ${npmError}\n`);
271 assert.include(stderr, `Remote host could not install ${packageSpec}.`);
272 assert.notInclude(stderr, "Remote host installed");
273 assert.notInclude(stderr, "Install a C toolchain");
274 } else if (missingExecutable) {
275 assert.include(stderr, `Remote host installed ${packageSpec}`);
276 assert.include(stderr, "npm produced no t3 executable");
277 assert.include(stderr, "Install a C toolchain");
278 } else {
279 assert.equal(stderr, "");
280 }
281 const expectedCall = [
282 ...(packageManager === "npm" ? ["exec"] : []),
283 "--yes",
284 "--package",
285 packageSpec,
286 "--",
287 "sh",
288 "-c",
289 "command -v t3",
290 ];
291 const usesInstaller = mode !== "existing-cli" && mode !== "node-override";
292 const calls = yield* fs.readFileString(callsPath);
293 if (usesInstaller) {
294 assert.deepEqual(
295 calls
296 .trim()
297 .split("\n")
298 .map((line) => decodeArguments(line)),
299 [expectedCall],
300 );
301 } else {
302 assert.equal(calls, "");
303 }
304 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
305 );
306 },
307);