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

VcsProcess.ts

269 lines9.4 KB

1import * as Context from "effect/Context";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Match from "effect/Match";
6import * as Option from "effect/Option";
7import * as Schedule from "effect/Schedule";
8import * as Schema from "effect/Schema";
9import * as Semaphore from "effect/Semaphore";
10import { ChildProcessSpawner } from "effect/unstable/process";
11​
12import {
13 type VcsError,
14 VcsProcessExitError,
15 type VcsProcessExitFailureKind,
16 VcsProcessMissingExitCodeError,
17 VcsProcessOutputLimitError,
18 VcsProcessOutputReadError,
19 VcsProcessSpawnError,
20 VcsProcessStdinWriteError,
21 VcsProcessTimeoutError,
22} from "@t3tools/contracts";
23import * as ProcessRunner from "../processRunner.ts";
24​
25export interface VcsProcessInput {
26 readonly operation: string;
27 readonly command: string;
28 readonly args: ReadonlyArray<string>;
29 readonly cwd: string;
30 readonly spawnCwd?: string;
31 readonly stdin?: string;
32 readonly onStdoutChunk?: (chunk: Uint8Array) => void;
33 readonly env?: NodeJS.ProcessEnv;
34 readonly allowNonZeroExit?: boolean;
35 readonly timeoutMs?: number;
36 readonly maxOutputBytes?: number;
37 readonly outputMode?: ProcessRunner.ProcessRunInput["outputMode"];
38 readonly appendTruncationMarker?: boolean;
40​
41export interface VcsProcessOutput {
42 readonly exitCode: ChildProcessSpawner.ExitCode;
43 readonly stdout: string;
44 readonly stderr: string;
45 readonly stdoutTruncated: boolean;
46 readonly stderrTruncated: boolean;
47 /** Present on real process output; optional so narrow test doubles remain lightweight. */
48 readonly stdoutInvalidUtf8?: boolean;
49 readonly stderrInvalidUtf8?: boolean;
51​
52export class VcsProcess extends Context.Service<
53 VcsProcess,
54 {
55 readonly run: (input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>;
56 }
57>()("t3/vcs/VcsProcess") {}
58​
59const DEFAULT_TIMEOUT_MS = 30_000;
60const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
61const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
62const VCS_PROCESS_CONCURRENCY = 8;
63const GITHUB_PROCESS_CONCURRENCY = 4;
64​
65export const CHECKPOINT_CAPTURE_OPERATION = "GitVcsDriver.checkpoints.captureCheckpoint";
66​
67const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFailureKind => {
68 const normalized = stderr.toLowerCase();
69​
70 if (
71 normalized.includes("authentication failed") ||
72 normalized.includes("not logged in") ||
73 normalized.includes("gh auth login") ||
74 normalized.includes("glab auth login") ||
75 normalized.includes("az devops login") ||
76 normalized.includes("please run az login") ||
77 normalized.includes("no oauth token") ||
78 normalized.includes("unauthorized")
79 ) {
80 return "authentication";
81 }
82​
83 if (
84 normalized.includes("api rate limit") ||
85 normalized.includes("rate limit exceeded") ||
86 normalized.includes("secondary rate limit") ||
87 normalized.includes("too many requests") ||
88 normalized.includes("http 429")
89 ) {
90 return "rate-limited";
91 }
92​
93 if (
94 (command === "gh" &&
95 (normalized.includes("could not resolve to a pullrequest") ||
96 normalized.includes("repository.pullrequest") ||
97 normalized.includes("no pull requests found for branch") ||
98 normalized.includes("pull request not found"))) ||
99 (command === "glab" &&
100 (normalized.includes("merge request not found") ||
101 normalized.includes("not found") ||
102 normalized.includes("404"))) ||
103 (command === "az" &&
104 normalized.includes("pull request") &&
105 (normalized.includes("not found") || normalized.includes("does not exist")))
106 ) {
107 return "not-found";
108 }
109​
110 return "command-failed";
111};
112​
113/**
114 * The error body `gh api` prints for a refused REST call. gh itself reports only the top-level
115 * message ("Unprocessable Entity"), which says nothing; the reason is in `errors`.
116 */
117const decodeGitHubApiErrorBody = Schema.decodeUnknownOption(
118 Schema.fromJsonString(
119 Schema.Struct({
120 errors: Schema.Array(
121 Schema.Union([Schema.String, Schema.Struct({ message: Schema.optional(Schema.String) })]),
122 ),
123 }),
124 ),
125);
126​
127const HOST_MESSAGE_MAX_LENGTH = 300;
128​
129/** GitHub's validation reasons, bounded; only these leave the process, never the whole body. */
130const gitHubApiRefusal = (stdout: string): string | undefined => {
131 const body = decodeGitHubApiErrorBody(stdout.trim());
132 if (Option.isNone(body)) return undefined;
133 const reasons = body.value.errors
134 .map((error) => (typeof error === "string" ? error : (error.message ?? "")).trim())
135 .filter((reason) => reason.length > 0);
136 if (reasons.length === 0) return undefined;
137 const joined = reasons.join("; ");
138 return joined.length <= HOST_MESSAGE_MAX_LENGTH
139 ? joined
140 : `${joined.slice(0, HOST_MESSAGE_MAX_LENGTH - 1)}…`;
141};
142​
143// Classify before discarding stderr; keep paths and process output out of errors.
144const isTransientGitExit = (stderr: string) =>
145 /unable to create [^\n]*\.lock['"]?: file exists/i.test(stderr) ||
146 /(?:unable to stat|lstat\(|error: open\()[^\n]+: no such file or directory/i.test(stderr);
147​
148export const make = Effect.gen(function* () {
149 const processRunner = yield* ProcessRunner.ProcessRunner;
150 const vcsProcesses = yield* Semaphore.make(VCS_PROCESS_CONCURRENCY);
151 const githubProcesses = yield* Semaphore.make(GITHUB_PROCESS_CONCURRENCY);
152​
153 const runUnbounded = Effect.fn("VcsProcess.runUnbounded")(function* (input: VcsProcessInput) {
154 const baseError = {
155 operation: input.operation,
156 command: input.command,
157 cwd: input.cwd,
158 argumentCount: input.args.length,
159 };
160​
161 const result = yield* processRunner
162 .run({
163 command: input.command,
164 args: input.args,
165 cwd: input.cwd,
166 ...(input.spawnCwd !== undefined ? { spawnCwd: input.spawnCwd } : {}),
167 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
168 ...(input.onStdoutChunk !== undefined ? { onStdoutChunk: input.onStdoutChunk } : {}),
169 ...(input.env !== undefined ? { env: input.env } : {}),
170 timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
171 maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
172 outputMode: input.outputMode ?? "truncate",
173 truncatedMarker: input.appendTruncationMarker ? OUTPUT_TRUNCATED_MARKER : "",
174 timeoutBehavior: "error",
175 })
176 .pipe(
177 Effect.mapError(
178 Match.valueTags({
179 ProcessSpawnError: (error) =>
180 VcsProcessSpawnError.fromProcessSpawnError(baseError, error),
181 ProcessOutputLimitError: (error) =>
182 new VcsProcessOutputLimitError({
183 ...baseError,
184 stream: error.stream,
185 maxBytes: error.maxBytes,
186 observedBytes: error.observedBytes,
187 }),
188 ProcessTimeoutError: (error) =>
189 VcsProcessTimeoutError.fromProcessTimeoutError(baseError, error),
190 ProcessStdinError: (error) =>
191 new VcsProcessStdinWriteError({
192 ...baseError,
193 stdinBytes: error.stdinBytes,
194 cause: error.cause,
195 }),
196 ProcessReadError: (error) =>
197 new VcsProcessOutputReadError({
198 ...baseError,
199 stream: error.stream,
200 cause: error.cause,
201 }),
202 }),
203 ),
204 );
205​
206 if (result.code === null) {
207 return yield* new VcsProcessMissingExitCodeError(baseError);
208 }
209​
210 if (!input.allowNonZeroExit && result.code !== 0) {
211 const failureKind = classifyNonZeroExit(input.command, result.stderr);
212 return yield* VcsProcessExitError.fromProcessExit(
213 baseError,
214 {
215 exitCode: result.code,
216 stderr: result.stderr,
217 stderrTruncated: result.stderrTruncated,
218 hostMessage:
219 input.command === "gh" && input.args[0] === "api" && failureKind === "command-failed"
220 ? gitHubApiRefusal(result.stdout)
221 : undefined,
222 },
223 failureKind,
224 input.command === "git" &&
225 failureKind === "command-failed" &&
226 isTransientGitExit(result.stderr),
227 );
228 }
229​
230 return {
231 exitCode: result.code,
232 stdout: result.stdout,
233 stderr: result.stderr,
234 stdoutTruncated: result.stdoutTruncated,
235 stderrTruncated: result.stderrTruncated,
236 stdoutInvalidUtf8: result.stdoutInvalidUtf8 ?? false,
237 stderrInvalidUtf8: result.stderrInvalidUtf8 ?? false,
238 } satisfies VcsProcessOutput;
239 });
240​
241 const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) {
242 const bounded = vcsProcesses.withPermits(1)(runUnbounded(input));
243 if (
244 input.command === "git" &&
245 input.operation === CHECKPOINT_CAPTURE_OPERATION &&
246 input.onStdoutChunk === undefined
247 ) {
248 // Retry the failed command, retaining the private index/tree and recovery's outer deadline.
249 return yield* bounded.pipe(
250 Effect.tapError((error) =>
251 Effect.logDebug("checkpoint Git command failed", {
252 operation: input.operation,
253 errorTag: error._tag,
254 }),
255 ),
256 Effect.retry({
257 times: 2,
258 while: (error) => error._tag === "VcsProcessExitError" && error.retryable === true,
259 schedule: Schedule.spaced(Duration.millis(75)),
260 }),
261 );
262 }
263 return yield* input.command === "gh" ? githubProcesses.withPermits(1)(bounded) : bounded;
264 });
265​
266 return VcsProcess.of({ run });
267});
268​
269export const layer = Layer.effect(VcsProcess, make).pipe(Layer.provide(ProcessRunner.layer));