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

VcsProcess.test.ts

378 lines12.4 KB

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