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

VcsProcess.test.ts

397 lines13.1 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, expect, it } from "@effect/vitest";
3import { HostProcessWorkingDirectory } from "@t3tools/shared/hostProcess";
4import * as Duration from "effect/Duration";
5import * as Deferred from "effect/Deferred";
6import * as Effect from "effect/Effect";
7import * as Fiber from "effect/Fiber";
8import * as Layer from "effect/Layer";
9import * as Queue from "effect/Queue";
10import * as Ref from "effect/Ref";
11import { TestClock } from "effect/testing";
12import { ChildProcessSpawner } from "effect/unstable/process";
13​
14import {
15 VcsProcessExitError,
16 VcsProcessSpawnError,
17 VcsProcessTimeoutError,
18} from "@t3tools/contracts";
19import * as ProcessRunner from "../processRunner.ts";
20import * as VcsProcess from "./VcsProcess.ts";
21​
22const run = (input: VcsProcess.VcsProcessInput) =>
23 Effect.gen(function* () {
24 const process = yield* VcsProcess.VcsProcess;
25 return yield* process.run(input);
26 });
27​
28const liveLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
29​
30const provideLive = <A, E, R>(effect: Effect.Effect<A, E, R | VcsProcess.VcsProcess>) =>
31 effect.pipe(Effect.provide(liveLayer));
32​
33const baseInput = {
34 operation: "test.process-boundary",
35 command: "git",
36 args: ["status", "--short"],
37 cwd: "/workspace",
38} satisfies VcsProcess.VcsProcessInput;
39​
40const captureProcessResult = (
41 result: Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
42) =>
43 VcsProcess.make.pipe(
44 Effect.provideService(
45 ProcessRunner.ProcessRunner,
46 ProcessRunner.ProcessRunner.of({ run: () => result }),
47 ),
48 Effect.flatMap((service) => service.run(baseInput)),
49 Effect.flip,
50 );
51​
52describe("VcsProcess.run", () => {
53 it.effect("bounds a synthetic burst of GitHub API processes", () =>
54 Effect.gen(function* () {
55 const gate = yield* Deferred.make<void>();
56 const starts = yield* Queue.unbounded<number>();
57 const active = yield* Ref.make(0);
58 const peak = yield* Ref.make(0);
59 const total = yield* Ref.make(0);
60 const service = yield* VcsProcess.make.pipe(
61 Effect.provideService(
62 ProcessRunner.ProcessRunner,
63 ProcessRunner.ProcessRunner.of({
64 run: () =>
65 Effect.gen(function* () {
66 const count = yield* Ref.updateAndGet(active, (held) => held + 1);
67 yield* Ref.update(peak, (held) => Math.max(held, count));
68 yield* Ref.update(total, (held) => held + 1);
69 yield* Queue.offer(starts, count);
70 yield* Deferred.await(gate);
71 return {
72 stdout: "",
73 stderr: "",
74 code: ChildProcessSpawner.ExitCode(0),
75 timedOut: false,
76 stdoutTruncated: false,
77 stderrTruncated: false,
78 stdoutInvalidUtf8: false,
79 stderrInvalidUtf8: false,
80 };
81 }).pipe(Effect.ensuring(Ref.update(active, (count) => count - 1))),
82 }),
83 ),
84 );
85​
86 const burst = yield* Effect.all(
87 Array.from({ length: 32 }, (_, index) =>
88 service.run({
89 operation: `synthetic.github.${index}`,
90 command: "gh",
91 args: ["api", "user"],
92 cwd: "/workspace",
93 }),
94 ),
95 { concurrency: "unbounded" },
96 ).pipe(Effect.forkChild);
97​
98 yield* Effect.all(Array.from({ length: 4 }, () => Queue.take(starts)));
99 yield* Effect.yieldNow;
100 expect(yield* Queue.size(starts)).toBe(0);
101 expect(yield* Ref.get(peak)).toBe(4);
102​
103 yield* Deferred.succeed(gate, undefined);
104 yield* Fiber.join(burst);
105 expect(yield* Ref.get(total)).toBe(32);
106 expect(yield* Ref.get(peak)).toBe(4);
107 }),
108 );
109​
110 it.effect("collects stdout", () =>
111 Effect.gen(function* () {
112 const result = yield* run({
113 operation: "test.stdout",
114 command: "node",
115 args: ["-e", "process.stdout.write('hello')"],
116 cwd: process.cwd(),
117 });
118​
119 expect(result.stdout).toBe("hello");
120 expect(result.stderr).toBe("");
121 expect(result.stdoutTruncated).toBe(false);
122 expect(result.stderrTruncated).toBe(false);
123 }).pipe(provideLive),
124 );
125​
126 it.effect("writes stdin before waiting for exit", () =>
127 Effect.gen(function* () {
128 const result = yield* run({
129 operation: "test.stdin",
130 command: "node",
131 args: [
132 "-e",
133 [
134 "process.stdin.setEncoding('utf8');",
135 "let data='';",
136 "process.stdin.on('data', chunk => { data += chunk; });",
137 "process.stdin.on('end', () => { process.stdout.write(data); });",
138 ].join(""),
139 ],
140 cwd: process.cwd(),
141 stdin: "stdin payload",
142 });
143​
144 expect(result.stdout).toBe("stdin payload");
145 }).pipe(provideLive),
146 );
147​
148 it.effect("fails with VcsProcessExitError for non-zero exits by default", () =>
149 Effect.gen(function* () {
150 const secretArgument = "--token=super-secret-token";
151 const secretStderr = "remote rejected super-secret-token";
152 const error = yield* run({
153 operation: "test.exit",
154 command: "node",
155 args: [
156 "-e",
157 "process.stderr.write(process.argv[1]); process.exit(2)",
158 secretStderr,
159 secretArgument,
160 ],
161 cwd: process.cwd(),
162 }).pipe(Effect.flip);
163​
164 expect(error).toBeInstanceOf(VcsProcessExitError);
165 expect(error).toMatchObject({
166 operation: "test.exit",
167 command: "node",
168 argumentCount: 4,
169 exitCode: 2,
170 detail: "Process exited with a non-zero status.",
171 failureKind: "command-failed",
172 stderrLength: secretStderr.length,
173 stderrTruncated: false,
174 });
175 expect(error.message).not.toContain(secretArgument);
176 expect(error.message).not.toContain(secretStderr);
177 }).pipe(provideLive),
178 );
179​
180 it.effect("classifies authentication failures without retaining stderr", () =>
181 Effect.gen(function* () {
182 const secretStderr = "authentication failed for token super-secret-token";
183 const error = yield* run({
184 operation: "test.authentication",
185 command: "node",
186 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", secretStderr],
187 cwd: process.cwd(),
188 }).pipe(Effect.flip);
189​
190 expect(error).toBeInstanceOf(VcsProcessExitError);
191 expect(error).toMatchObject({
192 operation: "test.authentication",
193 command: "node",
194 exitCode: 1,
195 detail: "Authentication failed.",
196 failureKind: "authentication",
197 stderrLength: secretStderr.length,
198 stderrTruncated: false,
199 });
200 expect(error.message).not.toContain(secretStderr);
201 expect(error.message).not.toContain("super-secret-token");
202 }).pipe(provideLive),
203 );
204​
205 it.effect("classifies API rate limits without retaining provider stderr", () =>
206 Effect.gen(function* () {
207 const providerStderr =
208 "GraphQL: API rate limit already exceeded for user ID 51714798 and token secret-value.";
209 const error = yield* run({
210 operation: "test.rate-limit",
211 command: "node",
212 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
213 cwd: process.cwd(),
214 }).pipe(Effect.flip);
215​
216 expect(error).toBeInstanceOf(VcsProcessExitError);
217 expect(error).toMatchObject({
218 command: "node",
219 exitCode: 1,
220 detail: "API rate limit exceeded.",
221 failureKind: "rate-limited",
222 stderrLength: providerStderr.length,
223 stderrTruncated: false,
224 });
225 expect(error.message).not.toContain(providerStderr);
226 expect(error.message).not.toContain("secret-value");
227 }).pipe(provideLive),
228 );
229​
230 it.effect("classifies HTTP 429 responses as rate limits", () =>
231 Effect.gen(function* () {
232 const providerStderr = "HTTP 429: Too Many Requests. request-id=secret-value";
233 const error = yield* run({
234 operation: "test.rate-limit",
235 command: "node",
236 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
237 cwd: process.cwd(),
238 }).pipe(Effect.flip);
239​
240 expect(error).toMatchObject({
241 detail: "API rate limit exceeded.",
242 failureKind: "rate-limited",
243 });
244 expect(error.message).not.toContain(providerStderr);
245 }).pipe(provideLive),
246 );
247​
248 it.effect("retains spawn causes without exposing process arguments in the error message", () =>
249 Effect.gen(function* () {
250 const secretArgument = "--token=super-secret-token";
251 const error = yield* run({
252 operation: "test.spawn",
253 command: "definitely-not-a-t3code-executable",
254 args: [secretArgument],
255 cwd: process.cwd(),
256 }).pipe(Effect.flip);
257​
258 expect(error).toBeInstanceOf(VcsProcessSpawnError);
259 expect(error).toMatchObject({
260 operation: "test.spawn",
261 command: "definitely-not-a-t3code-executable",
262 argumentCount: 1,
263 });
264 expect(error).toHaveProperty("cause");
265 expect(error.message).not.toContain(secretArgument);
266 }).pipe(provideLive),
267 );
268​
269 it.effect("preserves real boundary causes without manufacturing structural ones", () =>
270 Effect.gen(function* () {
271 const cause = new Error("secret stdin failure");
272 const error = yield* captureProcessResult(
273 Effect.fail(
274 new ProcessRunner.ProcessStdinError({
275 command: baseInput.command,
276 argumentCount: baseInput.args.length,
277 cwd: baseInput.cwd,
278 stdinBytes: 47,
279 cause,
280 }),
281 ),
282 );
283​
284 expect(error).toMatchObject({
285 _tag: "VcsProcessStdinWriteError",
286 operation: baseInput.operation,
287 stdinBytes: 47,
288 cause,
289 });
290 expect(error.message).not.toContain(cause.message);
291​
292 const missingExitCodeError = yield* captureProcessResult(
293 Effect.succeed({
294 stdout: "",
295 stderr: "",
296 code: null,
297 timedOut: false,
298 stdoutTruncated: false,
299 stderrTruncated: false,
300 stdoutInvalidUtf8: false,
301 stderrInvalidUtf8: false,
302 }),
303 );
304​
305 expect(missingExitCodeError).toMatchObject({
306 _tag: "VcsProcessMissingExitCodeError",
307 operation: baseInput.operation,
308 command: baseInput.command,
309 cwd: baseInput.cwd,
310 argumentCount: baseInput.args.length,
311 });
312 expect(missingExitCodeError).not.toHaveProperty("cause");
313 }),
314 );
315​
316 it.effect("returns output when non-zero exits are allowed", () =>
317 Effect.gen(function* () {
318 const result = yield* run({
319 operation: "test.allowed-exit",
320 command: "node",
321 args: ["-e", "process.stderr.write('boom'); process.exit(2)"],
322 cwd: process.cwd(),
323 allowNonZeroExit: true,
324 });
325​
326 expect(result.exitCode).toBe(2);
327 expect(result.stderr).toBe("boom");
328 }).pipe(provideLive),
329 );
330​
331 it.effect("truncates output and appends the marker when requested", () =>
332 Effect.gen(function* () {
333 const result = yield* run({
334 operation: "test.truncate-marker",
335 command: "node",
336 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
337 cwd: process.cwd(),
338 maxOutputBytes: 128,
339 appendTruncationMarker: true,
340 });
341​
342 expect(result.stdoutTruncated).toBe(true);
343 expect(result.stdout).toContain("[truncated]");
344 expect(result.stderrTruncated).toBe(false);
345 }).pipe(provideLive),
346 );
347​
348 it.effect("truncates without the marker when truncation markers are disabled", () =>
349 Effect.gen(function* () {
350 const result = yield* run({
351 operation: "test.truncate-silent",
352 command: "node",
353 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
354 cwd: process.cwd(),
355 maxOutputBytes: 128,
356 });
357​
358 expect(result.stdoutTruncated).toBe(true);
359 expect(result.stdout).not.toContain("[truncated]");
360 }).pipe(provideLive),
361 );
362​
363 it.effect("fails with measured byte counts when output must not be truncated", () =>
364 Effect.gen(function* () {
365 const error = yield* run({
366 operation: "test.output-limit",
367 command: "node",
368 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
369 cwd: yield* HostProcessWorkingDirectory,
370 maxOutputBytes: 128,
371 outputMode: "error",
372 }).pipe(Effect.flip);
373​
374 assert(error._tag === "VcsProcessOutputLimitError");
375 expect(error.stream).toBe("stdout");
376 expect(error.maxBytes).toBe(128);
377 expect(error.observedBytes).toBeGreaterThan(error.maxBytes);
378 }).pipe(provideLive),
379 );
380​
381 it.effect("fails with VcsProcessTimeoutError on timeout", () =>
382 Effect.gen(function* () {
383 const errorFiber = yield* run({
384 operation: "test.timeout",
385 command: "node",
386 args: ["-e", "setTimeout(() => {}, 5000)"],
387 cwd: process.cwd(),
388 timeoutMs: 50,
389 }).pipe(Effect.flip, Effect.forkScoped);
390 yield* Effect.yieldNow;
391 yield* TestClock.adjust(Duration.millis(50));
392 const error = yield* Fiber.join(errorFiber);
393​
394 expect(error).toBeInstanceOf(VcsProcessTimeoutError);
395 }).pipe(provideLive),
396 );
397});