Open History to see the last commit
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 Sink from "effect/Sink";
8import * as Stream from "effect/Stream";
9import { TestClock } from "effect/testing";
10import { ChildProcessSpawner } from "effect/unstable/process";
11import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
12import { SpawnExecutableResolution } from "@t3tools/shared/shell";
13
14import {
15 isWindowsCommandNotFound,
16 ProcessOutputLimitError,
17 ProcessRunner,
18 ProcessTimeoutError,
19 layer as ProcessRunnerLive,
20 type ProcessRunInput,
21} from "./processRunner.ts";
22
23type ChildProcessCommand = {
24 readonly command: string;
25 readonly args: ReadonlyArray<string>;
26 readonly options: {
27 readonly shell?: boolean | string;
28 };
29};
30
31// Accesses private properties of ChildProcessCommand for testing purposes
32function asChildProcessCommand(command: unknown): ChildProcessCommand {
33 return command as ChildProcessCommand;
34}
35
36function makeHandle(input: {
37 readonly stdout?: string | Stream.Stream<Uint8Array>;
38 readonly stderr?: string | Stream.Stream<Uint8Array>;
39 readonly code?: number;
40 readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
41 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
42}) {
43 return ChildProcessSpawner.makeHandle({
44 pid: ChildProcessSpawner.ProcessId(1),
45 exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
46 isRunning: Effect.succeed(false),
47 kill: () => Effect.void,
48 unref: Effect.succeed(Effect.void),
49 stdin: input.stdin ?? Sink.drain,
50 stdout:
51 typeof input.stdout === "string"
52 ? Stream.encodeText(Stream.make(input.stdout))
53 : (input.stdout ?? Stream.empty),
54 stderr:
55 typeof input.stderr === "string"
56 ? Stream.encodeText(Stream.make(input.stderr))
57 : (input.stderr ?? Stream.empty),
58 all: Stream.empty,
59 getInputFd: () => Sink.drain,
60 getOutputFd: () => Stream.empty,
61 });
62}
63
64function makeSpawner(
65 f: (command: ChildProcessCommand) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle>,
66) {
67 return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
68}
69
70const runWith =
71 (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) => (input: ProcessRunInput) =>
72 Effect.service(ProcessRunner).pipe(
73 Effect.flatMap((runner) =>
74 runner.run({
75 ...input,
76 }),
77 ),
78 Effect.provide(
79 ProcessRunnerLive.pipe(
80 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
81 ),
82 ),
83 );
84
85describe("runProcess", () => {
86 it.effect("collects stdout through an injected ChildProcessSpawner", () =>
87 Effect.gen(function* () {
88 const spawner = makeSpawner((command) =>
89 Effect.sync(() => {
90 expect(command.command).toBe("fake");
91 expect(command.args).toEqual(["stdout-bytes", "32"]);
92 return makeHandle({ stdout: "x".repeat(32) });
93 }),
94 );
95
96 const result = yield* runWith(spawner)({
97 command: "fake",
98 args: ["stdout-bytes", "32"],
99 });
100
101 expect(result.code).toBe(0);
102 expect(result.stdout).toBe("x".repeat(32));
103 expect(result.timedOut).toBe(false);
104 }),
105 );
106
107 it.effect("runs through the ProcessRunner service", () => {
108 const spawner = makeSpawner((command) =>
109 Effect.sync(() => {
110 expect(command.command).toBe("fake");
111 expect(command.args).toEqual(["--service"]);
112 return makeHandle({ stdout: "service ok" });
113 }),
114 );
115 const layer = ProcessRunnerLive.pipe(
116 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
117 );
118
119 return Effect.gen(function* () {
120 const runner = yield* ProcessRunner;
121 const result = yield* runner.run({
122 command: "fake",
123 args: ["--service"],
124 });
125
126 expect(result.stdout).toBe("service ok");
127 }).pipe(Effect.provide(layer));
128 });
129
130 it.effect("resolves and escapes Windows command shims before spawning", () => {
131 const spawner = makeSpawner((command) =>
132 Effect.sync(() => {
133 expect(command.command).toBe('^"C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd^"');
134 expect(command.args).toEqual([
135 '^"repos^"',
136 '^"pr^"',
137 '^"list^"',
138 '^"--source-branch^"',
139 '^"feature^ ^&^ release^"',
140 ]);
141 expect(command.options.shell).toBe(true);
142 return makeHandle({ stdout: "[]" });
143 }),
144 );
145
146 return runWith(spawner)({
147 command: "az",
148 args: ["repos", "pr", "list", "--source-branch", "feature & release"],
149 env: { AZURE_CONFIG_DIR: "C:\\Users\\tester\\.azure" },
150 }).pipe(
151 Effect.provideService(HostProcessPlatform, "win32"),
152 Effect.provideService(HostProcessEnvironment, {
153 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
154 PATHEXT: ".COM;.EXE;.BAT;.CMD",
155 }),
156 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) =>
157 env.PATH === "C:\\Users\\tester\\AppData\\Roaming\\npm" &&
158 env.AZURE_CONFIG_DIR === "C:\\Users\\tester\\.azure"
159 ? "C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd"
160 : undefined,
161 ),
162 Effect.map((result) => {
163 expect(result.stdout).toBe("[]");
164 }),
165 );
166 });
167
168 it.effect("fails when output exceeds max buffer in default mode", () =>
169 Effect.gen(function* () {
170 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
171
172 const error = yield* runWith(spawner)({
173 command: "fake",
174 args: ["stdout-bytes", "2048"],
175 maxOutputBytes: 128,
176 }).pipe(Effect.flip);
177
178 expect(error).toBeInstanceOf(ProcessOutputLimitError);
179 }),
180 );
181
182 it.effect("fails fast on output limit before timeout for long-running output", () =>
183 Effect.gen(function* () {
184 const textChunk = "x".repeat(64);
185 const spawner = makeSpawner(() =>
186 Effect.succeed(
187 makeHandle({
188 stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
189 Stream.encodeText,
190 ),
191 exitCode: Effect.never,
192 }),
193 ),
194 );
195
196 const error = yield* runWith(spawner)({
197 command: "fake",
198 args: ["spam-stdout"],
199 maxOutputBytes: 128,
200 timeout: "2 seconds",
201 }).pipe(Effect.flip);
202
203 expect(error).toBeInstanceOf(ProcessOutputLimitError);
204 }),
205 );
206
207 it.effect("truncates output when outputMode is truncate", () =>
208 Effect.gen(function* () {
209 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
210
211 const result = yield* runWith(spawner)({
212 command: "fake",
213 args: ["stdout-bytes", "2048"],
214 maxOutputBytes: 128,
215 outputMode: "truncate",
216 });
217
218 expect(result.code).toBe(0);
219 expect(result.stdout.length).toBeLessThanOrEqual(128);
220 expect(result.stdoutTruncated).toBe(true);
221 expect(result.stderrTruncated).toBe(false);
222 }),
223 );
224
225 it.effect("writes stdin before waiting for exit", () =>
226 Effect.gen(function* () {
227 const stdinWritten = yield* Deferred.make<void>();
228 const decoder = new TextDecoder();
229 const spawner = makeSpawner(() =>
230 Effect.succeed(
231 makeHandle({
232 stdout: "stdin payload",
233 stdin: Sink.forEach((chunk: Uint8Array) => {
234 const text = decoder.decode(chunk, { stream: true });
235 return text.includes("stdin payload")
236 ? Deferred.succeed(stdinWritten, undefined)
237 : Effect.void;
238 }),
239 exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
240 }),
241 ),
242 );
243
244 const result = yield* runWith(spawner)({
245 command: "fake",
246 args: ["stdin-echo"],
247 stdin: "stdin payload",
248 });
249
250 expect(result.stdout).toBe("stdin payload");
251 expect(result.code).toBe(0);
252 }),
253 );
254
255 it.effect("returns output for non-zero exit codes", () =>
256 Effect.gen(function* () {
257 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stderr: "boom", code: 2 })));
258
259 const result = yield* runWith(spawner)({
260 command: "fake",
261 args: ["stderr-exit", "boom", "2"],
262 });
263
264 expect(result.code).toBe(2);
265 expect(result.stderr).toBe("boom");
266 }),
267 );
268
269 it.effect("fails on timeout", () =>
270 Effect.gen(function* () {
271 const spawner = makeSpawner(() =>
272 Effect.succeed(
273 makeHandle({
274 exitCode: Effect.never,
275 }),
276 ),
277 );
278 const errorFiber = yield* runWith(spawner)({
279 command: "fake",
280 args: ["sleep"],
281 timeout: "50 millis",
282 }).pipe(Effect.flip, Effect.forkScoped);
283
284 yield* Effect.yieldNow;
285 yield* TestClock.adjust(Duration.millis(50));
286 const error = yield* Fiber.join(errorFiber);
287
288 expect(error).toBeInstanceOf(ProcessTimeoutError);
289 }),
290 );
291
292 it.effect("returns a synthetic timed out result when timeoutBehavior is timedOutResult", () =>
293 Effect.gen(function* () {
294 const spawner = makeSpawner(() =>
295 Effect.succeed(
296 makeHandle({
297 exitCode: Effect.never,
298 }),
299 ),
300 );
301 const resultFiber = yield* runWith(spawner)({
302 command: "fake",
303 args: ["sleep"],
304 timeout: "50 millis",
305 timeoutBehavior: "timedOutResult",
306 }).pipe(Effect.forkScoped);
307
308 yield* Effect.yieldNow;
309 yield* TestClock.adjust(Duration.millis(50));
310 const result = yield* Fiber.join(resultFiber);
311
312 expect(result).toMatchObject({
313 stdout: "",
314 stderr: "",
315 code: null,
316 timedOut: true,
317 stdoutTruncated: false,
318 stderrTruncated: false,
319 });
320 }),
321 );
322});
323
324describe("isWindowsCommandNotFound", () => {
325 it.effect("matches the localized German cmd.exe error text", () =>
326 Effect.gen(function* () {
327 const isCommandNotFound = yield* isWindowsCommandNotFound(
328 1,
329 "wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
330 ).pipe(Effect.provideService(HostProcessPlatform, "win32"));
331 expect(isCommandNotFound).toBe(true);
332 }),
333 );
334});