Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - the spawn host tests watch real child processes.
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5import * as NodeURL from "node:url";
6
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { describe, expect, it } from "@effect/vitest";
9import * as Deferred from "effect/Deferred";
10import * as Duration from "effect/Duration";
11import * as Effect from "effect/Effect";
12import * as Fiber from "effect/Fiber";
13import * as Layer from "effect/Layer";
14import * as PlatformError from "effect/PlatformError";
15import * as Sink from "effect/Sink";
16import * as Stream from "effect/Stream";
17import { TestClock } from "effect/testing";
18import { ChildProcess, ChildProcessSpawner } from "effect/process";
19import * as HostProcess from "@t3tools/shared/HostProcess";
20import { SpawnExecutableResolution } from "@t3tools/shared/shell";
21
22import * as SpawnHost from "./process/SpawnHost.ts";
23import * as ProcessRunner from "./processRunner.ts";
24
25type ChildProcessCommand = {
26 readonly command: string;
27 readonly args: ReadonlyArray<string>;
28 readonly options: {
29 readonly shell?: boolean | string;
30 };
31};
32
33function asChildProcessCommand(command: unknown): ChildProcessCommand {
34 return command as ChildProcessCommand;
35}
36
37function makeHandle(input: {
38 readonly stdout?: string | Stream.Stream<Uint8Array>;
39 readonly stderr?: string | Stream.Stream<Uint8Array>;
40 readonly code?: number;
41 readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
42 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
43}) {
44 return ChildProcessSpawner.makeHandle({
45 pid: ChildProcessSpawner.ProcessId(1),
46 exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
47 isRunning: Effect.succeed(false),
48 kill: () => Effect.void,
49 unref: Effect.succeed(Effect.void),
50 stdin: input.stdin ?? Sink.drain,
51 stdout:
52 typeof input.stdout === "string"
53 ? Stream.encodeText(Stream.make(input.stdout))
54 : (input.stdout ?? Stream.empty),
55 stderr:
56 typeof input.stderr === "string"
57 ? Stream.encodeText(Stream.make(input.stderr))
58 : (input.stderr ?? Stream.empty),
59 all: Stream.empty,
60 getInputFd: () => Sink.drain,
61 getOutputFd: () => Stream.empty,
62 });
63}
64
65function makeSpawner(
66 f: (
67 command: ChildProcessCommand,
68 ) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>,
69) {
70 return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
71}
72
73const runWith =
74 (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) =>
75 (input: ProcessRunner.ProcessRunInput) =>
76 Effect.service(ProcessRunner.ProcessRunner).pipe(
77 Effect.flatMap((runner) =>
78 runner.run({
79 ...input,
80 }),
81 ),
82 Effect.provide(
83 ProcessRunner.layer.pipe(
84 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
85 ),
86 ),
87 );
88
89describe("runProcess", () => {
90 it.effect("collects stdout through an injected ChildProcessSpawner", () =>
91 Effect.gen(function* () {
92 const spawner = makeSpawner((command) =>
93 Effect.sync(() => {
94 expect(command.command).toBe("fake");
95 expect(command.args).toEqual(["stdout-bytes", "32"]);
96 return makeHandle({ stdout: "x".repeat(32) });
97 }),
98 );
99
100 const result = yield* runWith(spawner)({
101 command: "fake",
102 args: ["stdout-bytes", "32"],
103 });
104
105 expect(result.code).toBe(0);
106 expect(result.stdout).toBe("x".repeat(32));
107 expect(result.timedOut).toBe(false);
108 }),
109 );
110
111 it.effect("runs through the ProcessRunner service", () => {
112 const spawner = makeSpawner((command) =>
113 Effect.sync(() => {
114 expect(command.command).toBe("fake");
115 expect(command.args).toEqual(["--service"]);
116 return makeHandle({ stdout: "service ok" });
117 }),
118 );
119 const layer = ProcessRunner.layer.pipe(
120 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
121 );
122
123 return Effect.gen(function* () {
124 const runner = yield* ProcessRunner.ProcessRunner;
125 const result = yield* runner.run({
126 command: "fake",
127 args: ["--service"],
128 });
129
130 expect(result.stdout).toBe("service ok");
131 }).pipe(Effect.provide(layer));
132 });
133
134 it.effect("resolves and escapes Windows command shims before spawning", () => {
135 const spawner = makeSpawner((command) =>
136 Effect.sync(() => {
137 expect(command.command).toBe(
138 [
139 '^"C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd^"',
140 '^"repos^"',
141 '^"pr^"',
142 '^"list^"',
143 '^"--source-branch^"',
144 '^"feature^ ^&^ release^"',
145 ].join(" "),
146 );
147 expect(command.args).toEqual([]);
148 expect(command.options.shell).toBe(true);
149 return makeHandle({ stdout: "[]" });
150 }),
151 );
152
153 return runWith(spawner)({
154 command: "az",
155 args: ["repos", "pr", "list", "--source-branch", "feature & release"],
156 env: { AZURE_CONFIG_DIR: "C:\\Users\\tester\\.azure" },
157 }).pipe(
158 Effect.provideService(HostProcess.Platform, "win32"),
159 Effect.provideService(HostProcess.Environment, {
160 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
161 PATHEXT: ".COM;.EXE;.BAT;.CMD",
162 }),
163 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) =>
164 env.PATH === "C:\\Users\\tester\\AppData\\Roaming\\npm" &&
165 env.AZURE_CONFIG_DIR === "C:\\Users\\tester\\.azure"
166 ? "C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd"
167 : undefined,
168 ),
169 Effect.map((result) => {
170 expect(result.stdout).toBe("[]");
171 }),
172 );
173 });
174
175 it.effect("preserves resolved spawn context and cause", () =>
176 Effect.gen(function* () {
177 const cause = PlatformError.systemError({
178 _tag: "PermissionDenied",
179 module: "ChildProcessSpawner",
180 method: "spawn",
181 pathOrDescriptor: "/actual/fake",
182 });
183 const spawner = makeSpawner(() => Effect.fail(cause));
184
185 const error = yield* runWith(spawner)({
186 command: "fake",
187 args: ["--flag", "secret-token-value"],
188 cwd: "/logical",
189 spawnCwd: "/actual",
190 }).pipe(Effect.flip);
191
192 expect(error._tag).toBe("ProcessSpawnError");
193 if (error._tag !== "ProcessSpawnError") {
194 return expect.fail("Expected ProcessSpawnError");
195 }
196 expect(error).toMatchObject({
197 command: "fake",
198 argumentCount: 2,
199 cwd: "/logical",
200 spawnCwd: "/actual",
201 resolvedCommand: "fake",
202 resolvedArgumentCount: 2,
203 shell: false,
204 });
205 expect(error.cause).toBe(cause);
206 expect(error.message).toBe("Failed to spawn process 'fake' in '/actual'");
207 expect(error).not.toHaveProperty("args");
208 expect(error).not.toHaveProperty("resolvedArgs");
209 expect(error.message).not.toContain("secret-token-value");
210 }),
211 );
212
213 it.effect("types spawn failures that the platform spawner throws synchronously", () =>
214 Effect.gen(function* () {
215 // A non-directory entry on PATH makes node's spawn throw ENOTDIR
216 // synchronously. The platform spawner calls it inside `Effect.callback`,
217 // so the throw arrives as a defect rather than a typed error.
218 const defect = Object.assign(new Error("spawn jj ENOTDIR"), { code: "ENOTDIR" });
219 const spawner = makeSpawner(() =>
220 Effect.callback<never, never>(() => {
221 throw defect;
222 }),
223 );
224
225 const error = yield* runWith(spawner)({
226 command: "jj",
227 args: ["--version"],
228 cwd: "/repo",
229 }).pipe(Effect.flip);
230
231 expect(error._tag).toBe("ProcessSpawnError");
232 if (error._tag !== "ProcessSpawnError") {
233 return expect.fail("Expected ProcessSpawnError");
234 }
235 expect(error).toMatchObject({ command: "jj", argumentCount: 1, cwd: "/repo" });
236 expect(error.cause).toBe(defect);
237 }),
238 );
239
240 it.effect("fails when output exceeds max buffer in default mode", () =>
241 Effect.gen(function* () {
242 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
243
244 const error = yield* runWith(spawner)({
245 command: "fake",
246 args: ["stdout-bytes", "2048"],
247 maxOutputBytes: 128,
248 }).pipe(Effect.flip);
249
250 expect(error._tag).toBe("ProcessOutputLimitError");
251 if (error._tag !== "ProcessOutputLimitError") {
252 return expect.fail("Expected ProcessOutputLimitError");
253 }
254 expect(error).toMatchObject({
255 stream: "stdout",
256 maxBytes: 128,
257 observedBytes: 2048,
258 });
259 expect(error.message).toBe(
260 "Process 'fake' stdout produced 2048 bytes, exceeding the 128 byte limit",
261 );
262 }),
263 );
264
265 it.effect("accepts output at the byte limit followed by an empty chunk", () =>
266 Effect.gen(function* () {
267 const output = new TextEncoder().encode("exactly");
268 const spawner = makeSpawner(() =>
269 Effect.succeed(
270 makeHandle({
271 stdout: Stream.make(output, new Uint8Array()),
272 }),
273 ),
274 );
275
276 const result = yield* runWith(spawner)({
277 command: "fake",
278 args: ["exact-limit"],
279 maxOutputBytes: output.byteLength,
280 });
281
282 expect(result.stdout).toBe("exactly");
283 }),
284 );
285
286 it.effect("fails fast on output limit before timeout for long-running output", () =>
287 Effect.gen(function* () {
288 const textChunk = "x".repeat(64);
289 const spawner = makeSpawner(() =>
290 Effect.succeed(
291 makeHandle({
292 stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
293 Stream.encodeText,
294 ),
295 exitCode: Effect.never,
296 }),
297 ),
298 );
299
300 const error = yield* runWith(spawner)({
301 command: "fake",
302 args: ["spam-stdout"],
303 maxOutputBytes: 128,
304 timeout: "2 seconds",
305 }).pipe(Effect.flip);
306
307 expect(error).toBeInstanceOf(ProcessRunner.ProcessOutputLimitError);
308 }),
309 );
310
311 it.effect("truncates output when outputMode is truncate", () =>
312 Effect.gen(function* () {
313 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
314
315 const result = yield* runWith(spawner)({
316 command: "fake",
317 args: ["stdout-bytes", "2048"],
318 maxOutputBytes: 128,
319 outputMode: "truncate",
320 });
321
322 expect(result.code).toBe(0);
323 expect(result.stdout.length).toBeLessThanOrEqual(128);
324 expect(result.stdoutTruncated).toBe(true);
325 expect(result.stderrTruncated).toBe(false);
326 }),
327 );
328
329 it.effect("writes stdin before waiting for exit", () =>
330 Effect.gen(function* () {
331 const stdinWritten = yield* Deferred.make<void>();
332 const decoder = new TextDecoder();
333 const spawner = makeSpawner(() =>
334 Effect.succeed(
335 makeHandle({
336 stdout: "stdin payload",
337 stdin: Sink.forEach((chunk: Uint8Array) => {
338 const text = decoder.decode(chunk, { stream: true });
339 return text.includes("stdin payload")
340 ? Deferred.succeed(stdinWritten, undefined)
341 : Effect.void;
342 }),
343 exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
344 }),
345 ),
346 );
347
348 const result = yield* runWith(spawner)({
349 command: "fake",
350 args: ["stdin-echo"],
351 stdin: "stdin payload",
352 });
353
354 expect(result.stdout).toBe("stdin payload");
355 expect(result.code).toBe(0);
356 }),
357 );
358
359 it.effect("returns output for non-zero exit codes", () =>
360 Effect.gen(function* () {
361 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stderr: "boom", code: 2 })));
362
363 const result = yield* runWith(spawner)({
364 command: "fake",
365 args: ["stderr-exit", "boom", "2"],
366 });
367
368 expect(result.code).toBe(2);
369 expect(result.stderr).toBe("boom");
370 }),
371 );
372
373 it.effect("fails on timeout", () =>
374 Effect.gen(function* () {
375 const spawner = makeSpawner(() =>
376 Effect.succeed(
377 makeHandle({
378 exitCode: Effect.never,
379 }),
380 ),
381 );
382 const errorFiber = yield* runWith(spawner)({
383 command: "fake",
384 args: ["sleep"],
385 cwd: "/logical",
386 spawnCwd: "/actual",
387 timeout: "50 millis",
388 }).pipe(Effect.flip, Effect.forkScoped);
389
390 yield* Effect.yieldNow;
391 yield* TestClock.adjust(Duration.millis(50));
392 const error = yield* Fiber.join(errorFiber);
393
394 expect(error._tag).toBe("ProcessTimeoutError");
395 if (error._tag !== "ProcessTimeoutError") {
396 return expect.fail("Expected ProcessTimeoutError");
397 }
398 expect(error).toMatchObject({
399 command: "fake",
400 argumentCount: 1,
401 cwd: "/logical",
402 spawnCwd: "/actual",
403 timeoutMs: 50,
404 });
405 expect(error.message).toBe("Process 'fake' in '/actual' timed out after 50ms");
406 }),
407 );
408
409 it.effect("returns a synthetic timed out result when timeoutBehavior is timedOutResult", () =>
410 Effect.gen(function* () {
411 const spawner = makeSpawner(() =>
412 Effect.succeed(
413 makeHandle({
414 exitCode: Effect.never,
415 }),
416 ),
417 );
418 const resultFiber = yield* runWith(spawner)({
419 command: "fake",
420 args: ["sleep"],
421 timeout: "50 millis",
422 timeoutBehavior: "timedOutResult",
423 }).pipe(Effect.forkScoped);
424
425 yield* Effect.yieldNow;
426 yield* TestClock.adjust(Duration.millis(50));
427 const result = yield* Fiber.join(resultFiber);
428
429 expect(result).toMatchObject({
430 stdout: "",
431 stderr: "",
432 code: null,
433 timedOut: true,
434 stdoutTruncated: false,
435 stderrTruncated: false,
436 });
437 }),
438 );
439});
440
441const hostPlatform = HostProcess.Platform.defaultValue();
442
443describe.skipIf(hostPlatform === "win32")("runProcess through the spawn host", () => {
444 const hostFailures: Array<SpawnHost.SpawnHostFailure> = [];
445 const layer = ProcessRunner.layer.pipe(
446 Layer.provideMerge(
447 SpawnHost.layerHost(
448 process.execPath,
449 [NodeURL.fileURLToPath(new URL("./bin.ts", import.meta.url)), "__spawn-host"],
450 (failure) => hostFailures.push(failure),
451 ),
452 ),
453 Layer.provide(NodeServices.layer),
454 );
455 const run = (input: ProcessRunner.ProcessRunInput) =>
456 Effect.flatMap(Effect.service(ProcessRunner.ProcessRunner), (runner) => runner.run(input));
457 const isAlive = (pid: number) => {
458 try {
459 process.kill(pid, 0);
460 return true;
461 } catch {
462 return false;
463 }
464 };
465 /** Runs `sleep 30` that records its pid, so the test can find it. */
466 const sleeper = (pidFile: string) => ({
467 command: "sh",
468 args: ["-c", `echo $$ > '${pidFile}'; exec sleep 30`],
469 });
470 let pidFiles = 0;
471 const tempPidFile = () =>
472 NodePath.join(NodeOS.tmpdir(), `t3-spawn-host-${process.pid}-${++pidFiles}.pid`);
473 const readPid = (pidFile: string) =>
474 Effect.gen(function* () {
475 while (!NodeFS.existsSync(pidFile)) yield* Effect.sleep("20 millis");
476 yield* Effect.sleep("50 millis");
477 const pid = Number(NodeFS.readFileSync(pidFile, "utf8"));
478 NodeFS.rmSync(pidFile);
479 return pid;
480 });
481 /** `pid (comm) state ppid ...` */
482 const parentPid = (pid: number) =>
483 Number(NodeFS.readFileSync(`/proc/${pid}/stat`, "utf8").split(") ")[1]?.split(" ")[1]);
484 /** This process's open sockets by inode, so a reused fd number is not taken for the old socket. */
485 const openSockets = () =>
486 new Set(
487 NodeFS.readdirSync("/proc/self/fd").flatMap((fd) => {
488 try {
489 const target = NodeFS.readlinkSync(`/proc/self/fd/${fd}`);
490 return target.startsWith("socket:") ? [target] : [];
491 } catch {
492 return [];
493 }
494 }),
495 );
496
497 it.live("streams stdin, stdout, stderr and the exit code", () =>
498 Effect.gen(function* () {
499 const input = `${"x".repeat(2_000_000)}\n`;
500 const echoed = yield* run({
501 command: "sh",
502 args: ["-c", "cat; echo done >&2; exit 3"],
503 stdin: input,
504 maxOutputBytes: 4_000_000,
505 });
506 expect(echoed.stdout).toBe(input);
507 expect(echoed.stderr).toBe("done\n");
508 expect(echoed.code).toBe(3);
509 }).pipe(Effect.provide(layer)),
510 );
511
512 it.live("survives unread stdin resets and still reports active write failures", () =>
513 Effect.gen(function* () {
514 const child = { command: "sh", args: ["-c", "sleep .02; exit 0"] };
515 const result = yield* run({ ...child, stdin: "x".repeat(1024) });
516 expect(result.code).toBe(0);
517
518 const error = yield* run({ ...child, stdin: "x".repeat(2_000_000) }).pipe(Effect.flip);
519 expect(error).toBeInstanceOf(ProcessRunner.ProcessStdinError);
520 }).pipe(Effect.provide(layer)),
521 );
522
523 it.live.skipIf(hostPlatform !== "linux")(
524 "closes the sockets of output nobody reads once the child exits",
525 () =>
526 Effect.gen(function* () {
527 // Starts the host first, so its channel is not counted.
528 yield* run({ command: "true", args: [] });
529 const before = openSockets();
530 // The limit stops the reader with output still buffered in the socket.
531 const error = yield* run({ command: "yes", args: [], maxOutputBytes: 1_000 }).pipe(
532 Effect.flip,
533 );
534 expect(error._tag).toBe("ProcessOutputLimitError");
535 const leaked = () => [...openSockets()].filter((socket) => !before.has(socket));
536 for (let attempt = 0; attempt < 100 && leaked().length > 0; attempt++) {
537 yield* Effect.sleep("20 millis");
538 }
539 expect(leaked()).toEqual([]);
540 }).pipe(Effect.provide(layer)),
541 );
542
543 it.live.skipIf(hostPlatform !== "linux")(
544 "fails and stops a running child when the host dies, then starts a new host",
545 () =>
546 Effect.gen(function* () {
547 // An unreferenced child, like an editor the launcher detaches, outlives the host.
548 const keptPidFile = tempPidFile();
549 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
550 yield* spawner
551 .spawn(
552 ChildProcess.make("sh", ["-c", `echo $$ > '${keptPidFile}'; exec sleep 30`], {
553 detached: true,
554 stdin: "ignore",
555 stdout: "ignore",
556 stderr: "ignore",
557 }),
558 )
559 .pipe(
560 Effect.flatMap((handle) => handle.unref),
561 Effect.asVoid,
562 Effect.scoped,
563 );
564 const keptPid = yield* readPid(keptPidFile);
565 const pidFile = tempPidFile();
566 const running = yield* run(sleeper(pidFile)).pipe(Effect.flip, Effect.forkScoped);
567 const childPid = yield* readPid(pidFile);
568 // The children's parent is the host.
569 const hostPid = parentPid(childPid);
570 expect(hostPid).not.toBe(process.pid);
571 expect(parentPid(keptPid)).toBe(hostPid);
572 process.kill(hostPid, "SIGKILL");
573
574 const error = yield* Fiber.join(running);
575 expect(error._tag).toBe("ProcessReadError");
576 expect(isAlive(childPid)).toBe(false);
577 expect(isAlive(keptPid)).toBe(true);
578 process.kill(-keptPid, "SIGKILL");
579 expect(hostFailures.at(-1)).toMatchObject({ failures: 1, disabled: false });
580
581 const after = yield* run({ command: "echo", args: ["again"] });
582 expect(after.stdout).toBe("again\n");
583 }).pipe(Effect.provide(layer)),
584 );
585});
586
587describe("isWindowsCommandNotFound", () => {
588 it.effect("matches the localized German cmd.exe error text", () =>
589 Effect.gen(function* () {
590 const isCommandNotFound = yield* ProcessRunner.isWindowsCommandNotFound(
591 1,
592 "wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
593 ).pipe(Effect.provideService(HostProcess.Platform, "win32"));
594 expect(isCommandNotFound).toBe(true);
595 }),
596 );
597});
598
599describe("commandName", () => {
600 it("drops the directory from POSIX and Windows paths", () => {
601 expect(ProcessRunner.commandName("/Users/me/.local/bin/claude")).toBe("claude");
602 expect(ProcessRunner.commandName("C:\\Program Files\\nodejs\\npx.cmd")).toBe("npx.cmd");
603 expect(ProcessRunner.commandName("git")).toBe("git");
604 });
605});