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