Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - A test kills the helper mid-handoff and watches its child through a FIFO.
2import { isWindowsCommandNotFound } from "@t3tools/provider-core/server/snapshotProbe";
3import * as NodeChildProcess from "node:child_process";
4import * as NodeFS from "node:fs";
5import * as NodeModule from "node:module";
6import * as NodeNet from "node:net";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import { describe, expect, it } from "@effect/vitest";
9import * as Context from "effect/Context";
10import * as Deferred from "effect/Deferred";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Cause from "effect/Cause";
14import * as FileSystem from "effect/FileSystem";
15import * as Fiber from "effect/Fiber";
16import * as Layer from "effect/Layer";
17import * as PlatformError from "effect/PlatformError";
18import * as Sink from "effect/Sink";
19import * as Stream from "effect/Stream";
20import { ChildProcess, ChildProcessSpawner } from "effect/process";
21import * as HostProcess from "@t3tools/shared/HostProcess";
22import { SpawnExecutableResolution } from "@t3tools/shared/shell";
23
24import * as ProcessLauncher from "./process/ProcessLauncher.ts";
25import * as ProcessRunner from "./processRunner.ts";
26
27type ChildProcessCommand = {
28 readonly command: string;
29 readonly args: ReadonlyArray<string>;
30 readonly options: {
31 readonly shell?: boolean | string;
32 };
33};
34
35function asChildProcessCommand(command: unknown): ChildProcessCommand {
36 return command as ChildProcessCommand;
37}
38
39function makeHandle(input: {
40 readonly stdout?: string | Stream.Stream<Uint8Array>;
41 readonly stderr?: string | Stream.Stream<Uint8Array>;
42 readonly code?: number;
43 readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
44 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
45}) {
46 return ChildProcessSpawner.makeHandle({
47 pid: ChildProcessSpawner.ProcessId(1),
48 exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
49 isRunning: Effect.succeed(false),
50 kill: () => Effect.void,
51 unref: Effect.succeed(Effect.void),
52 stdin: input.stdin ?? Sink.drain,
53 stdout:
54 typeof input.stdout === "string"
55 ? Stream.encodeText(Stream.make(input.stdout))
56 : (input.stdout ?? Stream.empty),
57 stderr:
58 typeof input.stderr === "string"
59 ? Stream.encodeText(Stream.make(input.stderr))
60 : (input.stderr ?? Stream.empty),
61 all: Stream.empty,
62 getInputFd: () => Sink.drain,
63 getOutputFd: () => Stream.empty,
64 });
65}
66
67function makeSpawner(
68 f: (
69 command: ChildProcessCommand,
70 ) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>,
71) {
72 return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
73}
74
75const runWith =
76 (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) =>
77 (input: ProcessRunner.ProcessRunInput) =>
78 Effect.service(ProcessRunner.ProcessRunner).pipe(
79 Effect.flatMap((runner) =>
80 runner.run({
81 ...input,
82 }),
83 ),
84 Effect.provide(
85 ProcessRunner.layer.pipe(
86 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
87 ),
88 ),
89 );
90
91describe("runProcess", () => {
92 it.effect("resolves and escapes Windows command shims before spawning", () => {
93 const spawner = makeSpawner((command) =>
94 Effect.sync(() => {
95 expect(command.command).toBe(
96 [
97 '^"C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd^"',
98 '^"repos^"',
99 '^"pr^"',
100 '^"list^"',
101 '^"--source-branch^"',
102 '^"feature^ ^&^ release^"',
103 ].join(" "),
104 );
105 expect(command.args).toEqual([]);
106 expect(command.options.shell).toBe(true);
107 return makeHandle({ stdout: "[]" });
108 }),
109 );
110
111 return runWith(spawner)({
112 command: "az",
113 args: ["repos", "pr", "list", "--source-branch", "feature & release"],
114 env: { AZURE_CONFIG_DIR: "C:\\Users\\tester\\.azure" },
115 }).pipe(
116 Effect.provideService(HostProcess.Platform, "win32"),
117 Effect.provideService(HostProcess.Environment, {
118 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
119 PATHEXT: ".COM;.EXE;.BAT;.CMD",
120 }),
121 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) =>
122 env.PATH === "C:\\Users\\tester\\AppData\\Roaming\\npm" &&
123 env.AZURE_CONFIG_DIR === "C:\\Users\\tester\\.azure"
124 ? "C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd"
125 : undefined,
126 ),
127 Effect.map((result) => {
128 expect(result.stdout).toBe("[]");
129 }),
130 );
131 });
132
133 it.effect("types spawn failures that the platform spawner throws synchronously", () =>
134 Effect.gen(function* () {
135 // File-valued PATH entries make spawn throw ENOTDIR synchronously, arriving through Effect.callback as a defect.
136 const defect = Object.assign(new Error("spawn jj ENOTDIR"), { code: "ENOTDIR" });
137 const spawner = makeSpawner(() =>
138 Effect.callback<never, never>(() => {
139 throw defect;
140 }),
141 );
142
143 const error = yield* runWith(spawner)({
144 command: "jj",
145 args: ["--version"],
146 cwd: "/repo",
147 }).pipe(Effect.flip);
148
149 expect(error._tag).toBe("ProcessSpawnError");
150 if (error._tag !== "ProcessSpawnError") {
151 return expect.fail("Expected ProcessSpawnError");
152 }
153 expect(error).toMatchObject({ command: "jj", argumentCount: 1, cwd: "/repo" });
154 expect(error.cause).toBe(defect);
155 }),
156 );
157
158 it.effect("reports child startup before delivering cancellation during acquisition", () =>
159 Effect.gen(function* () {
160 let started = false;
161 const spawner = makeSpawner(() =>
162 Effect.withFiber((fiber) =>
163 Effect.sync(() => {
164 fiber.interruptUnsafe();
165 return makeHandle({});
166 }),
167 ),
168 );
169 const result = yield* runWith(spawner)({
170 command: "git",
171 args: ["restore"],
172 onSpawn: () => {
173 started = true;
174 },
175 }).pipe(Effect.exit);
176 expect(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)).toBe(true);
177 expect(started).toBe(true);
178 }).pipe(Effect.scoped),
179 );
180
181 it.effect("fails when output exceeds max buffer in default mode", () =>
182 Effect.gen(function* () {
183 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
184
185 const error = yield* runWith(spawner)({
186 command: "fake",
187 args: ["stdout-bytes", "2048"],
188 maxOutputBytes: 128,
189 }).pipe(Effect.flip);
190
191 expect(error._tag).toBe("ProcessOutputLimitError");
192 if (error._tag !== "ProcessOutputLimitError") {
193 return expect.fail("Expected ProcessOutputLimitError");
194 }
195 expect(error).toMatchObject({
196 stream: "stdout",
197 maxBytes: 128,
198 observedBytes: 2048,
199 });
200 expect(error.message).toBe(
201 "Process 'fake' stdout produced 2048 bytes, exceeding the 128 byte limit",
202 );
203 }),
204 );
205
206 it.effect("accepts output at the byte limit followed by an empty chunk", () =>
207 Effect.gen(function* () {
208 const output = new TextEncoder().encode("exactly");
209 const spawner = makeSpawner(() =>
210 Effect.succeed(
211 makeHandle({
212 stdout: Stream.make(output, new Uint8Array()),
213 }),
214 ),
215 );
216
217 const result = yield* runWith(spawner)({
218 command: "fake",
219 args: ["exact-limit"],
220 maxOutputBytes: output.byteLength,
221 });
222
223 expect(result.stdout).toBe("exactly");
224 }),
225 );
226
227 it.effect("fails fast on output limit before timeout for long-running output", () =>
228 Effect.gen(function* () {
229 const textChunk = "x".repeat(64);
230 const spawner = makeSpawner(() =>
231 Effect.succeed(
232 makeHandle({
233 stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
234 Stream.encodeText,
235 ),
236 exitCode: Effect.never,
237 }),
238 ),
239 );
240
241 const error = yield* runWith(spawner)({
242 command: "fake",
243 args: ["spam-stdout"],
244 maxOutputBytes: 128,
245 timeout: "2 seconds",
246 }).pipe(Effect.flip);
247
248 expect(error).toBeInstanceOf(ProcessRunner.ProcessOutputLimitError);
249 }),
250 );
251
252 it.effect("truncates output when outputMode is truncate", () =>
253 Effect.gen(function* () {
254 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
255
256 const result = yield* runWith(spawner)({
257 command: "fake",
258 args: ["stdout-bytes", "2048"],
259 maxOutputBytes: 128,
260 outputMode: "truncate",
261 });
262
263 expect(result.code).toBe(0);
264 expect(result.stdout.length).toBeLessThanOrEqual(128);
265 expect(result.stdoutTruncated).toBe(true);
266 expect(result.stderrTruncated).toBe(false);
267 }),
268 );
269
270 it.effect("writes stdin before waiting for exit", () =>
271 Effect.gen(function* () {
272 const stdinWritten = yield* Deferred.make<void>();
273 const decoder = new TextDecoder();
274 const spawner = makeSpawner(() =>
275 Effect.succeed(
276 makeHandle({
277 stdout: "stdin payload",
278 stdin: Sink.forEach((chunk: Uint8Array) => {
279 const text = decoder.decode(chunk, { stream: true });
280 return text.includes("stdin payload")
281 ? Deferred.succeed(stdinWritten, undefined)
282 : Effect.void;
283 }),
284 exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
285 }),
286 ),
287 );
288
289 const result = yield* runWith(spawner)({
290 command: "fake",
291 args: ["stdin-echo"],
292 stdin: "stdin payload",
293 });
294
295 expect(result.stdout).toBe("stdin payload");
296 expect(result.code).toBe(0);
297 }),
298 );
299});
300
301// The server's spawner stack, as server.ts builds it.
302const layerLaunched = ProcessRunner.layer.pipe(Layer.provide(ProcessLauncher.layerServer));
303
304// A command's $PPID, required to be the helper: signalling a fallback's parent would hit the test runner.
305const expectHelperPid = (stdout: string) => {
306 expect(stdout.trim()).toMatch(/^[1-9]\d*$/);
307 const pid = Number(stdout.trim());
308 expect(pid, "the command's parent process is the server process itself").not.toBe(process.pid);
309 return pid;
310};
311
312describe("ProcessRunner.layer", () => {
313 // Forking the server for every git call stalls its event loop in proportion to its RSS.
314 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
315 "launches commands from a helper process instead of forking the server",
316 () =>
317 Effect.gen(function* () {
318 const runner = yield* ProcessRunner.ProcessRunner;
319 const result = yield* runner.run({ command: "sh", args: ["-c", "echo $PPID"] });
320
321 expectHelperPid(result.stdout);
322 }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))),
323 );
324
325 // The helper's stdin and stdout are /dev/null, so inherited stdio must come from the server.
326 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
327 "forks the server for a command that inherits its stdio",
328 () =>
329 Effect.gen(function* () {
330 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
331 const handle = yield* spawner.spawn(
332 ChildProcess.make("sh", ["-c", "echo $PPID >&2"], { stdin: "inherit" }),
333 );
334 const parent = yield* handle.stderr.pipe(Stream.decodeText(), Stream.mkString);
335
336 expect(Number(parent.trim())).toBe(process.pid);
337 }).pipe(
338 Effect.scoped,
339 Effect.provide(ProcessLauncher.layerServer.pipe(Layer.provideMerge(NodeServices.layer))),
340 ),
341 );
342
343 // Node throws some spawn errnos, such as ENOMEM, instead of emitting "error".
344 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
345 "runs commands natively when starting the helper throws",
346 () =>
347 Effect.gen(function* () {
348 const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)(
349 "node:child_process",
350 );
351 const spawn = childProcess.spawn;
352 yield* Effect.acquireRelease(
353 Effect.sync(() => {
354 childProcess.spawn = ((...args: Parameters<typeof spawn>) => {
355 const launcherArgs = args[1];
356 if (
357 Array.isArray(launcherArgs) &&
358 launcherArgs.some((arg) => String(arg).includes("process-launcher"))
359 ) {
360 throw Object.assign(new Error("spawn ENOMEM"), { code: "ENOMEM" });
361 }
362 return spawn(...args);
363 }) as typeof spawn;
364 NodeModule.syncBuiltinESMExports();
365 }),
366 () =>
367 Effect.sync(() => {
368 childProcess.spawn = spawn;
369 NodeModule.syncBuiltinESMExports();
370 }),
371 );
372 const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner);
373 const result = yield* runner.run({ command: "sh", args: ["-c", "echo $PPID"] });
374
375 expect(Number(result.stdout.trim())).toBe(process.pid);
376 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
377 );
378
379 // Callers report a missing CLI from the NotFound reason.
380 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
381 "reports a missing command as a NotFound spawn failure",
382 () =>
383 Effect.gen(function* () {
384 const runner = yield* ProcessRunner.ProcessRunner;
385 const error = yield* runner
386 .run({ command: "t3code-missing-command", args: [] })
387 .pipe(Effect.flip);
388
389 expect(error._tag).toBe("ProcessSpawnError");
390 expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
391 expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("NotFound");
392 }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))),
393 );
394
395 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
396 "kills descendants that ignore SIGTERM when a run is interrupted",
397 () =>
398 Effect.gen(function* () {
399 const fs = yield* FileSystem.FileSystem;
400 const runner = yield* ProcessRunner.ProcessRunner;
401 const started = yield* Deferred.make<number>();
402 const run = yield* runner
403 .run({
404 command: "sh",
405 // The descendant prints its pid only once it ignores SIGTERM.
406 args: ["-c", `sh -c 'trap "" TERM; echo $$; exec sleep 1000' & wait`],
407 onStdoutChunk: (chunk) =>
408 Deferred.doneUnsafe(started, Exit.succeed(Number(new TextDecoder().decode(chunk)))),
409 })
410 .pipe(Effect.forkChild);
411 const descendant = yield* Deferred.await(started);
412 const ignored = (yield* fs.readFileString(`/proc/${descendant}/status`)).match(
413 /^SigIgn:\s*([0-9a-f]+)$/m,
414 )?.[1];
415 expect(
416 BigInt(`0x${ignored ?? "0"}`) & (1n << 14n),
417 "the descendant ignores SIGTERM",
418 ).not.toBe(0n);
419 yield* Fiber.interrupt(run);
420 // A killed process stays a zombie until reaped, and a PID namespace's init may never reap it.
421 const state = yield* fs.readFileString(`/proc/${descendant}/stat`).pipe(
422 Effect.map((stat) => stat.slice(stat.lastIndexOf(")") + 2).split(" ")[0]),
423 Effect.orElseSucceed(() => "gone"),
424 );
425
426 expect(["gone", "Z"]).toContain(state);
427 }).pipe(Effect.provide(layerLaunched.pipe(Layer.provideMerge(NodeServices.layer)))),
428 );
429
430 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
431 "runs in the server's working directory and fails stdin a command never reads",
432 () =>
433 Effect.gen(function* () {
434 const runner = yield* ProcessRunner.ProcessRunner;
435 const result = yield* runner.run({ command: "pwd", args: [] });
436 const error = yield* runner
437 .run({ command: "true", args: [], stdin: "x".repeat(16 * 1024 * 1024) })
438 .pipe(Effect.flip);
439
440 expect(result.stdout.trim()).toBe(process.cwd());
441 expect(error._tag).toBe("ProcessStdinError");
442 }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))),
443 );
444
445 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
446 "rejects a NUL byte in an environment value without echoing the value",
447 () =>
448 Effect.gen(function* () {
449 const runner = yield* ProcessRunner.ProcessRunner;
450 const error = yield* runner
451 .run({ command: "true", args: [], env: { T3_TOKEN: "secret\0value" } })
452 .pipe(Effect.flip);
453
454 expect(error._tag).toBe("ProcessSpawnError");
455 expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("BadArgument");
456 expect(String(error.cause)).toContain("T3_TOKEN");
457 expect(String(error.cause)).not.toContain("secret");
458 }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))),
459 );
460
461 // Descendants keep writing after the leader exits; losing the helper must not truncate that.
462 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
463 "delivers output written after the helper process dies",
464 () =>
465 Effect.gen(function* () {
466 const fs = yield* FileSystem.FileSystem;
467 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
468 const handle = yield* spawner.spawn(
469 ChildProcess.make("sh", [
470 "-c",
471 `d=$(mktemp -d); mkfifo "$d/f"; (cat "$d/f"; rm -r "$d") & echo "$PPID $d/f"`,
472 ]),
473 );
474 expect(yield* handle.exitCode).toBe(0);
475 const output = yield* handle.stdout.pipe(
476 Stream.tap((chunk) => {
477 const [helper = "", fifo] = new TextDecoder().decode(chunk).trim().split(" ");
478 if (fifo === undefined) return Effect.void;
479 process.kill(expectHelperPid(helper), "SIGKILL");
480 return fs.writeFileString(fifo, "complete\n");
481 }),
482 Stream.decodeText(),
483 Stream.mkString,
484 );
485
486 expect(output).toMatch(/ \S+\ncomplete\n$/);
487 }).pipe(
488 Effect.scoped,
489 Effect.provide(ProcessLauncher.layer.pipe(Layer.provideMerge(NodeServices.layer))),
490 ),
491 );
492
493 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
494 "kills a command whose helper dies while handing over its pipes",
495 () =>
496 Effect.gen(function* () {
497 const fs = yield* FileSystem.FileSystem;
498 const fifo = `${yield* fs.makeTempDirectoryScoped()}/alive`;
499 NodeChildProcess.execFileSync("mkfifo", [fifo]);
500 // Reaches EOF once the command, its only writer, is gone.
501 const alive = new NodeNet.Socket({
502 fd: NodeFS.openSync(fifo, NodeFS.constants.O_RDONLY | NodeFS.constants.O_NONBLOCK),
503 readable: true,
504 writable: false,
505 });
506 const commandReady = Deferred.makeUnsafe<void>();
507 const commandGone = Deferred.makeUnsafe<void>();
508 alive.once("data", () => Deferred.doneUnsafe(commandReady, Exit.void));
509 alive.once("end", () => Deferred.doneUnsafe(commandGone, Exit.void));
510
511 const helperPaused = Deferred.makeUnsafe<number>();
512 const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)(
513 "node:child_process",
514 );
515 const spawn = childProcess.spawn;
516 yield* Effect.acquireRelease(
517 Effect.sync(() => {
518 childProcess.spawn = ((...args: Parameters<typeof spawn>) => {
519 const helper = spawn(...args);
520 helper.on("message", (event: { readonly type: string }) => {
521 if (event.type !== "stdio" || Deferred.isDoneUnsafe(helperPaused)) return;
522 process.kill(helper.pid!, "SIGSTOP");
523 Deferred.doneUnsafe(helperPaused, Exit.succeed(helper.pid!));
524 });
525 return helper;
526 }) as typeof spawn;
527 NodeModule.syncBuiltinESMExports();
528 }),
529 () =>
530 Effect.sync(() => {
531 childProcess.spawn = spawn;
532 NodeModule.syncBuiltinESMExports();
533 }),
534 );
535 const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner);
536 const run = yield* runner
537 .run({
538 command: "sh",
539 args: ["-c", `exec 3>"$0"; echo ready >&3; exec sleep 1000`, fifo],
540 })
541 .pipe(Effect.forkChild);
542 const helper = yield* Deferred.await(helperPaused);
543 yield* Deferred.await(commandReady);
544 process.kill(helper, "SIGKILL");
545
546 expect((yield* Effect.flip(Fiber.join(run)))._tag).toBe("ProcessSpawnError");
547 yield* Deferred.await(commandGone);
548 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
549 );
550
551 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
552 "fails a command whose output pipe never arrives instead of returning no output",
553 () =>
554 Effect.gen(function* () {
555 const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)(
556 "node:child_process",
557 );
558 const spawn = childProcess.spawn;
559 yield* Effect.acquireRelease(
560 Effect.sync(() => {
561 childProcess.spawn = ((...args: Parameters<typeof spawn>) => {
562 const helper = spawn(...args);
563 const emit = helper.emit.bind(helper);
564 helper.emit = ((event: string, ...rest: Array<unknown>) => {
565 const [message, socket] = rest as [{ type?: string; fd?: number }, NodeNet.Socket?];
566 if (event !== "message" || message.type !== "stdio" || message.fd !== 1) {
567 return emit(event, ...rest);
568 }
569 socket?.destroy();
570 return emit(event, message, undefined);
571 }) as typeof helper.emit;
572 return helper;
573 }) as typeof spawn;
574 NodeModule.syncBuiltinESMExports();
575 }),
576 () =>
577 Effect.sync(() => {
578 childProcess.spawn = spawn;
579 NodeModule.syncBuiltinESMExports();
580 }),
581 );
582 const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner);
583
584 const error = yield* runner.run({ command: "echo", args: ["output"] }).pipe(Effect.flip);
585
586 expect(error._tag).toBe("ProcessSpawnError");
587 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
588 );
589
590 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
591 "replaces a helper that stops answering",
592 () =>
593 Effect.gen(function* () {
594 const runner = yield* ProcessRunner.ProcessRunner;
595 const launcher = yield* ProcessLauncher.ProcessLauncher;
596 const parentPid = runner
597 .run({ command: "sh", args: ["-c", "echo $PPID"] })
598 .pipe(Effect.map((result) => expectHelperPid(result.stdout)));
599 const helper = yield* parentPid;
600 expect(yield* launcher.currentPid).toBe(helper);
601 process.kill(helper, "SIGSTOP");
602 const error = yield* runner.run({ command: "true", args: [] }).pipe(Effect.flip);
603 const replacement = yield* parentPid;
604
605 expect(error._tag).toBe("ProcessSpawnError");
606 expect(replacement).not.toBe(helper);
607 expect(replacement).not.toBe(process.pid);
608 expect(yield* launcher.currentPid).toBe(replacement);
609 }).pipe(
610 Effect.provide(
611 ProcessRunner.layer.pipe(
612 Layer.provideMerge(Layer.effectContext(ProcessLauncher.make("1 second"))),
613 Layer.provide(NodeServices.layer),
614 ),
615 ),
616 ),
617 );
618
619 // Under load the server reads the helper's replies late; that is not a hung helper.
620 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
621 "keeps a helper whose replies wait behind a busy server",
622 () =>
623 Effect.gen(function* () {
624 const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)(
625 "node:child_process",
626 );
627 const spawn = childProcess.spawn;
628 let blocked = false;
629 yield* Effect.acquireRelease(
630 Effect.sync(() => {
631 childProcess.spawn = ((...args: Parameters<typeof spawn>) => {
632 const helper = spawn(...args);
633 helper.on("message", (event: { readonly type: string }) => {
634 if (event.type !== "pid" || blocked) return;
635 blocked = true;
636 // Holds the server's event loop past the reply deadline, as a loaded server does.
637 NodeChildProcess.execFileSync("sleep", ["1.5"]);
638 });
639 return helper;
640 }) as typeof spawn;
641 NodeModule.syncBuiltinESMExports();
642 }),
643 () =>
644 Effect.sync(() => {
645 childProcess.spawn = spawn;
646 NodeModule.syncBuiltinESMExports();
647 }),
648 );
649 const runner = Context.get(
650 yield* Layer.build(
651 ProcessRunner.layer.pipe(
652 Layer.provide(Layer.effectContext(ProcessLauncher.make("1 second"))),
653 ),
654 ),
655 ProcessRunner.ProcessRunner,
656 );
657 const parentPid = runner
658 .run({ command: "sh", args: ["-c", "echo $PPID"] })
659 .pipe(Effect.map((result) => expectHelperPid(result.stdout)));
660 const first = yield* parentPid;
661 const second = yield* parentPid;
662
663 expect(blocked).toBe(true);
664 expect(second).toBe(first);
665 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
666 );
667});
668
669describe("isWindowsCommandNotFound", () => {
670 it.effect("matches the localized German cmd.exe error text", () =>
671 Effect.gen(function* () {
672 const isCommandNotFound = yield* isWindowsCommandNotFound(
673 1,
674 "wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
675 ).pipe(Effect.provideService(HostProcess.Platform, "win32"));
676 expect(isCommandNotFound).toBe(true);
677 }),
678 );
679});