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

processRunner.test.ts

451 lines14.2 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Deferred from "effect/Deferred";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as Layer from "effect/Layer";
7import * as PlatformError from "effect/PlatformError";
8import * as Sink from "effect/Sink";
9import * as Stream from "effect/Stream";
10import { TestClock } from "effect/testing";
11import { ChildProcessSpawner } from "effect/process";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import { SpawnExecutableResolution } from "@t3tools/shared/shell";
14​
15import * as ProcessRunner from "./processRunner.ts";
16​
17type ChildProcessCommand = {
18 readonly command: string;
19 readonly args: ReadonlyArray<string>;
20 readonly options: {
21 readonly shell?: boolean | string;
22 };
23};
24​
25function asChildProcessCommand(command: unknown): ChildProcessCommand {
26 return command as ChildProcessCommand;
28​
29function makeHandle(input: {
30 readonly stdout?: string | Stream.Stream<Uint8Array>;
31 readonly stderr?: string | Stream.Stream<Uint8Array>;
32 readonly code?: number;
33 readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
34 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
35}) {
36 return ChildProcessSpawner.makeHandle({
37 pid: ChildProcessSpawner.ProcessId(1),
38 exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
39 isRunning: Effect.succeed(false),
40 kill: () => Effect.void,
41 unref: Effect.succeed(Effect.void),
42 stdin: input.stdin ?? Sink.drain,
43 stdout:
44 typeof input.stdout === "string"
45 ? Stream.encodeText(Stream.make(input.stdout))
46 : (input.stdout ?? Stream.empty),
47 stderr:
48 typeof input.stderr === "string"
49 ? Stream.encodeText(Stream.make(input.stderr))
50 : (input.stderr ?? Stream.empty),
51 all: Stream.empty,
52 getInputFd: () => Sink.drain,
53 getOutputFd: () => Stream.empty,
54 });
56​
57function makeSpawner(
58 f: (
59 command: ChildProcessCommand,
60 ) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>,
61) {
62 return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
64​
65const runWith =
66 (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) =>
67 (input: ProcessRunner.ProcessRunInput) =>
68 Effect.service(ProcessRunner.ProcessRunner).pipe(
69 Effect.flatMap((runner) =>
70 runner.run({
71 ...input,
72 }),
73 ),
74 Effect.provide(
75 ProcessRunner.layer.pipe(
76 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
77 ),
78 ),
79 );
80​
81describe("runProcess", () => {
82 it.effect("collects stdout through an injected ChildProcessSpawner", () =>
83 Effect.gen(function* () {
84 const spawner = makeSpawner((command) =>
85 Effect.sync(() => {
86 expect(command.command).toBe("fake");
87 expect(command.args).toEqual(["stdout-bytes", "32"]);
88 return makeHandle({ stdout: "x".repeat(32) });
89 }),
90 );
91​
92 const result = yield* runWith(spawner)({
93 command: "fake",
94 args: ["stdout-bytes", "32"],
95 });
96​
97 expect(result.code).toBe(0);
98 expect(result.stdout).toBe("x".repeat(32));
99 expect(result.timedOut).toBe(false);
100 }),
101 );
102​
103 it.effect("runs through the ProcessRunner service", () => {
104 const spawner = makeSpawner((command) =>
105 Effect.sync(() => {
106 expect(command.command).toBe("fake");
107 expect(command.args).toEqual(["--service"]);
108 return makeHandle({ stdout: "service ok" });
109 }),
110 );
111 const layer = ProcessRunner.layer.pipe(
112 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
113 );
114​
115 return Effect.gen(function* () {
116 const runner = yield* ProcessRunner.ProcessRunner;
117 const result = yield* runner.run({
118 command: "fake",
119 args: ["--service"],
120 });
121​
122 expect(result.stdout).toBe("service ok");
123 }).pipe(Effect.provide(layer));
124 });
125​
126 it.effect("resolves and escapes Windows command shims before spawning", () => {
127 const spawner = makeSpawner((command) =>
128 Effect.sync(() => {
129 expect(command.command).toBe(
130 [
131 '^"C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd^"',
132 '^"repos^"',
133 '^"pr^"',
134 '^"list^"',
135 '^"--source-branch^"',
136 '^"feature^ ^&^ release^"',
137 ].join(" "),
138 );
139 expect(command.args).toEqual([]);
140 expect(command.options.shell).toBe(true);
141 return makeHandle({ stdout: "[]" });
142 }),
143 );
144​
145 return runWith(spawner)({
146 command: "az",
147 args: ["repos", "pr", "list", "--source-branch", "feature & release"],
148 env: { AZURE_CONFIG_DIR: "C:\\Users\\tester\\.azure" },
149 }).pipe(
150 Effect.provideService(HostProcess.Platform, "win32"),
151 Effect.provideService(HostProcess.Environment, {
152 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
153 PATHEXT: ".COM;.EXE;.BAT;.CMD",
154 }),
155 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) =>
156 env.PATH === "C:\\Users\\tester\\AppData\\Roaming\\npm" &&
157 env.AZURE_CONFIG_DIR === "C:\\Users\\tester\\.azure"
158 ? "C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd"
159 : undefined,
160 ),
161 Effect.map((result) => {
162 expect(result.stdout).toBe("[]");
163 }),
164 );
165 });
166​
167 it.effect("preserves resolved spawn context and cause", () =>
168 Effect.gen(function* () {
169 const cause = PlatformError.systemError({
170 _tag: "PermissionDenied",
171 module: "ChildProcessSpawner",
172 method: "spawn",
173 pathOrDescriptor: "/actual/fake",
174 });
175 const spawner = makeSpawner(() => Effect.fail(cause));
176​
177 const error = yield* runWith(spawner)({
178 command: "fake",
179 args: ["--flag", "secret-token-value"],
180 cwd: "/logical",
181 spawnCwd: "/actual",
182 }).pipe(Effect.flip);
183​
184 expect(error._tag).toBe("ProcessSpawnError");
185 if (error._tag !== "ProcessSpawnError") {
186 return expect.fail("Expected ProcessSpawnError");
187 }
188 expect(error).toMatchObject({
189 command: "fake",
190 argumentCount: 2,
191 cwd: "/logical",
192 spawnCwd: "/actual",
193 resolvedCommand: "fake",
194 resolvedArgumentCount: 2,
195 shell: false,
196 });
197 expect(error.cause).toBe(cause);
198 expect(error.message).toBe("Failed to spawn process 'fake' in '/actual'");
199 expect(error).not.toHaveProperty("args");
200 expect(error).not.toHaveProperty("resolvedArgs");
201 expect(error.message).not.toContain("secret-token-value");
202 }),
203 );
204​
205 it.effect("types spawn failures that the platform spawner throws synchronously", () =>
206 Effect.gen(function* () {
207 // A non-directory entry on PATH makes node's spawn throw ENOTDIR
208 // synchronously. The platform spawner calls it inside `Effect.callback`,
209 // so the throw arrives as a defect rather than a typed error.
210 const defect = Object.assign(new Error("spawn jj ENOTDIR"), { code: "ENOTDIR" });
211 const spawner = makeSpawner(() =>
212 Effect.callback<never, never>(() => {
213 throw defect;
214 }),
215 );
216​
217 const error = yield* runWith(spawner)({
218 command: "jj",
219 args: ["--version"],
220 cwd: "/repo",
221 }).pipe(Effect.flip);
222​
223 expect(error._tag).toBe("ProcessSpawnError");
224 if (error._tag !== "ProcessSpawnError") {
225 return expect.fail("Expected ProcessSpawnError");
226 }
227 expect(error).toMatchObject({ command: "jj", argumentCount: 1, cwd: "/repo" });
228 expect(error.cause).toBe(defect);
229 }),
230 );
231​
232 it.effect("fails when output exceeds max buffer in default mode", () =>
233 Effect.gen(function* () {
234 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
235​
236 const error = yield* runWith(spawner)({
237 command: "fake",
238 args: ["stdout-bytes", "2048"],
239 maxOutputBytes: 128,
240 }).pipe(Effect.flip);
241​
242 expect(error._tag).toBe("ProcessOutputLimitError");
243 if (error._tag !== "ProcessOutputLimitError") {
244 return expect.fail("Expected ProcessOutputLimitError");
245 }
246 expect(error).toMatchObject({
247 stream: "stdout",
248 maxBytes: 128,
249 observedBytes: 2048,
250 });
251 expect(error.message).toBe(
252 "Process 'fake' stdout produced 2048 bytes, exceeding the 128 byte limit",
253 );
254 }),
255 );
256​
257 it.effect("accepts output at the byte limit followed by an empty chunk", () =>
258 Effect.gen(function* () {
259 const output = new TextEncoder().encode("exactly");
260 const spawner = makeSpawner(() =>
261 Effect.succeed(
262 makeHandle({
263 stdout: Stream.make(output, new Uint8Array()),
264 }),
265 ),
266 );
267​
268 const result = yield* runWith(spawner)({
269 command: "fake",
270 args: ["exact-limit"],
271 maxOutputBytes: output.byteLength,
272 });
273​
274 expect(result.stdout).toBe("exactly");
275 }),
276 );
277​
278 it.effect("fails fast on output limit before timeout for long-running output", () =>
279 Effect.gen(function* () {
280 const textChunk = "x".repeat(64);
281 const spawner = makeSpawner(() =>
282 Effect.succeed(
283 makeHandle({
284 stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
285 Stream.encodeText,
286 ),
287 exitCode: Effect.never,
288 }),
289 ),
290 );
291​
292 const error = yield* runWith(spawner)({
293 command: "fake",
294 args: ["spam-stdout"],
295 maxOutputBytes: 128,
296 timeout: "2 seconds",
297 }).pipe(Effect.flip);
298​
299 expect(error).toBeInstanceOf(ProcessRunner.ProcessOutputLimitError);
300 }),
301 );
302​
303 it.effect("truncates output when outputMode is truncate", () =>
304 Effect.gen(function* () {
305 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
306​
307 const result = yield* runWith(spawner)({
308 command: "fake",
309 args: ["stdout-bytes", "2048"],
310 maxOutputBytes: 128,
311 outputMode: "truncate",
312 });
313​
314 expect(result.code).toBe(0);
315 expect(result.stdout.length).toBeLessThanOrEqual(128);
316 expect(result.stdoutTruncated).toBe(true);
317 expect(result.stderrTruncated).toBe(false);
318 }),
319 );
320​
321 it.effect("writes stdin before waiting for exit", () =>
322 Effect.gen(function* () {
323 const stdinWritten = yield* Deferred.make<void>();
324 const decoder = new TextDecoder();
325 const spawner = makeSpawner(() =>
326 Effect.succeed(
327 makeHandle({
328 stdout: "stdin payload",
329 stdin: Sink.forEach((chunk: Uint8Array) => {
330 const text = decoder.decode(chunk, { stream: true });
331 return text.includes("stdin payload")
332 ? Deferred.succeed(stdinWritten, undefined)
333 : Effect.void;
334 }),
335 exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
336 }),
337 ),
338 );
339​
340 const result = yield* runWith(spawner)({
341 command: "fake",
342 args: ["stdin-echo"],
343 stdin: "stdin payload",
344 });
345​
346 expect(result.stdout).toBe("stdin payload");
347 expect(result.code).toBe(0);
348 }),
349 );
350​
351 it.effect("returns output for non-zero exit codes", () =>
352 Effect.gen(function* () {
353 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stderr: "boom", code: 2 })));
354​
355 const result = yield* runWith(spawner)({
356 command: "fake",
357 args: ["stderr-exit", "boom", "2"],
358 });
359​
360 expect(result.code).toBe(2);
361 expect(result.stderr).toBe("boom");
362 }),
363 );
364​
365 it.effect("fails on timeout", () =>
366 Effect.gen(function* () {
367 const spawner = makeSpawner(() =>
368 Effect.succeed(
369 makeHandle({
370 exitCode: Effect.never,
371 }),
372 ),
373 );
374 const errorFiber = yield* runWith(spawner)({
375 command: "fake",
376 args: ["sleep"],
377 cwd: "/logical",
378 spawnCwd: "/actual",
379 timeout: "50 millis",
380 }).pipe(Effect.flip, Effect.forkScoped);
381​
382 yield* Effect.yieldNow;
383 yield* TestClock.adjust(Duration.millis(50));
384 const error = yield* Fiber.join(errorFiber);
385​
386 expect(error._tag).toBe("ProcessTimeoutError");
387 if (error._tag !== "ProcessTimeoutError") {
388 return expect.fail("Expected ProcessTimeoutError");
389 }
390 expect(error).toMatchObject({
391 command: "fake",
392 argumentCount: 1,
393 cwd: "/logical",
394 spawnCwd: "/actual",
395 timeoutMs: 50,
396 });
397 expect(error.message).toBe("Process 'fake' in '/actual' timed out after 50ms");
398 }),
399 );
400​
401 it.effect("returns a synthetic timed out result when timeoutBehavior is timedOutResult", () =>
402 Effect.gen(function* () {
403 const spawner = makeSpawner(() =>
404 Effect.succeed(
405 makeHandle({
406 exitCode: Effect.never,
407 }),
408 ),
409 );
410 const resultFiber = yield* runWith(spawner)({
411 command: "fake",
412 args: ["sleep"],
413 timeout: "50 millis",
414 timeoutBehavior: "timedOutResult",
415 }).pipe(Effect.forkScoped);
416​
417 yield* Effect.yieldNow;
418 yield* TestClock.adjust(Duration.millis(50));
419 const result = yield* Fiber.join(resultFiber);
420​
421 expect(result).toMatchObject({
422 stdout: "",
423 stderr: "",
424 code: null,
425 timedOut: true,
426 stdoutTruncated: false,
427 stderrTruncated: false,
428 });
429 }),
430 );
431});
432​
433describe("isWindowsCommandNotFound", () => {
434 it.effect("matches the localized German cmd.exe error text", () =>
435 Effect.gen(function* () {
436 const isCommandNotFound = yield* ProcessRunner.isWindowsCommandNotFound(
437 1,
438 "wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
439 ).pipe(Effect.provideService(HostProcess.Platform, "win32"));
440 expect(isCommandNotFound).toBe(true);
441 }),
442 );
443});
444​
445describe("commandName", () => {
446 it("drops the directory from POSIX and Windows paths", () => {
447 expect(ProcessRunner.commandName("/Users/me/.local/bin/claude")).toBe("claude");
448 expect(ProcessRunner.commandName("C:\\Program Files\\nodejs\\npx.cmd")).toBe("npx.cmd");
449 expect(ProcessRunner.commandName("git")).toBe("git");
450 });
451});