Public: anyone can read this; the crew can change it.
A pass over every repository reads each blob with one short git, never a pooled reader (#17629) #17717
Merged 11h 41m ago, live in production
boot-readers → main 0 commits 1 thread · 1 unresolved
7 files
changed +204
−12
src/core/exposure.ts +7 −3
| @@ -5,7 +5,7 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import type { Database } from "bun:sqlite"; |
| 8 | import { blobForRender } from "../git/read.ts"; | |
| 8 | import { blobOnce } from "../git/read.ts"; | |
| 9 | 9 | import { repoDir } from "../git/repos.ts"; |
| 10 | 10 | import { advisoryVersion, exposure, listAdvisories, lockfilePackages, npmIndex, type Listed, type Hit, type Pkg } from "./advisories.ts"; |
| 11 | 11 | import { listEveryRepo, type Repo } from "./repos.ts"; |
| @@ -13,9 +13,13 @@ import { listEveryRepo, type Repo } from "./repos.ts"; | ||
| 13 | 13 | const LOCKFILE_MAX = 5_000_000; |
| 14 | 14 | const parsedBy = new WeakMap<Database, Map<string, Pkg[]>>(); |
| 15 | 15 | |
| 16 | /** | |
| 17 | * One repository's lockfile packages. Read with one short-lived git (`blobOnce`), not the pooled | |
| 18 | * readers: the feed reads every repository's lockfile soon after boot and hourly (#17629). | |
| 19 | */ | |
| 16 | 20 | export async function repoPackages(db: Database, reposRoot: string, repo: Repo): Promise<Pkg[]> { |
| 17 | const blob = await blobForRender(repoDir(reposRoot, repo.ownerName, repo.name), repo.defaultBranch, "package-lock.json", LOCKFILE_MAX); | |
| 18 | if (blob.kind !== "text") return []; | |
| 21 | const blob = await blobOnce(repoDir(reposRoot, repo.ownerName, repo.name), repo.defaultBranch, "package-lock.json", LOCKFILE_MAX); | |
| 22 | if (blob === undefined) return []; | |
| 19 | 23 | let parsed = parsedBy.get(db); |
| 20 | 24 | if (parsed === undefined) parsedBy.set(db, (parsed = new Map())); |
| 21 | 25 | const seen = parsed.get(blob.oid); |
src/display/config.ts +16 −6
| @@ -27,12 +27,15 @@ import { REPO_KEYED } from "../kernel/repo_keyed.ts"; | ||
| 27 | 27 | import type { App } from "../app.ts"; |
| 28 | 28 | import type { Repo } from "../core/repos.ts"; |
| 29 | 29 | import { exactRefOid } from "../git/branches.ts"; |
| 30 | import { isSafeRef } from "../git/guard.ts"; | |
| 31 | import { blobOnce } from "../git/read.ts"; | |
| 30 | 32 | import { isLaunch, isPinLabel, type Launch } from "../git/builds.ts"; |
| 31 | import { readFileAt } from "../apps/checkout.ts"; | |
| 32 | 33 | import { repoDir } from "../git/repos.ts"; |
| 33 | 34 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 34 | 35 | |
| 35 | 36 | export const DISPLAY_FILE = "display.json"; |
| 37 | /** The largest display file read: a display is a few kilobytes of settings. */ | |
| 38 | const DISPLAY_MAX = 1_048_576; | |
| 36 | 39 | |
| 37 | 40 | export const LAYOUTS = ["shelf", "grid", "graph"] as const; |
| 38 | 41 | export type Layout = (typeof LAYOUTS)[number]; |
| @@ -174,14 +177,21 @@ export function parseBuilds(raw: unknown): Result<readonly string[] | undefined, | ||
| 174 | 177 | /** |
| 175 | 178 | * A repository's display, read from the tip of its default branch: |
| 176 | 179 | * undefined when it has no `display.json`, an error when the file is bad. |
| 180 | * | |
| 181 | * One short-lived git (`blobOnce`), never a pooled reader (#17629): the boot reads every | |
| 182 | * repository's display (`warmDisplays`), and through `show-ref` and the reader pool that was two | |
| 183 | * git processes a repository and a long-lived `cat-file` left open for each, in every forge | |
| 184 | * booting at once. `cat-file` still looks a missing full ref up as a tag of that name | |
| 185 | * (`refs/tags/refs/heads/…`), so a display that is found costs one `show-ref` more, which takes only | |
| 186 | * the branch itself. | |
| 177 | 187 | */ |
| 178 | 188 | export async function readDisplay(app: App, repo: Repo): Promise<Result<DisplayConfig, string> | undefined> { |
| 189 | const ref = `refs/heads/${repo.defaultBranch}`; | |
| 190 | if (!isSafeRef(ref)) return undefined; | |
| 179 | 191 | const dir = repoDir(app.reposRoot, repo.ownerName, repo.name); |
| 180 | const tip = await exactRefOid(dir, `refs/heads/${repo.defaultBranch}`); | |
| 181 | if (tip === undefined) return undefined; | |
| 182 | const text = await readFileAt(dir, tip, DISPLAY_FILE); | |
| 183 | if (text === undefined) return undefined; | |
| 184 | return parseDisplay(text); | |
| 192 | const blob = await blobOnce(dir, ref, DISPLAY_FILE, DISPLAY_MAX); | |
| 193 | if (blob === undefined || (await exactRefOid(dir, ref)) === undefined) return undefined; | |
| 194 | return parseDisplay(new TextDecoder().decode(blob.body)); | |
| 185 | 195 | } |
| 186 | 196 | |
| 187 | 197 | /** |
src/display/known.ts +4 −2
| @@ -276,12 +276,14 @@ export function knownDisplays(app: App, viewer: User | undefined): { rows: Liste | ||
| 276 | 276 | |
| 277 | 277 | /** |
| 278 | 278 | * `listedDisplays`, but never later than `ms`: a cold cache reads git for |
| 279 | * every repository on the forge (two processes each, #11007), so a slow | |
| 280 | * read answers with what is kept and finishes behind the page. | |
| 279 | * every repository on the forge (a process each, #11007), so a slow | |
| 280 | * read answers with what is kept and finishes behind the page. With no time | |
| 281 | * at all (`ms` 0) it answers at once, never racing the read it started. | |
| 281 | 282 | */ |
| 282 | 283 | export async function listedDisplaysWithin(app: App, viewer: User | undefined, ms: number): Promise<{ rows: ListedDisplay[]; complete: boolean }> { |
| 283 | 284 | const full = listedDisplays(app, viewer).then((rows) => ({ rows, complete: true })); |
| 284 | 285 | full.catch(() => undefined); |
| 286 | if (ms <= 0) return knownDisplays(app, viewer); | |
| 285 | 287 | let timer: ReturnType<typeof setTimeout> | undefined; |
| 286 | 288 | const late = new Promise<undefined>((resolve) => { |
| 287 | 289 | timer = setTimeout(() => resolve(undefined), ms); |
src/git/read.ts +24
| @@ -412,6 +412,30 @@ export async function blobForRender( | ||
| 412 | 412 | return classify(body.value, size, named.value.trim()); |
| 413 | 413 | } |
| 414 | 414 | |
| 415 | /** | |
| 416 | * One blob read with one short-lived `cat-file --batch`, never a pooled reader (#17629): for a pass | |
| 417 | * over every repository on the forge (each display at boot, each lockfile for the advisory feed), | |
| 418 | * where the pool's 64 readers would open one long-lived `cat-file` a repository, close each for the | |
| 419 | * next, and leave the last 64 running. Production and its previews of the forge did that at | |
| 420 | * once on the 0.7.718 release: 254 `cat-file`s, at a load of 1,095. Undefined when `rev:path` is not a | |
| 421 | * blob or is over `maxBytes`; the oid comes with the body. git is killed once its output passes the | |
| 422 | * cap and the header's room, so a file of gigabytes is never held. | |
| 423 | */ | |
| 424 | export async function blobOnce(dir: string, rev: string, path: string, maxBytes: number): Promise<{ oid: string; body: Uint8Array } | undefined> { | |
| 425 | const spec = `${rev}:${path}`; | |
| 426 | assertBatchSafe(spec); | |
| 427 | // `<oid> blob <size>\n` before the body and a newline after it: under 100 bytes. | |
| 428 | const read = await runGitRaw(["cat-file", "--batch"], { cwd: dir, stdin: `${spec}\n`, maxBytes: maxBytes + 128 }); | |
| 429 | if (!read.ok) return undefined; | |
| 430 | const raw = read.value; | |
| 431 | const end = raw.indexOf(10); | |
| 432 | if (end < 0) return undefined; | |
| 433 | const [oid, type, sizeText] = new TextDecoder().decode(raw.subarray(0, end)).split(" "); | |
| 434 | const size = Number(sizeText); | |
| 435 | if (type !== "blob" || oid === undefined || !Number.isSafeInteger(size) || size > maxBytes) return undefined; | |
| 436 | return { oid, body: raw.subarray(end + 1, end + 1 + size) }; | |
| 437 | } | |
| 438 | ||
| 415 | 439 | /** |
| 416 | 440 | * The blob `path` names at `rev` (a commit), or undefined when there is none there: what an |
| 417 | 441 | * editor opened, compared with what is there now before a save replaces it. The pooled reader |
test/advisories.test.ts +36 −1
| @@ -1,8 +1,15 @@ | ||
| 1 | import { expect, test } from "bun:test"; | |
| 1 | import { expect, spyOn, test } from "bun:test"; | |
| 2 | 2 | import type { Database } from "bun:sqlite"; |
| 3 | 3 | import { openDb } from "../src/kernel/db.ts"; |
| 4 | 4 | import { migrations } from "../src/core/schema.ts"; |
| 5 | import { mkdtempSync, writeFileSync } from "node:fs"; | |
| 6 | import { tmpdir } from "node:os"; | |
| 7 | import { join } from "node:path"; | |
| 5 | 8 | import { affects, compareVersions, exposure, ingest, listAdvisories, lockfilePackages, npmIndex, parseOsv, saveAdvisories, saveKev } from "../src/core/advisories.ts"; |
| 9 | import { repoPackages } from "../src/core/exposure.ts"; | |
| 10 | import type { Repo } from "../src/core/repos.ts"; | |
| 11 | import { closeAllReaders, readerPoolSize } from "../src/git/read.ts"; | |
| 12 | import { gitClientEnv } from "./helpers/git-client.ts"; | |
| 6 | 13 | |
| 7 | 14 | const OSV = JSON.stringify({ |
| 8 | 15 | id: "GHSA-aaaa-bbbb-cccc", |
| @@ -74,3 +81,31 @@ test("ingest takes either feed and says which", () => { | ||
| 74 | 81 | expect(ingest(d, "nope", "").ok).toBe(false); |
| 75 | 82 | expect(ingest(d, OSV, "osv").ok).toBe(true); |
| 76 | 83 | }); |
| 84 | ||
| 85 | test("the feed reads each lockfile with one short git and leaves no reader open (#17629)", async () => { | |
| 86 | // Every repository's lockfile is read soon after boot; through the pooled readers that left a | |
| 87 | // long-lived cat-file per repository in every forge booting at once. | |
| 88 | const root = mkdtempSync(join(tmpdir(), "advisory-lock-")); | |
| 89 | const work = join(root, "work"); | |
| 90 | const git = (...args: string[]) => { | |
| 91 | const r = Bun.spawnSync(["git", "-c", "user.name=t", "-c", "user.email=t@t", ...args], { env: gitClientEnv() }); | |
| 92 | if (r.exitCode !== 0) throw new Error(r.stderr.toString()); | |
| 93 | }; | |
| 94 | git("init", "-q", "-b", "main", work); | |
| 95 | writeFileSync(join(work, "package-lock.json"), JSON.stringify({ packages: { "node_modules/lodash": { version: "4.17.0" } } })); | |
| 96 | git("-C", work, "add", "."); | |
| 97 | git("-C", work, "commit", "-qm", "lock"); | |
| 98 | git("clone", "-q", "--bare", work, join(root, "o", "lock.git")); | |
| 99 | git("init", "-q", "--bare", "-b", "main", join(root, "o", "empty.git")); | |
| 100 | closeAllReaders(); | |
| 101 | const repo = (name: string) => ({ ownerName: "o", name, defaultBranch: "main" }) as Repo; | |
| 102 | const spawn = spyOn(Bun, "spawn"); | |
| 103 | try { | |
| 104 | expect(await repoPackages(db(), root, repo("lock"))).toEqual([{ name: "lodash", version: "4.17.0" }]); | |
| 105 | expect(await repoPackages(db(), root, repo("empty"))).toEqual([]); | |
| 106 | expect(readerPoolSize()).toBe(0); | |
| 107 | expect(spawn.mock.calls.length).toBe(2); | |
| 108 | } finally { | |
| 109 | spawn.mockRestore(); | |
| 110 | } | |
| 111 | }); |
test/blob-once.test.ts added +76
| @@ -0,0 +1,76 @@ | ||
| 1 | /** | |
| 2 | * `blobOnce`: one blob by one short git, with no pooled reader, and never more of it held than the | |
| 3 | * cap (#17629). And what reads a display through it: only the default branch itself. | |
| 4 | */ | |
| 5 | import { afterAll, beforeAll, expect, spyOn, test } from "bun:test"; | |
| 6 | import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; | |
| 7 | import { tmpdir } from "node:os"; | |
| 8 | import { join } from "node:path"; | |
| 9 | import type { App } from "../src/app.ts"; | |
| 10 | import type { Repo } from "../src/core/repos.ts"; | |
| 11 | import { readDisplay } from "../src/display/config.ts"; | |
| 12 | import { blobOnce, closeAllReaders, readerPoolSize } from "../src/git/read.ts"; | |
| 13 | import { gitRun } from "./helpers/git-client.ts"; | |
| 14 | ||
| 15 | const BIG = 3_000_000; | |
| 16 | let root: string; | |
| 17 | let dir: string; | |
| 18 | ||
| 19 | beforeAll(() => { | |
| 20 | root = mkdtempSync(join(tmpdir(), "blob-once-")); | |
| 21 | // Where `repoDir` finds alice/shelf; a work tree reads the same to git. | |
| 22 | dir = join(root, "alice", "shelf.git"); | |
| 23 | mkdirSync(join(dir, "folder"), { recursive: true }); | |
| 24 | gitRun(dir, "init", "-q", "-b", "main"); | |
| 25 | writeFileSync(join(dir, "small.txt"), "0123456789"); | |
| 26 | writeFileSync(join(dir, "folder", "a.txt"), "a"); | |
| 27 | writeFileSync(join(dir, "big.txt"), "x".repeat(BIG)); | |
| 28 | writeFileSync(join(dir, "display.json"), JSON.stringify({ title: "Shelf", layout: "shelf", sources: ["alice/shelf"] })); | |
| 29 | gitRun(dir, "add", "."); | |
| 30 | gitRun(dir, "commit", "-qm", "files"); | |
| 31 | closeAllReaders(); | |
| 32 | }); | |
| 33 | ||
| 34 | afterAll(() => rmSync(root, { recursive: true, force: true })); | |
| 35 | ||
| 36 | test("a blob comes with its oid, up to exactly the cap, and no reader is left open", async () => { | |
| 37 | const got = await blobOnce(dir, "main", "small.txt", 10); | |
| 38 | expect(new TextDecoder().decode(got!.body)).toBe("0123456789"); | |
| 39 | expect(got!.oid).toBe(gitRun(dir, "rev-parse", "main:small.txt")); | |
| 40 | expect(await blobOnce(dir, "main", "small.txt", 9)).toBeUndefined(); | |
| 41 | expect(readerPoolSize()).toBe(0); | |
| 42 | }); | |
| 43 | ||
| 44 | test("a path that is not there, a revision that is not there and a folder are undefined", async () => { | |
| 45 | expect(await blobOnce(dir, "main", "none.txt", 1000)).toBeUndefined(); | |
| 46 | expect(await blobOnce(dir, "no-such-branch", "small.txt", 1000)).toBeUndefined(); | |
| 47 | expect(await blobOnce(dir, "main", "folder", 1000)).toBeUndefined(); | |
| 48 | }); | |
| 49 | ||
| 50 | test("a blob over the cap is undefined, and git is killed instead of read to its end", async () => { | |
| 51 | const spawn = spyOn(Bun, "spawn"); | |
| 52 | try { | |
| 53 | expect(await blobOnce(dir, "main", "big.txt", 1000)).toBeUndefined(); | |
| 54 | expect(spawn.mock.calls.length).toBe(1); | |
| 55 | const proc = spawn.mock.results[0]!.value as Bun.Subprocess; | |
| 56 | await proc.exited; | |
| 57 | expect(proc.signalCode).toBe("SIGKILL"); | |
| 58 | } finally { | |
| 59 | spawn.mockRestore(); | |
| 60 | } | |
| 61 | expect((await blobOnce(dir, "main", "big.txt", BIG))!.body.length).toBe(BIG); | |
| 62 | }); | |
| 63 | ||
| 64 | test("a display is read from the default branch alone: a tag of that name never answers for it", async () => { | |
| 65 | const app = { reposRoot: root } as App; | |
| 66 | const repo = { ownerName: "alice", name: "shelf", defaultBranch: "main" } as Repo; | |
| 67 | expect((await readDisplay(app, repo))?.ok).toBe(true); | |
| 68 | const gone = { ...repo, defaultBranch: "gone" }; | |
| 69 | expect(await readDisplay(app, gone)).toBeUndefined(); | |
| 70 | gitRun(dir, "update-ref", "refs/tags/gone", "main"); | |
| 71 | expect(await readDisplay(app, gone)).toBeUndefined(); | |
| 72 | // git looks `refs/heads/gone` up under refs/tags/ too. | |
| 73 | gitRun(dir, "update-ref", "refs/tags/refs/heads/gone", "main"); | |
| 74 | expect(await blobOnce(dir, "refs/heads/gone", "display.json", 1000)).toBeDefined(); | |
| 75 | expect(await readDisplay(app, gone)).toBeUndefined(); | |
| 76 | }); |
test/displays-fast.test.ts +41
| @@ -13,6 +13,8 @@ import { createApp, type App } from "../src/app.ts"; | ||
| 13 | 13 | import { getRepo } from "../src/core/repos.ts"; |
| 14 | 14 | import { createSession } from "../src/core/sessions.ts"; |
| 15 | 15 | import { createUser, type User } from "../src/core/users.ts"; |
| 16 | import { closeAllReaders, readerPoolSize } from "../src/git/read.ts"; | |
| 17 | import * as displayConfig from "../src/display/config.ts"; | |
| 16 | 18 | import { DISPLAYS_NOTE, DISPLAYS_READING, DISPLAYS_SENTENCE, knownDisplays, listedDisplaysWithin, warmDisplays, type ListedDisplay } from "../src/display/known.ts"; |
| 17 | 19 | import { serve, type Servers } from "../src/http/server.ts"; |
| 18 | 20 | import { createForgeApp } from "../src/tui/forge.ts"; |
| @@ -71,6 +73,25 @@ const gitCalls = (calls: unknown[][]) => | ||
| 71 | 73 | return Array.isArray(argv) && /(^|\/)git$/.test(String(argv[0])); |
| 72 | 74 | }).length; |
| 73 | 75 | |
| 76 | /** | |
| 77 | * Every display read waits for `release`. A list given 0 ms never waits, but a page may start a | |
| 78 | * read of its own before it draws the list, and one short git can be kept by then. | |
| 79 | */ | |
| 80 | function holdReads(): { release: () => void } { | |
| 81 | const real = displayConfig.readDisplay; | |
| 82 | const gate = Promise.withResolvers<void>(); | |
| 83 | const spy = spyOn(displayConfig, "readDisplay").mockImplementation(async (a, repo) => { | |
| 84 | await gate.promise; | |
| 85 | return real(a, repo); | |
| 86 | }); | |
| 87 | return { | |
| 88 | release() { | |
| 89 | spy.mockRestore(); | |
| 90 | gate.resolve(); | |
| 91 | }, | |
| 92 | }; | |
| 93 | } | |
| 94 | ||
| 74 | 95 | test("a cold list that cannot finish in time answers with what is kept, and the later call has the row", async () => { |
| 75 | 96 | const cold = coldApp(); |
| 76 | 97 | const early = await listedDisplaysWithin(cold, alice, 0); |
| @@ -86,6 +107,7 @@ test("a cold, empty answer says it is still reading, links Reload, and never say | ||
| 86 | 107 | const cold = coldApp(); |
| 87 | 108 | const srv = await serve(cold); |
| 88 | 109 | listWait.ms = 0; |
| 110 | const reads = holdReads(); | |
| 89 | 111 | const cookie = () => ({ cookie: `forge_session=${createSession(cold.db, alice.id).token}` }); |
| 90 | 112 | try { |
| 91 | 113 | const res = await fetch(`${srv.url}/displays`, { headers: cookie() }); |
| @@ -97,12 +119,14 @@ test("a cold, empty answer says it is still reading, links Reload, and never say | ||
| 97 | 119 | expect(page).not.toContain("No displays"); |
| 98 | 120 | expect(page).not.toContain('data-display="'); |
| 99 | 121 | // Once read, the notice is gone and the row is there. |
| 122 | reads.release(); | |
| 100 | 123 | await listedDisplaysWithin(cold, alice, 60_000); |
| 101 | 124 | const full = await (await fetch(`${srv.url}/displays`, { headers: cookie() })).text(); |
| 102 | 125 | expect(full).not.toContain('data-by="displays-reading"'); |
| 103 | 126 | expect(full).not.toContain(">Reload<"); |
| 104 | 127 | expect(full).toContain('data-display="alice/r0"'); |
| 105 | 128 | } finally { |
| 129 | reads.release(); | |
| 106 | 130 | listWait.ms = LIST_WAIT_MS; |
| 107 | 131 | await srv.stop(); |
| 108 | 132 | } |
| @@ -124,6 +148,23 @@ test("a warmed list reads no git", async () => { | ||
| 124 | 148 | } |
| 125 | 149 | }); |
| 126 | 150 | |
| 151 | test("warming every display leaves no long-lived reader open, and costs one git a repository and one more a display (#17629)", async () => { | |
| 152 | // The boot warms every repository's display; production and its previews booting at once each | |
| 153 | // opened a pooled cat-file per repository and ran two git processes a repository. | |
| 154 | closeAllReaders(); | |
| 155 | const warmed = coldApp(); | |
| 156 | const spawn = spyOn(Bun, "spawn"); | |
| 157 | try { | |
| 158 | await warmDisplays(warmed); | |
| 159 | expect(readerPoolSize()).toBe(0); | |
| 160 | const repos = (warmed.db.query("SELECT COUNT(*) AS n FROM repo").get() as { n: number }).n; | |
| 161 | // alice/r0 and alice/secret have a display: each is checked to be on the branch itself. | |
| 162 | expect(gitCalls(spawn.mock.calls)).toBeLessThanOrEqual(repos + 2); | |
| 163 | } finally { | |
| 164 | spawn.mockRestore(); | |
| 165 | } | |
| 166 | }); | |
| 167 | ||
| 127 | 168 | test("what is kept hides a private repository's display from a non-reader", async () => { |
| 128 | 169 | const warmed = coldApp(); |
| 129 | 170 | await warmDisplays(warmed); |
new above
offline
runGitRawbuffers all of the blob beforesize > maxBytesis tested, so an oversized blob is read whole into memory. Ask--batch-checkfirst, or cap the output, and test the over-cap case.