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

VcsProcess.ts

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