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