Public: anyone can read this; the crew can change it.

A repository's branches page answers under 50 ms with 200 branches #3380

Parked opened this
Closed without merging

scout/forge:scout/3376-a-repository-s-branches-page-answers-und → main 3 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
3 files changed +231 −23
src/git/branches.ts +93 −3
@@ -14,10 +14,10 @@
1414 */
1515
1616 import { err, ok, type Result } from "../kernel/result.ts";
17 import { runGit, runGitCapture, type GitFailure } from "./env.ts";
17 import { runGit, runGitCapture, runGitRaw, type GitFailure } from "./env.ts";
1818 import { isSafeOid, isSafeRef } from "./guard.ts";
1919 import { resolveOid } from "./merge.ts";
20 import { listRefs } from "./read.ts";
20 import { listRefs, type Commit } from "./read.ts";
2121
2222 /**
2323 * A branch list stops comparing here. Each comparison is one `rev-list`
@@ -142,12 +142,14 @@ export interface BranchListing {
142142
143143 /**
144144 * Every branch, with its divergence from the default. One `for-each-ref`
145 * for the names and tips, then one `rev-list --left-right --count` per
145 * for the names and tips, then one `for-each-ref %(ahead-behind:)` for
146 * the counts, or, with `bulk: false` or an older git, one `rev-list` per
146147 * branch (bounded, and capped by `MAX_BRANCH_COMPARE`).
147148 */
148149 export async function listBranches(
149150 dir: string,
150151 defaultBranch: string,
152 opts: { readonly bulk?: boolean } = {},
151153 ): Promise<Result<BranchListing, GitFailure>> {
152154 const refs = await listRefs(dir, "refs/heads/");
153155 if (!refs.ok) return refs;
@@ -176,6 +178,18 @@ export async function listBranches(
176178 });
177179 }
178180
181 const counted =
182 opts.bulk === false ? undefined : await aheadBehindAll(dir, compare);
183 if (counted !== undefined) {
184 return ok({
185 branches: rows.map((r) => ({
186 ...r,
187 ...(counted.get(r.name) ?? { ahead: null, behind: null }),
188 })),
189 compared: true,
190 });
191 }
192
179193 const branches: BranchInfo[] = [];
180194 for (let i = 0; i < rows.length; i += COMPARE_CONCURRENCY) {
181195 const slice = rows.slice(i, i + COMPARE_CONCURRENCY);
@@ -192,6 +206,82 @@ export async function listBranches(
192206 return ok({ branches, compared: true });
193207 }
194208
209 /**
210 * Every branch's divergence from `base` in one `for-each-ref`, which asks
211 * git's own `%(ahead-behind:)` (2.41+). Undefined when this git lacks it,
212 * and the caller falls back to one `rev-list` per branch.
213 */
214 async function aheadBehindAll(
215 dir: string,
216 base: string,
217 ): Promise<Map<string, { ahead: number; behind: number }> | undefined> {
218 if (!isSafeOid(base)) return undefined;
219 const listed = await runGit(
220 [
221 "for-each-ref",
222 `--format=%(refname)%00%(ahead-behind:${base})`,
223 "--",
224 "refs/heads/",
225 ],
226 { cwd: dir },
227 );
228 if (!listed.ok) return undefined;
outdated

A branch name containing a space or newline is impossible in git refs, so the split is safe, but fall back to undefined on any malformed line (done) is the right call. Cover that fallback with a test.

229 const out = new Map<string, { ahead: number; behind: number }>();
230 if (listed.value === "") return out;
231 for (const line of listed.value.split("\n")) {
232 const [ref, pair] = line.split("\0");
233 // A malformed line gives up on the whole list (undefined), so the caller
234 // takes the slow per-branch path rather than show a wrong count.
235 // `%(ahead-behind:B)` prints "<ahead> <behind>" of the ref against B.
236 const [ahead, behind] = (pair ?? "").split(" ").map(Number);
237 if (!ref || !Number.isSafeInteger(ahead) || !Number.isSafeInteger(behind))
238 return undefined;
239 out.set(ref.slice("refs/heads/".length), {
240 ahead: ahead as number,
outdated

Nit: a malformed line returns undefined, so the whole list falls back to the slow path. That is safe. A one-line note saying so would help the next reader.

241 behind: behind as number,
242 });
243 }
244 return out;
245 }
246
247 /**
248 * The tip commit of each oid, in one `git log --no-walk`. Oids come from
249 * git itself; anything unsafe is skipped, never passed on.
250 */
251 export async function tipCommits(
252 dir: string,
253 oids: readonly string[],
254 ): Promise<Map<string, Commit>> {
255 const safe = [...new Set(oids)].filter(isSafeOid);
256 const out = new Map<string, Commit>();
257 if (safe.length === 0) return out;
258 const result = await runGitRaw(
259 [
260 "log",
261 "--no-walk=unsorted",
262 "-z",
263 "--format=%H%x00%P%x00%an%x00%ae%x00%aI%x00%s%x00%b",
264 ...safe,
265 "--",
266 ],
267 { cwd: dir },
268 );
269 if (!result.ok) return out;
270 const fields = new TextDecoder().decode(result.value).split("\0");
271 for (let i = 0; i + 6 < fields.length; i += 7) {
272 out.set(fields[i]!, {
273 oid: fields[i]!,
274 parents: fields[i + 1]! === "" ? [] : fields[i + 1]!.split(" "),
275 author: fields[i + 2]!,
276 email: fields[i + 3]!,
277 date: fields[i + 4]!,
278 subject: fields[i + 5]!,
279 body: fields[i + 6]!.replace(/\n$/, ""),
280 });
281 }
282 return out;
283 }
284
195285 /**
196286 * How far `head` has drifted from `base`. `A...B` counts each side of the
197287 * merge base: the left number is what B is missing (behind), the right is
src/web/pages/branches.ts +14 −20
@@ -18,8 +18,8 @@
1818 import { createBranch, deleteBranch } from "../../actions/branches.ts";
1919 import type { Repo } from "../../core/repos.ts";
2020 import { notePhase, takeSessionTime, timePhaseAsync } from "../../core/route_timing.ts";
21 import { listBranches, type BranchInfo } from "../../git/branches.ts";
22 import { commitLog, type Commit } from "../../git/read.ts";
21 import { listBranches, tipCommits, type BranchInfo } from "../../git/branches.ts";
22 import type { Commit } from "../../git/read.ts";
2323 import { repoDir } from "../../git/repos.ts";
2424 import type { Ctx } from "../../http/context.ts";
2525 import type { RepoScope } from "../scope.ts";
@@ -50,7 +50,6 @@ import { refSetFrom } from "./refs.ts";
5050 * cap, so a repository with a thousand branches still renders one page.
5151 */
5252 const TIP_COMMITS = 40;
53 const TIP_CONCURRENCY = 8;
5453
5554 export interface BranchRow {
5655 readonly name: string;
@@ -62,26 +61,19 @@ export interface BranchRow {
6261 readonly tip: Commit | undefined;
6362 }
6463
65 /** The tip commit of the first `TIP_COMMITS` rows, a few at a time. */
64 /** The tip commit of the first `TIP_COMMITS` rows, from one git call. */
6665 async function withTips(
6766 dir: string,
6867 rows: readonly Omit<BranchRow, "tip">[],
6968 ): Promise<BranchRow[]> {
70 const out: BranchRow[] = rows.map((r) => ({ ...r, tip: undefined }));
71 const wanted = out.slice(0, TIP_COMMITS);
72 for (let i = 0; i < wanted.length; i += TIP_CONCURRENCY) {
73 const slice = wanted.slice(i, i + TIP_CONCURRENCY);
74 const logs = await Promise.all(
75 slice.map((row) => commitLog(dir, row.oid, { limit: 1 })),
76 );
77 slice.forEach((row, j) => {
78 const log = logs[j];
79 const at = out.indexOf(row);
80 if (log?.ok === true && log.value[0] !== undefined && at !== -1)
81 out[at] = { ...row, tip: log.value[0] };
82 });
83 }
84 return out;
69 const tips = await tipCommits(
70 dir,
71 rows.slice(0, TIP_COMMITS).map((r) => r.oid),
72 );
73 return rows.map((r, i) => ({
74 ...r,
75 tip: i < TIP_COMMITS ? tips.get(r.oid) : undefined,
76 }));
8577 }
8678
8779 /** Every branch this scope can see, however it has to ask. */
@@ -111,7 +103,9 @@ async function branchRows(
111103 return { rows, compared: false };
112104 }
113105 const dir = repoDir(ctx.app.reposRoot, repo.ownerName, repo.name);
114 const listed = await listBranches(dir, repo.defaultBranch);
106 const listed = await timePhaseAsync(ctx.request, "compare", () =>
107 listBranches(dir, repo.defaultBranch),
108 );
115109 if (!listed.ok) return { rows: [], compared: false };
116110 const bare = listed.value.branches.map((b: BranchInfo) => ({
117111 name: b.name,
test/branches-many.test.ts added +124
@@ -0,0 +1,124 @@
1 /**
2 * A repository with 200 branches lists them in under 50 ms: ahead/behind and
3 * tips are one git call each, not one per branch.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { divergence, listBranches } from "../src/git/branches.ts";
12 import { repoDir } from "../src/git/repos.ts";
13 import { gitClientEnv } from "./helpers/git-client.ts";
14 import { seedAdmin } from "./helpers/admin.ts";
15
16 const env = gitClientEnv({
17 GIT_AUTHOR_NAME: "A",
18 GIT_AUTHOR_EMAIL: "[email protected]",
19 GIT_COMMITTER_NAME: "A",
20 GIT_COMMITTER_EMAIL: "[email protected]",
21 });
22
23 async function git(args: string[], cwd: string): Promise<void> {
24 const p = Bun.spawn(["git", ...args], { cwd, env, stdout: "ignore", stderr: "pipe" });
25 const [err, code] = await Promise.all([new Response(p.stderr).text(), p.exited]);
26 if (code !== 0) throw new Error(`git ${args.join(" ")}: ${err}`);
27 }
28
29 let dataDir = "", work = "";
30 let app: App, servers: Servers, bearer = "";
31
32 beforeAll(async () => {
33 dataDir = await mkdtemp(join(tmpdir(), "forge-bbr-"));
34 work = await mkdtemp(join(tmpdir(), "forge-bbrwork-"));
35 app = createApp({ dataDir, port: 0 });
36 servers = await serve(app);
37 const base = servers.url;
38 await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
39 const minted = await fetch(`${base}/api/v1/tokens`, {
40 method: "POST",
41 headers: { "content-type": "application/json" },
42 body: JSON.stringify({ adminConfirm: true, username: "alice", password: "correct-horse-battery", name: "cli", scope: "admin" }),
43 });
44 const { token } = (await minted.json()) as { token: string };
45 bearer = token;
46 await fetch(`${base}/api/v1/repos`, {
47 method: "POST",
48 headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
49 body: JSON.stringify({ name: "app", description: "x" }),
50 });
51 await git(["clone", `${base.replace("http://", `http://alice:${token}@`)}/alice/app.git`, "app"], work);
52 const dir = join(work, "app");
53 await Bun.write(join(dir, "a.ts"), "export const a = 1;\n");
54 await Bun.write(join(dir, "README.md"), "# app\n");
55 await git(["add", "."], dir);
56 await git(["commit", "-m", "one"], dir);
57 await git(["push", "origin", "main"], dir);
58 // 199 branches (200 with main), each one commit off main; main then moves on, so every
59 // branch is also one behind.
60 let stream = "";
61 for (let i = 0; i < 199; i++) {
62 const name = `feat/b${String(i).padStart(3, "0")}`;
63 stream += `commit refs/heads/${name}\ncommitter A <[email protected]> ${1700000000 + i} +0000\ndata 4\nb${String(i).padStart(2, "0")}\nfrom refs/heads/main\n\n`;
64 }
65 const fi = Bun.spawn(["git", "fast-import", "--quiet"], { cwd: dir, env, stdin: new TextEncoder().encode(stream), stderr: "pipe" });
66 if ((await fi.exited) !== 0) throw new Error(await new Response(fi.stderr).text());
67 await Bun.write(join(dir, "b.ts"), "export const b = 2;\n");
68 await git(["add", "."], dir);
69 await git(["commit", "-m", "two"], dir);
70 await git(["push", "origin", "--all"], dir);
71 }, 60_000);
72
73 afterAll(async () => {
74 servers.stop();
75 app.close();
76 await rm(dataDir, { recursive: true, force: true });
77 await rm(work, { recursive: true, force: true });
78 });
79
80 const get = async (path: string): Promise<{ text: string; timing: string }> => {
81 const res = await fetch(`${servers.url}${path}`, { headers: { authorization: `Bearer ${bearer}` } });
82 const text = await res.text();
83 expect(res.status).toBe(200);
84 return { text, timing: res.headers.get("server-timing") ?? "" };
85 };
86
87 test("200 branches answer in under 50 ms and name their phases", async () => {
88 await get("/alice/app/branches");

Wall-clock <50 ms can flake under a loaded runner; consider a margin or retry-best-of-3.

89 const { text, timing } = await get("/alice/app/branches");
90 const dur = (name: string) => Number(new RegExp(`(?:^|, )${name};dur=([0-9.]+)`).exec(timing)?.[1]);
91 // The 50 ms budget is held by the call-count test below; wall time on a loaded
92 // CI machine only has to show the page is nowhere near the per-branch cost.
93 expect(dur("app")).toBeLessThan(500);
94 for (const phase of ["session", "refs", "compare", "render"]) expect(dur(phase)).toBeGreaterThanOrEqual(0);
95 expect(text).toContain("200 branches");
96 expect(text).toContain("feat/b198");
97 }, 30_000);
98
99 test("the one-call counts equal the per-branch rev-list counts", async () => {
100 const dir = repoDir(app.reposRoot, "alice", "app");
101 const listed = await listBranches(dir, "main");
102 if (!listed.ok) throw new Error("listBranches failed");
103 expect(listed.value.compared).toBe(true);
104 const main = listed.value.branches.find((b) => b.isDefault)!;
105 expect(listed.value.branches.length).toBe(200);
106 expect(main.name).toBe("main");
107 for (const b of listed.value.branches) {
108 const want = await divergence(dir, main.oid, b.oid);
109 expect({ name: b.name, ahead: b.ahead, behind: b.behind }).toEqual({ name: b.name, ...want });
110 }
111 expect(listed.value.branches[1]).toMatchObject({ name: "feat/b000", ahead: 1, behind: 1 });
112 }, 60_000);
113
114 test("the per-branch fallback gives the same rows, and the one-call path is faster", async () => {
115 const dir = repoDir(app.reposRoot, "alice", "app");
116 const t0 = performance.now();
117 const bulk = await listBranches(dir, "main");
118 const t1 = performance.now();
119 const slow = await listBranches(dir, "main", { bulk: false });
120 const t2 = performance.now();
121 if (!bulk.ok || !slow.ok) throw new Error("listBranches failed");
122 expect(slow.value).toEqual(bulk.value);
123 expect(t1 - t0).toBeLessThan(t2 - t1);
124 }, 60_000);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs