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

processRunner.test.ts

318 lines10.3 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as PlatformError from "effect/PlatformError";
6import * as Sink from "effect/Sink";
7import * as Stream from "effect/Stream";
8import { ChildProcessSpawner } from "effect/process";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import { SpawnExecutableResolution } from "@t3tools/shared/shell";
11​
12import * as ProcessRunner from "./processRunner.ts";
13​
14type ChildProcessCommand = {
15 readonly command: string;
16 readonly args: ReadonlyArray<string>;
17 readonly options: {
18 readonly shell?: boolean | string;
19 };
20};
21​
22function asChildProcessCommand(command: unknown): ChildProcessCommand {
23 return command as ChildProcessCommand;
25​
26function makeHandle(input: {
27 readonly stdout?: string | Stream.Stream<Uint8Array>;
28 readonly stderr?: string | Stream.Stream<Uint8Array>;
29 readonly code?: number;
30 readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
31 readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
32}) {
33 return ChildProcessSpawner.makeHandle({
34 pid: ChildProcessSpawner.ProcessId(1),
35 exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
36 isRunning: Effect.succeed(false),
37 kill: () => Effect.void,
38 unref: Effect.succeed(Effect.void),
39 stdin: input.stdin ?? Sink.drain,
40 stdout:
41 typeof input.stdout === "string"
42 ? Stream.encodeText(Stream.make(input.stdout))
43 : (input.stdout ?? Stream.empty),
44 stderr:
45 typeof input.stderr === "string"
46 ? Stream.encodeText(Stream.make(input.stderr))
47 : (input.stderr ?? Stream.empty),
48 all: Stream.empty,
49 getInputFd: () => Sink.drain,
50 getOutputFd: () => Stream.empty,
51 });
53​
54function makeSpawner(
55 f: (
56 command: ChildProcessCommand,
57 ) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle, PlatformError.PlatformError>,
58) {
59 return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
61​
62const runWith =
63 (spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) =>
64 (input: ProcessRunner.ProcessRunInput) =>
65 Effect.service(ProcessRunner.ProcessRunner).pipe(
66 Effect.flatMap((runner) =>
67 runner.run({
68 ...input,
69 }),
70 ),
71 Effect.provide(
72 ProcessRunner.layer.pipe(
73 Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
74 ),
75 ),
76 );
77​
78describe("runProcess", () => {
79 it.effect("resolves and escapes Windows command shims before spawning", () => {
80 const spawner = makeSpawner((command) =>
81 Effect.sync(() => {
82 expect(command.command).toBe(
83 [
84 '^"C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd^"',
85 '^"repos^"',
86 '^"pr^"',
87 '^"list^"',
88 '^"--source-branch^"',
89 '^"feature^ ^&^ release^"',
90 ].join(" "),
91 );
92 expect(command.args).toEqual([]);
93 expect(command.options.shell).toBe(true);
94 return makeHandle({ stdout: "[]" });
95 }),
96 );
97​
98 return runWith(spawner)({
99 command: "az",
100 args: ["repos", "pr", "list", "--source-branch", "feature & release"],
101 env: { AZURE_CONFIG_DIR: "C:\\Users\\tester\\.azure" },
102 }).pipe(
103 Effect.provideService(HostProcess.Platform, "win32"),
104 Effect.provideService(HostProcess.Environment, {
105 PATH: "C:\\Users\\tester\\AppData\\Roaming\\npm",
106 PATHEXT: ".COM;.EXE;.BAT;.CMD",
107 }),
108 Effect.provideService(SpawnExecutableResolution, (_command, _platform, env) =>
109 env.PATH === "C:\\Users\\tester\\AppData\\Roaming\\npm" &&
110 env.AZURE_CONFIG_DIR === "C:\\Users\\tester\\.azure"
111 ? "C:\\Users\\tester\\AppData\\Roaming\\npm\\az.cmd"
112 : undefined,
113 ),
114 Effect.map((result) => {
115 expect(result.stdout).toBe("[]");
116 }),
117 );
118 });
119​
120 it.effect("preserves resolved spawn context and cause", () =>
121 Effect.gen(function* () {
122 const cause = PlatformError.systemError({
123 _tag: "PermissionDenied",
124 module: "ChildProcessSpawner",
125 method: "spawn",
126 pathOrDescriptor: "/actual/fake",
127 });
128 const spawner = makeSpawner(() => Effect.fail(cause));
129​
130 const error = yield* runWith(spawner)({
131 command: "fake",
132 args: ["--flag", "secret-token-value"],
133 cwd: "/logical",
134 spawnCwd: "/actual",
135 }).pipe(Effect.flip);
136​
137 expect(error._tag).toBe("ProcessSpawnError");
138 if (error._tag !== "ProcessSpawnError") {
139 return expect.fail("Expected ProcessSpawnError");
140 }
141 expect(error).toMatchObject({
142 command: "fake",
143 argumentCount: 2,
144 cwd: "/logical",
145 spawnCwd: "/actual",
146 resolvedCommand: "fake",
147 resolvedArgumentCount: 2,
148 shell: false,
149 });
150 expect(error.cause).toBe(cause);
151 expect(error.message).toBe("Failed to spawn process 'fake' in '/actual'");
152 expect(error).not.toHaveProperty("args");
153 expect(error).not.toHaveProperty("resolvedArgs");
154 expect(error.message).not.toContain("secret-token-value");
155 }),
156 );
157​
158 it.effect("types spawn failures that the platform spawner throws synchronously", () =>
159 Effect.gen(function* () {
160 // A non-directory entry on PATH makes node's spawn throw ENOTDIR
161 // synchronously. The platform spawner calls it inside `Effect.callback`,
162 // so the throw arrives as a defect rather than a typed error.
163 const defect = Object.assign(new Error("spawn jj ENOTDIR"), { code: "ENOTDIR" });
164 const spawner = makeSpawner(() =>
165 Effect.callback<never, never>(() => {
166 throw defect;
167 }),
168 );
169​
170 const error = yield* runWith(spawner)({
171 command: "jj",
172 args: ["--version"],
173 cwd: "/repo",
174 }).pipe(Effect.flip);
175​
176 expect(error._tag).toBe("ProcessSpawnError");
177 if (error._tag !== "ProcessSpawnError") {
178 return expect.fail("Expected ProcessSpawnError");
179 }
180 expect(error).toMatchObject({ command: "jj", argumentCount: 1, cwd: "/repo" });
181 expect(error.cause).toBe(defect);
182 }),
183 );
184​
185 it.effect("fails when output exceeds max buffer in default mode", () =>
186 Effect.gen(function* () {
187 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
188​
189 const error = yield* runWith(spawner)({
190 command: "fake",
191 args: ["stdout-bytes", "2048"],
192 maxOutputBytes: 128,
193 }).pipe(Effect.flip);
194​
195 expect(error._tag).toBe("ProcessOutputLimitError");
196 if (error._tag !== "ProcessOutputLimitError") {
197 return expect.fail("Expected ProcessOutputLimitError");
198 }
199 expect(error).toMatchObject({
200 stream: "stdout",
201 maxBytes: 128,
202 observedBytes: 2048,
203 });
204 expect(error.message).toBe(
205 "Process 'fake' stdout produced 2048 bytes, exceeding the 128 byte limit",
206 );
207 }),
208 );
209​
210 it.effect("accepts output at the byte limit followed by an empty chunk", () =>
211 Effect.gen(function* () {
212 const output = new TextEncoder().encode("exactly");
213 const spawner = makeSpawner(() =>
214 Effect.succeed(
215 makeHandle({
216 stdout: Stream.make(output, new Uint8Array()),
217 }),
218 ),
219 );
220​
221 const result = yield* runWith(spawner)({
222 command: "fake",
223 args: ["exact-limit"],
224 maxOutputBytes: output.byteLength,
225 });
226​
227 expect(result.stdout).toBe("exactly");
228 }),
229 );
230​
231 it.effect("fails fast on output limit before timeout for long-running output", () =>
232 Effect.gen(function* () {
233 const textChunk = "x".repeat(64);
234 const spawner = makeSpawner(() =>
235 Effect.succeed(
236 makeHandle({
237 stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
238 Stream.encodeText,
239 ),
240 exitCode: Effect.never,
241 }),
242 ),
243 );
244​
245 const error = yield* runWith(spawner)({
246 command: "fake",
247 args: ["spam-stdout"],
248 maxOutputBytes: 128,
249 timeout: "2 seconds",
250 }).pipe(Effect.flip);
251​
252 expect(error).toBeInstanceOf(ProcessRunner.ProcessOutputLimitError);
253 }),
254 );
255​
256 it.effect("truncates output when outputMode is truncate", () =>
257 Effect.gen(function* () {
258 const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
259​
260 const result = yield* runWith(spawner)({
261 command: "fake",
262 args: ["stdout-bytes", "2048"],
263 maxOutputBytes: 128,
264 outputMode: "truncate",
265 });
266​
267 expect(result.code).toBe(0);
268 expect(result.stdout.length).toBeLessThanOrEqual(128);
269 expect(result.stdoutTruncated).toBe(true);
270 expect(result.stderrTruncated).toBe(false);
271 }),
272 );
273​
274 it.effect("writes stdin before waiting for exit", () =>
275 Effect.gen(function* () {
276 const stdinWritten = yield* Deferred.make<void>();
277 const decoder = new TextDecoder();
278 const spawner = makeSpawner(() =>
279 Effect.succeed(
280 makeHandle({
281 stdout: "stdin payload",
282 stdin: Sink.forEach((chunk: Uint8Array) => {
283 const text = decoder.decode(chunk, { stream: true });
284 return text.includes("stdin payload")
285 ? Deferred.succeed(stdinWritten, undefined)
286 : Effect.void;
287 }),
288 exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
289 }),
290 ),
291 );
292​
293 const result = yield* runWith(spawner)({
294 command: "fake",
295 args: ["stdin-echo"],
296 stdin: "stdin payload",
297 });
298​
299 expect(result.stdout).toBe("stdin payload");
300 expect(result.code).toBe(0);
301 }),
302 );
303​
304 for (const {} of ["timeout", "success"] as const) {
305 }
306});
307​
308describe("isWindowsCommandNotFound", () => {
309 it.effect("matches the localized German cmd.exe error text", () =>
310 Effect.gen(function* () {
311 const isCommandNotFound = yield* ProcessRunner.isWindowsCommandNotFound(
312 1,
313 "wird nicht als interner oder externer Befehl, betriebsfahiges Programm oder Batch-Datei erkannt",
314 ).pipe(Effect.provideService(HostProcess.Platform, "win32"));
315 expect(isCommandNotFound).toBe(true);
316 }),
317 );
318});