perf(server): answer cheap git metadata from repository files instead of spawning git #12602
ClosedSkiTee3000(GitHub profile, opens in a new tab)wants to merge 15 commits into
main fromrefs/pull/12602/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/server/src/vcs/GitMetadataFastPath.ts line 114OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +94,21 @@94+ try {95+ return await NodeFSP.stat(target);96+ } catch {97+ return null;98+ }99+}100+101+// git bounds what it reads from a repository too (HEAD, the `.git` file). The102+// server opens folders it did not create, so a huge or special file is git's to refuse.103+const SMALL_FILE_BYTES = 4 * 1024;104+const CONFIG_FILE_BYTES = 1024 * 1024;105+const PACKED_REFS_BYTES = 32 * 1024 * 1024;106+107+/** Text of a regular file no larger than `maxBytes`, `null` when it does not exist. */108+async function readBoundedFile(file: string, maxBytes: number): Promise<string | null> {109+ const stat = await NodeFSP.stat(file).catch((error: NodeJS.ErrnoException) =>110+ error.code === "ENOENT" || error.code === "ENOTDIR" ? null : unsure("unreadable file"),111+ );112+ if (stat === null) return null;113+ if (!stat.isFile() || stat.size > maxBytes) unsure("not a small regular file");114+ const text = await NodeFSP.readFile(file, "utf8");apps/server/src/vcs/GitMetadataFastPath.ts line 436Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +282,21 @@282+ return new Promise((resolve, reject) => {283+ NodeChildProcess.execFile(284+ "git",285+ ["config", "--list", "--show-scope", "--show-origin", "-z"],286+ { cwd: NodeOS.tmpdir(), windowsHide: true, timeout: 10_000, maxBuffer: 4 * 1024 * 1024 },287+ (error, stdout) => (error ? reject(error) : resolve(stdout)),288+ );289+ });290+}291+292+async function loadOuterConfig(): Promise<OuterConfig> {293+ // Records: scope NUL origin NUL key LF value NUL294+ const fields = (await listOuterConfig()).split("\0");295+ const entries: Array<GitConfigEntry> = [];296+ const origins: Array<string> = [];297+ for (let index = 0; index + 2 < fields.length; index += 3) {298+ const scope = fields[index]!;299+ const origin = fields[index + 1]!;300+ const record = fields[index + 2]!;301+ if (scope !== "system" && scope !== "global") continue;302+ if (!origin.startsWith("file:")) unsure("outer config: non-file origin");apps/server/src/vcs/GitVcsDriverCore.ts line 1010OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -964,10 +1000,11 @@964- counter: gitCommandsTotal,965- timer: gitCommandDuration,966- attributes: {967- operation: input.operation,968- },969- }),970- (execution) =>971- input.timeoutMs === null || (input.timeoutMs ?? DEFAULT_TIMEOUT_MS) > DEFAULT_TIMEOUT_MS972- ? execution973- : gitProcesses.withPermits(1)(execution),1000+ const execute: GitVcsDriver.GitVcsDriver["Service"]["execute"] = (input) => {1001+ // Times the command itself, not the wait for a process permit.1002+ const metrics = {1003+ counter: gitCommandsTotal,1004+ timer: gitCommandDuration,1005+ attributes: {1006+ operation: input.operation,1007+ },1008+ };1009+ const spawnGit = executeRaw(input).pipe(withMetrics(metrics));1010+ return answerWithoutGit(input).pipe(apps/server/src/vcs/GitVcsDriver.ts lines 563 to 564Resolvedby SkiTee3000(GitHub profile, opens in a new tab)@@ -495,3 +498,19 @@495498 : {}),496499 });497500501+const gitCommand = (502+ process: VcsProcess.VcsProcess["Service"],503+ operation: string,504+ cwd: string,505+ args: ReadonlyArray<string>,506+ options?: GitCommandOptions,507+) =>508+ Effect.promise(() =>509+ options?.stdin === undefined510+ ? GitMetadataFastPath.tryAnswerGitCommand({ cwd, args, env: options?.env })511+ : Promise.resolve(null),512+ ).pipe(513+ Effect.flatMap((answer) =>514+ // A failing exit code without allowNonZeroExit needs git's own error details.515+ answer !== null && (answer.exitCode === 0 || options?.allowNonZeroExit)516+ ? Effect.succeed({apps/server/src/vcs/GitMetadataFastPath.ts line 286OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +266,21 @@266+ const xdg = process.env.XDG_CONFIG_HOME?.trim() || NodePath.join(home, ".config");267+ return [268+ ...new Set([269+ ...origins,270+ NodePath.join(home, ".gitconfig"),271+ NodePath.join(xdg, "git", "config"),272+ ]),273+ ];274+}275+276+async function fingerprintFiles(files: ReadonlyArray<string>): Promise<string> {277+ const stats = await Promise.all(files.map(statOrNull));278+ return stats.map((stat) => (stat ? `${stat.mtimeMs}:${stat.size}:${stat.ino}` : "-")).join("|");279+}280+281+function listOuterConfig(): Promise<string> {282+ return new Promise((resolve, reject) => {283+ NodeChildProcess.execFile(284+ "git",285+ ["config", "--list", "--show-scope", "--show-origin", "-z"],286+ { cwd: NodeOS.tmpdir(), windowsHide: true, timeout: 10_000, maxBuffer: 4 * 1024 * 1024 },
- apps/server/src/vcs/GitMetadataFastPath.ts lines 456 to 481Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +308,21 @@308+ const files = outerConfigCandidates(origins);309+ return { entries, files, fingerprint: await fingerprintFiles(files), loadedAtMs: Date.now() };310+}311+312+/**313+ * Also the proof that git runs at all: every answer asks for it first, so a314+ * missing or broken git stays as visible as it was when each question spawned it.315+ */316+async function getOuterConfig(): Promise<ReadonlyArray<GitConfigEntry>> {317+ const pending = outerConfig;318+ const current = pending ? await pending.catch(() => null) : null;319+ if (320+ current &&321+ Date.now() - current.loadedAtMs < OUTER_CONFIG_MAX_AGE_MS &&322+ (await fingerprintFiles(current.files)) === current.fingerprint323+ ) {324+ return current.entries;325+ }326+ // Concurrent callers share one listing.327+ if (outerConfig === pending) outerConfig = loadOuterConfig();328+ return (await outerConfig!).entries;apps/server/src/vcs/GitMetadataFastPath.ts lines 768 to 782Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +578,21 @@578+ if (packedRefsCache.size >= 64) packedRefsCache.clear();579+ packedRefsCache.set(file, { fingerprint, refs });580+ return refs;581+}582+583+type RefState = "exists" | "missing";584+585+/** Object id a ref points at, `null` when the ref does not exist. */586+async function refObjectId(repo: Repository, ref: string): Promise<string | null> {587+ if (!isSafeRefName(ref)) unsure("unsafe ref name");588+ const looseFile = NodePath.join(repo.commonDir, ...ref.split("/"));589+ // A directory here means deeper refs exist (`refs/heads/a` vs `refs/heads/a/b`), not this one.590+ const loose = (await statOrNull(looseFile))?.isDirectory()591+ ? null592+ : await readBoundedFile(looseFile, SMALL_FILE_BYTES);593+ if (loose !== null) {594+ // Symbolic or damaged loose refs need git's full resolution.595+ return OBJECT_ID.test(loose.trim()) ? loose.trim() : unsure("loose ref is not an object id");596+ }597+ return (await readPackedRefs(repo.commonDir)).get(ref) ?? null;598+}
- apps/server/src/vcs/GitMetadataFastPath.ts lines 1244 to 1251OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1231,21 @@1231+ * Returns git's exact output for a supported read-only command, or `null` when1232+ * the caller has to spawn git. Never throws.1233+ */1234+export async function tryAnswerGitCommand(1235+ input: GitFastPathInput,1236+): Promise<GitFastPathAnswer | null> {1237+ if (!isGitFastPathEnabled() || !isGitFastPathEnabled(input.env ?? {})) return null;1238+ if (hasGitEnvOverride(process.env) || hasGitEnvOverride(input.env)) return null;1239+ if (movesGitOrItsConfig(input.env)) return null;1240+ const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;1241+ let timer: NodeJS.Timeout | undefined;1242+ try {1243+ // Reads that take this long mean a stuck disk or share; git gets the question instead.1244+ const timedOut = new Promise<null>((resolve) => {1245+ timer = setTimeout(resolve, Math.min(ANSWER_TIMEOUT_MS, input.timeoutMs ?? Infinity), null);1246+ });1247+ // Asking for the outer config first proves git runs at all, so a missing git is not papered over.1248+ const answering = getOuterConfig().then(() => answer(input));1249+ // When the timer wins, the abandoned attempt still settles; its decline is not an error.1250+ answering.catch(() => undefined);1251+ const result = await Promise.race([answering, timedOut]);apps/server/src/vcs/GitVcsDriverCore.ts lines 927 to 928Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -826,3 +827,16 @@826827 const { worktreesDir } = yield* ServerConfig;827828 const crypto = yield* Crypto.Crypto;828829830+ /**831+ * The command's result read from the repository files, or `null` when git has832+ * to run. Holds no git process permit.833+ */834+ const answerWithoutGit = Effect.fnUntraced(function* (input: GitVcsDriver.ExecuteGitInput) {835+ if (input.stdin !== undefined || input.progress !== undefined) return null;836+ const answer = yield* Effect.promise(() =>837+ GitMetadataFastPath.tryAnswerGitCommand({838+ cwd: input.cwd,839+ args: input.args,840+ env: input.env,841+ timeoutMs: input.timeoutMs,842+ maxOutputBytes: input.maxOutputBytes,
- @@ -0,0 +121,21 @@121+ */122+export function makeTaskLimiter(max: number) {123+ let running = 0;124+ const waiting: Array<() => void> = [];125+ return async <T>(task: () => Promise<T>): Promise<T> => {126+ // A finishing task hands its slot to the next one, so `running` stays put.127+ if (running >= max) await new Promise<void>((resolve) => waiting.push(resolve));128+ else running++;129+ try {130+ return await task();131+ } finally {132+ const next = waiting.shift();133+ if (next) next();134+ else running--;135+ }136+ };137+}138+139+// The git processes started here run outside the drivers' process permits. A140+// sweep over many repositories asks for one verdict each, all at once.141+const withOwnGitProcess = makeTaskLimiter(4);
juliusmarminge added labelsmacroscope-review
- apps/server/src/vcs/GitMetadataFastPath.ts line 1314OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1294,21 @@1294+ return error instanceof NotARepository && !gitMessagesMayBeTranslated(input.env)1295+ ? { exitCode: 128, stdout: "", stderr: error.stderr }1296+ : null;1297+ } finally {1298+ clearTimeout(timer);1299+ }1300+}1301+1302+/**1303+ * Identifies a command whose answer depends only on commits that can be read1304+ * from the repository files, or `null`. Take it before spawning git and hand it1305+ * to `rememberGitAnswer` with git's output, so the same question is answered1306+ * without a process until one of those commits changes.1307+ */1308+export async function gitAnswerMemoKey(input: GitFastPathInput): Promise<string | null> {1309+ if (!isGitFastPathEnabled() || !isGitFastPathEnabled(input.env ?? {})) return null;1310+ if (hasGitEnvOverride(process.env) || hasGitEnvOverride(input.env)) return null;1311+ const [command, ...rest] = input.args;1312+ if (command !== "rev-list") return null;1313+ try {1314+ const { repo } = await discoverRepository(input.cwd);
- apps/server/src/vcs/GitVcsDriverCore.ts line 1020OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -967,7 +1007,14 @@967- operation: input.operation,968- },969- }),970- (execution) =>971- input.timeoutMs === null || (input.timeoutMs ?? DEFAULT_TIMEOUT_MS) > DEFAULT_TIMEOUT_MS972- ? execution973- : gitProcesses.withPermits(1)(execution),1007+ const execute: GitVcsDriver.GitVcsDriver["Service"]["execute"] = (input) => {1008+ // Times the command itself, not the wait for a process permit.1009+ const metrics = {1010+ counter: gitCommandsTotal,1011+ timer: gitCommandDuration,1012+ attributes: {1013+ operation: input.operation,1014+ },1015+ };1016+ const spawnGit = executeRaw(input).pipe(withMetrics(metrics));1017+ return answerWithoutGit(input).pipe(1018+ Effect.flatMap((answer) =>1019+ answer !== null1020+ ? Effect.succeed(answer).pipe(withMetrics(metrics))apps/server/src/vcs/GitMetadataFastPath.ts line 1308OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1288,21 @@1288+ : null;1289+ }1290+}1291+1292+/**1293+ * Settles with `work`'s result, or with `null` once the caller's budget or1294+ * ANSWER_TIMEOUT_MS runs out, whichever comes first. A rejection of `work`1295+ * before then is passed on.1296+ */1297+async function withinReadBudget<T>(1298+ timeoutMs: number | null | undefined,1299+ work: () => Promise<T>,1300+): Promise<T | null> {1301+ // No budget at all: nothing may be answered, however fast the reads turn out.1302+ if (typeof timeoutMs === "number" && timeoutMs <= 0) return null;1303+ let timer: NodeJS.Timeout | undefined;1304+ // Reads that take this long mean a stuck disk or share; git gets the question instead.1305+ const timedOut = new Promise<null>((resolve) => {1306+ timer = setTimeout(resolve, Math.min(ANSWER_TIMEOUT_MS, timeoutMs ?? Infinity), null);1307+ });1308+ const working = work();
- apps/server/src/vcs/GitMetadataFastPath.ts lines 44 to 46Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +25,21 @@25+import * as NodePath from "node:path";26+27+export interface GitFastPathInput {28+ readonly cwd: string;29+ readonly args: ReadonlyArray<string>;30+ readonly env?: NodeJS.ProcessEnv | undefined;31+ /** The caller's budget for the command; the answer never takes longer than this. */32+ readonly timeoutMs?: number | null | undefined;33+ /** The caller's output cap. A larger answer is left to git, which truncates or fails as asked. */34+ readonly maxOutputBytes?: number | undefined;35+}36+37+export interface GitFastPathAnswer {38+ readonly exitCode: number;39+ readonly stdout: string;40+ readonly stderr: string;41+}42+43+/** `T3CODE_GIT_FAST_PATH=0` turns the fast path off; every command spawns git again. */44+export const isGitFastPathEnabled = (env: NodeJS.ProcessEnv = process.env) =>45+ env.T3CODE_GIT_FAST_PATH !== "0";apps/server/src/vcs/GitVcsDriverCore.ts lines 985 to 994OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -943 +975,20 @@943- const execution = runGitCommand().pipe(Effect.scoped);975+ const fastPathInput = {976+ cwd: input.cwd,977+ args: input.args,978+ env: input.env,979+ timeoutMs: input.timeoutMs,980+ };981+ const memoKey =982+ input.stdin === undefined && input.progress === undefined983+ ? yield* Effect.promise(() => GitMetadataFastPath.gitAnswerMemoKey(fastPathInput))984+ : null;985+ const execution = runGitCommand().pipe(986+ Effect.scoped,987+ Effect.tap((result) =>988+ memoKey !== null && result.exitCode === 0 && !result.stdoutTruncated989+ ? Effect.promise(() =>990+ GitMetadataFastPath.rememberGitAnswer(fastPathInput, memoKey, result.stdout),991+ )992+ : Effect.void,993+ ),994+ );
- apps/server/src/vcs/GitMetadataFastPath.ts lines 584 to 584Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +515,21 @@515+ const worktreeConfigFile = isGitTrue(lastValue(sharedConfig, "extensions.worktreeconfig"))516+ ? ((await readBoundedFile(NodePath.join(gitDir, "config.worktree"), CONFIG_FILE_BYTES)) ?? "")517+ : "";518+ const localConfig = [...sharedConfig, ...parseGitConfig(worktreeConfigFile)];519+ const version = Number(versionText ?? "0");520+ if (version !== 0 && version !== 1) unsure("unknown repository format");521+ for (const { key } of localConfig) {522+ if (key.startsWith("include.") || key.startsWith("includeif.")) unsure("config includes");523+ if (key.startsWith("extensions.") && !SUPPORTED_EXTENSIONS.has(key)) unsure("extension");524+ }525+ if (isGitTrue(lastValue(localConfig, "core.bare"))) unsure("bare repository");526+ if (lastValue(localConfig, "core.worktree") !== undefined) unsure("core.worktree");527+528+ return { workTree, gitDir, commonDir, dotGitIsDirectory, localConfig } satisfies Repository;529+}530+531+async function discoverRepository(cwd: string): Promise<{ repo: Repository; realCwd: string }> {532+ const realCwd = await NodeFSP.realpath(cwd);533+ if (realCwd.startsWith("\\\\")) unsure("UNC path");534+ const startStat = await NodeFSP.stat(realCwd);535+ // Windows has no device ids worth comparing, and git for Windows does not compare them either.
- apps/server/src/vcs/GitMetadataFastPath.ts line 683Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +599,21 @@599+ windowsHide: true,600+ timeout: 10_000,601+ maxBuffer: 64 * 1024,602+ },603+ (error, stdout, stderr) =>604+ error && typeof error.code !== "number"605+ ? reject(error)606+ : resolve({607+ exitCode: typeof error?.code === "number" ? error.code : 0,608+ stdout,609+ stderr,610+ }),611+ );612+ }),613+ );614+}615+616+function gitVerdict(args: ReadonlyArray<string>): Promise<GitVerdict> {617+ const key = args.join("\0");618+ const known = verdicts.get(key);619+ if (known && Date.now() - known.at < VERDICT_MAX_AGE_MS) return known.verdict;apps/server/src/vcs/GitVcsDriver.ts line 552Resolvedby SkiTee3000(GitHub profile, opens in a new tab)@@ -537,3 +540,13 @@537540 : {}),538541 });539542543+const gitCommand = (544+ process: VcsProcess.VcsProcess["Service"],545+ operation: string,546+ cwd: string,547+ args: ReadonlyArray<string>,548+ options?: GitCommandOptions,549+) =>550+ Effect.promise(() =>551+ options?.stdin === undefined552+ ? GitMetadataFastPath.tryAnswerGitCommand({
- apps/server/src/vcs/GitMetadataFastPath.ts lines 175 to 175Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +152,21 @@152+153+function isKnownSymlinkFree(dir: string): boolean {154+ const now = Date.now();155+ for (const [known, at] of symlinkFreeDirs) {156+ if (now - at >= SYMLINK_FREE_MAX_AGE_MS) continue;157+ if (known === dir || known.startsWith(dir.endsWith(NodePath.sep) ? dir : dir + NodePath.sep))158+ return true;159+ }160+ return false;161+}162+163+function rememberSymlinkFree(dir: string): void {164+ if (symlinkFreeDirs.size >= 256) symlinkFreeDirs.clear();165+ symlinkFreeDirs.set(dir, Date.now());166+}167+168+/** Declines when `target` or a directory above it is a symlink. */169+async function assertNoSymlinks(target: string): Promise<void> {170+ const parent = NodePath.dirname(target);171+ let parentChecked = false;172+ for (let dir = parent; !isKnownSymlinkFree(dir);) {
- apps/server/src/vcs/GitMetadataFastPath.ts line 919OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +899,21 @@899+ ["--show-toplevel"],900+ ["--git-common-dir"],901+ ["--abbrev-ref", "HEAD"],902+ ["--abbrev-ref", "--symbolic-full-name", "@{upstream}"],903+];904+905+async function answerRevParse(906+ cwd: string,907+ args: ReadonlyArray<string>,908+ env: NodeJS.ProcessEnv | undefined,909+) {910+ // Other forms (`--sq-quote`, `--parseopt`, ...) work outside a repository.911+ if (!REV_PARSE_FORMS.some((form) => sameArgs(args, form))) unsure("rev-parse arguments");912+ const { repo, realCwd } = await discoverRepository(cwd);913+ await requireGitAgrees(repo, false);914+ if (sameArgs(args, ["--is-inside-work-tree"])) return ok("true\n");915+ if (sameArgs(args, ["--show-toplevel"])) return ok(`${toGitPath(repo.workTree)}\n`);916+ if (sameArgs(args, ["--git-common-dir"])) {917+ // Below the worktree root git prints a relative path; leave that form to git.918+ if (realCwd !== repo.workTree) unsure("common dir from a subdirectory");919+ return ok(repo.dotGitIsDirectory ? ".git\n" : `${toGitPath(repo.commonDir)}\n`);
- apps/server/src/vcs/GitMetadataFastPath.ts lines 954 to 954OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +934,21 @@934+ // Detached and unborn HEADs fail with messages of their own.935+ if (head.ref === null || !head.ref.startsWith("refs/heads/")) unsure("detached HEAD");936+ if ((await refState(repo, head.ref!)) === "missing") unsure("unborn branch");937+ const branch = head.ref!.slice("refs/heads/".length);938+ const upstream = await resolveUpstream(repo, await mergedConfig(repo), branch);939+ if (!upstream && gitMessagesMayBeTranslated(env)) unsure("translated error message");940+ return upstream941+ ? ok(`${upstream.short}\n`)942+ : {943+ exitCode: 128,944+ stdout: "",945+ stderr: `fatal: no upstream configured for branch '${branch}'\n`,946+ };947+ }948+ return unsure("rev-parse arguments");949+}950+951+async function answerSymbolicRef(repo: Repository, args: ReadonlyArray<string>) {952+ if (sameArgs(args, ["--quiet", "--short", "HEAD"])) {953+ const head = await readHead(repo);954+ return head.ref === null ? silentFailure : ok(`${await shortBranchName(repo, head.ref)}\n`);apps/server/src/vcs/GitMetadataFastPath.ts line 321Resolvedby SkiTee3000(GitHub profile, opens in a new tab)@@ -0,0 +301,21 @@301+ while (index < length && isSpace(text[index]!)) index++;302+ if (text[index] !== "=") unsure("config: value-less key");303+ index++;304+ while (index < length && isSpace(text[index]!)) index++;305+306+ let value = "";307+ let inQuotes = false;308+ let pendingSpace = "";309+ for (; index < length; index++) {310+ const current = text[index]!;311+ if (current === "\n") break;312+ if (current === "\r" && text[index + 1] === "\n") continue;313+ if (!inQuotes && (current === "#" || current === ";")) {314+ while (index < length && text[index] !== "\n") index++;315+ break;316+ }317+ if (!inQuotes && (current === " " || current === "\t")) {318+ pendingSpace += current;319+ continue;320+ }321+ value += pendingSpace;
maria-rcks closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed