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

processRunner.test.ts

531 lines19.6 KB

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 PlatformError from "effect/PlatformError";
16import * as Sink from "effect/Sink";
17import * as Stream from "effect/Stream";
18import { ChildProcessSpawner } from "effect/process";
19import * as HostProcess from "@t3tools/shared/HostProcess";
20import { SpawnExecutableResolution } from "@t3tools/shared/shell";
21​
22import * as ProcessLauncher from "./process/ProcessLauncher.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;
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 });
64​
65function makeSpawner(
66 f: (
67 command: ChildProcessCommand,
68 ) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>,
69) {
70 return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
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("resolves and escapes Windows command shims before spawning", () => {
91 const spawner = makeSpawner((command) =>
92 Effect.sync(() => {
93 expect(command.command).toBe(
94 [
95 '^"C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd^"',
96 '^"repos^"',
97 '^"pr^"',
98 '^"list^"',
99 '^"--source-branch^"',
100 '^"feature^ ^&^ release^"',
101 ].join(" "),
102 );
103 expect(command.args).toEqual([]);
104 expect(command.options.shell).toBe(true);
105 return makeHandle({ stdout: "[]" });
106 }),
107 );
108​
109 return runWith(spawner)({
110 command: "az",
111 args: ["repos", "pr", "list", "--source-branch", "feature & release"],
112 env: { AZURE_CONFIG_DIR: "C:\\Users\\tester\\.azure" },
113 }).pipe(
114 Effect.provideService(HostProcess.Platform, "win32"),
115 Effect.provideService(HostProcess.Environment, {
116 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
117 PATHEXT: ".COM;.EXE;.BAT;.CMD",
118 }),
119 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) =>
120 env.PATH === "C:\\Users\\tester\\AppData\\Roaming\\npm" &&
121 env.AZURE_CONFIG_DIR === "C:\\Users\\tester\\.azure"
122 ? "C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd"
123 : undefined,
124 ),
125 Effect.map((result) => {
126 expect(result.stdout).toBe("[]");
127 }),
128 );
129 });
130​
131 it.effect("types spawn failures that the platform spawner throws synchronously", () =>
132 Effect.gen(function* () {
133 // File-valued PATH entries make spawn throw ENOTDIR synchronously, arriving through Effect.callback as a defect.
134 const defect = Object.assign(new Error("spawn jj ENOTDIR"), { code: "ENOTDIR" });
135 const spawner = makeSpawner(() =>
136 Effect.callback<never, never>(() => {
137 throw defect;
138 }),
139 );
140​
141 const error = yield* runWith(spawner)({
142 command: "jj",
143 args: ["--version"],
144 cwd: "/repo",
145 }).pipe(Effect.flip);
146​
147 expect(error._tag).toBe("ProcessSpawnError");
148 if (error._tag !== "ProcessSpawnError") {
149 return expect.fail("Expected ProcessSpawnError");
150 }
151 expect(error).toMatchObject({ command: "jj", argumentCount: 1, cwd: "/repo" });
152 expect(error.cause).toBe(defect);
153 }),
154 );
155​
156 it.effect("reports child startup before delivering cancellation during acquisition", () =>
157 Effect.gen(function* () {
158 let started = false;
159 const spawner = makeSpawner(() =>
160 Effect.withFiber((fiber) =>
161 Effect.sync(() => {
162 fiber.interruptUnsafe();
163 return makeHandle({});
164 }),
165 ),
166 );
167 const result = yield* runWith(spawner)({
168 command: "git",
169 args: ["restore"],
170 onSpawn: () => {
171 started = true;
172 },
173 }).pipe(Effect.exit);
174 expect(Exit.isFailure(result) && Cause.hasInterruptsOnly(result.cause)).toBe(true);
175 expect(started).toBe(true);
176 }).pipe(Effect.scoped),
177 );
178​
179 it.effect("fails when output exceeds max buffer in default mode", () =>
180 Effect.gen(function* () {
181 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
182​
183 const error = yield* runWith(spawner)({
184 command: "fake",
185 args: ["stdout-bytes", "2048"],
186 maxOutputBytes: 128,
187 }).pipe(Effect.flip);
188​
189 expect(error._tag).toBe("ProcessOutputLimitError");
190 if (error._tag !== "ProcessOutputLimitError") {
191 return expect.fail("Expected ProcessOutputLimitError");
192 }
193 expect(error).toMatchObject({
194 stream: "stdout",
195 maxBytes: 128,
196 observedBytes: 2048,
197 });
198 expect(error.message).toBe(
199 "Process 'fake' stdout produced 2048 bytes, exceeding the 128 byte limit",
200 );
201 }),
202 );
203​
204 it.effect("accepts output at the byte limit followed by an empty chunk", () =>
205 Effect.gen(function* () {
206 const output = new TextEncoder().encode("exactly");
207 const spawner = makeSpawner(() =>
208 Effect.succeed(
209 makeHandle({
210 stdout: Stream.make(output, new Uint8Array()),
211 }),
212 ),
213 );
214​
215 const result = yield* runWith(spawner)({
216 command: "fake",
217 args: ["exact-limit"],
218 maxOutputBytes: output.byteLength,
219 });
220​
221 expect(result.stdout).toBe("exactly");
222 }),
223 );
224​
225 it.effect("fails fast on output limit before timeout for long-running output", () =>
226 Effect.gen(function* () {
227 const textChunk = "x".repeat(64);
228 const spawner = makeSpawner(() =>
229 Effect.succeed(
230 makeHandle({
231 stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
232 Stream.encodeText,
233 ),
234 exitCode: Effect.never,
235 }),
236 ),
237 );
238​
239 const error = yield* runWith(spawner)({
240 command: "fake",
241 args: ["spam-stdout"],
242 maxOutputBytes: 128,
243 timeout: "2 seconds",
244 }).pipe(Effect.flip);
245​
246 expect(error).toBeInstanceOf(ProcessRunner.ProcessOutputLimitError);
247 }),
248 );
249​
250 it.effect("truncates output when outputMode is truncate", () =>
251 Effect.gen(function* () {
252 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
253​
254 const result = yield* runWith(spawner)({
255 command: "fake",
256 args: ["stdout-bytes", "2048"],
257 maxOutputBytes: 128,
258 outputMode: "truncate",
259 });
260​
261 expect(result.code).toBe(0);
262 expect(result.stdout.length).toBeLessThanOrEqual(128);
263 expect(result.stdoutTruncated).toBe(true);
264 expect(result.stderrTruncated).toBe(false);
265 }),
266 );
267​
268 it.effect("writes stdin before waiting for exit", () =>
269 Effect.gen(function* () {
270 const stdinWritten = yield* Deferred.make<void>();
271 const decoder = new TextDecoder();
272 const spawner = makeSpawner(() =>
273 Effect.succeed(
274 makeHandle({
275 stdout: "stdin payload",
276 stdin: Sink.forEach((chunk: Uint8Array) => {
277 const text = decoder.decode(chunk, { stream: true });
278 return text.includes("stdin payload")
279 ? Deferred.succeed(stdinWritten, undefined)
280 : Effect.void;
281 }),
282 exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
283 }),
284 ),
285 );
286​
287 const result = yield* runWith(spawner)({
288 command: "fake",
289 args: ["stdin-echo"],
290 stdin: "stdin payload",
291 });
292​
293 expect(result.stdout).toBe("stdin payload");
294 expect(result.code).toBe(0);
295 }),
296 );
297});
298​
299// The server's spawner stack, as server.ts builds it.
300const layerLaunched = ProcessRunner.layer.pipe(Layer.provide(ProcessLauncher.layerServer));
301​
302// A command's $PPID, required to be the helper: signalling a fallback's parent would hit the test runner.
303const expectHelperPid = (stdout: string) => {
304 expect(stdout.trim()).toMatch(/^[1-9]\d*$/);
305 const pid = Number(stdout.trim());
306 expect(pid, "the command's parent process is the server process itself").not.toBe(process.pid);
307 return pid;
308};
309​
310describe("ProcessRunner.layer", () => {
311 // Forking the server for every git call stalls its event loop in proportion to its RSS.
312 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
313 "launches commands from a helper process instead of forking the server",
314 () =>
315 Effect.gen(function* () {
316 const runner = yield* ProcessRunner.ProcessRunner;
317 const result = yield* runner.run({ command: "sh", args: ["-c", "echo $PPID"] });
318​
319 expectHelperPid(result.stdout);
320 }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))),
321 );
322​
323 // Node throws some spawn errnos, such as ENOMEM, instead of emitting "error".
324 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
325 "runs commands natively when starting the helper throws",
326 () =>
327 Effect.gen(function* () {
328 const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)(
329 "node:child_process",
330 );
331 const spawn = childProcess.spawn;
332 yield* Effect.acquireRelease(
333 Effect.sync(() => {
334 childProcess.spawn = ((...args: Parameters<typeof spawn>) => {
335 const launcherArgs = args[1];
336 if (Array.isArray(launcherArgs) && launcherArgs.includes("--input-type=module")) {
337 throw Object.assign(new Error("spawn ENOMEM"), { code: "ENOMEM" });
338 }
339 return spawn(...args);
340 }) as typeof spawn;
341 NodeModule.syncBuiltinESMExports();
342 }),
343 () =>
344 Effect.sync(() => {
345 childProcess.spawn = spawn;
346 NodeModule.syncBuiltinESMExports();
347 }),
348 );
349 const runner = Context.get(yield* Layer.build(layerLaunched), ProcessRunner.ProcessRunner);
350 const result = yield* runner.run({ command: "sh", args: ["-c", "echo $PPID"] });
351​
352 expect(Number(result.stdout.trim())).toBe(process.pid);
353 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
354 );
355​
356 // Callers report a missing CLI from the NotFound reason.
357 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
358 "reports a missing command as a NotFound spawn failure",
359 () =>
360 Effect.gen(function* () {
361 const runner = yield* ProcessRunner.ProcessRunner;
362 const error = yield* runner
363 .run({ command: "t3code-missing-command", args: [] })
364 .pipe(Effect.flip);
365​
366 expect(error._tag).toBe("ProcessSpawnError");
367 expect(error.cause).toBeInstanceOf(PlatformError.PlatformError);
368 expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("NotFound");
369 }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))),
370 );
371​
372 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
373 "kills descendants that ignore SIGTERM when a run is interrupted",
374 () =>
375 Effect.gen(function* () {
376 const fs = yield* FileSystem.FileSystem;
377 const runner = yield* ProcessRunner.ProcessRunner;
378 const started = yield* Deferred.make<number>();
379 const run = yield* runner
380 .run({
381 command: "sh",
382 // The descendant prints its pid only once it ignores SIGTERM.
383 args: ["-c", `sh -c 'trap "" TERM; echo $$; exec sleep 1000' & wait`],
384 onStdoutChunk: (chunk) =>
385 Deferred.doneUnsafe(started, Exit.succeed(Number(new TextDecoder().decode(chunk)))),
386 })
387 .pipe(Effect.forkChild);
388 const descendant = yield* Deferred.await(started);
389 const ignored = (yield* fs.readFileString(`/proc/${descendant}/status`)).match(
390 /^SigIgn:\s*([0-9a-f]+)$/m,
391 )?.[1];
392 expect(
393 BigInt(`0x${ignored ?? "0"}`) & (1n << 14n),
394 "the descendant ignores SIGTERM",
395 ).not.toBe(0n);
396 yield* Fiber.interrupt(run);
397 // A killed process stays a zombie until reaped, and a PID namespace's init may never reap it.
398 const state = yield* fs.readFileString(`/proc/${descendant}/stat`).pipe(
399 Effect.map((stat) => stat.slice(stat.lastIndexOf(")") + 2).split(" ")[0]),
400 Effect.orElseSucceed(() => "gone"),
401 );
402​
403 expect(["gone", "Z"]).toContain(state);
404 }).pipe(Effect.provide(layerLaunched.pipe(Layer.provideMerge(NodeServices.layer)))),
405 );
406​
407 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
408 "runs in the server's working directory and fails stdin a command never reads",
409 () =>
410 Effect.gen(function* () {
411 const runner = yield* ProcessRunner.ProcessRunner;
412 const result = yield* runner.run({ command: "pwd", args: [] });
413 const error = yield* runner
414 .run({ command: "true", args: [], stdin: "x".repeat(16 * 1024 * 1024) })
415 .pipe(Effect.flip);
416​
417 expect(result.stdout.trim()).toBe(process.cwd());
418 expect(error._tag).toBe("ProcessStdinError");
419 }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))),
420 );
421​
422 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
423 "rejects a NUL byte in an environment value without echoing the value",
424 () =>
425 Effect.gen(function* () {
426 const runner = yield* ProcessRunner.ProcessRunner;
427 const error = yield* runner
428 .run({ command: "true", args: [], env: { T3_TOKEN: "secret\0value" } })
429 .pipe(Effect.flip);
430​
431 expect(error._tag).toBe("ProcessSpawnError");
432 expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("BadArgument");
433 expect(String(error.cause)).toContain("T3_TOKEN");
434 expect(String(error.cause)).not.toContain("secret");
435 }).pipe(Effect.provide(layerLaunched.pipe(Layer.provide(NodeServices.layer)))),
436 );
437​
438 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
439 "replaces a helper that stops answering",
440 () =>
441 Effect.gen(function* () {
442 const runner = yield* ProcessRunner.ProcessRunner;
443 const launcher = yield* ProcessLauncher.ProcessLauncher;
444 const parentPid = runner
445 .run({ command: "sh", args: ["-c", "echo $PPID"] })
446 .pipe(Effect.map((result) => expectHelperPid(result.stdout)));
447 const helper = yield* parentPid;
448 expect(yield* launcher.currentPid).toBe(helper);
449 process.kill(helper, "SIGSTOP");
450 const error = yield* runner.run({ command: "true", args: [] }).pipe(Effect.flip);
451 const replacement = yield* parentPid;
452​
453 expect(error._tag).toBe("ProcessSpawnError");
454 expect(replacement).not.toBe(helper);
455 expect(replacement).not.toBe(process.pid);
456 expect(yield* launcher.currentPid).toBe(replacement);
457 }).pipe(
458 Effect.provide(
459 ProcessRunner.layer.pipe(
460 Layer.provideMerge(Layer.effectContext(ProcessLauncher.make("1 second"))),
461 Layer.provide(NodeServices.layer),
462 ),
463 ),
464 ),
465 );
466​
467 // Under load the server reads the helper's replies late; that is not a hung helper.
468 it.live.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
469 "keeps a helper whose replies wait behind a busy server",
470 () =>
471 Effect.gen(function* () {
472 const childProcess: typeof NodeChildProcess = NodeModule.createRequire(import.meta.url)(
473 "node:child_process",
474 );
475 const spawn = childProcess.spawn;
476 let blocked = false;
477 yield* Effect.acquireRelease(
478 Effect.sync(() => {
479 childProcess.spawn = ((...args: Parameters<typeof spawn>) => {
480 const helper = spawn(...args);
481 const send = helper.send.bind(helper);
482 helper.send = ((message: { readonly command?: string }, ...rest: Array<never>) => {
483 const sent = send(message, ...rest);
484 if (message.command !== undefined && !blocked) {
485 blocked = true;
486 // Holds the server's event loop past the reply deadline, as a loaded server does.
487 NodeChildProcess.execFileSync("sleep", ["1.5"]);
488 }
489 return sent;
490 }) as typeof helper.send;
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 runner = Context.get(
502 yield* Layer.build(
503 ProcessRunner.layer.pipe(
504 Layer.provide(Layer.effectContext(ProcessLauncher.make("1 second"))),
505 ),
506 ),
507 ProcessRunner.ProcessRunner,
508 );
509 const parentPid = runner
510 .run({ command: "sh", args: ["-c", "echo $PPID"] })
511 .pipe(Effect.map((result) => expectHelperPid(result.stdout)));
512 const first = yield* parentPid;
513 const second = yield* parentPid;
514​
515 expect(blocked).toBe(true);
516 expect(second).toBe(first);
517 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
518 );
519});
520​
521describe("isWindowsCommandNotFound", () => {
522 it.effect("matches the localized German cmd.exe error text", () =>
523 Effect.gen(function* () {
524 const isCommandNotFound = yield* isWindowsCommandNotFound(
525 1,
526 "wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
527 ).pipe(Effect.provideService(HostProcess.Platform, "win32"));
528 expect(isCommandNotFound).toBe(true);
529 }),
530 );
531});