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

VcsProcess.ts

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