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

VcsProcess.test.ts

548 lines20.3 KB

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 Deferred from "effect/Deferred";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Cause from "effect/Cause";
8import * as Fiber from "effect/Fiber";
9import * as FileSystem from "effect/FileSystem";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
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 * as TestClock from "effect/testing/TestClock";
17import { ChildProcessSpawner } from "effect/process";
18​
19import { VcsProcessExitError, VcsProcessSpawnError } from "@t3tools/contracts";
20import * as ProcessRunner from "../processRunner.ts";
21import * as VcsProcess from "./VcsProcess.ts";
22​
23const encodeExitError = Schema.encodeEffect(Schema.fromJsonString(VcsProcessExitError));
24​
25const run = (input: VcsProcess.VcsProcessInput) =>
26 Effect.gen(function* () {
27 const process = yield* VcsProcess.VcsProcess;
28 return yield* process.run(input);
29 });
30​
31const layerLive = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
32​
33const provideLive = <A, E, R>(effect: Effect.Effect<A, E, R | VcsProcess.VcsProcess>) =>
34 effect.pipe(Effect.provide(layerLive));
35​
36const baseInput = {
37 operation: "test.process-boundary",
38 command: "git",
39 args: ["status", "--short"],
40 cwd: "/workspace",
41} satisfies VcsProcess.VcsProcessInput;
42​
43const captureProcessResult = (
44 result: Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
45) =>
46 VcsProcess.make.pipe(
47 Effect.provideService(
48 ProcessRunner.ProcessRunner,
49 ProcessRunner.ProcessRunner.of({ run: () => result }),
50 ),
51 Effect.flatMap((service) => service.run(baseInput)),
52 Effect.flip,
53 );
54​
55describe("VcsProcess.run", () => {
56 it.effect("explains a locked Git index and allows restore after the lock is released", () =>
57 Effect.gen(function* () {
58 const fs = yield* FileSystem.FileSystem;
59 const path = yield* Path.Path;
60 const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "t3-index-lock-" });
61 const git = (args: readonly string[]) =>
62 run({ operation: "test.checkpoint.restore", command: "git", cwd, args });
63 yield* git(["init"]);
64 const file = path.join(cwd, "README.md");
65 yield* fs.writeFileString(file, "before\n");
66 yield* git(["add", "README.md"]);
67 yield* git([
68 "-c",
69 "user.name=Test",
70 "-c",
71 "user.email=test@example.com",
72 "commit",
73 "-m",
74 "initial",
75 ]);
76 yield* fs.writeFileString(file, "after\n");
77 const lock = path.join(cwd, ".git", "index.lock");
78 yield* fs.writeFileString(lock, "held by another process\n");
79 const restore = ["restore", "--source=HEAD", "--worktree", "--staged", "--", "README.md"];
80​
81 const error = yield* Effect.flip(git(restore));
82 expect(error).toBeInstanceOf(VcsProcessExitError);
83 expect(error).toMatchObject({
84 exitCode: 128,
85 failureKind: "command-failed",
86 detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",
87 });
88 expect(error.message).not.toContain("index.lock");
89 expect(yield* fs.readFileString(file)).toBe("after\n");
90 expect(yield* fs.readFileString(lock)).toBe("held by another process\n");
91​
92 yield* fs.remove(lock);
93 yield* git(restore);
94 expect(yield* fs.readFileString(file)).toBe("before\n");
95 }).pipe(provideLive, Effect.provide(NodeServices.layer), Effect.scoped),
96 );
97​
98 it.effect.each([
99 {
100 stderr: "fatal: Unable to create '/private/repo/index.lock': File exists",
101 retryable: true,
102 detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",
103 },
104 {
105 stderr: "fatal: Unable to create 'C:\\private\\repo\\.git\\index.lock': File exists.",
106 retryable: true,
107 detail: "Git's index is locked. Wait for other Git operations to finish, then try again.",
108 },
109 {
110 stderr: "fatal: Unable to create '/private/repo/.git/config.lock': File exists.",
111 retryable: true,
112 },
113 {
114 stderr: "fatal: Unable to create '/private/repo/index.lock': Permission denied",
115 retryable: false,
116 },
117 { stderr: 'error: open("/private/repo/file"): No such file or directory', retryable: true },
118 {
119 stderr: "fatal: unable to stat '/private/repo/file': No such file or directory",
120 retryable: true,
121 },
122 { stderr: 'error: open("/private/repo/file"): Permission denied', retryable: false },
123 {
124 stderr: "error: '/private/repo/child/' does not have a commit checked out",
125 retryable: false,
126 },
127 { stderr: "fatal: index file corrupt", retryable: false },
128 ])(
129 "classifies Git exit retryability and safe detail without retaining stderr: $stderr",
130 ({ stderr, retryable, detail = "Process exited with a non-zero status." }) =>
131 Effect.gen(function* () {
132 const error = yield* captureProcessResult(
133 Effect.succeed({
134 stdout: "",
135 stderr,
136 code: ChildProcessSpawner.ExitCode(128),
137 timedOut: false,
138 stdoutTruncated: false,
139 stderrTruncated: false,
140 stdoutInvalidUtf8: false,
141 stderrInvalidUtf8: false,
142 }),
143 );
144 assert.instanceOf(error, VcsProcessExitError);
145 expect(error.retryable === true).toBe(retryable);
146 expect(error.detail).toBe(detail);
147 const encoded = yield* encodeExitError(error);
148 expect(encoded).not.toContain("private");
149 }),
150 );
151​
152 it.effect.each([
153 {
154 stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
155 fsyncMethods: ["fsync", "writeout-only"],
156 },
157 {
158 stderr:
159 "fatal: update_ref failed for ref 'refs/t3/checkpoints/x': cannot update ref 'refs/t3/checkpoints/x': couldn't write '/Volumes/share/.git/refs/t3/checkpoints/x.lock'",
160 fsyncMethods: ["fsync", "writeout-only"],
161 },
162 { stderr: "fatal: Operation not supported", fsyncMethods: ["fsync"] },
163 {
164 stderr:
165 "fatal: update_ref failed for ref 'refs/t3/checkpoints/x': cannot update ref 'refs/t3/checkpoints/x': couldn't write '/Volumes/share/.git/refs/t3/checkpoints/x.lock': Input/output error",
166 fsyncMethods: ["fsync"],
167 },
168 {
169 stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
170 fsyncMethods: ["fsync", "writeout-only"],
171 fallbackFails: true,
172 },
173 {
174 platform: "linux",
175 stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
176 fsyncMethods: ["fsync"],
177 },
178 {
179 operation: baseInput.operation,
180 stderr: "fatal: fsync error on '.git/objects/a5/tmp_obj_Pseg66': Operation not supported",
181 fsyncMethods: ["fsync"],
182 },
183 {
184 stderr: "fatal: fsync error on '.git/objects/bulk_fsync_Pseg66': Operation not supported",
185 fsyncMethods: ["batch", "writeout-only"],
186 },
187 {
188 stderr:
189 "fatal: update_ref failed for ref 'refs/t3/checkpoints/x': cannot update ref 'refs/t3/checkpoints/x': couldn't write '/Volumes/share/.git/refs/t3/checkpoints/x.lock'",
190 fsyncMethods: ["batch", "writeout-only"],
191 },
192 ] as const)(
193 "falls back to writeout-only only for unsupported flushes on macOS ($fsyncMethods): $stderr",
194 ({ stderr, fsyncMethods, ...scenario }) =>
195 Effect.gen(function* () {
196 const seen: Array<ReadonlyArray<string>> = [];
197 const service = yield* VcsProcess.make.pipe(
198 Effect.provideService(
199 HostProcess.Platform,
200 "platform" in scenario ? scenario.platform : "darwin",
201 ),
202 Effect.provideService(ProcessRunner.ProcessRunner, {
203 run: (input) =>
204 Effect.sync(() => {
205 seen.push(input.args);
206 const failed =
207 input.args.includes(`core.fsyncMethod=${fsyncMethods[0]}`) ||
208 ("fallbackFails" in scenario && scenario.fallbackFails);
209 return {
210 stdout: "",
211 stderr: failed ? stderr : "",
212 code: ChildProcessSpawner.ExitCode(failed ? 128 : 0),
213 timedOut: false,
214 stdoutTruncated: false,
215 stderrTruncated: false,
216 stdoutInvalidUtf8: false,
217 stderrInvalidUtf8: false,
218 };
219 }),
220 }),
221 );
222 const exit = yield* service
223 .run({
224 ...baseInput,
225 operation:
226 "operation" in scenario
227 ? scenario.operation
228 : VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
229 args: [
230 "-c",
231 "core.fsync=objects,reference",
232 "-c",
233 ...(fsyncMethods[0] === "batch" ? ["core.fsyncMethod=fsync", "-c"] : []),
234 `core.fsyncMethod=${fsyncMethods[0]}`,
235 "add",
236 ],
237 })
238 .pipe(Effect.exit);
239 expect(seen).toEqual(
240 fsyncMethods.map((method) => [
241 "-c",
242 "core.fsync=objects,reference",
243 "-c",
244 ...(fsyncMethods[0] === "batch"
245 ? [`core.fsyncMethod=${method === "batch" ? "fsync" : method}`, "-c"]
246 : []),
247 `core.fsyncMethod=${method}`,
248 "add",
249 ]),
250 );
251 expect(Exit.isSuccess(exit)).toBe(
252 fsyncMethods.length === 2 && !("fallbackFails" in scenario && scenario.fallbackFails),
253 );
254 if (Exit.isFailure(exit)) {
255 expect(Cause.findErrorOption(exit.cause)).toMatchObject({
256 _tag: "Some",
257 value: { _tag: "VcsProcessExitError", exitCode: 128 },
258 });
259 }
260 }),
261 );
262​
263 it.effect("bounds a burst of processes that share a concurrency key", () =>
264 Effect.gen(function* () {
265 const gate = yield* Deferred.make<void>();
266 const starts = yield* Queue.unbounded<number>();
267 const active = yield* Ref.make(0);
268 const peak = yield* Ref.make(0);
269 const total = yield* Ref.make(0);
270 const service = yield* VcsProcess.make.pipe(
271 Effect.provideService(
272 ProcessRunner.ProcessRunner,
273 ProcessRunner.ProcessRunner.of({
274 run: () =>
275 Effect.gen(function* () {
276 const count = yield* Ref.updateAndGet(active, (held) => held + 1);
277 yield* Ref.update(peak, (held) => Math.max(held, count));
278 yield* Ref.update(total, (held) => held + 1);
279 yield* Queue.offer(starts, count);
280 yield* Deferred.await(gate);
281 return {
282 stdout: "",
283 stderr: "",
284 code: ChildProcessSpawner.ExitCode(0),
285 timedOut: false,
286 stdoutTruncated: false,
287 stderrTruncated: false,
288 stdoutInvalidUtf8: false,
289 stderrInvalidUtf8: false,
290 };
291 }).pipe(Effect.ensuring(Ref.update(active, (count) => count - 1))),
292 }),
293 ),
294 );
295​
296 const burst = yield* Effect.all(
297 Array.from({ length: 32 }, (_, index) =>
298 service.run({
299 operation: `synthetic.cli.${index}`,
300 command: "host-cli",
301 args: ["api", "user"],
302 cwd: "/workspace",
303 concurrency: { key: "host-cli", limit: 4 },
304 }),
305 ),
306 { concurrency: "unbounded" },
307 ).pipe(Effect.forkChild);
308​
309 yield* Effect.all(Array.from({ length: 4 }, () => Queue.take(starts)));
310 yield* Effect.yieldNow;
311 expect(yield* Queue.size(starts)).toBe(0);
312 expect(yield* Ref.get(peak)).toBe(4);
313​
314 yield* Deferred.succeed(gate, undefined);
315 yield* Fiber.join(burst);
316 expect(yield* Ref.get(total)).toBe(32);
317 expect(yield* Ref.get(peak)).toBe(4);
318 }),
319 );
320​
321 it.effect("leaves git a slot while slow forge CLI processes are running", () =>
322 Effect.gen(function* () {
323 const gate = yield* Deferred.make<void>();
324 const service = yield* VcsProcess.make.pipe(
325 Effect.provideService(
326 ProcessRunner.ProcessRunner,
327 ProcessRunner.ProcessRunner.of({
328 run: (input) =>
329 Effect.gen(function* () {
330 if (input.command !== "git") yield* Deferred.await(gate);
331 return {
332 stdout: "",
333 stderr: "",
334 code: ChildProcessSpawner.ExitCode(0),
335 timedOut: false,
336 stdoutTruncated: false,
337 stderrTruncated: false,
338 stdoutInvalidUtf8: false,
339 stderrInvalidUtf8: false,
340 };
341 }),
342 }),
343 ),
344 );
345​
346 const forgeRuns = yield* Effect.forEach(Array.from({ length: 12 }), () =>
347 service
348 .run({
349 operation: "synthetic.forge.listChangeRequests",
350 command: "tea",
351 args: ["pulls", "list"],
352 cwd: "/workspace",
353 })
354 .pipe(Effect.forkChild({ startImmediately: true })),
355 );
356 const checkpoint = yield* service
357 .run({
358 ...baseInput,
359 operation: VcsProcess.CHECKPOINT_CAPTURE_OPERATION,
360 args: ["rev-parse", "HEAD"],
361 })
362 .pipe(Effect.timeoutOption("1 second"), Effect.forkChild({ startImmediately: true }));
363 yield* TestClock.adjust("1 second");
364​
365 const gitResult = yield* Fiber.join(checkpoint);
366 yield* Deferred.succeed(gate, undefined);
367 yield* Fiber.joinAll(forgeRuns);
368 expect(
369 Option.isSome(gitResult),
370 "git waited behind forge CLI runs that held every VCS process slot",
371 ).toBe(true);
372 }),
373 );
374​
375 it.effect("keeps git from opening a folder laid out as a bare repository", () =>
376 Effect.gen(function* () {
377 const fileSystem = yield* FileSystem.FileSystem;
378 const path = yield* Path.Path;
379 const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-vcs-bare-" });
380 yield* fileSystem.makeDirectory(path.join(cwd, "objects", "info"), { recursive: true });
381 yield* fileSystem.makeDirectory(path.join(cwd, "refs", "heads"), { recursive: true });
382 yield* fileSystem.writeFileString(path.join(cwd, "HEAD"), "ref: refs/heads/main\n");
383 yield* fileSystem.writeFileString(
384 path.join(cwd, "config"),
385 '[core]\n\trepositoryformatversion = 0\n\tbare = false\n\tworktree = .\n\tfsmonitor = "echo ran >> fsmonitor-runs; false"\n',
386 );
387​
388 const result = yield* run({
389 operation: "test.bare-repository",
390 command: "git",
391 args: ["status"],
392 cwd,
393 allowNonZeroExit: true,
394 });
395​
396 expect(result.exitCode).not.toBe(0);
397 expect(yield* fileSystem.exists(path.join(cwd, "fsmonitor-runs"))).toBe(false);
398 }).pipe(Effect.scoped, provideLive, Effect.provide(NodeServices.layer)),
399 );
400​
401 it.effect("classifies authentication failures without retaining stderr", () =>
402 Effect.gen(function* () {
403 const secretStderr = "authentication failed for token super-secret-token";
404 const error = yield* run({
405 operation: "test.authentication",
406 command: "node",
407 args: ["-e", "process.stderr.write(process.argv[1]); process.exit(1)", secretStderr],
408 cwd: process.cwd(),
409 }).pipe(Effect.flip);
410​
411 expect(error).toBeInstanceOf(VcsProcessExitError);
412 expect(error).toMatchObject({
413 operation: "test.authentication",
414 command: "node",
415 exitCode: 1,
416 detail: "Authentication failed.",
417 failureKind: "authentication",
418 stderrLength: secretStderr.length,
419 stderrTruncated: false,
420 });
421 expect(error.message).not.toContain(secretStderr);
422 expect(error.message).not.toContain("super-secret-token");
423 }).pipe(provideLive),
424 );
425​
426 it.effect("classifies API rate limits without retaining provider stderr", () =>
427 Effect.gen(function* () {
428 const providerStderr =
429 "GraphQL: API rate limit already exceeded for user ID 51714798 and token 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).toBeInstanceOf(VcsProcessExitError);
438 expect(error).toMatchObject({
439 command: "node",
440 exitCode: 1,
441 detail: "API rate limit exceeded.",
442 failureKind: "rate-limited",
443 stderrLength: providerStderr.length,
444 stderrTruncated: false,
445 });
446 expect(error.message).not.toContain(providerStderr);
447 expect(error.message).not.toContain("secret-value");
448 }).pipe(provideLive),
449 );
450​
451 it.effect("reads a failure with the command's own classifier and names it in its terms", () =>
452 Effect.gen(function* () {
453 const fail = (input: Partial<VcsProcess.VcsProcessInput>) =>
454 run({
455 operation: "test.classify",
456 command: "node",
457 args: ["-e", "process.stderr.write('HTTP 404: 404 Not Found'); process.exit(1)"],
458 cwd: process.cwd(),
459 ...input,
460 }).pipe(Effect.flip);
461​
462 expect(yield* fail({})).toMatchObject({
463 failureKind: "command-failed",
464 detail: "Process exited with a non-zero status.",
465 });
466 expect(
467 yield* fail({
468 classifyFailure: (stderr) => (stderr.includes("404") ? "not-found" : null),
469 notFoundDetail: "Merge request not found.",
470 }),
471 ).toMatchObject({ failureKind: "not-found", detail: "Merge request not found." });
472 }).pipe(provideLive),
473 );
474​
475 it.effect("retains spawn causes without exposing process arguments in the error message", () =>
476 Effect.gen(function* () {
477 const secretArgument = "--token=super-secret-token";
478 const error = yield* run({
479 operation: "test.spawn",
480 command: "definitely-not-a-t3code-executable",
481 args: [secretArgument],
482 cwd: process.cwd(),
483 }).pipe(Effect.flip);
484​
485 expect(error).toBeInstanceOf(VcsProcessSpawnError);
486 expect(error).toMatchObject({
487 operation: "test.spawn",
488 command: "definitely-not-a-t3code-executable",
489 argumentCount: 1,
490 });
491 expect(error).toHaveProperty("cause");
492 expect(error.message).not.toContain(secretArgument);
493 }).pipe(provideLive),
494 );
495​
496 it.effect("truncates output and appends the marker when requested", () =>
497 Effect.gen(function* () {
498 const result = yield* run({
499 operation: "test.truncate-marker",
500 command: "node",
501 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
502 cwd: process.cwd(),
503 maxOutputBytes: 128,
504 appendTruncationMarker: true,
505 });
506​
507 expect(result.stdoutTruncated).toBe(true);
508 expect(result.stdout).toContain("[truncated]");
509 expect(result.stderrTruncated).toBe(false);
510 }).pipe(provideLive),
511 );
512​
513 it.effect("fails with measured byte counts when output must not be truncated", () =>
514 Effect.gen(function* () {
515 const error = yield* run({
516 operation: "test.output-limit",
517 command: "node",
518 args: ["-e", "process.stdout.write('x'.repeat(2048))"],
519 cwd: yield* HostProcess.WorkingDirectory,
520 maxOutputBytes: 128,
521 outputMode: "error",
522 }).pipe(Effect.flip);
523​
524 assert(error._tag === "VcsProcessOutputLimitError");
525 expect(error.stream).toBe("stdout");
526 expect(error.maxBytes).toBe(128);
527 expect(error.observedBytes).toBeGreaterThan(error.maxBytes);
528 }).pipe(provideLive),
529 );
530​
531 it.effect("streams all stdout bytes beyond the buffered output cap", () =>
532 Effect.gen(function* () {
533 const chunks: Uint8Array[] = [];
534 const result = yield* run({
535 operation: "test.stream-output",
536 command: "node",
537 args: ["-e", "process.stdout.write('x'.repeat(131072) + '\\0S final\\0')"],
538 cwd: process.cwd(),
539 maxOutputBytes: 8,
540 onStdoutChunk: (chunk) => chunks.push(chunk),
541 });
542​
543 expect(result.stdout).toBe("xxxxxxxx");
544 expect(result.stdoutTruncated).toBe(true);
545 expect(Buffer.concat(chunks).toString()).toBe("x".repeat(131072) + "\0S final\0");
546 }).pipe(provideLive),
547 );
548});