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

processRunner.test.ts

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