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