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

runnerProcess.test.ts

430 lines16.6 KB

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 { buildRemoteStopScript, 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; });
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 stop process ownership",
171 () => {
172 it.live.each(["graceful", "timeout", "external"] as const)(
173 "confirms the stop result for a %s server",
174 (mode) =>
175 Effect.gen(function* () {
176 const fs = yield* FileSystem.FileSystem;
177 const path = yield* Path.Path;
178 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
179 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3-stop-" });
180 const signalPath = path.join(fixture, "signals");
181 const child = yield* spawner.spawn(
182 ChildProcess.make(
183 process.execPath,
184 [
185 "--input-type=module",
186 "-e",
187 `import * as fs from "node:fs";
188import * as net from "node:net";
189const server = net.createServer((socket) => socket.end());
190let signals = 0;
191process.on("SIGTERM", () => {
192 fs.writeFileSync(process.argv[2], String(++signals));
193 if (process.argv[1] !== "timeout" || signals > 1) server.close();
194});
195server.listen(0, "127.0.0.1", () => {
196 process.stdout.write(JSON.stringify({ pid: process.pid, port: server.address().port, args: [] }) + "\\n");
197});
198`,
199 mode,
200 signalPath,
201 ],
202 { cwd: fixture, detached: false },
203 ),
204 );
205 // A failed assertion must still stop this captured fixture process.
206 yield* Effect.addFinalizer(() =>
207 child.kill({ killSignal: "SIGKILL" }).pipe(Effect.ignore),
208 );
209 const started = decodeStarted(
210 yield* child.stdout.pipe(
211 Stream.decodeText(),
212 Stream.splitLines,
213 Stream.take(1),
214 Stream.mkString,
215 ),
216 );
217 assert.equal(started.pid, child.pid);
218 const savedState = {
219 pid: `${child.pid}\n`,
220 port: `${started.port}\n`,
221 managed: mode === "external" ? "external\n" : "managed\n",
222 };
223 for (const [name, contents] of Object.entries(savedState)) {
224 yield* fs.writeFileString(path.join(fixture, name), contents);
225 }
226 const script = buildRemoteStopScript({
227 alias: "fixture",
228 hostname: "fixture",
229 username: null,
230 port: null,
231 });
232 // Redirect only the state directory. Never use the developer's SSH state.
233 const isolatedScript = script.replace(
234 /^STATE_DIR=.*$/mu,
235 'STATE_DIR="$T3_TEST_STATE_DIR"',
236 );
237 assert.notEqual(isolatedScript, script);
238 const runStop = Effect.fn("test.remoteStop")(function* () {
239 const stop = yield* spawner.spawn(
240 ChildProcess.make("/bin/sh", ["-s"], {
241 cwd: fixture,
242 env: { T3_TEST_STATE_DIR: fixture },
243 stdin: Stream.make(new TextEncoder().encode(isolatedScript)),
244 }),
245 );
246 return yield* Effect.all(
247 {
248 stdout: stop.stdout.pipe(Stream.decodeText(), Stream.mkString),
249 stderr: stop.stderr.pipe(Stream.decodeText(), Stream.mkString),
250 exitCode: stop.exitCode,
251 },
252 { concurrency: "unbounded" },
253 );
254 }, Effect.scoped);
255 let result = yield* runStop();
256 if (mode !== "graceful") {
257 assert.isTrue(yield* child.isRunning);
258 yield* Effect.callback<void, Error>((resume) => {
259 const connection = NodeNet.connect(started.port, "127.0.0.1");
260 connection.once("error", (error) => resume(Effect.fail(error)));
261 connection.once("close", () => resume(Effect.void));
262 return Effect.sync(() => connection.destroy());
263 });
264 }
265 if (mode === "timeout") {
266 assert.equal(result.exitCode, 1);
267 assert.equal(result.stdout, "");
268 assert.include(result.stderr, "did not stop within 2 seconds");
269 assert.equal(yield* fs.readFileString(signalPath), "1");
270 for (const [name, contents] of Object.entries(savedState)) {
271 assert.equal(yield* fs.readFileString(path.join(fixture, name)), contents);
272 }
273 result = yield* runStop();
274 }
275 assert.equal(result.exitCode, 0);
276 assert.equal(result.stdout, '{"stopped":true}\n');
277 assert.equal(result.stderr, "");
278 for (const name of Object.keys(savedState)) {
279 assert.isFalse(yield* fs.exists(path.join(fixture, name)));
280 }
281 if (mode === "external") {
282 assert.isFalse(yield* fs.exists(signalPath));
283 } else {
284 assert.equal(yield* child.exitCode, 0);
285 assert.equal(yield* fs.readFileString(signalPath), mode === "timeout" ? "2" : "1");
286 }
287 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
288 );
289 },
290);
291​
292describe.skipIf(HostProcessPlatform.defaultValue() === "win32")(
293 "remote runner install diagnostics",
294 () => {
295 const decodeArguments = Schema.decodeUnknownSync(
296 Schema.fromJsonString(Schema.Array(Schema.String)),
297 );
298 const cases = (["npx", "npm"] as const).flatMap((packageManager) =>
299 (
300 [
301 "etarget",
302 "network",
303 "empty-success",
304 "success",
305 "failed-with-path",
306 "existing-cli",
307 "node-override",
308 ] as const
309 ).map((mode) => ({ packageManager, mode })),
310 );
311​
312 it.live.each(cases)("handles $packageManager/$mode", ({ packageManager, mode }) =>
313 Effect.gen(function* () {
314 const fs = yield* FileSystem.FileSystem;
315 const path = yield* Path.Path;
316 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
317 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3-runner-install-" });
318 const bin = path.join(fixture, "bin");
319 const cliPath = path.join(fixture, "installed cli.mjs");
320 const callsPath = path.join(fixture, "installer-calls.jsonl");
321 const packageSpec = "t3@0.0.39-nightly.20260905.1286";
322 const args = ["serve", "a path with spaces"];
323 yield* fs.makeDirectory(bin);
324 yield* fs.symlink(process.execPath, path.join(bin, "node"));
325 yield* fs.writeFileString(
326 cliPath,
327 `#!/usr/bin/env node
328process.stdout.write(JSON.stringify(process.argv.slice(2)) + "\\n");
329`,
330 );
331 yield* fs.chmod(cliPath, 0o700);
332 yield* fs.writeFileString(callsPath, "");
333 yield* fs.writeFileString(
334 path.join(bin, packageManager),
335 `#!/usr/bin/env node
336const fs = require("node:fs");
337fs.appendFileSync(process.env.T3_TEST_CALLS, JSON.stringify(process.argv.slice(2)) + "\\n");
338const mode = process.env.T3_TEST_MODE;
339if (mode === "success" || mode === "failed-with-path") {
340 process.stdout.write(process.env.T3_TEST_CLI + "\\n");
342if (mode === "etarget" || mode === "failed-with-path") {
343 process.stderr.write("npm error code ETARGET\\nnpm error notarget No matching version found.\\n");
344 process.exitCode = 42;
345} else if (mode === "network") {
346 process.stderr.write("npm error code ENETUNREACH\\n");
347 process.exitCode = 43;
349`,
350 );
351 yield* fs.chmod(path.join(bin, packageManager), 0o700);
352 if (mode === "existing-cli") yield* fs.symlink(cliPath, path.join(bin, "t3"));
353​
354 const child = yield* spawner.spawn(
355 ChildProcess.make("/bin/sh", ["-s", "--", ...args], {
356 cwd: fixture,
357 extendEnv: false,
358 env: {
359 PATH: bin,
360 T3_TEST_MODE: mode,
361 T3_TEST_CLI: cliPath,
362 T3_TEST_CALLS: callsPath,
363 },
364 stdin: Stream.make(
365 new TextEncoder().encode(
366 buildRemoteT3RunnerScript({
367 packageSpec,
368 ...(mode === "node-override" ? { nodeScriptPath: cliPath } : {}),
369 }),
370 ),
371 ),
372 }),
373 );
374 const { stdout, stderr, exitCode } = yield* Effect.all(
375 {
376 stdout: child.stdout.pipe(Stream.decodeText(), Stream.mkString),
377 stderr: child.stderr.pipe(Stream.decodeText(), Stream.mkString),
378 exitCode: child.exitCode,
379 },
380 { concurrency: "unbounded" },
381 );
382 const installFailed =
383 mode === "etarget" || mode === "network" || mode === "failed-with-path";
384 const missingExecutable = mode === "empty-success";
385 assert.equal(exitCode, installFailed || missingExecutable ? 1 : 0);
386 if (installFailed || missingExecutable) {
387 assert.equal(stdout, "");
388 } else {
389 assert.deepEqual(decodeArguments(stdout), args);
390 }
391 if (installFailed) {
392 const npmError = mode === "network" ? "ENETUNREACH" : "ETARGET";
393 assert.include(stderr, `npm error code ${npmError}\n`);
394 assert.include(stderr, `Remote host could not install ${packageSpec}.`);
395 assert.notInclude(stderr, "Remote host installed");
396 assert.notInclude(stderr, "Install a C toolchain");
397 } else if (missingExecutable) {
398 assert.include(stderr, `Remote host installed ${packageSpec}`);
399 assert.include(stderr, "npm produced no t3 executable");
400 assert.include(stderr, "Install a C toolchain");
401 } else {
402 assert.equal(stderr, "");
403 }
404 const expectedCall = [
405 ...(packageManager === "npm" ? ["exec"] : []),
406 "--yes",
407 "--package",
408 packageSpec,
409 "--",
410 "sh",
411 "-c",
412 "command -v t3",
413 ];
414 const usesInstaller = mode !== "existing-cli" && mode !== "node-override";
415 const calls = yield* fs.readFileString(callsPath);
416 if (usesInstaller) {
417 assert.deepEqual(
418 calls
419 .trim()
420 .split("\n")
421 .map((line) => decodeArguments(line)),
422 [expectedCall],
423 );
424 } else {
425 assert.equal(calls, "");
426 }
427 }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
428 );
429 },
430);