Open History to see the last commit
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";
23import type { SourceControlProcessInput } from "@t3tools/source-control-core/server/SourceControlHost";
24
25import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../observability/Metrics.ts";
26import * as ProcessRunner from "../processRunner.ts";
27
28export interface VcsProcessInput {
29 readonly operation: string;
30 readonly command: string;
31 readonly args: ReadonlyArray<string>;
32 readonly cwd: string;
33 readonly spawnCwd?: string;
34 readonly stdin?: string;
35 readonly onStdoutChunk?: (chunk: Uint8Array) => void;
36 readonly env?: NodeJS.ProcessEnv;
37 readonly allowNonZeroExit?: boolean;
38 readonly timeoutMs?: number;
39 readonly maxOutputBytes?: number;
40 readonly outputMode?: ProcessRunner.ProcessRunInput["outputMode"];
41 readonly appendTruncationMarker?: boolean;
42 readonly classifyFailure?: SourceControlProcessInput["classifyFailure"];
43 readonly notFoundDetail?: string;
44 readonly concurrency?: SourceControlProcessInput["concurrency"];
45}
46
47export interface VcsProcessOutput {
48 readonly exitCode: ChildProcessSpawner.ExitCode;
49 readonly stdout: string;
50 readonly stderr: string;
51 readonly stdoutTruncated: boolean;
52 readonly stderrTruncated: boolean;
53 readonly stdoutInvalidUtf8?: boolean;
54 readonly stderrInvalidUtf8?: boolean;
55}
56
57export class VcsProcess extends Context.Service<
58 VcsProcess,
59 {
60 readonly run: (input: VcsProcessInput) => Effect.Effect<VcsProcessOutput, VcsError>;
61 }
62>()("t3/vcs/VcsProcess") {}
63
64const DEFAULT_TIMEOUT_MS = 30_000;
65const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
66const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]";
67const VCS_PROCESS_CONCURRENCY = 8;
68
69/** Shown to users when a Git command fails because another process holds the index lock. */
70export const GIT_INDEX_LOCKED_DETAIL =
71 "Git's index is locked. Wait for other Git operations to finish, then try again.";
72
73export const CHECKPOINT_CAPTURE_OPERATION = "GitVcsDriver.checkpoints.captureCheckpoint";
74
75// Caller operations are diagnostic strings; only known labels may become metric attributes.
76const gitMetricOperations = new Set([
77 CHECKPOINT_CAPTURE_OPERATION,
78 "GitVcsDriver.checkpoints.deleteCheckpointRefs",
79 "GitVcsDriver.checkpoints.diffCheckpoints",
80 "GitVcsDriver.checkpoints.hasHeadCommit",
81 "GitVcsDriver.checkpoints.listAuthoredPaths",
82 "GitVcsDriver.checkpoints.resolveCheckpointCommit",
83 "GitVcsDriver.checkpoints.resolveGitCommonDir",
84 "GitVcsDriver.checkpoints.resolveHeadCommit",
85 "GitVcsDriver.checkpoints.restoreCheckpoint",
86 "GitVcsDriver.detectRepository.commonDir",
87 "GitVcsDriver.detectRepository.root",
88 "GitVcsDriver.filterIgnoredPaths",
89 "GitVcsDriver.initRepository",
90 "GitVcsDriver.isInsideWorkTree",
91 "GitVcsDriver.listRemotes",
92 "GitVcsDriver.listWorkspaceFiles",
93 "GitVcsDriver.resolveGitCommonDir",
94]);
95
96/**
97 * Append after inherited entries without changing argv or the user's config.
98 * Windows env keys ignore case: read the last spelling of the count so command overrides win,
99 * then update every spelling because Node may keep any one.
100 * Leave invalid counts untouched so Git reports them.
101 */
102export const gitConfigEnv = (
103 env: NodeJS.ProcessEnv,
104 key: string,
105 value: string,
106 platform: NodeJS.Platform,
107): NodeJS.ProcessEnv => {
108 const countKeys = Object.keys(env).filter((name) =>
109 platform === "win32" ? name.toUpperCase() === "GIT_CONFIG_COUNT" : name === "GIT_CONFIG_COUNT",
110 );
111 const countKey = countKeys.at(-1) ?? "GIT_CONFIG_COUNT";
112 const inherited = env[countKey];
113 if (
114 inherited !== undefined &&
115 inherited !== "" &&
116 // Match Git's strtoul count syntax, including whitespace, signs and non-negative -0.
117 /^[ \t\r\n\v\f]*(?:\+?\d+|-0+)/.exec(inherited)?.[0] !== inherited
118 ) {
119 return {};
120 }
121 const count = inherited === undefined || inherited === "" ? 0 : Number.parseInt(inherited, 10);
122 return {
123 ...Object.fromEntries([...countKeys, countKey].map((name) => [name, String(count + 1)])),
124 [`GIT_CONFIG_KEY_${count}`]: key,
125 [`GIT_CONFIG_VALUE_${count}`]: value,
126 };
127};
128
129/**
130 * A project can contain a fake bare repository whose config runs commands such as `core.fsmonitor`.
131 * Require `--git-dir` or `GIT_DIR` to open bare repositories; Git before 2.38 ignores this setting.
132 */
133export const explicitBareRepositoryEnv = (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) =>
134 gitConfigEnv(env, "safe.bareRepository", "explicit", platform);
135
136const classifyNonZeroExit = (
137 stderr: string,
138 classifyFailure: VcsProcessInput["classifyFailure"],
139): VcsProcessExitFailureKind => {
140 const normalized = stderr.toLowerCase();
141 const commandKind = classifyFailure?.(stderr) ?? null;
142
143 if (
144 commandKind === "authentication" ||
145 normalized.includes("authentication failed") ||
146 normalized.includes("not logged in") ||
147 normalized.includes("no oauth token") ||
148 normalized.includes("unauthorized")
149 ) {
150 return "authentication";
151 }
152
153 if (
154 commandKind === "rate-limited" ||
155 normalized.includes("api rate limit") ||
156 normalized.includes("rate limit exceeded") ||
157 normalized.includes("secondary rate limit") ||
158 normalized.includes("too many requests") ||
159 normalized.includes("http 429")
160 ) {
161 return "rate-limited";
162 }
163
164 return commandKind ?? "command-failed";
165};
166
167// Classify before discarding stderr; keep paths and process output out of errors.
168const isTransientGitExit = (stderr: string) =>
169 /unable to create [^\n]*\.lock['"]?: file exists/i.test(stderr) ||
170 /(?:unable to stat|lstat\(|error: open\()[^\n]+: no such file or directory/i.test(stderr);
171
172// On macOS, Git's fsync uses F_FULLFSYNC; writeout-only still uses fsync(2).
173// Network mounts can reject F_FULLFSYNC. Ref writes omit errno, so retry their
174// bare write error too; explicit unrelated errors remain failures.
175// Linux writeout-only only starts writeback, so it must not use this fallback.
176const FULL_FSYNC_ARG = "core.fsyncMethod=fsync";
177const BATCH_FSYNC_ARG = "core.fsyncMethod=batch";
178const WRITEOUT_ONLY_FSYNC_ARG = "core.fsyncMethod=writeout-only";
179const canRetryFullFsync = (stderr: string) =>
180 /fsync error on [^\r\n]+: operation not supported\r?$/im.test(stderr) ||
181 /cannot update ref [^\r\n]+: couldn't write '[^\r\n]+\.lock'\r?$/im.test(stderr);
182
183export const make = Effect.gen(function* () {
184 const processRunner = yield* ProcessRunner.ProcessRunner;
185 const hostPlatform = yield* HostProcess.Platform;
186 const vcsProcesses = yield* Semaphore.make(VCS_PROCESS_CONCURRENCY);
187 const keyedProcesses = new Map<string, Semaphore.Semaphore>();
188 const keyedPermit = (concurrency: NonNullable<VcsProcessInput["concurrency"]>) => {
189 let semaphore = keyedProcesses.get(concurrency.key);
190 if (semaphore === undefined) {
191 semaphore = Semaphore.makeUnsafe(concurrency.limit);
192 keyedProcesses.set(concurrency.key, semaphore);
193 }
194 return semaphore.withPermits(1);
195 };
196
197 const spawn = Effect.fn("VcsProcess.spawn")(function* (
198 input: VcsProcessInput,
199 baseError: VcsProcessErrorContext,
200 ) {
201 let failedExit = false;
202 const execution = processRunner
203 .run({
204 command: input.command,
205 args: input.args,
206 cwd: input.cwd,
207 ...(input.spawnCwd !== undefined ? { spawnCwd: input.spawnCwd } : {}),
208 ...(input.stdin !== undefined ? { stdin: input.stdin } : {}),
209 ...(input.onStdoutChunk !== undefined ? { onStdoutChunk: input.onStdoutChunk } : {}),
210 env: {
211 ...input.env,
212 ...explicitBareRepositoryEnv({ ...process.env, ...input.env }, hostPlatform),
213 },
214 timeout: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
215 maxOutputBytes: input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES,
216 outputMode: input.outputMode ?? "truncate",
217 truncatedMarker: input.appendTruncationMarker ? OUTPUT_TRUNCATED_MARKER : "",
218 timeoutBehavior: "error",
219 })
220 .pipe(
221 Effect.tap((result) => {
222 failedExit = result.code === null || (!input.allowNonZeroExit && result.code !== 0);
223 return Effect.void;
224 }),
225 Effect.mapError(
226 Match.valueTags({
227 ProcessSpawnError: (error) =>
228 VcsProcessSpawnError.fromProcessSpawnError(baseError, error),
229 ProcessOutputLimitError: (error) =>
230 new VcsProcessOutputLimitError({
231 ...baseError,
232 stream: error.stream,
233 maxBytes: error.maxBytes,
234 observedBytes: error.observedBytes,
235 }),
236 ProcessTimeoutError: (error) =>
237 VcsProcessTimeoutError.fromProcessTimeoutError(baseError, error),
238 ProcessStdinError: (error) =>
239 new VcsProcessStdinWriteError({
240 ...baseError,
241 stdinBytes: error.stdinBytes,
242 cause: error.cause,
243 }),
244 ProcessReadError: (error) =>
245 new VcsProcessOutputReadError({
246 ...baseError,
247 stream: error.stream,
248 cause: error.cause,
249 }),
250 }),
251 ),
252 );
253
254 return yield* input.command === "git"
255 ? execution.pipe(
256 withMetrics({
257 counter: gitCommandsTotal,
258 timer: gitCommandDuration,
259 attributes: {
260 operation: gitMetricOperations.has(input.operation) ? input.operation : "other",
261 },
262 outcomeAttributes: (outcome) => ({
263 outcome: outcome === "success" && failedExit ? "failure" : outcome,
264 }),
265 }),
266 )
267 : execution;
268 });
269
270 const runUnbounded = Effect.fn("VcsProcess.runUnbounded")(function* (input: VcsProcessInput) {
271 const baseError = {
272 operation: input.operation,
273 command: input.command,
274 cwd: input.cwd,
275 argumentCount: input.args.length,
276 };
277
278 let result = yield* spawn(input, baseError);
279
280 if (
281 hostPlatform === "darwin" &&
282 input.operation === CHECKPOINT_CAPTURE_OPERATION &&
283 !input.allowNonZeroExit &&
284 result.code !== null &&
285 result.code !== 0 &&
286 input.command === "git" &&
287 (input.args.includes(FULL_FSYNC_ARG) || input.args.includes(BATCH_FSYNC_ARG)) &&
288 canRetryFullFsync(result.stderr)
289 ) {
290 result = yield* spawn(
291 {
292 ...input,
293 args: input.args.map((arg) =>
294 arg === FULL_FSYNC_ARG || arg === BATCH_FSYNC_ARG ? WRITEOUT_ONLY_FSYNC_ARG : arg,
295 ),
296 },
297 baseError,
298 );
299 }
300
301 if (result.code === null) {
302 return yield* new VcsProcessMissingExitCodeError(baseError);
303 }
304
305 if (!input.allowNonZeroExit && result.code !== 0) {
306 const failureKind = classifyNonZeroExit(result.stderr, input.classifyFailure);
307 const error = VcsProcessExitError.fromProcessExit(
308 baseError,
309 {
310 exitCode: result.code,
311 stderr: result.stderr,
312 stderrTruncated: result.stderrTruncated,
313 },
314 failureKind,
315 {
316 retryable:
317 input.command === "git" &&
318 failureKind === "command-failed" &&
319 isTransientGitExit(result.stderr),
320 ...(input.notFoundDetail === undefined ? {} : { notFoundDetail: input.notFoundDetail }),
321 },
322 );
323 if (
324 input.command === "git" &&
325 /^fatal: unable to create ['"][^\r\n]*[/\\]index\.lock['"]: file exists\.?$/im.test(
326 result.stderr,
327 )
328 ) {
329 return yield* new VcsProcessExitError({
330 ...error,
331 detail: GIT_INDEX_LOCKED_DETAIL,
332 });
333 }
334 return yield* error;
335 }
336
337 return {
338 exitCode: result.code,
339 stdout: result.stdout,
340 stderr: result.stderr,
341 stdoutTruncated: result.stdoutTruncated,
342 stderrTruncated: result.stderrTruncated,
343 stdoutInvalidUtf8: result.stdoutInvalidUtf8 ?? false,
344 stderrInvalidUtf8: result.stderrInvalidUtf8 ?? false,
345 } satisfies VcsProcessOutput;
346 });
347
348 const run = Effect.fn("VcsProcess.run")(function* (input: VcsProcessInput) {
349 const bounded = vcsProcesses.withPermits(1)(runUnbounded(input));
350 if (
351 input.command === "git" &&
352 input.operation === CHECKPOINT_CAPTURE_OPERATION &&
353 input.onStdoutChunk === undefined
354 ) {
355 return yield* bounded.pipe(
356 Effect.tapError((error) =>
357 Effect.logDebug("checkpoint Git command failed", {
358 operation: input.operation,
359 errorTag: error._tag,
360 }),
361 ),
362 Effect.retry({
363 times: 2,
364 while: (error) => error._tag === "VcsProcessExitError" && error.retryable === true,
365 schedule: Schedule.spaced(Duration.millis(75)),
366 }),
367 );
368 }
369 return yield* input.concurrency === undefined
370 ? bounded
371 : keyedPermit(input.concurrency)(bounded);
372 });
373
374 return VcsProcess.of({ run });
375});
376
377export const layer = Layer.effect(VcsProcess, make).pipe(Layer.provide(ProcessRunner.layer));