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