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