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

VcsProcess.ts

334 lines11.9 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 Schedule from "effect/Schedule";
7import * as Semaphore from "effect/Semaphore";
8import { ChildProcessSpawner } from "effect/process";
9​
10import {
11 type VcsError,
12 type VcsProcessErrorContext,
13 VcsProcessExitError,
14 type VcsProcessExitFailureKind,
15 VcsProcessMissingExitCodeError,
16 VcsProcessOutputLimitError,
17 VcsProcessOutputReadError,
18 VcsProcessSpawnError,
19 VcsProcessStdinWriteError,
20 VcsProcessTimeoutError,
21} from "@t3tools/contracts";
22import * as HostProcess from "@t3tools/shared/HostProcess";
23​
24import * as ProcessRunner from "../processRunner.ts";
25​
26export interface VcsProcessInput {
27 readonly operation: string;
28 readonly command: string;
29 readonly args: ReadonlyArray<string>;
30 readonly cwd: string;
31 readonly spawnCwd?: string;
32 readonly stdin?: string;
33 readonly onStdoutChunk?: (chunk: Uint8Array) => void;
34 readonly env?: NodeJS.ProcessEnv;
35 readonly allowNonZeroExit?: boolean;
36 readonly timeoutMs?: number;
37 readonly maxOutputBytes?: number;
38 readonly outputMode?: ProcessRunner.ProcessRunInput["outputMode"];
39 readonly appendTruncationMarker?: boolean;
41​
42export interface VcsProcessOutput {
43 readonly exitCode: ChildProcessSpawner.ExitCode;
44 readonly stdout: string;
45 readonly stderr: string;
46 readonly stdoutTruncated: boolean;
47 readonly stderrTruncated: boolean;
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​
65/** Shown to users when a Git command fails because another process holds the index lock. */
66export const GIT_INDEX_LOCKED_DETAIL =
67 "Git's index is locked. Wait for other Git operations to finish, then try again.";
68​
69export const CHECKPOINT_CAPTURE_OPERATION = "GitVcsDriver.checkpoints.captureCheckpoint";
70​
71/**
72 * Appends `key=value` to the `GIT_CONFIG_*` entries git reads as command-line
73 * config, so argv stays the same on every platform and nothing is written to
74 * the user's config. The entry goes after any inherited ones. Windows env names
75 * are case-insensitive (elsewhere git reads only `GIT_CONFIG_COUNT`), so there the
76 * count is found regardless of casing, read from
77 * the last spelling (a per-command value spread over process.env), and updated
78 * under every spelling so the child sees it whichever one Node keeps. A count
79 * git would reject is left alone so git still reports it.
80 */
81export const gitConfigEnv = (
82 env: NodeJS.ProcessEnv,
83 key: string,
84 value: string,
85 platform: NodeJS.Platform,
86): NodeJS.ProcessEnv => {
87 const countKeys = Object.keys(env).filter((name) =>
88 platform === "win32" ? name.toUpperCase() === "GIT_CONFIG_COUNT" : name === "GIT_CONFIG_COUNT",
89 );
90 const countKey = countKeys.at(-1) ?? "GIT_CONFIG_COUNT";
91 const inherited = env[countKey];
92 if (
93 inherited !== undefined &&
94 inherited !== "" &&
95 // Git parses the count with strtoul: leading whitespace, an optional sign
96 // (only -0 is non-negative), digits, and nothing after them.
97 /^[ \t\r\n\v\f]*(?:\+?\d+|-0+)/.exec(inherited)?.[0] !== inherited
98 ) {
99 return {};
100 }
101 const count = inherited === undefined || inherited === "" ? 0 : Number.parseInt(inherited, 10);
102 return {
103 ...Object.fromEntries([...countKeys, countKey].map((name) => [name, String(count + 1)])),
104 [`GIT_CONFIG_KEY_${count}`]: key,
105 [`GIT_CONFIG_VALUE_${count}`]: value,
106 };
107};
108​
109/**
110 * Git otherwise opens any folder holding `HEAD`, `objects/` and `refs/` as a
111 * bare repository and applies its `config`, including commands such as
112 * `core.fsmonitor`. Files saved in a project or checked out from a clone can
113 * form one, so git started by T3 (or by gh and friends) only opens a bare
114 * repository named with `--git-dir` or `GIT_DIR`. Git before 2.38 ignores it.
115 */
116export const explicitBareRepositoryEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) =>
117 gitConfigEnv(env, "safe.bareRepository", "explicit", platform);
118​
119const classifyNonZeroExit = (command: string, stderr: string): VcsProcessExitFailureKind => {
120 const normalized = stderr.toLowerCase();
121​
122 if (
123 normalized.includes("authentication failed") ||
124 normalized.includes("not logged in") ||
125 normalized.includes("gh auth login") ||
126 normalized.includes("glab auth login") ||
127 normalized.includes("az devops login") ||
128 normalized.includes("please run az login") ||
129 normalized.includes("no oauth token") ||
130 normalized.includes("unauthorized")
131 ) {
132 return "authentication";
133 }
134​
135 if (
136 normalized.includes("api rate limit") ||
137 normalized.includes("rate limit exceeded") ||
138 normalized.includes("secondary rate limit") ||
139 normalized.includes("too many requests") ||
140 normalized.includes("http 429")
141 ) {
142 return "rate-limited";
143 }
144​
145 if (
146 (command === "gh" &&
147 (normalized.includes("could not resolve to a pullrequest") ||
148 normalized.includes("repository.pullrequest") ||
149 normalized.includes("no pull requests found for branch") ||
150 normalized.includes("pull request not found"))) ||
151 (command === "glab" &&
152 (normalized.includes("merge request not found") ||
153 normalized.includes("not found") ||
154 normalized.includes("404"))) ||
155 (command === "az" &&
156 normalized.includes("pull request") &&
157 (normalized.includes("not found") || normalized.includes("does not exist")))
158 ) {
159 return "not-found";
160 }
161​
162 return "command-failed";
163};
164​
165// Classify before discarding stderr; keep paths and process output out of errors.
166const isTransientGitExit = (stderr: string) =>
167 /unable to create [^\n]*\.lock['"]?: file exists/i.test(stderr) ||
168 /(?:unable to stat|lstat\(|error: open\()[^\n]+: no such file or directory/i.test(stderr);
169​
170// On macOS, Git's fsync uses F_FULLFSYNC; writeout-only still uses fsync(2).
171// Network mounts can reject F_FULLFSYNC. Ref writes omit errno, so retry their
172// bare write error too; explicit unrelated errors remain failures.
173// Linux writeout-only only starts writeback, so it must not use this fallback.
174const FULL_FSYNC_ARG = "core.fsyncMethod=fsync";
175const WRITEOUT_ONLY_FSYNC_ARG = "core.fsyncMethod=writeout-only";
176const canRetryFullFsync = (stderr: string) =>
177 /fsync error on [^\r\n]+: operation not supported\r?$/im.test(stderr) ||
178 /cannot update ref [^\r\n]+: couldn't write '[^\r\n]+\.lock'\r?$/im.test(stderr);
179​
180export const make = Effect.gen(function* () {
181 const processRunner = yield* ProcessRunner.ProcessRunner;
182 const hostPlatform = yield* HostProcess.Platform;
183 const vcsProcesses = yield* Semaphore.make(VCS_PROCESS_CONCURRENCY);
184 const githubProcesses = yield* Semaphore.make(GITHUB_PROCESS_CONCURRENCY);
185​
186 const spawn = (input: VcsProcessInput, baseError: VcsProcessErrorContext) =>
187 processRunner
188 .run({
189 command: input.command,
190 args: input.args,
191 cwd: input.cwd,
192 ...(input.spawnCwd !== undefined ? { spawnCwd: input.spawnCwd } : {}),
193 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
194 ...(input.onStdoutChunk !== undefined ? { onStdoutChunk: input.onStdoutChunk } : {}),
195 env: {
196 ...input.env,
197 ...explicitBareRepositoryEnv({ ...process.env, ...input.env }, hostPlatform),
198 },
199 timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
200 maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
201 outputMode: input.outputMode ?? "truncate",
202 truncatedMarker: input.appendTruncationMarker ? OUTPUT_TRUNCATED_MARKER : "",
203 timeoutBehavior: "error",
204 })
205 .pipe(
206 Effect.mapError(
207 Match.valueTags({
208 ProcessSpawnError: (error) =>
209 VcsProcessSpawnError.fromProcessSpawnError(baseError, error),
210 ProcessOutputLimitError: (error) =>
211 new VcsProcessOutputLimitError({
212 ...baseError,
213 stream: error.stream,
214 maxBytes: error.maxBytes,
215 observedBytes: error.observedBytes,
216 }),
217 ProcessTimeoutError: (error) =>
218 VcsProcessTimeoutError.fromProcessTimeoutError(baseError, error),
219 ProcessStdinError: (error) =>
220 new VcsProcessStdinWriteError({
221 ...baseError,
222 stdinBytes: error.stdinBytes,
223 cause: error.cause,
224 }),
225 ProcessReadError: (error) =>
226 new VcsProcessOutputReadError({
227 ...baseError,
228 stream: error.stream,
229 cause: error.cause,
230 }),
231 }),
232 ),
233 );
234​
235 const runUnbounded = Effect.fn("VcsProcess.runUnbounded")(function* (input: VcsProcessInput) {
236 const baseError = {
237 operation: input.operation,
238 command: input.command,
239 cwd: input.cwd,
240 argumentCount: input.args.length,
241 };
242​
243 let result = yield* spawn(input, baseError);
244​
245 if (
246 hostPlatform === "darwin" &&
247 input.operation === CHECKPOINT_CAPTURE_OPERATION &&
248 !input.allowNonZeroExit &&
249 result.code !== null &&
250 result.code !== 0 &&
251 input.command === "git" &&
252 input.args.includes(FULL_FSYNC_ARG) &&
253 canRetryFullFsync(result.stderr)
254 ) {
255 result = yield* spawn(
256 {
257 ...input,
258 args: input.args.map((arg) => (arg === FULL_FSYNC_ARG ? WRITEOUT_ONLY_FSYNC_ARG : arg)),
259 },
260 baseError,
261 );
262 }
263​
264 if (result.code === null) {
265 return yield* new VcsProcessMissingExitCodeError(baseError);
266 }
267​
268 if (!input.allowNonZeroExit && result.code !== 0) {
269 const failureKind = classifyNonZeroExit(input.command, result.stderr);
270 const error = VcsProcessExitError.fromProcessExit(
271 baseError,
272 {
273 exitCode: result.code,
274 stderr: result.stderr,
275 stderrTruncated: result.stderrTruncated,
276 },
277 failureKind,
278 input.command === "git" &&
279 failureKind === "command-failed" &&
280 isTransientGitExit(result.stderr),
281 );
282 if (
283 input.command === "git" &&
284 /^fatal: unable to create ['"][^\r\n]*[/\\]index\.lock['"]: file exists\.?$/im.test(
285 result.stderr,
286 )
287 ) {
288 return yield* new VcsProcessExitError({
289 ...error,
290 detail: GIT_INDEX_LOCKED_DETAIL,
291 });
292 }
293 return yield* error;
294 }
295​
296 return {
297 exitCode: result.code,
298 stdout: result.stdout,
299 stderr: result.stderr,
300 stdoutTruncated: result.stdoutTruncated,
301 stderrTruncated: result.stderrTruncated,
302 stdoutInvalidUtf8: result.stdoutInvalidUtf8 ?? false,
303 stderrInvalidUtf8: result.stderrInvalidUtf8 ?? false,
304 } satisfies VcsProcessOutput;
305 });
306​
307 const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) {
308 const bounded = vcsProcesses.withPermits(1)(runUnbounded(input));
309 if (
310 input.command === "git" &&
311 input.operation === CHECKPOINT_CAPTURE_OPERATION &&
312 input.onStdoutChunk === undefined
313 ) {
314 return yield* bounded.pipe(
315 Effect.tapError((error) =>
316 Effect.logDebug("checkpoint Git command failed", {
317 operation: input.operation,
318 errorTag: error._tag,
319 }),
320 ),
321 Effect.retry({
322 times: 2,
323 while: (error) => error._tag === "VcsProcessExitError" && error.retryable === true,
324 schedule: Schedule.spaced(Duration.millis(75)),
325 }),
326 );
327 }
328 return yield* input.command === "gh" ? githubProcesses.withPermits(1)(bounded) : bounded;
329 });
330​
331 return VcsProcess.of({ run });
332});
333​
334export const layer = Layer.effect(VcsProcess, make).pipe(Layer.provide(ProcessRunner.layer));