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

processRunner.test.ts

575 lines19.6 KB

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