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

VcsProcess.test.ts

689 lines22.9 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 Exit from "effect/Exit";
8import * as Cause from "effect/Cause";
9import * as Fiber from "effect/Fiber";
10import * as Layer from "effect/Layer";
11import * as Queue from "effect/Queue";
12import * as Ref from "effect/Ref";
13import * as Schema from "effect/Schema";
14import { TestClock } from "effect/testing";
15import { ChildProcessSpawner } from "effect/unstable/process";
16​
17import {
18 VcsProcessExitError,
19 VcsProcessSpawnError,
20 VcsProcessTimeoutError,
21} from "@t3tools/contracts";
22import * as ProcessRunner from "../processRunner.ts";
23import * as VcsProcess from "./VcsProcess.ts";
24​
25const encodeExitError = Schema.encodeEffect(Schema.fromJsonString(VcsProcessExitError));
26​
27const run = (input: VcsProcess.VcsProcessInput) =>
28 Effect.gen(function* () {
29 const process = yield* VcsProcess.VcsProcess;
30 return yield* process.run(input);
31 });
32​
33const liveLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
34​
35const provideLive = <A, E, R>(effect: Effect.Effect<A, E, R | VcsProcess.VcsProcess>) =>
36 effect.pipe(Effect.provide(liveLayer));
37​
38const baseInput = {
39 operation: "test.process-boundary",
40 command: "git",
41 args: ["status", "--short"],
42 cwd: "/workspace",
43} satisfies VcsProcess.VcsProcessInput;
44​
45const captureProcessResult = (
46 result: Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
47 input: VcsProcess.VcsProcessInput = baseInput,
48) =>
49 VcsProcess.make.pipe(
50 Effect.provideService(
51 ProcessRunner.ProcessRunner,
52 ProcessRunner.ProcessRunner.of({ run: () => result }),
53 ),
54 Effect.flatMap((service) => service.run(input)),
55 Effect.flip,
56 );
57​
58const failedExit = (stdout: string, stderr: string) =>
59 Effect.succeed({
60 stdout,
61 stderr,
62 code: ChildProcessSpawner.ExitCode(1),
63 timedOut: false,
64 stdoutTruncated: false,
65 stderrTruncated: false,
66 stdoutInvalidUtf8: false,
67 stderrInvalidUtf8: false,
68 });
69​
70const ghApiInput = {
71 operation: "test.gh-api",
72 command: "gh",
73 args: ["api", "--method", "POST", "repos/owner/repo/pulls/1/reviews", "--input", "-"],
74 cwd: "/workspace",
75} satisfies VcsProcess.VcsProcessInput;
76​
77describe("VcsProcess.run", () => {
78 it.effect.each([
79 { stderr: "fatal: Unable to create '/private/repo/index.lock': File exists", retryable: true },
80 {
81 stderr: "fatal: Unable to create '/private/repo/index.lock': Permission denied",
82 retryable: false,
83 },
84 { stderr: 'error: open("/private/repo/file"): No such file or directory', retryable: true },
85 {
86 stderr: "fatal: unable to stat '/private/repo/file': No such file or directory",
87 retryable: true,
88 },
89 { stderr: 'error: open("/private/repo/file"): Permission denied', retryable: false },
90 {
91 stderr: "error: '/private/repo/child/' does not have a commit checked out",
92 retryable: false,
93 },
94 { stderr: "fatal: index file corrupt", retryable: false },
95 ])(
96 "classifies Git exit retryability without retaining stderr: $stderr",
97 ({ stderr, retryable }) =>
98 Effect.gen(function* () {
99 const error = yield* captureProcessResult(
100 Effect.succeed({
101 stdout: "",
102 stderr,
103 code: ChildProcessSpawner.ExitCode(128),
104 timedOut: false,
105 stdoutTruncated: false,
106 stderrTruncated: false,
107 stdoutInvalidUtf8: false,
108 stderrInvalidUtf8: false,
109 }),
110 );
111 assert.instanceOf(error, VcsProcessExitError);
112 expect(error.retryable === true).toBe(retryable);
113 const encoded = yield* encodeExitError(error);
114 expect(encoded).not.toContain("/private/repo");
115 }),
116 );
117​
118 it.effect.each([
119 {
120 name: "string errors",
121 // @effect-diagnostics-next-line preferSchemaOverJson:off
122 body: JSON.stringify({
123 message: "Unprocessable Entity",
124 errors: ["Line could not be resolved"],
125 status: "422",
126 }),
127 hostMessage: "Line could not be resolved",
128 },
129 {
130 name: "error objects",
131 // @effect-diagnostics-next-line preferSchemaOverJson:off
132 body: JSON.stringify({
133 message: "Validation Failed",
134 errors: [
135 { resource: "PullRequestReviewComment", code: "custom", message: "Path is missing" },
136 { resource: "PullRequestReviewComment", code: "custom", message: "Body is too long" },
137 ],
138 status: "422",
139 }),
140 hostMessage: "Path is missing; Body is too long",
141 },
142 ])("keeps GitHub's own reason for refusing a gh api request: $name", ({ body, hostMessage }) =>
143 Effect.gen(function* () {
144 // gh prints only the generic top-level message on stderr; the reason is in the body.
145 const error = yield* captureProcessResult(
146 failedExit(body, "gh: Unprocessable Entity (HTTP 422)\n"),
147 ghApiInput,
148 );
149 assert.instanceOf(error, VcsProcessExitError);
150 expect(error.failureKind).toBe("command-failed");
151 expect(error.hostMessage).toBe(hostMessage);
152 }),
153 );
154​
155 it.effect.each([
156 { name: "a non-JSON body", command: "gh", stdout: "not json" },
157 {
158 name: "errors without a message",
159 command: "gh",
160 // @effect-diagnostics-next-line preferSchemaOverJson:off
161 stdout: JSON.stringify({
162 message: "Validation Failed",
163 errors: [{ resource: "Label", code: "missing_field", field: "name" }],
164 }),
165 },
166 {
167 name: "a command other than gh",
168 command: "git",
169 // @effect-diagnostics-next-line preferSchemaOverJson:off
170 stdout: JSON.stringify({ errors: ["Line could not be resolved"] }),
171 },
172 {
173 name: "a gh command other than api",
174 command: "gh",
175 args: ["pr", "view", "1", "--json", "number"],
176 // @effect-diagnostics-next-line preferSchemaOverJson:off
177 stdout: JSON.stringify({ errors: ["Line could not be resolved"] }),
178 },
179 ])("keeps no host reason for $name", ({ command, args, stdout }) =>
180 Effect.gen(function* () {
181 const error = yield* captureProcessResult(failedExit(stdout, "failed\n"), {
182 ...ghApiInput,
183 command,
184 ...(args === undefined ? {} : { args }),
185 });
186 assert.instanceOf(error, VcsProcessExitError);
187 expect(error.hostMessage).toBeUndefined();
188 }),
189 );
190​
191 it.effect("bounds the host reason GitHub gives", () =>
192 Effect.gen(function* () {
193 const error = yield* captureProcessResult(
194 // @effect-diagnostics-next-line preferSchemaOverJson:off
195 failedExit(JSON.stringify({ errors: ["x".repeat(2_000)] }), "gh: HTTP 422\n"),
196 ghApiInput,
197 );
198 assert.instanceOf(error, VcsProcessExitError);
199 expect(error.hostMessage?.length).toBeLessThanOrEqual(300);
200 }),
201 );
202​
203 it.effect.each(["timeout", "spawn"] as const)(
204 "checkpoint commands do not retry %s failures",
205 (kind) =>
206 Effect.gen(function* () {
207 let attempts = 0;
208 const fields = { command: "git", argumentCount: 2, cwd: "/workspace" };
209 const failure =
210 kind === "timeout"
211 ? new ProcessRunner.ProcessTimeoutError({ ...fields, timeoutMs: 30_000 })
212 : new ProcessRunner.ProcessSpawnError({ ...fields, cause: new Error("spawn failed") });
213 const service = yield* VcsProcess.make.pipe(
214 Effect.provideService(ProcessRunner.ProcessRunner, {
215 run: () =>
216 Effect.sync(() => {
217 attempts += 1;
218 }).pipe(Effect.andThen(Effect.fail(failure))),
219 }),
220 );
221 const error = yield* service
222 .run({
223 ...baseInput,
224 operation: VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
225 })
226 .pipe(Effect.flip);
227 expect(attempts).toBe(1);
228 expect(error._tag).toBe(
229 kind === "timeout" ? "VcsProcessTimeoutError" : "VcsProcessSpawnError",
230 );
231 }),
232 );
233​
234 it.effect.each([
235 {
236 name: "recovers after two lock failures",
237 failures: 2,
238 attempts: 3,
239 transient: true,
240 capture: true,
241 streaming: false,
242 },
243 {
244 name: "bounds persistent lock failures",
245 failures: Infinity,
246 attempts: 3,
247 transient: true,
248 capture: true,
249 streaming: false,
250 },
251 {
252 name: "does not retry unknown exits",
253 failures: Infinity,
254 attempts: 1,
255 transient: false,
256 capture: true,
257 streaming: false,
258 },
259 {
260 name: "leaves other operations unchanged",
261 failures: Infinity,
262 attempts: 1,
263 transient: true,
264 capture: false,
265 streaming: false,
266 },
267 {
268 name: "does not replay stdout callbacks",
269 failures: Infinity,
270 attempts: 1,
271 transient: true,
272 capture: true,
273 streaming: true,
274 },
275 ])(
276 "checkpoint command retry $name",
277 ({ failures, attempts: expectedAttempts, transient, capture, streaming }) =>
278 Effect.gen(function* () {
279 let attempts = 0;
280 const service = yield* VcsProcess.make.pipe(
281 Effect.provideService(ProcessRunner.ProcessRunner, {
282 run: () =>
283 Effect.sync(() => {
284 attempts += 1;
285 return {
286 stdout: "",
287 stderr:
288 attempts > failures
289 ? ""
290 : transient
291 ? "fatal: Unable to create '/repo/index.lock': File exists"
292 : "fatal: index file corrupt",
293 code: ChildProcessSpawner.ExitCode(attempts > failures ? 0 : attempts),
294 timedOut: false,
295 stdoutTruncated: false,
296 stderrTruncated: false,
297 stdoutInvalidUtf8: false,
298 stderrInvalidUtf8: false,
299 };
300 }),
301 }),
302 );
303 const fiber = yield* service
304 .run({
305 ...baseInput,
306 operation: capture ? VcsProcess.CHECKPOINT_CAPTURE_OPERATION : baseInput.operation,
307 ...(streaming ? { onStdoutChunk: () => {} } : {}),
308 })
309 .pipe(Effect.exit, Effect.forkScoped);
310 yield* TestClock.adjust("150 millis");
311 const result = yield* Fiber.join(fiber);
312 expect(attempts).toBe(expectedAttempts);
313 if (failures === Infinity) {
314 if (Exit.isSuccess(result))
315 return yield* Effect.die("Expected a capture command failure");
316 const error = Cause.findErrorOption(result.cause);
317 if (error._tag === "None" || error.value._tag !== "VcsProcessExitError") {
318 return yield* Effect.die("Expected a Git exit error");
319 }
320 expect(error.value.exitCode).toBe(expectedAttempts);
321 } else {
322 expect(Exit.isSuccess(result)).toBe(true);
323 }
324 }),
325 );
326​
327 it.effect("bounds a synthetic burst of GitHub API processes", () =>
328 Effect.gen(function* () {
329 const gate = yield* Deferred.make<void>();
330 const starts = yield* Queue.unbounded<number>();
331 const active = yield* Ref.make(0);
332 const peak = yield* Ref.make(0);
333 const total = yield* Ref.make(0);
334 const service = yield* VcsProcess.make.pipe(
335 Effect.provideService(
336 ProcessRunner.ProcessRunner,
337 ProcessRunner.ProcessRunner.of({
338 run: () =>
339 Effect.gen(function* () {
340 const count = yield* Ref.updateAndGet(active, (held) => held + 1);
341 yield* Ref.update(peak, (held) => Math.max(held, count));
342 yield* Ref.update(total, (held) => held + 1);
343 yield* Queue.offer(starts, count);
344 yield* Deferred.await(gate);
345 return {
346 stdout: "",
347 stderr: "",
348 code: ChildProcessSpawner.ExitCode(0),
349 timedOut: false,
350 stdoutTruncated: false,
351 stderrTruncated: false,
352 stdoutInvalidUtf8: false,
353 stderrInvalidUtf8: false,
354 };
355 }).pipe(Effect.ensuring(Ref.update(active, (count) => count - 1))),
356 }),
357 ),
358 );
359​
360 const burst = yield* Effect.all(
361 Array.from({ length: 32 }, (_, index) =>
362 service.run({
363 operation: `synthetic.github.${index}`,
364 command: "gh",
365 args: ["api", "user"],
366 cwd: "/workspace",
367 }),
368 ),
369 { concurrency: "unbounded" },
370 ).pipe(Effect.forkChild);
371​
372 yield* Effect.all(Array.from({ length: 4 }, () => Queue.take(starts)));
373 yield* Effect.yieldNow;
374 expect(yield* Queue.size(starts)).toBe(0);
375 expect(yield* Ref.get(peak)).toBe(4);
376​
377 yield* Deferred.succeed(gate, undefined);
378 yield* Fiber.join(burst);
379 expect(yield* Ref.get(total)).toBe(32);
380 expect(yield* Ref.get(peak)).toBe(4);
381 }),
382 );
383​
384 it.effect("collects stdout", () =>
385 Effect.gen(function* () {
386 const result = yield* run({
387 operation: "test.stdout",
388 command: "node",
389 args: ["-e", "process.stdout.write('hello')"],
390 cwd: process.cwd(),
391 });
392​
393 expect(result.stdout).toBe("hello");
394 expect(result.stderr).toBe("");
395 expect(result.stdoutTruncated).toBe(false);
396 expect(result.stderrTruncated).toBe(false);
397 }).pipe(provideLive),
398 );
399​
400 it.effect("writes stdin before waiting for exit", () =>
401 Effect.gen(function* () {
402 const result = yield* run({
403 operation: "test.stdin",
404 command: "node",
405 args: [
406 "-e",
407 [
408 "process.stdin.setEncoding('utf8');",
409 "let data='';",
410 "process.stdin.on('data', chunk => { data += chunk; });",
411 "process.stdin.on('end', () => { process.stdout.write(data); });",
412 ].join(""),
413 ],
414 cwd: process.cwd(),
415 stdin: "stdin payload",
416 });
417​
418 expect(result.stdout).toBe("stdin payload");
419 }).pipe(provideLive),
420 );
421​
422 it.effect("fails with VcsProcessExitError for non-zero exits by default", () =>
423 Effect.gen(function* () {
424 const secretArgument = "--token=super-secret-token";
425 const secretStderr = "remote rejected super-secret-token";
426 const error = yield* run({
427 operation: "test.exit",
428 command: "node",
429 args: [
430 "-e",
431 "process.stderr.write(process.argv[1]); process.exit(2)",
432 secretStderr,
433 secretArgument,
434 ],
435 cwd: process.cwd(),
436 }).pipe(Effect.flip);
437​
438 expect(error).toBeInstanceOf(VcsProcessExitError);
439 expect(error).toMatchObject({
440 operation: "test.exit",
441 command: "node",
442 argumentCount: 4,
443 exitCode: 2,
444 detail: "Process exited with a non-zero status.",
445 failureKind: "command-failed",
446 stderrLength: secretStderr.length,
447 stderrTruncated: false,
448 });
449 expect(error.message).not.toContain(secretArgument);
450 expect(error.message).not.toContain(secretStderr);
451 }).pipe(provideLive),
452 );
453​
454 it.effect("classifies authentication failures without retaining stderr", () =>
455 Effect.gen(function* () {
456 const secretStderr = "authentication failed for token super-secret-token";
457 const error = yield* run({
458 operation: "test.authentication",
459 command: "node",
460 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", secretStderr],
461 cwd: process.cwd(),
462 }).pipe(Effect.flip);
463​
464 expect(error).toBeInstanceOf(VcsProcessExitError);
465 expect(error).toMatchObject({
466 operation: "test.authentication",
467 command: "node",
468 exitCode: 1,
469 detail: "Authentication failed.",
470 failureKind: "authentication",
471 stderrLength: secretStderr.length,
472 stderrTruncated: false,
473 });
474 expect(error.message).not.toContain(secretStderr);
475 expect(error.message).not.toContain("super-secret-token");
476 }).pipe(provideLive),
477 );
478​
479 it.effect("classifies API rate limits without retaining provider stderr", () =>
480 Effect.gen(function* () {
481 const providerStderr =
482 "GraphQL: API rate limit already exceeded for user ID 51714798 and token secret-value.";
483 const error = yield* run({
484 operation: "test.rate-limit",
485 command: "node",
486 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
487 cwd: process.cwd(),
488 }).pipe(Effect.flip);
489​
490 expect(error).toBeInstanceOf(VcsProcessExitError);
491 expect(error).toMatchObject({
492 command: "node",
493 exitCode: 1,
494 detail: "API rate limit exceeded.",
495 failureKind: "rate-limited",
496 stderrLength: providerStderr.length,
497 stderrTruncated: false,
498 });
499 expect(error.message).not.toContain(providerStderr);
500 expect(error.message).not.toContain("secret-value");
501 }).pipe(provideLive),
502 );
503​
504 it.effect("classifies HTTP 429 responses as rate limits", () =>
505 Effect.gen(function* () {
506 const providerStderr = "HTTP 429: Too Many Requests. request-id=secret-value";
507 const error = yield* run({
508 operation: "test.rate-limit",
509 command: "node",
510 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", providerStderr],
511 cwd: process.cwd(),
512 }).pipe(Effect.flip);
513​
514 expect(error).toMatchObject({
515 detail: "API rate limit exceeded.",
516 failureKind: "rate-limited",
517 });
518 expect(error.message).not.toContain(providerStderr);
519 }).pipe(provideLive),
520 );
521​
522 it.effect("retains spawn causes without exposing process arguments in the error message", () =>
523 Effect.gen(function* () {
524 const secretArgument = "--token=super-secret-token";
525 const error = yield* run({
526 operation: "test.spawn",
527 command: "definitely-not-a-t3code-executable",
528 args: [secretArgument],
529 cwd: process.cwd(),
530 }).pipe(Effect.flip);
531​
532 expect(error).toBeInstanceOf(VcsProcessSpawnError);
533 expect(error).toMatchObject({
534 operation: "test.spawn",
535 command: "definitely-not-a-t3code-executable",
536 argumentCount: 1,
537 });
538 expect(error).toHaveProperty("cause");
539 expect(error.message).not.toContain(secretArgument);
540 }).pipe(provideLive),
541 );
542​
543 it.effect("preserves real boundary causes without manufacturing structural ones", () =>
544 Effect.gen(function* () {
545 const cause = new Error("secret stdin failure");
546 const error = yield* captureProcessResult(
547 Effect.fail(
548 new ProcessRunner.ProcessStdinError({
549 command: baseInput.command,
550 argumentCount: baseInput.args.length,
551 cwd: baseInput.cwd,
552 stdinBytes: 47,
553 cause,
554 }),
555 ),
556 );
557​
558 expect(error).toMatchObject({
559 _tag: "VcsProcessStdinWriteError",
560 operation: baseInput.operation,
561 stdinBytes: 47,
562 cause,
563 });
564 expect(error.message).not.toContain(cause.message);
565​
566 const missingExitCodeError = yield* captureProcessResult(
567 Effect.succeed({
568 stdout: "",
569 stderr: "",
570 code: null,
571 timedOut: false,
572 stdoutTruncated: false,
573 stderrTruncated: false,
574 stdoutInvalidUtf8: false,
575 stderrInvalidUtf8: false,
576 }),
577 );
578​
579 expect(missingExitCodeError).toMatchObject({
580 _tag: "VcsProcessMissingExitCodeError",
581 operation: baseInput.operation,
582 command: baseInput.command,
583 cwd: baseInput.cwd,
584 argumentCount: baseInput.args.length,
585 });
586 expect(missingExitCodeError).not.toHaveProperty("cause");
587 }),
588 );
589​
590 it.effect("returns output when non-zero exits are allowed", () =>
591 Effect.gen(function* () {
592 const result = yield* run({
593 operation: "test.allowed-exit",
594 command: "node",
595 args: ["-e", "process.stderr.write('boom'); process.exit(2)"],
596 cwd: process.cwd(),
597 allowNonZeroExit: true,
598 });
599​
600 expect(result.exitCode).toBe(2);
601 expect(result.stderr).toBe("boom");
602 }).pipe(provideLive),
603 );
604​
605 it.effect("truncates output and appends the marker when requested", () =>
606 Effect.gen(function* () {
607 const result = yield* run({
608 operation: "test.truncate-marker",
609 command: "node",
610 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
611 cwd: process.cwd(),
612 maxOutputBytes: 128,
613 appendTruncationMarker: true,
614 });
615​
616 expect(result.stdoutTruncated).toBe(true);
617 expect(result.stdout).toContain("[truncated]");
618 expect(result.stderrTruncated).toBe(false);
619 }).pipe(provideLive),
620 );
621​
622 it.effect("truncates without the marker when truncation markers are disabled", () =>
623 Effect.gen(function* () {
624 const result = yield* run({
625 operation: "test.truncate-silent",
626 command: "node",
627 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
628 cwd: process.cwd(),
629 maxOutputBytes: 128,
630 });
631​
632 expect(result.stdoutTruncated).toBe(true);
633 expect(result.stdout).not.toContain("[truncated]");
634 }).pipe(provideLive),
635 );
636​
637 it.effect("fails with measured byte counts when output must not be truncated", () =>
638 Effect.gen(function* () {
639 const error = yield* run({
640 operation: "test.output-limit",
641 command: "node",
642 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
643 cwd: yield* HostProcessWorkingDirectory,
644 maxOutputBytes: 128,
645 outputMode: "error",
646 }).pipe(Effect.flip);
647​
648 assert(error._tag === "VcsProcessOutputLimitError");
649 expect(error.stream).toBe("stdout");
650 expect(error.maxBytes).toBe(128);
651 expect(error.observedBytes).toBeGreaterThan(error.maxBytes);
652 }).pipe(provideLive),
653 );
654​
655 it.effect("streams all stdout bytes beyond the buffered output cap", () =>
656 Effect.gen(function* () {
657 const chunks: Uint8Array[] = [];
658 const result = yield* run({
659 operation: "test.stream-output",
660 command: "node",
661 args: ["-e", "process.stdout.write('x'.repeat(131072) + '\\0S final\\0')"],
662 cwd: process.cwd(),
663 maxOutputBytes: 8,
664 onStdoutChunk: (chunk) => chunks.push(chunk),
665 });
666​
667 expect(result.stdout).toBe("xxxxxxxx");
668 expect(result.stdoutTruncated).toBe(true);
669 expect(Buffer.concat(chunks).toString()).toBe("x".repeat(131072) + "\0S final\0");
670 }).pipe(provideLive),
671 );
672​
673 it.effect("fails with VcsProcessTimeoutError on timeout", () =>
674 Effect.gen(function* () {
675 const errorFiber = yield* run({
676 operation: "test.timeout",
677 command: "node",
678 args: ["-e", "setTimeout(() => {}, 5000)"],
679 cwd: process.cwd(),
680 timeoutMs: 50,
681 }).pipe(Effect.flip, Effect.forkScoped);
682 yield* Effect.yieldNow;
683 yield* TestClock.adjust(Duration.millis(50));
684 const error = yield* Fiber.join(errorFiber);
685​
686 expect(error).toBeInstanceOf(VcsProcessTimeoutError);
687 }).pipe(provideLive),
688 );
689});