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

VcsProcess.ts

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