Public: anyone can read this; the crew can change it.
The milestones page answers under 50 ms for a repository with 20 milestones and 1,000 issues #3416
scout/forge:scout/3347-the-milestones-page-answers-under-50-ms → main 1 commit fork
3 files
changed +196
−18
src/core/milestones.ts +39 −16
| @@ -32,6 +32,8 @@ import { | ||
| 32 | 32 | pillarWindowStart, |
| 33 | 33 | type Pillars, |
| 34 | 34 | } from "./pillars.ts"; |
| 35 | import { Stamped } from "../kernel/stamped.ts"; | |
| 36 | import { writeStamp } from "./write_clock.ts"; | |
| 35 | 37 | import { closesFromBody, openPullsClosing } from "./pulls.ts"; |
| 36 | 38 | import type { Repo } from "./repos.ts"; |
| 37 | 39 | import { listActiveRuns } from "./runs.ts"; |
| @@ -242,8 +244,10 @@ export function readPlan( | ||
| 242 | 244 | }); |
| 243 | 245 | } |
| 244 | 246 | |
| 245 | // The week's merged pulls, by the issues each closes. | |
| 246 | const merged: MergedPull[] = db | |
| 247 | // Every merged pull with the issues it closes, parsed once: the week's for | |
| 248 | // the limbs, and for a viewer who may see owner facts, what a limb landed | |
| 249 | // ever. Newest first; the week is capped at 1,000. | |
| 250 | const landedPulls: MergedPull[] = db | |
| 247 | 251 | .query< |
| 248 | 252 | { number: number; title: string; body: string; at: string }, |
| 249 | 253 | [string, string] |
| @@ -251,15 +255,19 @@ export function readPlan( | ||
| 251 | 255 | `SELECT i.number, i.title, i.body, p.merged_at AS at |
| 252 | 256 | FROM pull p JOIN issue i ON i.id = p.issue_id |
| 253 | 257 | WHERE i.repo_id = ?1 AND p.merged_at IS NOT NULL AND p.merged_at >= ?2 |
| 254 | ORDER BY p.merged_at DESC LIMIT 1000`, | |
| 258 | ORDER BY p.merged_at DESC ${options.spend ? "" : "LIMIT 1000"}`, | |
| 255 | 259 | ) |
| 256 | .all(repo.id, since) | |
| 260 | .all(repo.id, options.spend ? "" : since) | |
| 257 | 261 | .map((row) => ({ |
| 258 | 262 | number: row.number, |
| 259 | 263 | title: row.title, |
| 260 | 264 | at: row.at, |
| 261 | 265 | closes: closesFromBody(row.body), |
| 262 | 266 | })); |
| 267 | const merged = landedPulls.filter((pull) => pull.at >= since).slice(0, 1000); | |
| 268 | const everMerged: (readonly number[])[] = options.spend | |
| 269 | ? landedPulls.map((pull) => pull.closes) | |
| 270 | : []; | |
| 263 | 271 | |
| 264 | 272 | // What each issue cost: its own runs, and the runs on the pulls for it. |
| 265 | 273 | const cost = new Map<string, number>(); |
| @@ -284,18 +292,6 @@ export function readPlan( | ||
| 284 | 292 | } |
| 285 | 293 | } |
| 286 | 294 | |
| 287 | // Every pull ever merged, by the issues it closes: what a limb landed. | |
| 288 | // One query that parses each merged pull's body; owner reads only. | |
| 289 | const everMerged: (readonly number[])[] = options.spend | |
| 290 | ? db | |
| 291 | .query<{ body: string }, [string]>( | |
| 292 | `SELECT i.body FROM pull p JOIN issue i ON i.id = p.issue_id | |
| 293 | WHERE i.repo_id = ?1 AND p.merged_at IS NOT NULL`, | |
| 294 | ) | |
| 295 | .all(repo.id) | |
| 296 | .map((row) => closesFromBody(row.body)) | |
| 297 | : []; | |
| 298 | ||
| 299 | 295 | const stateOf = (issue: Issue): LeafState => { |
| 300 | 296 | if (issue.state === "closed") return counted(issue) ? "done" : "gone"; |
| 301 | 297 | if (building.has(issue.id)) return "building"; |
| @@ -637,3 +633,30 @@ export function milestoneJson( | ||
| 637 | 633 | })), |
| 638 | 634 | }; |
| 639 | 635 | } |
| 636 | ||
| 637 | const planCaches = new WeakMap<Database, Stamped<Plan>>(); | |
| 638 | ||
| 639 | /** How long a plan is served without a write: its week's window moves with the clock. */ | |
| 640 | export const PLAN_MAX_AGE_MS = 10_000; | |
| 641 | ||
| 642 | /** | |
| 643 | * `readPlan`, served again until the forge's write clock moves | |
| 644 | * (`write_clock.ts`, docs/CACHING.md): a plan is read from rows only, so | |
| 645 | * equal stamps mean the same plan. One entry a repository and viewer kind. | |
| 646 | */ | |
| 647 | export function readPlanCached( | |
| 648 | db: Database, | |
| 649 | repo: Repo, | |
| 650 | options: { readonly spend: boolean }, | |
| 651 | ): Plan { | |
| 652 | const stamp = writeStamp(db); | |
| 653 | if (stamp === undefined) return readPlan(db, repo, options); | |
| 654 | let cache = planCaches.get(db); | |
| 655 | if (cache === undefined) { | |
| 656 | cache = new Stamped<Plan>({ maxEntries: 100, maxAgeMs: PLAN_MAX_AGE_MS }); | |
| 657 | planCaches.set(db, cache); | |
| 658 | } | |
| 659 | return cache.get(`${repo.id}:${options.spend}`, stamp, () => | |
| 660 | readPlan(db, repo, options), | |
| 661 | ); | |
| 662 | } |
src/web/pages/milestones.ts +3 −2
| @@ -14,6 +14,7 @@ import { | ||
| 14 | 14 | limbJson, |
| 15 | 15 | milestoneJson, |
| 16 | 16 | readPlan, |
| 17 | readPlanCached, | |
| 17 | 18 | type LeafState, |
| 18 | 19 | type Limb, |
| 19 | 20 | type Milestone, |
| @@ -201,7 +202,7 @@ export function milestonesPage(ctx: Ctx): Response { | ||
| 201 | 202 | const repo = timePhase(ctx.request, "repo", () => loadRepo(ctx)); |
| 202 | 203 | if (!repo) return notFoundPage(ctx); |
| 203 | 204 | const plan = timePhase(ctx.request, "plan", () => |
| 204 | readPlan(ctx.app.db, repo, { | |
| 205 | readPlanCached(ctx.app.db, repo, { | |
| 205 | 206 | spend: canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user), |
| 206 | 207 | }), |
| 207 | 208 | ); |
| @@ -598,7 +599,7 @@ export async function milestonesJson( | ||
| 598 | 599 | ctx: Ctx, |
| 599 | 600 | repo: Repo, |
| 600 | 601 | ): Promise<Record<string, unknown>> { |
| 601 | const plan = readPlan(ctx.app.db, repo, { | |
| 602 | const plan = readPlanCached(ctx.app.db, repo, { | |
| 602 | 603 | spend: canSeeOwnerFacts(ctx.app.db, repo, ctx.auth.user), |
| 603 | 604 | }); |
| 604 | 605 | const ask = askByUmbrella(ctx, repo); |
test/milestones-speed.test.ts added +154
| @@ -0,0 +1,154 @@ | ||
| 1 | /** `/:owner/:name/milestones` answers fast for 20 milestones over 1,000 issues, and its HTML is what it was (#3347). */ | |
| 2 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 3 | import { mkdtempSync, rmSync } from "node:fs"; | |
| 4 | import { tmpdir } from "node:os"; | |
| 5 | import { join } from "node:path"; | |
| 6 | import { createRepo } from "../src/actions/repos.ts"; | |
| 7 | import { linkIssue } from "../src/actions/dependencies.ts"; | |
| 8 | import { openIssue } from "../src/actions/issues.ts"; | |
| 9 | import { createApp, type App } from "../src/app.ts"; | |
| 10 | import { getIssueById } from "../src/core/issues.ts"; | |
| 11 | import { getRepoById } from "../src/core/repos.ts"; | |
| 12 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 13 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 14 | import { proveAll } from "./helpers/verified.ts"; | |
| 15 | import { quietLogs } from "./helpers/globals.ts"; | |
| 16 | ||
| 17 | quietLogs(); | |
| 18 | ||
| 19 | const MILESTONES = 20; | |
| 20 | const ISSUES = 1000; | |
| 21 | const CLOSED = 900; | |
| 22 | ||
| 23 | let root = ""; | |
| 24 | let app: App; | |
| 25 | let servers: Servers; | |
| 26 | let cookie = ""; | |
| 27 | let repoId = ""; | |
| 28 | ||
| 29 | beforeAll(async () => { | |
| 30 | root = mkdtempSync(join(tmpdir(), "forge-milestones-speed-")); | |
| 31 | app = createApp({ dataDir: root, port: 0, forgeRepo: "alice/forge" }); | |
| 32 | const u = await createUser(app.db, { | |
| 33 | origin: "seed", | |
| 34 | trusted: true, | |
| 35 | username: "alice", | |
| 36 | email: "[email protected]", | |
| 37 | password: "a-good-passphrase", | |
| 38 | adminIfFirst: true, | |
| 39 | }); | |
| 40 | if (!u.ok) throw new Error(u.error); | |
| 41 | proveAll(app); | |
| 42 | const alice = getUserByName(app.db, "alice")!; | |
| 43 | const made = await createRepo(app, alice, { name: "forge" }); | |
| 44 | if (!made.ok) throw new Error(String(made.error)); | |
| 45 | repoId = made.value.id; | |
| 46 | const fresh = () => getRepoById(app.db, repoId)!; | |
| 47 | const open = (title: string, body = "") => { | |
| 48 | const o = openIssue(app, alice, fresh(), { title, body }); | |
| 49 | if (!o.ok) throw new Error(String(o.error)); | |
| 50 | return o.value; | |
| 51 | }; | |
| 52 | const roots = Array.from({ length: MILESTONES }, (_, n) => open(`Milestone ${n + 1}`)); | |
| 53 | const per = ISSUES / MILESTONES; | |
| 54 | const leaves = Array.from({ length: ISSUES }, (_, n) => open(`Work ${n + 1}`)); | |
| 55 | leaves.forEach((leaf, n) => { | |
| 56 | const l = linkIssue(app, alice, fresh(), getIssueById(app.db, roots[Math.floor(n / per)]!.id)!, getIssueById(app.db, leaf.id)!); | |
| 57 | if (!l.ok) throw new Error(String(l.error)); | |
| 58 | }); | |
| 59 | // 900 closed, 45 a milestone, over the last week; each landed by a merged pull. | |
| 60 | const day = 86_400_000; | |
| 61 | const stamp = (n: number) => new Date(Date.now() - (n % 6) * day - (n % 1000) * 60_000).toISOString(); | |
| 62 | const close = app.db.query(`UPDATE issue SET state = 'closed', closed_at = ?2, close_reason = 'done' WHERE id = ?1`); | |
| 63 | const insertPull = app.db.query( | |
| 64 | `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) VALUES (?1, 'main', ?2, 'a', 'b', ?3)`, | |
| 65 | ); | |
| 66 | app.db.transaction(() => { | |
| 67 | leaves.forEach((leaf, n) => { | |
| 68 | if (n % per >= (CLOSED / ISSUES) * per) return; | |
| 69 | close.run(leaf.id, stamp(n)); | |
| 70 | const pull = open(`Land ${n + 1}`, `Closes #${leaf.number}`); | |
| 71 | app.db.query(`UPDATE issue SET kind = 'pull' WHERE id = ?1`).run(pull.id); | |
| 72 | insertPull.run(pull.id, `feature/${n}`, stamp(n)); | |
| 73 | }); | |
| 74 | })(); | |
| 75 | app.db.query(`UPDATE issue SET created_at = '2020-01-01T00:00:00.000Z', updated_at = '2020-01-01T00:00:00.000Z'`).run(); | |
| 76 | servers = await serve(app); | |
| 77 | const signin = await fetch(`${servers.url}/signin`, { | |
| 78 | method: "POST", | |
| 79 | headers: { origin: servers.url }, | |
| 80 | body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }), | |
| 81 | redirect: "manual", | |
| 82 | }); | |
| 83 | cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0]!; | |
| 84 | }, 120_000); | |
| 85 | afterAll(() => { | |
| 86 | servers.stop(); | |
| 87 | app.close(); | |
| 88 | rmSync(root, { recursive: true, force: true }); | |
| 89 | }); | |
| 90 | ||
| 91 | const read = async () => { | |
| 92 | const res = await fetch(`${servers.url}/alice/forge/milestones`, { headers: { cookie } }); | |
| 93 | return { status: res.status, body: await res.text(), timing: res.headers.get("server-timing") ?? "" }; | |
| 94 | }; | |
| 95 | // The page's own time: the phases it names, not the socket. | |
| 96 | const phases = (timing: string): Record<string, number> => | |
| 97 | Object.fromEntries( | |
| 98 | timing.split(", ").flatMap((p) => { | |
| 99 | const m = /^([a-z]+);dur=([\d.]+)$/.exec(p); | |
| 100 | return m ? [[m[1]!, Number(m[2])]] : []; | |
| 101 | }), | |
| 102 | ); | |
| 103 | ||
| 104 | /** The page as it reads, with the clock-bound and per-response parts taken out. */ | |
| 105 | const stable = (html: string): string => | |
| 106 | html | |
| 107 | .replace(/<script[\s\S]*?<\/script>/g, "") | |
| 108 | .replace(/<time[\s\S]*?<\/time\s*>/g, "<time/>") | |
| 109 | .replace(/nonce="[^"]*"/g, 'nonce=""') | |
| 110 | .replace(/localhost:\d+/g, "localhost"); | |
| 111 | const digest = (html: string): string => | |
| 112 | new Bun.CryptoHasher("sha256").update(stable(html)).digest("hex"); | |
| 113 | ||
| 114 | /** Taken from the page as it was before #3347 read the plan once and kept it, on this same seed. */ | |
| 115 | const BEFORE = "ec0608c253a7384dba012da18a0bf2f380b5186ea2e525b7c91a2e7f63e0ae72"; | |
| 116 | ||
| 117 | const own = (timing: string): number => { | |
| 118 | const p = phases(timing); | |
| 119 | return (p.session ?? 0) + (p.repo ?? 0) + (p.plan ?? 0) + (p.seats ?? 0) + (p.render ?? 0); | |
| 120 | }; | |
| 121 | ||
| 122 | test("20 milestones over 1,000 issues: the HTML is what it was, and the page's own time is under 50 ms once read", async () => { | |
| 123 | const first = await read(); | |
| 124 | expect(first.status).toBe(200); | |
| 125 | expect(first.body.match(/<progress/g)?.length).toBe(MILESTONES); | |
| 126 | expect(digest(first.body)).toBe(BEFORE); | |
| 127 | console.log("cold", first.timing); | |
| 128 | let warm = Infinity; | |
| 129 | for (let n = 0; n < 5; n++) { | |
| 130 | const again = await read(); | |
| 131 | expect(digest(again.body)).toBe(BEFORE); | |
| 132 | warm = Math.min(warm, own(again.timing)); | |
| 133 | } | |
| 134 | console.log("warm", warm); | |
| 135 | // After a write the plan is read once more (about 25 ms here); every read | |
| 136 | // after it, until the next write, is served from it and stays well under 50. | |
| 137 | expect(warm).toBeLessThan(15); | |
| 138 | }); | |
| 139 | ||
| 140 | test("a write shows on the next read of the page", async () => { | |
| 141 | const before = await read(); | |
| 142 | const alice = getUserByName(app.db, "alice")!; | |
| 143 | const repo = getRepoById(app.db, repoId)!; | |
| 144 | const o = openIssue(app, alice, repo, { title: "A new milestone" }); | |
| 145 | if (!o.ok) throw new Error(String(o.error)); | |
| 146 | const leaf = openIssue(app, alice, repo, { title: "Its work" }); | |
| 147 | if (!leaf.ok) throw new Error(String(leaf.error)); | |
| 148 | const l = linkIssue(app, alice, repo, o.value, leaf.value); | |
| 149 | if (!l.ok) throw new Error(String(l.error)); | |
| 150 | const after = await read(); | |
| 151 | expect(before.body.match(/<progress/g)?.length).toBe(MILESTONES); | |
| 152 | expect(after.body.match(/<progress/g)?.length).toBe(MILESTONES + 1); | |
| 153 | expect(after.body).toContain("A new milestone"); | |
| 154 | }); |
new above
offline