diff --git a/src/agents/accounts.ts b/src/agents/accounts.ts index 2517b35e1..486bb6dc3 100644 --- a/src/agents/accounts.ts +++ b/src/agents/accounts.ts @@ -53,10 +53,10 @@ const validPct = (v: unknown): v is number => typeof v === "number" && Number.is /** The usage levels at which an account stops taking calls; absent or unreadable gives the defaults. */ export async function usagePause(db: Db): Promise { - const row = await db.get(db.k.selectFrom("settings").select("value").where("key", "=", USAGE_PAUSE_KEY)); - if (!row || row.value === null) return USAGE_PAUSE_DEFAULT; + const value = await setting(db, USAGE_PAUSE_KEY); + if (value === undefined) return USAGE_PAUSE_DEFAULT; try { - const v = JSON.parse(row.value) as Partial | null; + const v = JSON.parse(value) as Partial | null; return v && validPct(v.fiveHour) && validPct(v.weekly) ? { fiveHour: v.fiveHour, weekly: v.weekly } : USAGE_PAUSE_DEFAULT; } catch { return USAGE_PAUSE_DEFAULT; diff --git a/src/classify/settled.ts b/src/classify/settled.ts index 7e61cd5e1..ad714c936 100644 --- a/src/classify/settled.ts +++ b/src/classify/settled.ts @@ -134,7 +134,7 @@ export const runExists = async (db: Db, run: string): Promise => /** Makes `run` the current classification run (settings.classify_run), audited. */ export async function setCurrentRun(db: Db, run: string, by: string): Promise { - const prev = (await db.get(db.k.selectFrom("settings").select("value").where("key", "=", "classify_run")))?.value ?? null; + const prev = (await setting(db, "classify_run")) ?? null; await db.run(db.k.insertInto("settings").values({ key: "classify_run", value: run }).onConflict((oc) => oc.column("key").doUpdateSet(kx.excluded(["value"])))); await audit(db, by, "classify-run", `run:${run}`, { previous: prev }); } diff --git a/src/dash/api/admin.ts b/src/dash/api/admin.ts index ff8d3a302..15ee098f4 100644 --- a/src/dash/api/admin.ts +++ b/src/dash/api/admin.ts @@ -36,6 +36,7 @@ import { mapSeq } from "../../async-seq.ts"; import type { Db } from "../../db/index.ts"; import * as kx from "../../db/kx.ts"; import type { Expression, SqlBool } from "kysely"; +import { setting } from "../../settings-read.ts"; const NOTE_MAX = 300; const ACCESS_NOTE_MAX = 500; @@ -139,7 +140,7 @@ export function clearContributorCache(db: Db): void { contributorCache.delete(db); } async function cachedContributors(db: Db, repo: string | undefined): Promise { - const hw = (await db.get(db.k.selectFrom("main.settings").select("value").where("key", "=", "org_high_water")))?.value ?? null; + const hw = (await setting(db, "org_high_water")) ?? null; const byRepo = contributorCache.get(db) ?? new Map(); contributorCache.set(db, byRepo); const key = repo ?? ""; diff --git a/src/dash/api/decisions.ts b/src/dash/api/decisions.ts index 4a5bf7dd3..d5f390a0f 100644 --- a/src/dash/api/decisions.ts +++ b/src/dash/api/decisions.ts @@ -323,13 +323,39 @@ export async function decisionPage(db: Db, ds: DecisionRow[], viewer: Viewer): P const singles = ds.filter((d) => !isBatch(d)).map((d) => ({ repo: d.repo!, number: d.number! })); const refs = singles.map((r) => [r.repo, r.number] as [string, number]); const itemRows = (of: [string, number][]) => db.all(db.k.selectFrom("items").select(["repo", "number", "title", "body", "kind", "state", "closing_issues"]).where(kx.refIn(db, "items", of))); + const batchRefs = ds.filter(isBatch).flatMap((d) => itemsOf(d)); + const adoptedIds = ds.flatMap((d) => (d.adopted_opinion ? [d.adopted_opinion] : [])); + const heads = ds.flatMap((d) => { const h = riskHead(d); return h ? [[d.repo!, d.number!, h] as [string, number, string]] : []; }); + const groupIds = ds.filter(isGroup).map((d) => d.id); + // The page's reads do not depend on each other, so they run together. + const [itemsRead, dupRows, shown, opinions, adopted, claims, comments, classes, areas, priority, risks, groups, texts, quiet, members] = await Promise.all([ + itemRows(refs), + // In dup_of order, as the (repo, dup_of) index gives them to the one-item read. + db.all(db.k.selectFrom("classifications").select(["repo", "number", "dup_of"]).distinct().where(kx.refIn(db, "classifications", refs)) + .where("dup_of", "is not", null).$narrowType<{ dup_of: NotNull }>().orderBy("repo").orderBy("number").orderBy("dup_of")), + batchRefs.length ? shownMap(db, batchRefs) : undefined, + db.all(db.k.selectFrom("decision_opinions").select(["decision_id", "id", "login", "option", "note", "at", "permission", "via"]) + .where(kx.inList(db, "decision_id", ids)).where("retracted_at", "is", null).orderBy("decision_id").orderBy("at", "desc")), + adoptedIds.length ? db.all(db.k.selectFrom("decision_opinions").select(["id", "login", "option", "note", "at", "permission", "via"]).where(kx.inList(db, "id", adoptedIds))) : [], + db.all(db.k.selectFrom("decision_claims").select(["decision_id", "login", "since"]).where(kx.inList(db, "decision_id", ids)) + .where("at", ">", new Date(Date.now() - CLAIM_TTL).toISOString()).where("login", "<>", viewer.login).orderBy("decision_id").orderBy("at", "desc")), + db.all(db.k.selectFrom("decision_comments").select(["decision_id", (eb) => eb.fn.countAll().as("n")]).where(kx.inList(db, "decision_id", ids)).groupBy("decision_id")), + // In the primary key's order within an item, as the one-item read walks it. + singles.length ? db.all(db.k.selectFrom("classifications").select(["repo", "number", "classifier", "at", "type_label", "want", "reference", "reason", "dup_of"]) + .where(kx.refIn(db, "classifications", refs)).orderBy("repo").orderBy("number").orderBy("classifier").orderBy("run_id")) : [], + singles.length ? db.all(db.k.selectFrom("item_areas").select(["repo", "number", "area"]).where(kx.refIn(db, "item_areas", refs))) : [], + singles.length ? db.all(db.k.selectFrom("item_priority").select(["repo", "number", "impact", "model", "reason"]).$narrowType<{ impact: Level }>().where(kx.refIn(db, "item_priority", refs))) : [], + heads.length ? db.all(db.k.selectFrom("opus_reviews").select(["repo", "number", "head_oid", "risks"]) + .where(kx.tupleIn(db, ["repo", "number", "head_oid"], heads, ["text", "bigint", "text"])).where("verdict", "is not", null)) : [], + groupIds.length ? db.all(groupRows(db).where(kx.inList(db, "gi.decision_id", groupIds))) : [], + groupIds.length ? optionTextsMany(db, groupIds) : undefined, + viewer.staff ? undefined : quietFixPrs(db), + viewer.staff ? [] : db.all(db.k.selectFrom("dupe_group_items").select(["decision_id", "repo", "number"]).where(kx.inList(db, "decision_id", ids))), + ]); const items = new Map(); - for (const r of await itemRows(refs)) items.set(keyOf(r), r); + for (const r of itemsRead) items.set(keyOf(r), r); const dupOf = new Map(); - // In dup_of order, as the (repo, dup_of) index gives them to the one-item read. - for (const r of await db.all(db.k.selectFrom("classifications").select(["repo", "number", "dup_of"]).distinct().where(kx.refIn(db, "classifications", refs)) - .where("dup_of", "is not", null).$narrowType<{ dup_of: NotNull }>().orderBy("repo").orderBy("number").orderBy("dup_of"))) - pushTo(dupOf, keyOf(r), r.dup_of); + for (const r of dupRows) pushTo(dupOf, keyOf(r), r.dup_of); const page: DecisionPage = { items, shown: new Map(), opinions: new Map(), adopted: new Map(), claims: new Map(), comments: new Map(), classes: new Map(), dupOf, areas: new Map(), priority: new Map(), risks: new Map(), groups: new Map(), texts: new Map(), members: new Map(), @@ -339,47 +365,28 @@ export async function decisionPage(db: Db, ds: DecisionRow[], viewer: Viewer): P for (const r of singles) for (const x of await relatedNumbers(db, r.repo, r.number, viewer.related, page)) if (!items.has(`${r.repo}#${x.number}`)) related.set(`${r.repo}#${x.number}`, [r.repo, x.number]); if (related.size) for (const r of await itemRows([...related.values()])) items.set(keyOf(r), r); - const batchRefs = ds.filter(isBatch).flatMap((d) => itemsOf(d)); - if (batchRefs.length) page.shown = await shownMap(db, batchRefs); - for (const o of await db.all(db.k.selectFrom("decision_opinions").select(["decision_id", "id", "login", "option", "note", "at", "permission", "via"]) - .where(kx.inList(db, "decision_id", ids)).where("retracted_at", "is", null).orderBy("decision_id").orderBy("at", "desc"))) { + if (shown) page.shown = shown; + for (const o of opinions) { const { decision_id, ...op } = o; pushTo(page.opinions, decision_id, op); } - const adopted = ds.flatMap((d) => (d.adopted_opinion ? [d.adopted_opinion] : [])); - if (adopted.length) for (const o of await db.all(db.k.selectFrom("decision_opinions").select(["id", "login", "option", "note", "at", "permission", "via"]).where(kx.inList(db, "id", adopted)))) page.adopted.set(o.id, o); - for (const c of await db.all(db.k.selectFrom("decision_claims").select(["decision_id", "login", "since"]).where(kx.inList(db, "decision_id", ids)) - .where("at", ">", new Date(Date.now() - CLAIM_TTL).toISOString()).where("login", "<>", viewer.login).orderBy("decision_id").orderBy("at", "desc"))) - if (!page.claims.has(c.decision_id)) page.claims.set(c.decision_id, { login: c.login, since: c.since }); - for (const c of await db.all(db.k.selectFrom("decision_comments").select(["decision_id", (eb) => eb.fn.countAll().as("n")]).where(kx.inList(db, "decision_id", ids)).groupBy("decision_id"))) page.comments.set(c.decision_id, c.n); - if (singles.length) { - // In the primary key's order within an item, as the one-item read walks it. - for (const c of await db.all(db.k.selectFrom("classifications").select(["repo", "number", "classifier", "at", "type_label", "want", "reference", "reason", "dup_of"]) - .where(kx.refIn(db, "classifications", refs)).orderBy("repo").orderBy("number").orderBy("classifier").orderBy("run_id"))) { - const { repo, number, ...row } = c; - pushTo(page.classes, `${repo}#${number}`, row); - } - for (const a of await db.all(db.k.selectFrom("item_areas").select(["repo", "number", "area"]).where(kx.refIn(db, "item_areas", refs)))) page.areas.set(keyOf(a), a.area); - for (const p of await db.all(db.k.selectFrom("item_priority").select(["repo", "number", "impact", "model", "reason"]).$narrowType<{ impact: Level }>().where(kx.refIn(db, "item_priority", refs)))) - page.priority.set(keyOf(p), { level: p.impact, model: p.model, reason: p.reason }); + for (const o of adopted) page.adopted.set(o.id, o); + for (const c of claims) if (!page.claims.has(c.decision_id)) page.claims.set(c.decision_id, { login: c.login, since: c.since }); + for (const c of comments) page.comments.set(c.decision_id, c.n); + for (const c of classes) { + const { repo, number, ...row } = c; + pushTo(page.classes, `${repo}#${number}`, row); } - const heads = ds.flatMap((d) => { const h = riskHead(d); return h ? [[d.repo!, d.number!, h] as [string, number, string]] : []; }); - if (heads.length) for (const o of await db.all(db.k.selectFrom("opus_reviews").select(["repo", "number", "head_oid", "risks"]) - .where(kx.tupleIn(db, ["repo", "number", "head_oid"], heads, ["text", "bigint", "text"])).where("verdict", "is not", null))) - page.risks.set(`${o.repo}#${o.number}@${o.head_oid}`, { risks: o.risks }); - const groups = ds.filter(isGroup).map((d) => d.id); - if (groups.length) { - for (const g of await db.all(groupRows(db).where(kx.inList(db, "gi.decision_id", groups)))) { - const { decision_id, ...row } = g; - pushTo(page.groups, decision_id, row); - } - page.texts = await optionTextsMany(db, groups); - } - if (!viewer.staff) { - page.quiet = await quietFixPrs(db); - for (const m of await db.all(db.k.selectFrom("dupe_group_items").select(["decision_id", "repo", "number"]).where(kx.inList(db, "decision_id", ids)))) - pushTo(page.members, m.decision_id, { repo: m.repo, number: m.number }); + for (const a of areas) page.areas.set(keyOf(a), a.area); + for (const p of priority) page.priority.set(keyOf(p), { level: p.impact, model: p.model, reason: p.reason }); + for (const o of risks) page.risks.set(`${o.repo}#${o.number}@${o.head_oid}`, { risks: o.risks }); + for (const g of groups) { + const { decision_id, ...row } = g; + pushTo(page.groups, decision_id, row); } + if (texts) page.texts = texts; + if (quiet) page.quiet = quiet; + for (const m of members) pushTo(page.members, m.decision_id, { repo: m.repo, number: m.number }); return page; } @@ -615,9 +622,14 @@ export async function listDecisions(db: Db, req: Req): Promise { const rowOf = new Map((shownIds.length ? await db.all(db.k.selectFrom("decisions").select(kx.cols("decisions")).where(kx.inList(db, "id", shownIds.map((r) => r.id)))) as DecisionRow[] : []).map((d) => [d.id, d])); const shown = shownIds.map((r) => rowOf.get(r.id)!); const viewer = shown.length ? await viewerWith(db, req) : viewerOf(req); - viewer.prep = await prepareStates(db, shown); - if (shown.some((d) => d.answer === null)) viewer.blocks = await blocksIndex(db, viewer.hidden ?? (viewer.operator ? [] : ALL_HIDDEN)); - if (shown.some((d) => d.number !== null)) viewer.related = await relatedIndex(db); + const [prep, blocks, related] = await Promise.all([ + prepareStates(db, shown), + shown.some((d) => d.answer === null) ? blocksIndex(db, viewer.hidden ?? (viewer.operator ? [] : ALL_HIDDEN)) : undefined, + shown.some((d) => d.number !== null) ? relatedIndex(db) : undefined, + ]); + viewer.prep = prep; + if (blocks) viewer.blocks = blocks; + if (related) viewer.related = related; if (shown.length) viewer.page = await decisionPage(db, shown, viewer); return { decisions: await mapSeq(shown, async (d) => await toDecision(db, d, viewer)), total, byKind, oldestAskedAt, diff --git a/src/dash/api/discord.ts b/src/dash/api/discord.ts index 451c4f249..646ad67af 100644 --- a/src/dash/api/discord.ts +++ b/src/dash/api/discord.ts @@ -14,6 +14,7 @@ import { signalCountOf, signalLinks } from "../../discord/signals.ts"; import { createLinkCode, linkedSince, listLinks, unlinkLogin, unlinkRow } from "../../discord/links.ts"; import type { Req } from "../types.ts"; import type { Db } from "../../db/index.ts"; +import { setting } from "../../settings-read.ts"; const PRIVACY_PATH = DISCORD_PRIVACY_PATH; @@ -33,7 +34,7 @@ export function discordKeys(): DiscordKeys | null { } export const contactOf = async (db: Db): Promise => - (await db.get(db.k.selectFrom("settings").select("value").where("key", "=", "discord_contact")))?.value ?? ""; + (await setting(db, "discord_contact")) ?? ""; /** Count for everyone who sees the item; message links only with the key. */ export async function discordOf(db: Db, repo: string, n: number): Promise { diff --git a/src/dash/api/home.ts b/src/dash/api/home.ts index b9e45d897..ba19a4d2c 100644 --- a/src/dash/api/home.ts +++ b/src/dash/api/home.ts @@ -26,19 +26,19 @@ const itemKindOf = (k: string | undefined): "pr" | "issue" | null => (k === unde async function phases(db: Db, hidden: string[]): Promise> { const hide = excludeHiddenExpr(db, "i.repo", hidden); const out = Object.fromEntries(ITEM_PHASES.map((x) => [x, 0])) as Record; - for (const r of await db.all(db.k.selectFrom("items as i").leftJoin("main.item_plans as p", (j) => j.onRef("p.repo", "=", "i.repo").onRef("p.number", "=", "i.number")) - .select((eb) => [phaseExpr(db, eb).as("phase"), eb.fn.countAll().as("n")]) - .$if(!!hide, (q) => q.where(hide!)).groupBy("phase"))) - if (r.phase in out) out[r.phase] += r.n; // Home's Merged and Closed tiles are today's (UTC), not every item ever closed. const day = new Date().toISOString().slice(0, 10); - const t = (await db.get(db.k.selectFrom("items as i") + const [byPhase, today] = await Promise.all([db.all(db.k.selectFrom("items as i").leftJoin("main.item_plans as p", (j) => j.onRef("p.repo", "=", "i.repo").onRef("p.number", "=", "i.number")) + .select((eb) => [phaseExpr(db, eb).as("phase"), eb.fn.countAll().as("n")]) + .$if(!!hide, (q) => q.where(hide!)).groupBy("phase")), db.get(db.k.selectFrom("items as i") .select((eb) => [ eb.fn.sum(eb.case().when("i.merged_at", ">=", day).then(eb.lit(1)).else(eb.lit(0)).end()).as("merged"), eb.fn.sum(eb.case().when(eb.and([eb("i.merged_at", "is", null), eb("i.closed_at", ">=", day)])).then(eb.lit(1)).else(eb.lit(0)).end()).as("closed"), ]) .where((eb) => eb.or([eb("i.merged_at", ">=", day), eb("i.closed_at", ">=", day)])) - .$if(!!hide, (q) => q.where(hide!))))!; + .$if(!!hide, (q) => q.where(hide!)))]); + for (const r of byPhase) if (r.phase in out) out[r.phase] += r.n; + const t = today!; out.Merged = t.merged ?? 0; out.Closed = t.closed ?? 0; return out; @@ -60,7 +60,13 @@ async function needs(db: Db, req: Req, hidden: HiddenRepos, staff: boolean, page if (counts.stopped) byKind.stopped = counts.stopped; if (!staff) return { total, byKind, oldest: [] }; - const oldest = await db.all(db.k.selectFrom("decisions").select(kx.cols("decisions")).$narrowType<{ kind: DecisionRow["kind"] }>().where(where).orderBy("asked_at").orderBy("id").limit(OLDEST)); + const fhide = excludeHiddenExpr(db, "repo", hidden); + const findings = () => db.k.selectFrom("security_findings").where("state", "=", "new").where("severity", "in", ["high", "critical"]).$if(!!fhide, (q) => q.where(fhide!)); + const [oldest, fcRow, foundRows] = await Promise.all([ + db.all(db.k.selectFrom("decisions").select(kx.cols("decisions")).$narrowType<{ kind: DecisionRow["kind"] }>().where(where).orderBy("asked_at").orderBy("id").limit(OLDEST)), + db.get(findings().select((eb) => eb.fn.countAll().as("n"))), + db.all(findings().select(["repo", "number", "title", "created_at"]).orderBy("created_at").orderBy("number").limit(OLDEST)), + ]); const items = await itemsByRef(db, oldest.flatMap((d) => (d.number !== null && d.repo ? [[d.repo, d.number] as [string, number]] : []))); const asked: HomeNeed[] = oldest.map((d) => { const it = d.number !== null && d.repo ? items.get(`${d.repo}#${d.number}`) : undefined; @@ -71,10 +77,8 @@ async function needs(db: Db, req: Req, hidden: HiddenRepos, staff: boolean, page }; }); - const fhide = excludeHiddenExpr(db, "repo", hidden); - const findings = () => db.k.selectFrom("security_findings").where("state", "=", "new").where("severity", "in", ["high", "critical"]).$if(!!fhide, (q) => q.where(fhide!)); - const fc = (await db.get(findings().select((eb) => eb.fn.countAll().as("n"))))!.n; - const found: HomeNeed[] = (await db.all(findings().select(["repo", "number", "title", "created_at"]).orderBy("created_at").orderBy("number").limit(OLDEST))) + const fc = fcRow!.n; + const found: HomeNeed[] = foundRows .map((f) => ({ id: `finding:${f.repo}:${f.number}`, kind: "security" as const, repo: f.repo, number: f.number, title: f.title, recommendation: null, askedAt: f.created_at, itemKind: null, to: `/security/${f.repo}/${f.number}` })); if (fc) byKind.security = fc; return { total, byKind, oldest: [...asked, ...found].sort((a, b) => a.askedAt.localeCompare(b.askedAt)).slice(0, OLDEST) }; @@ -85,19 +89,22 @@ async function problems(db: Db, hidden: string[], staff: boolean, stops: NeedsSt for (const s of stops) out.push({ kind: "stopped", title: s.title, detail: staff ? s.reason : "", to: "/needs/stopped" }); const seen = new Set(stops.map((s) => s.id)); // The health list repeats breakers, limits and paused accounts; those are the stopped rows above. - for (const p of (await healthOf(db, hidden, staff, Date.now())).problems) - if (!seen.has(p.id)) out.push({ kind: p.area === "deadline" ? "stuck" : "health", title: p.text, detail: "", to: p.to }); - if (staff) { - const fhide = excludeHiddenExpr(db, "repo", hidden); - for (const f of await db.all(db.k.selectFrom("security_findings").select(["repo", "number", "fix_attempts", "last_failure"]).$narrowType<{ last_failure: NotNull }>() - .where("state", "=", "new").where("last_failure", "is not", null).$if(!!fhide, (q) => q.where(fhide!)).orderBy("updated_at", "desc"))) - out.push({ kind: "gave-up", title: `${f.repo} finding ${f.number}: fix gave up after ${f.fix_attempts} round${f.fix_attempts === 1 ? "" : "s"}`, detail: f.last_failure, to: `/security/${f.repo}/${f.number}` }); - const ihide = excludeHiddenExpr(db, "i.repo", hidden); - for (const r of await db.all(db.k.selectFrom("item_plans as p").innerJoin("items as i", (j) => j.onRef("i.repo", "=", "p.repo").onRef("i.number", "=", "p.number")) + const fhide = excludeHiddenExpr(db, "repo", hidden); + const ihide = excludeHiddenExpr(db, "i.repo", hidden); + const [health, gaveUp, cifixFailed] = await Promise.all([ + healthOf(db, hidden, staff, Date.now()), + staff ? db.all(db.k.selectFrom("security_findings").select(["repo", "number", "fix_attempts", "last_failure"]).$narrowType<{ last_failure: NotNull }>() + .where("state", "=", "new").where("last_failure", "is not", null).$if(!!fhide, (q) => q.where(fhide!)).orderBy("updated_at", "desc")) : [], + staff ? db.all(db.k.selectFrom("item_plans as p").innerJoin("items as i", (j) => j.onRef("i.repo", "=", "p.repo").onRef("i.number", "=", "p.number")) .select(["p.repo", "p.number", "i.title"]).where("i.state", "=", "OPEN").where((eb) => eb(kx.jsonText(db, "p.view", "$.cifix"), "=", "cifix-failed")) - .$if(!!ihide, (q) => q.where(ihide!)).orderBy("p.planned_at", "desc").limit(20))) - out.push({ kind: "gave-up", title: `${r.repo}#${r.number}: CI fix gave up`, detail: r.title ?? "", to: itemPath(r.repo, r.number) }); - } + .$if(!!ihide, (q) => q.where(ihide!)).orderBy("p.planned_at", "desc").limit(20)) : [], + ]); + for (const p of health.problems) + if (!seen.has(p.id)) out.push({ kind: p.area === "deadline" ? "stuck" : "health", title: p.text, detail: "", to: p.to }); + for (const f of gaveUp) + out.push({ kind: "gave-up", title: `${f.repo} finding ${f.number}: fix gave up after ${f.fix_attempts} round${f.fix_attempts === 1 ? "" : "s"}`, detail: f.last_failure, to: `/security/${f.repo}/${f.number}` }); + for (const r of cifixFailed) + out.push({ kind: "gave-up", title: `${r.repo}#${r.number}: CI fix gave up`, detail: r.title ?? "", to: itemPath(r.repo, r.number) }); return out; } @@ -139,10 +146,14 @@ async function done(db: Db, hidden: string[]): Promise { async function running(db: Db, hidden: string[]): Promise { const hide = excludeHiddenExpr(db, "repo", hidden); - const jobs = (await db.get(db.k.selectFrom("jobs").select((eb) => eb.fn.countAll().as("n")).where("state", "=", "running") - .$if(!!hide, (q) => q.where((eb) => eb.or([eb("repo", "is", null), hide!])))))!.n; const bhide = excludeHiddenExpr(db, "repo", hidden); - const batches = (await db.all(db.k.selectFrom("merge_batches").select("id").where("state", "=", "checking").$if(!!bhide, (q) => q.where(bhide!)).orderBy("id"))).map((b) => `#${b.id}`); + const [jobRow, batchRows] = await Promise.all([ + db.get(db.k.selectFrom("jobs").select((eb) => eb.fn.countAll().as("n")).where("state", "=", "running") + .$if(!!hide, (q) => q.where((eb) => eb.or([eb("repo", "is", null), hide!])))), + db.all(db.k.selectFrom("merge_batches").select("id").where("state", "=", "checking").$if(!!bhide, (q) => q.where(bhide!)).orderBy("id")), + ]); + const jobs = jobRow!.n; + const batches = batchRows.map((b) => `#${b.id}`); const parts = [jobs ? `${jobs} job${jobs === 1 ? "" : "s"} running` : "", batches.length ? `batch${batches.length === 1 ? "" : "es"} ${batches.join(", ")} checking` : ""].filter(Boolean); return parts.length ? parts.join(", ") : "Nothing running"; } @@ -171,16 +182,21 @@ async function byAutoCraftPct(db: Db, hidden: string[], since: string): Promise< export async function home(db: Db, req: Req, deps: Deps): Promise { const hidden = await hiddenRepos(db, req); const staff = canSeeInternals(req); - const pg = await deps.progress(hidden); + // The parts read independently, so they run together. + const [pg, page, phasesNow, runningNow, spend, doneNow] = await Promise.all([ + deps.progress(hidden), + // The Needs page's stopped rows are the problems list's first rows. + needsPage(db, req), + phases(db, hidden), running(db, hidden), spendToday(db, hidden), done(db, hidden), + ]); const start = pg.repos.reduce((s, r) => s + (r.openTrend[0] ?? 0), 0); - // The Needs page's stopped rows are the problems list's first rows. - const page = await needsPage(db, req); + const [needsNow, problemsNow, pct] = await Promise.all([needs(db, req, hidden, staff, page), problems(db, hidden, staff, page.stopped), byAutoCraftPct(db, hidden, pg.trackingSince)]); return { - needs: await needs(db, req, hidden, staff, page), - problems: await problems(db, hidden, staff, page.stopped), - phases: await phases(db, hidden), - running: await running(db, hidden), - progress: { openNow: pg.funnel.open, openAtStart: start, done24h: pg.perHour.reduce((a, b) => a + b, 0), byAutoCraftPct: await byAutoCraftPct(db, hidden, pg.trackingSince), perHour: pg.perHour, spendTodayUsd: await spendToday(db, hidden) }, - done: await done(db, hidden), + needs: needsNow, + problems: problemsNow, + phases: phasesNow, + running: runningNow, + progress: { openNow: pg.funnel.open, openAtStart: start, done24h: pg.perHour.reduce((a, b) => a + b, 0), byAutoCraftPct: pct, perHour: pg.perHour, spendTodayUsd: spend }, + done: doneNow, }; } diff --git a/src/dash/api/index.ts b/src/dash/api/index.ts index 9bc1e2e7b..0163b9531 100644 --- a/src/dash/api/index.ts +++ b/src/dash/api/index.ts @@ -125,29 +125,45 @@ export async function itemCore(db: Db, req: Req): Promise { const repo = req.params.repo!; const n = Number(req.params.n); if (!Number.isInteger(n)) throw new HttpError(400, "not an item number"); - await needVisible(db, req, repo); - const it = await db.get(db.k.selectFrom("items").select(kx.cols("items")).where("repo", "=", repo).where("number", "=", n)); + // The visibility check decides first: an item of a hidden repo is a 404 for its repo whether or not the mirror has it. + const [, it] = await Promise.all([needVisible(db, req, repo), db.get(db.k.selectFrom("items").select(kx.cols("items")).where("repo", "=", repo).where("number", "=", n))]); if (!it) throw new HttpError(404, `no item ${repo}#${n} in the mirror`); - const c = it.author ? (await contributors(db, { login: it.author })).find((x) => x.login === it.author) : undefined; let labels: string[] = []; try { const l = JSON.parse(it.labels ?? "[]") as unknown; if (Array.isArray(l)) labels = l.filter((x): x is string => typeof x === "string"); } catch { /* malformed: no labels */ } - const stages = await db.all(db.k.selectFrom("stages").select(["stage", "at", "actor as by", "note"]).where("repo", "=", repo).where("number", "=", n) - .orderBy("at").orderBy(kx.rowid("stages")).$narrowType<{ stage: Item["stages"][number]["stage"] }>()); - const comments = await db.all(db.k.selectFrom("comments").select(["id", "author", "created_at as at", "body", "kind", "review_state as reviewState"]) - .where("repo", "=", repo).where("number", "=", n) - .where((eb) => eb.not(eb.and([eb("kind", "=", "review"), eb(eb.fn.coalesce(eb.fn("trim", ["body"]), eb.val("")), "=", "")]))) - .orderBy("created_at", (o) => o.asc().nullsFirst()).orderBy(kx.rowid("comments")).$narrowType<{ kind: ItemComment["kind"] | null }>()); - const decisionIds = (await db.all(db.k.selectFrom("decisions").select("id").where((eb) => eb.or([ - eb.and([eb("repo", "=", repo), eb("number", "=", n)]), - eb.and([eb("number", "is", null), eb.exists( - db.k.selectFrom(kx.jsonEach(db, eb.case().when(kx.jsonValid(db, "items")).then(eb.ref("items")).else("[]").end(), "j")).select(eb.lit(1).as("one")) - .where((e) => e.and([e(kx.jsonText(db, "j.value", "$.repo"), "=", repo), e(kx.jsonNum(db, "j.value", "$.number"), "=", n)])))]), - ])).orderBy("asked_at"))).map((r) => r.id); + const internals = canSeeInternals(req); + const pr = it.kind === "pr"; + // The parts read independently, so they run together. + const [c, stages, comments, decisionIds, quiet, files, ciChecks, tracked, related, classifications, area, discordOf, settled, priority, work, checks, reviews, premerge, postmerge, actions, releases, slots, preapproval] = await Promise.all([ + it.author ? contributors(db, { login: it.author }).then((cs) => cs.find((x) => x.login === it.author)) : undefined, + db.all(db.k.selectFrom("stages").select(["stage", "at", "actor as by", "note"]).where("repo", "=", repo).where("number", "=", n) + .orderBy("at").orderBy(kx.rowid("stages")).$narrowType<{ stage: Item["stages"][number]["stage"] }>()), + db.all(db.k.selectFrom("comments").select(["id", "author", "created_at as at", "body", "kind", "review_state as reviewState"]) + .where("repo", "=", repo).where("number", "=", n) + .where((eb) => eb.not(eb.and([eb("kind", "=", "review"), eb(eb.fn.coalesce(eb.fn("trim", ["body"]), eb.val("")), "=", "")]))) + .orderBy("created_at", (o) => o.asc().nullsFirst()).orderBy(kx.rowid("comments")).$narrowType<{ kind: ItemComment["kind"] | null }>()), + db.all(db.k.selectFrom("decisions").select("id").where((eb) => eb.or([ + eb.and([eb("repo", "=", repo), eb("number", "=", n)]), + eb.and([eb("number", "is", null), eb.exists( + db.k.selectFrom(kx.jsonEach(db, eb.case().when(kx.jsonValid(db, "items")).then(eb.ref("items")).else("[]").end(), "j")).select(eb.lit(1).as("one")) + .where((e) => e.and([e(kx.jsonText(db, "j.value", "$.repo"), "=", repo), e(kx.jsonNum(db, "j.value", "$.number"), "=", n)])))]), + ])).orderBy("asked_at")).then((rows) => rows.map((r) => r.id)), + isQuiet(db, repo, n), + pr ? filesOf(db, repo, n) : [], pr ? ciChecksOf(db, repo, n) : [], + db.get(db.k.selectFrom("tracked_repos").select("pipeline").where("name", "=", repo)), + relatedOf(db, repo, n), classificationsOf(db, repo, n), areaNameOf(db, repo, n), discord.discordOf(db, repo, n), settledOf(db, repo, n), priorityOf(db, repo, n), + pr ? prWork(db, repo, n, internals) : { verification: null, fixups: [], prBuild: null }, + checksOf(db, repo, n), + pr ? hiddenRepos(db, req).then((hidden) => reviewsOf(db, repo, n, internals, hidden)) : null, + pr ? premergeOf(db, repo, n) : [], pr ? postmergeOf(db, repo, n, internals) : null, + actionsOf(db, repo, n), releasesOf(db, repo, n), + visibleRepos(db, req).then((v) => queueSlots(db, v)), + pr ? preapprovalOf(db, repo, n) : null, + ]); // The quiet pull request of a security fix: viewers get none of the model text about it. - const veil = !canSeeInternals(req) && await isQuiet(db, repo, n); + const veil = !internals && quiet; const out: Item = { repo, number: n, kind: it.kind === "pr" ? "pr" : "issue", title: it.title ?? "", body: it.body ?? "", state: itemState(it.state), author: it.author ?? "", @@ -160,24 +176,24 @@ export async function itemCore(db: Db, req: Req): Promise { mergeable: MERGEABLE[it.mergeable ?? ""] ?? "unknown", labels, createdAt: it.created_at ?? "", updatedAt: it.updated_at ?? "", closedAt: it.closed_at, mergedAt: it.merged_at, mergedBy: it.merged_by, - pipelineOn: (await db.get(db.k.selectFrom("tracked_repos").select("pipeline").where("name", "=", repo)))?.pipeline === 1, - related: await relatedOf(db, repo, n), classifications: await classificationsOf(db, repo, n), area: await areaNameOf(db, repo, n), + pipelineOn: tracked?.pipeline === 1, + related, classifications, area, // Stage notes quote review reasons, verification summaries and fix-up reasons: staff only. - stages: stages.map((s) => ({ ...s, by: s.by ?? "", note: canSeeInternals(req) ? s.note : null })), - discord: await discord.discordOf(db, repo, n), + stages: stages.map((s) => ({ ...s, by: s.by ?? "", note: internals ? s.note : null })), + discord: discordOf, comments: comments.map((x) => ({ ...x, author: x.author ?? "", body: x.body ?? "" })), - decisionIds, settled: unflagged(await settledOf(db, repo, n), await isQuiet(db, repo, n), !veil) as Item["settled"], priority: await priorityOf(db, repo, n), - ...(it.kind === "pr" ? await prWork(db, repo, n, canSeeInternals(req)) : { verification: null, fixups: [], prBuild: null }), + decisionIds, settled: unflagged(settled, quiet, !veil) as Item["settled"], priority, + ...work, // The reviewer's reasons quote the patch, so viewers get the verdict only. - patchChecks: (await checksOf(db, repo, n)).map(({ kind, subject, patchHash, round, verdict, reasons, problems, model, createdAt }) => - ({ kind, subject, patchHash, round, verdict, reasons: canSeeInternals(req) ? reasons : "", problems: canSeeInternals(req) ? problems : [], model, createdAt })), - reviews: it.kind === "pr" ? await reviewsOf(db, repo, n, canSeeInternals(req), await hiddenRepos(db, req)) : null, - premerge: it.kind === "pr" ? await premergeOf(db, repo, n) : [], - postmerge: it.kind === "pr" ? await postmergeOf(db, repo, n, canSeeInternals(req)) : null, - actions: await actionsOf(db, repo, n), releases: await releasesOf(db, repo, n), - queue: (await queueSlots(db, await visibleRepos(db, req))).get(`${repo}#${n}`) ?? null, + patchChecks: checks.map(({ kind, subject, patchHash, round, verdict, reasons, problems, model, createdAt }) => + ({ kind, subject, patchHash, round, verdict, reasons: internals ? reasons : "", problems: internals ? problems : [], model, createdAt })), + reviews, + premerge, + postmerge, + actions, releases, + queue: slots.get(`${repo}#${n}`) ?? null, // The operator's instructions are shown to those who see the internals only. - ...(it.kind === "pr" ? { preapproval: ((p) => (p && !canSeeInternals(req) ? { ...p, instructions: "" } : p))(await preapprovalOf(db, repo, n)) } : {}), + ...(pr ? { preapproval: preapproval && !internals ? { ...preapproval, instructions: "" } : preapproval } : {}), }; if (!veil) return out; return { diff --git a/src/dash/api/item-bar.ts b/src/dash/api/item-bar.ts index df828a0e2..2543ca334 100644 --- a/src/dash/api/item-bar.ts +++ b/src/dash/api/item-bar.ts @@ -145,30 +145,34 @@ export async function barOf(c: Ctx, it: { kind: ItemKind; state: ItemState; merg if (c.veiled) return { headline: { tone: "idle", text: status.phase, next: null, model: null, startedAt: null, jobId: null }, steps: [] }; // A job_items row of a running job means the item is finished, so running work is matched by the job's params and by the item's own running calls. - const active = await db.all(db.k.selectFrom("jobs").select(["id", "step", "state", "started_at"]) - .where("state", "in", ["running", "queued"]).where("repo", "=", repo).where((eb) => eb(kx.jsonNum(db, "params", "$.number"), "=", n)).orderBy("id")); - const runs = await db.all(db.k.selectFrom("agent_run_items as i").innerJoin("agent_runs as r", "r.id", "i.run_id").select(["r.step", "r.model", "r.job_id", "r.started_at"]) - .where("i.repo", "=", repo).where("i.number", "=", n).where("r.state", "=", "running").orderBy("r.id")); + const open = it.state === "open"; + // The bar's reads do not depend on each other, so they run together. + const [active, runs, mergedByUs, costRows, pre] = await Promise.all([ + db.all(db.k.selectFrom("jobs").select(["id", "step", "state", "started_at"]) + .where("state", "in", ["running", "queued"]).where("repo", "=", repo).where((eb) => eb(kx.jsonNum(db, "params", "$.number"), "=", n)).orderBy("id")), + db.all(db.k.selectFrom("agent_run_items as i").innerJoin("agent_runs as r", "r.id", "i.run_id").select(["r.step", "r.model", "r.job_id", "r.started_at"]) + .where("i.repo", "=", repo).where("i.number", "=", n).where("r.state", "=", "running").orderBy("r.id")), + it.state === "merged" && db.get(db.k.selectFrom("merges").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", n).where("outcome", "=", "merged").limit(1)).then((r) => r !== undefined), + db.all(db.k.selectFrom("agent_run_items as i").innerJoin("agent_runs as r", "r.id", "i.run_id").select(["r.step", "r.cost_usd as cost"]).$narrowType<{ cost: NotNull }>() + .where("i.repo", "=", repo).where("i.number", "=", n).where("r.cost_usd", "is not", null).where((eb) => hiddenExpr(db, eb, c.hidden) ?? eb.lit(true)).orderBy("i.run_id")), + open ? db.get(db.k.selectFrom("preapprovals").select(["state", "reason"]).where("repo", "=", repo).where("number", "=", n).orderBy("id", "desc").limit(1)) : undefined, + ]); const job = active.find((j) => j.state === "running"); const run = runs.find((r) => job && r.job_id === job.id) ?? runs[0]; const queued = active.find((j) => j.state === "queued"); - const mergedByUs = it.state === "merged" && await db.get(db.k.selectFrom("merges").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", n).where("outcome", "=", "merged").limit(1)) !== undefined; const evidence = await evidenceOf(c, it.mergedAt, mergedByUs); const costs = new Map(); - for (const r of await db.all(db.k.selectFrom("agent_run_items as i").innerJoin("agent_runs as r", "r.id", "i.run_id").select(["r.step", "r.cost_usd as cost"]).$narrowType<{ cost: NotNull }>() - .where("i.repo", "=", repo).where("i.number", "=", n).where("r.cost_usd", "is not", null).where((eb) => hiddenExpr(db, eb, c.hidden) ?? eb.lit(true)).orderBy("i.run_id"))) { + for (const r of costRows) { const id = stageOfStep(r.step)?.id; if (id) costs.set(id, (costs.get(id) ?? 0) + r.cost); } const runningStep = job?.step ?? run?.step ?? null; - const open = it.state === "open"; const phaseStage = PHASE_STAGE[status.phase]; const latestFail = [...evidence].filter((e) => e.state === "failed").sort((a, b) => (a.at < b.at ? 1 : -1)) .find((f) => !evidence.some((e) => e.stage === f.stage && e.state === "done" && e.at > f.at) && (!phaseStage || f.stage === phaseStage || Date.now() - Date.parse(f.at) < RECENT_MS)); // A failed pre-approval heads the bar until a newer one replaces it or the PR merges. - const pre = open ? await db.get(db.k.selectFrom("preapprovals").select(["state", "reason"]).where("repo", "=", repo).where("number", "=", n).orderBy("id", "desc").limit(1)) : undefined; const preFailed = pre?.state === "failed" ? { label: /fix-up/i.test(pre.reason ?? "") ? "Fix-up" : "Pre-approved merge", reason: c.staff && pre.reason ? clip(pre.reason, 160) : null } : null; const current: StageId | null = runningStep ? stageOfStep(runningStep)?.id ?? null : queued ? stageOfStep(queued.step)?.id ?? null : open ? phaseStage ?? null : null; diff --git a/src/dash/api/item-page.ts b/src/dash/api/item-page.ts index 701dcf7dc..72edab2af 100644 --- a/src/dash/api/item-page.ts +++ b/src/dash/api/item-page.ts @@ -114,30 +114,38 @@ const prBuildOf = async (c: Ctx): Promise => { async function stampOf(c: Ctx, req: Req): Promise { const { db, repo, n, ref } = c; - const parts: unknown[] = [await fingerprint(c, "page"), c.veiled]; - parts.push(...await rowValuesOf(db, extraQueries(db, repo, n))); - parts.push((await queueSlots(db, await visibleRepos(db, req))).get(ref) ?? null, await discordOf(db, repo, n), await releasesOf(db, repo, n), await prBuildOf(c), await backlogOf(c, req)); + const [print, extra, slots, discord, releases, prBuild, backlog] = await Promise.all([fingerprint(c, "page"), rowValuesOf(db, extraQueries(db, repo, n)), + visibleRepos(db, req).then((v) => queueSlots(db, v)), discordOf(db, repo, n), releasesOf(db, repo, n), prBuildOf(c), backlogOf(c, req)]); + const parts: unknown[] = [print, c.veiled, ...extra, slots.get(ref) ?? null, discord, releases, prBuild, backlog]; return createHash("sha1").update(JSON.stringify(parts)).digest("hex").slice(0, 16); } // ---- header and status ----------------------------------------------------------------------------------------------- -const backlogOf = async (c: Ctx, req: Req): Promise => - ({ held: await backlogHeld(c.db, c.repo, c.n), canSettle: await canSettleCached(c.db, req.user.login, req.user.role, [c.repo]) }); +const backlogOf = async (c: Ctx, req: Req): Promise => { + const [held, canSettle] = await Promise.all([backlogHeld(c.db, c.repo, c.n), canSettleCached(c.db, req.user.login, req.user.role, [c.repo])]); + return { held, canSettle }; +}; async function headerOf(c: Ctx, it: Item, queue: QueueSlot | null, req: Req): Promise { const { db, repo, n } = c; const lines = it.additions + it.deletions; - const assignees = arr((await db.get(db.k.selectFrom("items").select("assignees").where("repo", "=", repo).where("number", "=", n)))!.assignees).filter((x) => typeof x === "string"); + const [row, fast, hold, backlog] = await Promise.all([ + db.get(db.k.selectFrom("items").select("assignees").where("repo", "=", repo).where("number", "=", n)), + db.get(db.k.selectFrom("main.fast_track").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", n)), + db.get(db.k.selectFrom("main.merge_holds").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", n)), + backlogOf(c, req), + ]); + const assignees = arr(row!.assignees).filter((x) => typeof x === "string"); const pre = it.kind === "pr" ? (it as { preapproval?: Preapproval | null }).preapproval ?? null : null; return { labels: it.labels, assignees, autocraftAssigned: c.box !== "" && assignees.includes(c.box), pipelineOn: it.pipelineOn === true, discord: it.discord ?? null, queue, - fastTracked: await db.get(db.k.selectFrom("main.fast_track").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", n)) !== undefined, - held: await db.get(db.k.selectFrom("main.merge_holds").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", n)) !== undefined, + fastTracked: fast !== undefined, + held: hold !== undefined, preapproval: pre, releases: it.releases, tier: it.tier, size: it.kind !== "pr" ? null : lines < 50 ? "S" : lines < 300 ? "M" : lines < 1000 ? "L" : "XL", - backlog: await backlogOf(c, req), + backlog, }; } @@ -157,13 +165,17 @@ type ReviewRow = { key: string; head_oid: string; at: string; model: string | nu async function reviewsOf(c: Ctx, headNow: string | null, events: Ev[]): Promise { const { db, repo, n } = c; - const rows: (ReviewRow & { rowid: number })[] = (await db.all(db.k.selectFrom("opus_review_history") - .select([rowid("opus_review_history").as("rowid"), "head_oid", "at", "model", "verdict", "sure", "reason", "summary", "risks", "fixes", "claims", "blocked_by", "trigger"]) - .where("repo", "=", repo).where("number", "=", n).where("verdict", "is not", null))).map((r) => ({ ...r, key: `opus:${r.rowid}` })); + const [history, latest] = await Promise.all([ + db.all(db.k.selectFrom("opus_review_history") + .select([rowid("opus_review_history").as("rowid"), "head_oid", "at", "model", "verdict", "sure", "reason", "summary", "risks", "fixes", "claims", "blocked_by", "trigger"]) + .where("repo", "=", repo).where("number", "=", n).where("verdict", "is not", null)), + db.all(db.k.selectFrom("opus_reviews").select(["head_oid", "at", "model", "verdict", "sure", "reason", "risks", "fixes", "claims"]) + .where("repo", "=", repo).where("number", "=", n).where("verdict", "is not", null).orderBy("head_oid")), + ]); + const rows: (ReviewRow & { rowid: number })[] = history.map((r) => ({ ...r, key: `opus:${r.rowid}` })); // Reviews stored before the history table existed. const seen = new Set(rows.map((r) => `${r.head_oid}|${r.at}`)); - for (const r of await db.all(db.k.selectFrom("opus_reviews").select(["head_oid", "at", "model", "verdict", "sure", "reason", "risks", "fixes", "claims"]) - .where("repo", "=", repo).where("number", "=", n).where("verdict", "is not", null).orderBy("head_oid"))) + for (const r of latest) if (!seen.has(`${r.head_oid}|${r.at}`)) rows.push({ ...r, key: `opus-latest:${r.head_oid}`, summary: null, blocked_by: null, trigger: null, rowid: 0 }); rows.sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : b.rowid - a.rowid)); const costs = new Map(events.filter((e) => e.kind === "review").map((e) => [e.id, e.costUsd ?? 0])); @@ -203,14 +215,23 @@ const writeType = (action: string): GithubEvent["type"] => async function githubOf(c: Ctx, it: Item, ev: Ev[], url: string, syncedAt: string | null): Promise { const { db, repo, n } = c; const events: GithubEvent[] = []; - const writes = (await writesOf(db, repo, n)).filter((w) => w.state !== "failed"); + // The GitHub side's reads do not depend on each other, so they run together. + const [allWrites, comments, acts, pushed, commitRows] = await Promise.all([ + writesOf(db, repo, n), + db.all(db.k.selectFrom("comments").select(["id", "kind", "author", "created_at", "body", "review_state"]).where("repo", "=", repo).where("number", "=", n) + .where("created_at", "is not", null).$narrowType<{ created_at: string }>() + .where((eb) => eb.not(eb.and([eb("kind", "=", "review"), eb(eb.fn.coalesce(eb.fn("trim", ["body"]), eb.val("")), "=", "")])))), + db.all(db.k.selectFrom("item_activity").select(["id", "kind", "at", "actor", "label", "before_oid", "after_oid"]).where("repo", "=", repo).where("number", "=", n).orderBy("id")), + pushedCommits(db, repo, n), + db.all(db.k.selectFrom("pr_commits") + .select((eb) => ["oid", "message", "author", least(db, ["committed_at", eb.fn.coalesce("first_seen_at", "committed_at")], "text").as("at")]) + .$narrowType<{ at: string }>().where("repo", "=", repo).where("number", "=", n).orderBy("at").orderBy("oid")), + ]); + const writes = allWrites.filter((w) => w.state !== "failed"); const summaryOf = new Map(ev.filter((e) => e.kind === "write").map((e) => [e.id, e.summary])); const byComment = new Map(writes.filter((w) => w.comment).map((w) => [w.comment!.id, w])); const used = new Set(); const own = c.own; - const comments = await db.all(db.k.selectFrom("comments").select(["id", "kind", "author", "created_at", "body", "review_state"]).where("repo", "=", repo).where("number", "=", n) - .where("created_at", "is not", null).$narrowType<{ created_at: string }>() - .where((eb) => eb.not(eb.and([eb("kind", "=", "review"), eb(eb.fn.coalesce(eb.fn("trim", ["body"]), eb.val("")), "=", "")])))); if (it.createdAt) events.push({ id: "gh:opened", type: "opened", at: it.createdAt, actor: it.author, body: clean(it.body, 1500), autocraft: null }); for (const m of comments) { const w = byComment.get(m.id); @@ -221,7 +242,6 @@ async function githubOf(c: Ctx, it: Item, ev: Ev[], url: string, syncedAt: strin body: clean(m.body ?? ""), autocraft: ours ? { as: asOf(w), historyId: w ? `audit:${w.rowid}` : `comment:${m.id}` } : null, }); } - const acts = await db.all(db.k.selectFrom("item_activity").select(["id", "kind", "at", "actor", "label", "before_oid", "after_oid"]).where("repo", "=", repo).where("number", "=", n).orderBy("id")); const labelWrites = writes.filter((w) => w.action === "labels-apply" || w.action === "act-unlabel"); for (const a of acts) { const ours = !!a.actor && own.has(a.actor); @@ -243,10 +263,7 @@ async function githubOf(c: Ctx, it: Item, ev: Ev[], url: string, syncedAt: strin events.push({ id: `audit:${w.rowid}`, type: writeType(w.action), at: w.at, actor: "autocraft", body: summaryOf.get(`audit:${w.rowid}`) ?? GITHUB_ACTIONS[w.action] ?? w.action, autocraft: { as: asOf(w), historyId: `audit:${w.rowid}` } }); } events.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : a.id < b.id ? -1 : 1)); - const pushed = await pushedCommits(db, repo, n); - const commits = (await db.all(db.k.selectFrom("pr_commits") - .select((eb) => ["oid", "message", "author", least(db, ["committed_at", eb.fn.coalesce("first_seen_at", "committed_at")], "text").as("at")]) - .$narrowType<{ at: string }>().where("repo", "=", repo).where("number", "=", n).orderBy("at").orderBy("oid"))) + const commits = commitRows .map((m) => ({ sha: short(m.oid), message: clean(m.message ?? "", 500), author: m.author ?? "unknown", at: m.at, byAutoCraft: (!!m.author && own.has(m.author)) || pushed.has(m.oid) })); return { description: clean(it.body, 6000), events, checks: it.ciChecks.filter((x) => x.state !== "none").map((x) => ({ name: x.name, state: x.state })), commits, @@ -263,7 +280,7 @@ async function screenshotsOf(c: Ctx, headNow: string | null): Promise> => new Set(id === null ? [] : (await c.db.all(c.db.k.selectFrom("build_artifacts").select("name").where("task_id", "=", id).where("content_type", "=", "image/png"))).map((x) => x.name)); - const before = await names(r.base_task_id), after = await names(r.head_task_id); + const [before, after] = await Promise.all([names(r.base_task_id), names(r.head_task_id)]); const shots = [...after].filter((n) => before.has(n)).sort((a, b) => parseInt(a.slice(1), 10) - parseInt(b.slice(1), 10)) .map((name) => ({ name, before: { taskId: r.base_task_id!, name }, after: { taskId: r.head_task_id!, name } })); return [{ @@ -278,20 +295,28 @@ export async function itemPage(db: Db, req: Req): Promise eb.selectFrom("item_reads as r").select("r.synced_at").whereRef("r.repo", "=", "items.repo").whereRef("r.number", "=", "items.number").as("synced_at")]) - .where("repo", "=", c.repo).where("number", "=", c.n)))!; - const cost = (await db.get(db.k.selectFrom("agent_run_items as i").innerJoin("agent_runs as r", "r.id", "i.run_id").select((eb) => eb.fn.coalesce(eb.fn.sum("r.cost_usd"), eb.lit(0)).as("cost")) - .where("i.repo", "=", c.repo).where("i.number", "=", c.n).$if(filtered(c.hidden), (q) => q.where((eb) => hiddenExpr(db, eb, c.hidden)!))))!.cost; - const status = await statusOf(c, it); + // The parts read independently, so they run together. + const [it, ev, row, cost] = await Promise.all([ + itemCore(db, req), gather(c, null), + db.get(db.k.selectFrom("items").select(["url", "head_oid", (eb) => eb.selectFrom("item_reads as r").select("r.synced_at").whereRef("r.repo", "=", "items.repo").whereRef("r.number", "=", "items.number").as("synced_at")]) + .where("repo", "=", c.repo).where("number", "=", c.n)).then((r) => r!), + db.get(db.k.selectFrom("agent_run_items as i").innerJoin("agent_runs as r", "r.id", "i.run_id").select((eb) => eb.fn.coalesce(eb.fn.sum("r.cost_usd"), eb.lit(0)).as("cost")) + .where("i.repo", "=", c.repo).where("i.number", "=", c.n).$if(filtered(c.hidden), (q) => q.where((eb) => hiddenExpr(db, eb, c.hidden)!))).then((r) => r!.cost), + ]); + const pr = it.kind === "pr"; + const [status, header, reviews, timeline, github, prBuild, screenshots] = await Promise.all([ + statusOf(c, it), headerOf(c, it, it.queue ?? null, req), + pr ? reviewsOf(c, row.head_oid, ev) : { latest: null, earlier: [] }, + (pr ? preapprovalsOf(db, c.repo, c.n) : Promise.resolve([])).then((pre) => timelineOf(c, ev, pre)), + githubOf(c, it, ev, row.url ?? "", row.synced_at), prBuildOf(c), screenshotsOf(c, row.head_oid), + ]); return { repo: c.repo, number: c.n, kind: it.kind, state: it.state, title: it.title, author: it.author, stamp, - header: await headerOf(c, it, it.queue ?? null, req), status, bar: await barOf(c, { kind: it.kind, state: it.state, mergedAt: it.mergedAt, pipelineOn: it.pipelineOn === true }, status), costUsd: cost, - reviews: it.kind === "pr" ? await reviewsOf(c, row.head_oid, ev) : { latest: null, earlier: [] }, - timeline: (await timelineOf(c, ev, it.kind === "pr" ? await preapprovalsOf(db, c.repo, c.n) : [])).slice(-200), - github: await githubOf(c, it, ev, row.url ?? "", row.synced_at), - prBuild: await prBuildOf(c), - screenshots: await screenshotsOf(c, row.head_oid), + header, status, bar: await barOf(c, { kind: it.kind, state: it.state, mergedAt: it.mergedAt, pipelineOn: it.pipelineOn === true }, status), costUsd: cost, + reviews, + timeline: timeline.slice(-200), + github, + prBuild, + screenshots, }; } diff --git a/src/dash/api/needs.ts b/src/dash/api/needs.ts index da649a648..b6c410562 100644 --- a/src/dash/api/needs.ts +++ b/src/dash/api/needs.ts @@ -20,6 +20,7 @@ import type { SelectQueryBuilder, SqlBool } from "kysely"; import { filterSeq, mapSeq, reduceSeq } from "../../async-seq.ts"; import type { Db } from "../../db/index.ts"; import * as kx from "../../db/kx.ts"; +import { setting } from "../../settings-read.ts"; export const NEEDS_PAGE = 30; /** Older feedback is not asked for any more; the window also bounds the scans. */ @@ -92,7 +93,7 @@ const feedbackUnion = (db: Db, w: Window): Source => { return union; }; -const ownLogin = async (db: Db): Promise => (await db.get(db.k.selectFrom("main.settings").select("value").where("key", "=", "pipeline_login")))?.value ?? ""; +const ownLogin = async (db: Db): Promise => (await setting(db, "pipeline_login")) ?? ""; /** True when a feedback row is about a quiet pull request: its item, or any item of its decision (batch and duplicate-group members too). */ async function quietRow(db: Db, r: Pick, memo: Map): Promise { @@ -107,7 +108,8 @@ async function quietRow(db: Db, r: Pick, me } async function feedback(db: Db, hidden: HiddenRepos, cursor: { at: string; id: string } | null, limit: number, staff: boolean): Promise<{ rows: Raw[]; more: boolean; unhandled: number }> { - const window = { since: new Date(Date.now() - WINDOW_MS).toISOString(), own: await ownLogin(db), owns: [...await allOwnLogins(db)], bots: reviewBots() }; + const [own, owns] = await Promise.all([ownLogin(db), allOwnLogins(db)]); + const window = { since: new Date(Date.now() - WINDOW_MS).toISOString(), own, owns: [...owns], bots: reviewBots() }; const unhiddenRepo = >(q: QB): QB => (filtered(hidden) ? q.where((eb) => eb.or([eb("repo", "is", null), eb.not(hiddenTestExpr(db, "repo", hidden))])) : q) as QB; const size = limit * 3 + 1; @@ -123,6 +125,10 @@ async function feedback(db: Db, hidden: HiddenRepos, cursor: { at: string; id: s } return ok; }; + // The unhandled count reads alongside the page. + const openRead = db.all(unhiddenRepo(db.k.selectFrom(feedbackUnion(db, { ...window, cur: "9999" }).as("u")).select((eb) => ["u.source", eb.fn.max("u.number").as("number"), "u.decision", eb.fn.countAll().as("n")])) + .where((eb) => eb.not(kx.ref("u.handled"))).groupBy(["u.source", (eb) => eb("u.number", "is", null), "u.decision"])); + openRead.catch(() => {}); // Time-ordered, so each source reads its index range; rows that are filtered out make it read on until the page is full. const rows: Raw[] = []; let pos = cursor ?? { at: "9999", id: "\uffff" }; @@ -135,8 +141,7 @@ async function feedback(db: Db, hidden: HiddenRepos, cursor: { at: string; id: s if (batch.length < size || !tail) break; pos = { at: tail.at, id: tail.id }; } - const open = await db.all(unhiddenRepo(db.k.selectFrom(feedbackUnion(db, { ...window, cur: "9999" }).as("u")).select((eb) => ["u.source", eb.fn.max("u.number").as("number"), "u.decision", eb.fn.countAll().as("n")])) - .where((eb) => eb.not(kx.ref("u.handled"))).groupBy(["u.source", (eb) => eb("u.number", "is", null), "u.decision"])); + const open = await openRead; const unhandled = await reduceSeq(open, async (sum, r) => sum + (await visible(r) ? r.n : 0), 0); // What staff wrote about a quiet pull request reaches viewers as the row only, as the decision and conversation APIs give it. const quiet = new Map(); diff --git a/src/dash/api/now.ts b/src/dash/api/now.ts index 9c115f854..3aab35916 100644 --- a/src/dash/api/now.ts +++ b/src/dash/api/now.ts @@ -80,39 +80,44 @@ export async function checkProblems(db: Db, hidden: HiddenRepos, internals: bool } export async function healthOf(db: Db, hidden: HiddenRepos, internals: boolean, nowMs: number): Promise { - const state = await pipelineSwitch(db); - const out: NowProblem[] = []; + const since = new Date(nowMs - HOUR_MS).toISOString(); // Repos with the pipeline off are off by design; their red mains stay on the Main CI page. - const on = await pipelineRepos(db); + const onRead = pipelineRepos(db); + // Every source reads on its own, so they run together; the problems keep this order. + const [state, on, checks, trips, zero, accounts, outage, ci, failed] = await Promise.all([ + pipelineSwitch(db), onRead, checkProblems(db, hidden, internals, nowMs), + db.all(db.k.selectFrom("stage_trips").select(["stage", "reason", "tripped_at"]).where("active", "=", 1).orderBy("tripped_at")), + zeroLimits(db), listAccounts(db), + (async () => (await jevEnabled(db) ? await jevOutage(db) : null))(), + mainCiRepos(db, hidden), + onRead.then((o) => db.all(db.k.selectFrom("jobs").select(["step", (eb) => eb.fn.countAll().as("n")]).where("state", "=", "failed").where("ended_at", ">", since) + .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden, true))) + .where((eb) => eb.or([eb("repo", "is", null), kx.inList(db, "repo", [...o])])) + .groupBy("step").orderBy("n", "desc").orderBy("step"))), + ]); + const out: NowProblem[] = []; const add = (p: NowProblem) => void out.push(p); if (!state.enabled) add({ id: "pipeline", area: "pipeline", tone: "warn", text: `Pipeline is ${state.draining ? "draining" : "off"}${state.changedBy ? `, switched ${state.draining ? "to drain" : "off"} by ${state.changedBy}` : ""}`, to: "/pipeline", since: state.changedAt }); - for (const p of await checkProblems(db, hidden, internals, nowMs)) add(p); + for (const p of checks) add(p); - for (const t of await db.all(db.k.selectFrom("stage_trips").select(["stage", "reason", "tripped_at"]).where("active", "=", 1).orderBy("tripped_at"))) { + for (const t of trips) { const why = blankIfHidden(t.reason, hidden); add({ id: `breaker:${t.stage}`, area: "breaker", tone: "bad", text: `${stepTitle(t.stage)} is stopped by its breaker${why ? `: ${clip(why, 120)}` : ""}`, to: "/pipeline", since: t.tripped_at }); } - for (const l of await zeroLimits(db)) add({ id: `limit:${l.step}`, area: "limit", tone: "warn", text: `${l.title} is paused (limit 0 a day)`, to: "/pipeline", since: null }); + for (const l of zero) add({ id: `limit:${l.step}`, area: "limit", tone: "warn", text: `${l.title} is paused (limit 0 a day)`, to: "/pipeline", since: null }); - for (const a of (await listAccounts(db)).filter((x) => x.enabled)) { + for (const a of accounts.filter((x) => x.enabled)) { if (a.auth.loggedIn === false) add({ id: `account:${a.id}`, area: "account", tone: "bad", text: `Account ${a.label} is signed out`, to: "/accounts", since: null }); else if (a.pausedReason) add({ id: `account:${a.id}`, area: "account", tone: "warn", text: `Account ${a.label} is paused${blankIfHidden(a.pausedReason, hidden) ? `: ${clip(a.pausedReason, 100)}` : ""}`, to: "/accounts", since: null }); } - const outage = await jevEnabled(db) ? await jevOutage(db) : null; if (outage) add({ id: "jev", area: "jev", tone: "warn", text: `Jev is unavailable: ${clip(outage.reason, 100)}`, to: "/accounts", since: outage.since }); - for (const r of (await mainCiRepos(db, hidden)).filter((x) => x.state === "red" && on.has(x.repo))) { + for (const r of ci.filter((x) => x.state === "red" && on.has(x.repo))) { const names = r.failing.map((f) => f.name).slice(0, 2).join(", "); add({ id: `main-ci:${r.repo}`, area: "main-ci", tone: "bad", text: `Main is red in ${r.repo}${names ? `: ${names}` : ""}`, to: "/main-ci", since: r.redSince }); } - const since = new Date(nowMs - HOUR_MS).toISOString(); - const onList = [...on]; - const failed = await db.all(db.k.selectFrom("jobs").select(["step", (eb) => eb.fn.countAll().as("n")]).where("state", "=", "failed").where("ended_at", ">", since) - .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden, true))) - .where((eb) => eb.or([eb("repo", "is", null), kx.inList(db, "repo", onList)])) - .groupBy("step").orderBy("n", "desc").orderBy("step")); const nFailed = failed.reduce((a, f) => a + f.n, 0); if (nFailed) { const steps = failed.slice(0, 3).map((f) => stepTitle(f.step)).join(", "); @@ -173,8 +178,43 @@ async function feed(db: Db, hidden: HiddenRepos, staff: boolean, operator: boole const actions = [...Object.keys(GITHUB_ACTIONS).filter((a) => a !== "merge" && !HOUSEKEEPING.has(a)), ...(staff ? Object.keys(BATCH_ACTIONS) : [])]; // Events of a merge batch (details.batch, or a `repo:branch` target) show as one row per batch and action, linking to the batch page. const batchEvents = new Map(); - const audit = await db.all(db.k.selectFrom("audit").select([kx.rowid("audit").as("rowid"), "at", "login", "action", "target", "details"]).where(kx.inList(db, "action", actions)) - .$if(!!before, (q) => q.where("at", "<", before!)).orderBy("at", "desc").orderBy(kx.rowid("audit"), "desc").limit(SCAN)); + const jobCols = (eb: kx.Eb) => ["id", "step", "state", eb.fn.coalesce("started_at", "requested_at").as("at"), "ended_at", "progress", "summary", "error", "repo", "items", "acted"] as const; + // Every source reads on its own, so the reads run together; the rows are placed below in the order of the sources. + const [audit, merges, running, finished, liveRuns, liveTasks, openBatches, decisions, runs, tasks] = await Promise.all([ + db.all(db.k.selectFrom("audit").select([kx.rowid("audit").as("rowid"), "at", "login", "action", "target", "details"]).where(kx.inList(db, "action", actions)) + .$if(!!before, (q) => q.where("at", "<", before!)).orderBy("at", "desc").orderBy(kx.rowid("audit"), "desc").limit(SCAN)), + db.all(db.k.selectFrom("merges").select([kx.rowid("merges").as("rowid"), "repo", "number", "at", "path", "method"]).where("outcome", "=", "merged") + .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden))) + .$if(!!before, (q) => q.where("at", "<", before!)).orderBy("at", "desc").limit(SCAN)), + // Jobs. Running ones always show on the first page; finished ones by start time. + db.all(db.k.selectFrom("jobs").select((eb) => jobCols(eb)).where("state", "=", "running") + .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden, true))) + .$if(!!before, (q) => q.where((eb) => eb(eb.fn.coalesce("started_at", "requested_at"), "<", before!))).orderBy("id", "desc")), + db.all(db.k.selectFrom("jobs").select((eb) => jobCols(eb)).where("state", "in", ["done", "failed"]).where("started_at", "is not", null) + .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden, true))) + .$if(!!before, (q) => q.where("started_at", "<", before!)).orderBy("started_at", "desc").limit(SCAN)), + before ? [] : db.all(db.k.selectFrom("agent_runs as r").leftJoin("claude_accounts as a", "a.id", "r.account_id") + .select((eb) => ["r.id", "r.job_id", "r.step", "r.model", "r.provider", eb.fn.coalesce("a.label", "r.account_id").as("label"), "r.started_at", "r.progress", "r.item_count", "r.user_login", "r.harness", "r.reported_model"]) + .where("r.state", "=", "running").$if(filtered(hidden), (q) => q.where((eb) => touchesHiddenExpr(db, eb, hidden))).orderBy("r.id")), + before ? [] : db.all(db.k.selectFrom("build_tasks as t").leftJoin("build_envs as e", "e.id", "t.env_id") + .select(["t.id", "t.job_id", "t.step", "t.repo", "t.number", "t.state", "t.queued_at", "t.started_at", "t.summary", "e.label"]) + .where("t.state", "in", ["queued", "claimed", "running"]) + .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "t.repo", hidden))) + .$if(!staff, (q) => q.where((eb) => eb.not(privateStepExpr(eb, "t.step")))).orderBy("t.id")), + before ? [] : db.all(db.k.selectFrom("merge_batches").select(["id", "repo", "branch", "state", "created_at", "summary"]).where("state", "in", ["checking", "open"]) + .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden))).orderBy("id", "desc")), + db.all(db.k.selectFrom("decisions").select(["id", "repo", "number", "items", "question", "answer", "answered_at as at", "answered_by"]).$narrowType<{ at: NotNull }>().where("answered_at", "is not", null) + .$if(!!before, (q) => q.where("answered_at", "<", before!)).orderBy("answered_at", "desc").limit(SCAN)), + // Failed calls and tasks of a job show on the job; only those without one stand alone. + db.all(db.k.selectFrom("agent_runs as r").select((eb) => ["r.id", "r.step", "r.model", eb.fn.coalesce("r.ended_at", "r.started_at").as("at"), "r.error"]) + .where("r.state", "=", "failed").where("r.job_id", "is", null).$if(filtered(hidden), (q) => q.where((eb) => touchesHiddenExpr(db, eb, hidden))) + .$if(!!before, (q) => q.where((eb) => eb(eb.fn.coalesce("r.ended_at", "r.started_at"), "<", before!))).orderBy("at", "desc").limit(SCAN)), + db.all(db.k.selectFrom("build_tasks").select((eb) => ["id", "step", "repo", "number", "state", eb.fn.coalesce("ended_at", "queued_at").as("at"), "summary"]) + .where("state", "in", ["failed", "lost"]).where("job_id", "is", null) + .$if(!staff, (q) => q.where((eb) => eb.not(privateStepExpr(eb)))) + .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden))) + .$if(!!before, (q) => q.where((eb) => eb(eb.fn.coalesce("ended_at", "queued_at"), "<", before!))).orderBy("at", "desc").limit(SCAN)), + ]); bound(audit); const parsed = audit.map((a) => { let branch: string | null = null; @@ -185,7 +225,16 @@ async function feed(db: Db, hidden: HiddenRepos, staff: boolean, operator: boole if (t && !ref) branch = t[2]!; return { a, ref, repo, branch }; }); - const batchIds = await batchIdsOf(db, parsed.flatMap((p) => (p.repo && p.branch ? [[p.repo, p.branch] as [string, string]] : []))); + const listed = [...running, ...finished].filter((j) => !(QUIET_STEPS.has(j.step) && j.state !== "failed")); + const [batchIds, jobItems, itemsOfRun, prsOfOpen, quietPrs, firstOfRun] = await Promise.all([ + batchIdsOf(db, parsed.flatMap((p) => (p.repo && p.branch ? [[p.repo, p.branch] as [string, string]] : []))), + listed.length ? db.all(db.k.selectFrom("job_items").select(["job_id", "id", "repo", "number"]).where(kx.inList(db, "job_id", listed.map((j) => j.id), "bigint")) + .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden))).orderBy("id")) : [], + before ? new Map() : runItems(db, liveRuns.map((r) => r.id), PER_KIND), + before ? new Map() : batchPrs(db, openBatches.map((b) => b.id)), + decisions.length ? quietFixPrs(db) : new Set(), + runItems(db, runs.map((r) => r.id), 1), + ]); for (const { a, ref, repo, branch } of parsed) { const bid = repo && branch ? batchIds.get(`${repo}\0${branch}`) : undefined; if (repo && isHiddenRepo(hidden, repo)) continue; @@ -200,9 +249,6 @@ async function feed(db: Db, hidden: HiddenRepos, staff: boolean, operator: boole const e = writeEvent(a, staff); writes.push({ at: a.at, action: a.action, label: GITHUB_ACTIONS[a.action]!, item: item(ref.repo, ref.number), key: e.id, summary: e.summary, login: a.login }); } - const merges = await db.all(db.k.selectFrom("merges").select([kx.rowid("merges").as("rowid"), "repo", "number", "at", "path", "method"]).where("outcome", "=", "merged") - .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden))) - .$if(!!before, (q) => q.where("at", "<", before!)).orderBy("at", "desc").limit(SCAN)); bound(merges); for (const m of merges) { writes.push({ at: m.at, action: "merge", label: "Merged", item: item(m.repo, m.number), key: `merge:${m.rowid}`, login: "AutoCraft", @@ -210,19 +256,9 @@ async function feed(db: Db, hidden: HiddenRepos, staff: boolean, operator: boole } writes.sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : a.key < b.key ? 1 : -1)); - // Jobs. Running ones always show on the first page; finished ones by start time. - const jobCols = (eb: kx.Eb) => ["id", "step", "state", eb.fn.coalesce("started_at", "requested_at").as("at"), "ended_at", "progress", "summary", "error", "repo", "items", "acted"] as const; - const running = await db.all(db.k.selectFrom("jobs").select((eb) => jobCols(eb)).where("state", "=", "running") - .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden, true))) - .$if(!!before, (q) => q.where((eb) => eb(eb.fn.coalesce("started_at", "requested_at"), "<", before!))).orderBy("id", "desc")); - const finished = await db.all(db.k.selectFrom("jobs").select((eb) => jobCols(eb)).where("state", "in", ["done", "failed"]).where("started_at", "is not", null) - .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden, true))) - .$if(!!before, (q) => q.where("started_at", "<", before!)).orderBy("started_at", "desc").limit(SCAN)); bound(finished); const jobEntries = new Map; from: number; to: number }>(); - const listed = [...running, ...finished].filter((j) => !(QUIET_STEPS.has(j.step) && j.state !== "failed")); - const itemsOfJob = groupBy(listed.length ? await db.all(db.k.selectFrom("job_items").select(["job_id", "id", "repo", "number"]).where(kx.inList(db, "job_id", listed.map((j) => j.id), "bigint")) - .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden))).orderBy("id")) : [], (r) => r.job_id); + const itemsOfJob = groupBy(jobItems, (r) => r.job_id); for (const j of [...running, ...finished]) { const live = j.state === "running"; if (QUIET_STEPS.has(j.step) && j.state !== "failed") { @@ -251,10 +287,6 @@ async function feed(db: Db, hidden: HiddenRepos, staff: boolean, operator: boole }; // Calls and build tasks nest under a running job; those without a job stand alone. if (!before) { - const liveRuns = await db.all(db.k.selectFrom("agent_runs as r").leftJoin("claude_accounts as a", "a.id", "r.account_id") - .select((eb) => ["r.id", "r.job_id", "r.step", "r.model", "r.provider", eb.fn.coalesce("a.label", "r.account_id").as("label"), "r.started_at", "r.progress", "r.item_count", "r.user_login", "r.harness", "r.reported_model"]) - .where("r.state", "=", "running").$if(filtered(hidden), (q) => q.where((eb) => touchesHiddenExpr(db, eb, hidden))).orderBy("r.id")); - const itemsOfRun = await runItems(db, liveRuns.map((r) => r.id), PER_KIND); for (const r of liveRuns) { const its = itemsOfRun.get(r.id) ?? []; placeChild(r.job_id, base({ @@ -263,20 +295,13 @@ async function feed(db: Db, hidden: HiddenRepos, staff: boolean, operator: boole ...(staff && r.user_login && { via: { login: r.user_login, harness: r.harness ?? "", model: r.reported_model ?? "" } }), })); } - for (const t of await db.all(db.k.selectFrom("build_tasks as t").leftJoin("build_envs as e", "e.id", "t.env_id") - .select(["t.id", "t.job_id", "t.step", "t.repo", "t.number", "t.state", "t.queued_at", "t.started_at", "t.summary", "e.label"]) - .where("t.state", "in", ["queued", "claimed", "running"]) - .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "t.repo", hidden))) - .$if(!staff, (q) => q.where((eb) => eb.not(privateStepExpr(eb, "t.step")))).orderBy("t.id"))) { + for (const t of liveTasks) { const one = t.number === null ? null : item(t.repo, t.number); placeChild(t.job_id, base({ key: `task:${t.id}`, kind: "task", state: t.state === "queued" ? "queued" : "running", at: t.started_at ?? t.queued_at, title: `Build task, ${stepTitle(t.step)}`, what: t.label, progress: t.summary, item: one, items: one ? [one] : [], itemCount: one ? 1 : 0, event: one ? `task:${t.id}` : null, detail: `/envs/${t.id}`, })); } - const openBatches = await db.all(db.k.selectFrom("merge_batches").select(["id", "repo", "branch", "state", "created_at", "summary"]).where("state", "in", ["checking", "open"]) - .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden))).orderBy("id", "desc")); - const prsOfOpen = await batchPrs(db, openBatches.map((b) => b.id)); for (const b of openBatches) { const prs = prsOfOpen.get(b.id) ?? []; out.push(base({ @@ -329,10 +354,7 @@ async function feed(db: Db, hidden: HiddenRepos, staff: boolean, operator: boole out.push(e); } - const decisions = await db.all(db.k.selectFrom("decisions").select(["id", "repo", "number", "items", "question", "answer", "answered_at as at", "answered_by"]).$narrowType<{ at: NotNull }>().where("answered_at", "is not", null) - .$if(!!before, (q) => q.where("answered_at", "<", before!)).orderBy("answered_at", "desc").limit(SCAN)); bound(decisions); - const quietPrs = decisions.length ? await quietFixPrs(db) : new Set(); const isQuiet = (repo: string, number: number): boolean => quietPrs.has(`${repo}#${number}`); for (const d of decisions) { let ref: { repo: string; number: number } | null = d.repo && d.number !== null ? { repo: d.repo, number: d.number } : null; @@ -354,22 +376,12 @@ async function feed(db: Db, hidden: HiddenRepos, staff: boolean, operator: boole })); } - // Failed calls and tasks of a job show on the job; only those without one stand alone. - const runs = await db.all(db.k.selectFrom("agent_runs as r").select((eb) => ["r.id", "r.step", "r.model", eb.fn.coalesce("r.ended_at", "r.started_at").as("at"), "r.error"]) - .where("r.state", "=", "failed").where("r.job_id", "is", null).$if(filtered(hidden), (q) => q.where((eb) => touchesHiddenExpr(db, eb, hidden))) - .$if(!!before, (q) => q.where((eb) => eb(eb.fn.coalesce("r.ended_at", "r.started_at"), "<", before!))).orderBy("at", "desc").limit(SCAN)); bound(runs); - const firstOfRun = await runItems(db, runs.map((r) => r.id), 1); for (const r of runs) { const i = firstOfRun.get(r.id)?.[0]; out.push(base({ key: `failed-run:${r.id}`, kind: "failure", state: "failed", at: r.at, actor: r.model, item: i ? item(i.repo, i.number) : null, event: i ? `run:${r.id}` : null, detail: `/agents/${r.id}`, title: `${stepTitle(r.step)}: model call failed${r.error && staff ? `, ${clip(r.error, 100)}` : ""}` })); } - const tasks = await db.all(db.k.selectFrom("build_tasks").select((eb) => ["id", "step", "repo", "number", "state", eb.fn.coalesce("ended_at", "queued_at").as("at"), "summary"]) - .where("state", "in", ["failed", "lost"]).where("job_id", "is", null) - .$if(!staff, (q) => q.where((eb) => eb.not(privateStepExpr(eb)))) - .$if(filtered(hidden), (q) => q.where((eb) => notHidden(db, eb, "repo", hidden))) - .$if(!!before, (q) => q.where((eb) => eb(eb.fn.coalesce("ended_at", "queued_at"), "<", before!))).orderBy("at", "desc").limit(SCAN)); bound(tasks); for (const t of tasks) { out.push(base({ key: `failed-task:${t.id}`, kind: "failure", state: "failed", at: t.at, repo: t.repo, item: t.number === null ? null : item(t.repo, t.number), event: t.number === null ? null : `task:${t.id}`, detail: `/envs/${t.id}`, @@ -398,6 +410,6 @@ export async function nowFeed(db: Db, req: Req): Promise { export async function now(db: Db, req: Req): Promise { const hidden = await hiddenRepos(db, req); const nowMs = Date.now(); - const f = await feed(db, hidden, canSeeInternals(req), req.user.role === "operator", null, nowMs); - return { health: await healthOf(db, hidden, canSeeInternals(req), nowMs), alsoRunning: f.also, entries: f.entries, nextCursor: f.nextCursor }; + const [f, health] = await Promise.all([feed(db, hidden, canSeeInternals(req), req.user.role === "operator", null, nowMs), healthOf(db, hidden, canSeeInternals(req), nowMs)]); + return { health, alsoRunning: f.also, entries: f.entries, nextCursor: f.nextCursor }; } diff --git a/src/dash/api/pipeline.ts b/src/dash/api/pipeline.ts index 2b6bea7b0..64b6e1e1a 100644 --- a/src/dash/api/pipeline.ts +++ b/src/dash/api/pipeline.ts @@ -21,6 +21,7 @@ import { canSeeInternals } from "./staff.ts"; import { SECURITY_STEP } from "../../security/rules.ts"; import { mapSeq } from "../../async-seq.ts"; import type { Db } from "../../db/index.ts"; +import { setting } from "../../settings-read.ts"; // Stages of docs/pipeline.md. A stage with registered steps shows them; the // mirror also runs on its own timer. @@ -110,7 +111,7 @@ export async function overview(db: Db, req: Req): Promise { const lastSync = raw.find((r) => r.endedAt); // A sync error can quote GitHub's answer about any repo: staff read it unless it names a repo hidden from them, viewers read "failed". const runs = raw.map((r) => ({ ...r, error: r.error && (canSeeInternals(req) ? blankIfHidden(r.error, hidden) || "failed" : "failed") })); - const high = (await db.get(db.k.selectFrom("settings").select("value").where("key", "=", "org_high_water")))?.value ?? null; + const high = (await setting(db, "org_high_water")) ?? null; const stages: PipelineStage[] = await mapSeq(STAGES, async (st) => { const names = steps.filter((s) => s.stage === st.n).map((s) => s.name); const mode = st.automatic ? "automatic" : names.length ? "steps" : "planned"; @@ -119,7 +120,7 @@ export async function overview(db: Db, req: Req): Promise { state: mode === "planned" ? "planned" : await stageState(db, names, st.automatic ? (lastSync ? lastSync.error !== null : high ? false : null) : null), }; }); - const beat = (await db.get(db.k.selectFrom("settings").select("value").where("key", "=", HEARTBEAT_KEY)))?.value ?? null; + const beat = (await setting(db, HEARTBEAT_KEY)) ?? null; const count = async (state: string) => (await db.get(db.k.selectFrom("jobs").select((eb) => eb.fn.countAll().as("n")).where("state", "=", state) .$if(filtered(hidden), (q) => q.where((eb) => eb.or([eb("repo", "is", null), eb.not(hiddenTestExpr(db, "repo", hidden))])))))!.n; return { diff --git a/src/dash/api/queue-page.ts b/src/dash/api/queue-page.ts index c9b678dd9..e96759eaa 100644 --- a/src/dash/api/queue-page.ts +++ b/src/dash/api/queue-page.ts @@ -21,7 +21,7 @@ import { toBatch, toRow } from "./queue.ts"; import { needVisible, visibleRepos } from "./visible.ts"; import { readerOf, statusFor, veiledFor, type Reader } from "./reader.ts"; import { stageById } from "../../stages/registry.ts"; -import { flatMapSeq, mapSeq } from "../../async-seq.ts"; +import { flatMapSeq } from "../../async-seq.ts"; import type { Db } from "../../db/index.ts"; import type { NotNull } from "kysely"; import * as kx from "../../db/kx.ts"; @@ -76,13 +76,26 @@ export async function queuePage(db: Db, req: Req): Promise { const visible = await visibleRepos(db, req); const visibleSet = new Set(visible); if (reposParam !== "pipeline" && reposParam !== "all" && !visibleSet.has(reposParam)) throw new HttpError(404, `${reposParam} is not a tracked repo`); - const scoped = reposParam === "pipeline" ? new Set([...await openViews(db)].filter(([, v]) => v.scope).map(([k]) => k)) : null; - const fast = new Map([...await fastPositions(db)].filter(([k]) => visibleSet.has(k.slice(0, k.lastIndexOf("#"))))); + const internals = canSeeInternals(req); + // The page's reads do not depend on each other, so they run together. + const [views, fastAll, holds, allEntries, slots, ranked, reader, closes, originOf] = await Promise.all([ + reposParam === "pipeline" ? openViews(db) : null, fastPositions(db), + db.all(db.k.selectFrom("main.merge_holds").select(["repo", "number"])), + // Work rows (All, Review, Fix, Verify): each item's next step is the one its cached Plan stored; the position badges read the same rows. + cachedQueue(db, { merged: "exclude" }), queueSlots(db, visible), + db.all(db.k.selectFrom("items as i").innerJoin("item_rank as r", (j) => j.onRef("r.repo", "=", "i.repo").onRef("r.number", "=", "i.number")) + .leftJoin("item_plans as p", (j) => j.onRef("p.repo", "=", "i.repo").onRef("p.number", "=", "i.number")) + .select(["i.repo", "i.number", "i.kind", "i.title", "r.score", "r.breakdown", kx.jsonText(db, "p.view", "$.next").as("next"), kx.jsonText(db, "p.view", "$.label").as("label"), "p.item_state"]) + .where("i.state", "=", "OPEN").orderBy("r.score", "desc").orderBy("i.repo").orderBy("i.number")), + readerOf(db, req), closingIssues(db), queueOrigins(db, internals), + ]); + const scoped = views ? new Set([...views].filter(([, v]) => v.scope).map(([k]) => k)) : null; + const fast = new Map([...fastAll].filter(([k]) => visibleSet.has(k.slice(0, k.lastIndexOf("#"))))); // The default view is the pipeline's scope (src/rank/position.ts), the same one the position badges count. const inScope = (repo: string, number: number): boolean => reposParam === "all" ? visibleSet.has(repo) : reposParam === "pipeline" ? visibleSet.has(repo) && scoped!.has(`${repo}#${number}`) : repo === reposParam; const fastOf = (repo: string, number: number): FastPosition | null => fast.get(`${repo}#${number}`) ?? null; - const held = new Set((await db.all(db.k.selectFrom("main.merge_holds").select(["repo", "number"]))).map((r) => `${r.repo}#${r.number}`)); + const held = new Set(holds.map((r) => `${r.repo}#${r.number}`)); // A linked item (`item=repo:number`) comes with the first page: it is cut long enough to include the item. const item = req.query.get("item"); @@ -95,16 +108,9 @@ export async function queuePage(db: Db, req: Req): Promise { return at === null ? limit : Math.min(500, Math.max(limit, Math.ceil((at + 1) / 100) * 100)); }; - // Work rows (All, Review, Fix, Verify): each item's next step is the one its cached Plan stored; the position badges read the same rows. - const allEntries = await cachedQueue(db, { merged: "exclude" }); - const slots = await queueSlots(db, visible); const score = scoreLookup(db); - const ranked = await db.all(db.k.selectFrom("items as i").innerJoin("item_rank as r", (j) => j.onRef("r.repo", "=", "i.repo").onRef("r.number", "=", "i.number")) - .leftJoin("item_plans as p", (j) => j.onRef("p.repo", "=", "i.repo").onRef("p.number", "=", "i.number")) - .select(["i.repo", "i.number", "i.kind", "i.title", "r.score", "r.breakdown", kx.jsonText(db, "p.view", "$.next").as("next"), kx.jsonText(db, "p.view", "$.label").as("label"), "p.item_state"]) - .where("i.state", "=", "OPEN").orderBy("r.score", "desc").orderBy("i.repo").orderBy("i.number")); // Fast-tracked items (and the Fix PRs of fast-tracked issues) first, then the work rank. - const inView = await mapSeq(ranked.filter((r) => visibleSet.has(r.repo) && inScope(r.repo, r.number)), async (r) => ({ r, s: await score(r.repo, r.number) ?? r.score })); + const inView = await Promise.all(ranked.filter((r) => visibleSet.has(r.repo) && inScope(r.repo, r.number)).map(async (r) => ({ r, s: await score(r.repo, r.number) ?? r.score }))); inView.sort((a, b) => b.s - a.s); const work: QueueWorkRow[] = inView.map(({ r }) => { const bd = JSON.parse(r.breakdown) as RankBreakdown; @@ -117,10 +123,6 @@ export async function queuePage(db: Db, req: Req): Promise { // Merge queue rows const entries = allEntries.filter((e) => e.state !== "merged" && visibleSet.has(e.repo) && inScope(e.repo, e.number)); - const internals = canSeeInternals(req); - const reader = await readerOf(db, req); - const closes = await closingIssues(db); - const originOf = await queueOrigins(db, internals); const asRow = async (e: CachedEntry): Promise => ({ ...toRow(e, reader), fast: fastOf(e.repo, e.number), held: e.held, prBuild: await prBuildView(db, e.repo, e.number, e.head, internals), closes: closes.get(`${e.repo}#${e.number}`) ?? [], added: await originOf(e) }); // Tabs come from the stored next step; the text is veiled afterwards, so a quiet pull request stays in its tab. const tabOf = new Map(work.map((w) => [w, tabOfNext(w.next)])); @@ -138,12 +140,19 @@ export async function queuePage(db: Db, req: Req): Promise { out.next = offset + out.rows.length < match.length ? offset + out.rows.length : null; return out; } - const { batches } = await pageBatches(db, { hidden: reader.hidden, limit: 100 }); + const [{ batches }, rows, rankRows, ordered] = await Promise.all([ + pageBatches(db, { hidden: reader.hidden, limit: 100 }), + Promise.all(entries.map(async (e) => [e, await asRow(e)] as const)), + db.all(db.k.selectFrom("item_rank").select(["repo", "number", "score"])), + mergeOrder(db, entries), + ]); const active = batches.filter((b) => (b.state === "checking" || b.state === "open") && b.prs.some((p) => inScope(b.repo, p.number))); - const rowOf = new Map(await mapSeq(entries, async (e) => [`${e.repo}#${e.number}`, await asRow(e)])); + const rowOfEntry = new Map(rows); + const rowOf = new Map(rows.map(([e, r]) => [`${e.repo}#${e.number}`, r])); const batchOf = new Map(active.flatMap((b) => b.prs.map((p) => [`${b.repo}#${p.number}`, { id: b.id, branch: b.branch }] as const))); - const scores = new Map((await db.all(db.k.selectFrom("item_rank").select(["repo", "number", "score"]))).map((r) => [`${r.repo}#${r.number}`, r.score])); - const free = await mapSeq((await mergeOrder(db, entries)), asRow); + const scores = new Map(rankRows.map((r) => [`${r.repo}#${r.number}`, r.score])); + // The merge rows are the ones built above, in merge order. + const free = ordered.map((e) => rowOfEntry.get(e)!); out.itemIndex = indexOf(free); out.mergeRows = free.slice(offset, offset + sizeFor(free, offset)); out.total = free.length; @@ -163,26 +172,27 @@ export async function queuePage(db: Db, req: Req): Promise { async function pendingRows(db: Db, entries: CachedEntry[], all: CachedEntry[], want: (repo: string, number: number) => boolean, originOf: (e: Pick) => Promise, fastOf: (repo: string, number: number) => FastPosition | null, held: Set, reader: Reader, staff: boolean): Promise { const queued = new Set(entries.map((e) => `${e.repo}#${e.number}`)); - const rows = await db.all(db.k.selectFrom("preapprovals as p").innerJoin("main.items as i", (j) => j.onRef("i.repo", "=", "p.repo").onRef("i.number", "=", "p.number")) + const [rows, fast] = await Promise.all([db.all(db.k.selectFrom("preapprovals as p").innerJoin("main.items as i", (j) => j.onRef("i.repo", "=", "p.repo").onRef("i.number", "=", "p.number")) .leftJoin("item_rank as r", (j) => j.onRef("r.repo", "=", "p.repo").onRef("r.number", "=", "p.number")) .select(["p.repo", "p.number", "p.state", "i.title", "i.author", "r.breakdown"]).$narrowType<{ state: "fixup" | "review" | "ci" }>() - .where("p.state", "in", ["fixup", "review", "ci"]).where("i.state", "=", "OPEN").where("i.kind", "=", "pr").orderBy("p.id")); - const seen = new Set(); - const sizeOf = (breakdown: string | null) => (breakdown ? ((JSON.parse(breakdown) as RankBreakdown).size ?? null) : null); - const prs = await flatMapSeq(rows, async (p): Promise => { - const k = `${p.repo}#${p.number}`; - if (seen.has(k) || queued.has(k) || !want(p.repo, p.number)) return []; - seen.add(k); - return [{ - repo: p.repo, number: p.number, kind: "pr", title: p.title ?? "", author: p.author ?? "", size: sizeOf(p.breakdown), step: p.state, - fast: fastOf(p.repo, p.number), held: held.has(k), added: await originOf({ repo: p.repo, number: p.number, decisionId: null, reviewedAt: "" }), - }]; - }); - const fast = await db.all(db.k.selectFrom("main.fast_track as f").innerJoin("main.items as i", (j) => j.onRef("i.repo", "=", "f.repo").onRef("i.number", "=", "f.number")) + .where("p.state", "in", ["fixup", "review", "ci"]).where("i.state", "=", "OPEN").where("i.kind", "=", "pr").orderBy("p.id")), + db.all(db.k.selectFrom("main.fast_track as f").innerJoin("main.items as i", (j) => j.onRef("i.repo", "=", "f.repo").onRef("i.number", "=", "f.number")) .leftJoin("item_rank as r", (j) => j.onRef("r.repo", "=", "f.repo").onRef("r.number", "=", "f.number")) .leftJoin("item_plans as pl", (j) => j.onRef("pl.repo", "=", "f.repo").onRef("pl.number", "=", "f.number")) .select(["f.repo", "f.number", "i.title", "i.author", "r.breakdown", "f.added_by", "f.added_at", kx.jsonText(db, "pl.view", "$.next").as("next")]) - .where("i.state", "=", "OPEN").where("i.kind", "=", "issue").orderBy("f.weight", "desc").orderBy("f.id")); + .where("i.state", "=", "OPEN").where("i.kind", "=", "issue").orderBy("f.weight", "desc").orderBy("f.id"))]); + const seen = new Set(); + const sizeOf = (breakdown: string | null) => (breakdown ? ((JSON.parse(breakdown) as RankBreakdown).size ?? null) : null); + const shownPrs = rows.filter((p) => { + const k = `${p.repo}#${p.number}`; + if (seen.has(k) || queued.has(k) || !want(p.repo, p.number)) return false; + seen.add(k); + return true; + }); + const prs = await Promise.all(shownPrs.map(async (p): Promise => ({ + repo: p.repo, number: p.number, kind: "pr", title: p.title ?? "", author: p.author ?? "", size: sizeOf(p.breakdown), step: p.state, + fast: fastOf(p.repo, p.number), held: held.has(`${p.repo}#${p.number}`), added: await originOf({ repo: p.repo, number: p.number, decisionId: null, reviewedAt: "" }), + }))); // Listed in any scope: a closing PR queued outside the view's scope still stands for the issue. const shownAll = new Set(all.filter((e) => e.held || !UNSHOWN_STATES.has(e.state)).map((e) => `${e.repo}#${e.number}`)); const queuedAll = new Set(all.map((e) => `${e.repo}#${e.number}`)); diff --git a/src/dash/api/trace.ts b/src/dash/api/trace.ts index 19c940971..2c97c5fed 100644 --- a/src/dash/api/trace.ts +++ b/src/dash/api/trace.ts @@ -16,10 +16,11 @@ import { blankIfHidden, hiddenRepos, needVisible } from "./visible.ts"; import { reasonsFor, waitFor, type Reader } from "./reader.ts"; import { filtered, hiddenTestExpr, isHiddenRepo, type HiddenRepos } from "../../hidden-sql.ts"; import { ownLogins } from "../../github/identity.ts"; -import { flatMapSeq, mapSeq } from "../../async-seq.ts"; +import { mapSeq } from "../../async-seq.ts"; import type { AliasedExpression, AliasableExpression, SelectQueryBuilder, SqlBool } from "kysely"; import type { Db } from "../../db/index.ts"; import * as kx from "../../db/kx.ts"; +import { setting } from "../../settings-read.ts"; export type Ev = TraceEvent & { detail?: Record }; /** `staff`: operators and maintainers; `hidden`: repos the viewer may not see, whose runs are left out like getRun does. */ @@ -428,7 +429,8 @@ export function veilEvent(e: Ev): Ev { export async function gather(c: Ctx, kinds: Set | null): Promise { const all: Ev[] = []; - for (const e of await flatMapSeq(SOURCES, async (s) => await s.run(c))) { + // The sources read independently, so they run together; events keep the SOURCES order. + for (const e of (await Promise.all(SOURCES.map((s) => s.run(c)))).flat()) { if (c.veiled && VEILED_KINDS.includes(e.kind)) continue; const at = iso(e.at); if (at) all.push({ ...(c.veiled ? veilEvent(e) : e), at, ...(c.staff ? {} : { summary: plainSummary(c.veiled ? veilEvent(e) : e) }) }); @@ -536,10 +538,12 @@ export async function context(db: Db, req: Req): Promise { const repo = req.params.repo!; const n = Number(req.params.n); if (!Number.isInteger(n)) throw new HttpError(400, "not an item number"); - await needVisible(db, req, repo); - if (!await db.get(db.k.selectFrom("items").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", n))) throw new HttpError(404, `no item ${repo}#${n} in the mirror`); - const box = (await db.get(db.k.selectFrom("main.settings").select("value").where("key", "=", "pipeline_login")))?.value ?? ""; - return { db, repo, n, ref: `${repo}#${n}`, own: await ownLogins(db, repo), box, staff: canSeeInternals(req), veiled: !canSeeInternals(req) && await isQuiet(db, repo, n), operator: req.user.role === "operator", hidden: await hiddenRepos(db, req) }; + // The visibility check decides first: an item of a hidden repo is a 404 for its repo whether or not the mirror has it. + const [, found] = await Promise.all([needVisible(db, req, repo), db.get(db.k.selectFrom("items").select((eb) => eb.lit(1).as("one")).where("repo", "=", repo).where("number", "=", n))]); + if (!found) throw new HttpError(404, `no item ${repo}#${n} in the mirror`); + const staff = canSeeInternals(req); + const [box, own, veiled, hidden] = await Promise.all([setting(db, "pipeline_login"), ownLogins(db, repo), !staff && isQuiet(db, repo, n), hiddenRepos(db, req)]); + return { db, repo, n, ref: `${repo}#${n}`, own, box: box ?? "", staff, veiled, operator: req.user.role === "operator", hidden }; } /** diff --git a/src/dash/server/index.ts b/src/dash/server/index.ts index 20d25325f..9bb63e4c4 100644 --- a/src/dash/server/index.ts +++ b/src/dash/server/index.ts @@ -9,7 +9,7 @@ import { promisify } from "node:util"; import type { AddressInfo } from "node:net"; import { LOGIN, checkGithubId, getAccess } from "../../access.ts"; import { audit, auditRefusedSignIn } from "../audit.ts"; -import type { Req, Res, Role, Route } from "../types.ts"; +import type { Res, Role, Route } from "../types.ts"; import { isLoopbackHost, type Config } from "./config.ts"; import { resealLegacyValues } from "./reseal.ts"; import { pkceChallenge, randomToken, safeEqual, TokenBox } from "./crypto.ts"; @@ -34,6 +34,7 @@ import { FakeProvider, WRITE_PERMISSIONS, GitHubProvider, oauthProviderFor, prov import { retryWaiting } from "../../github/user-lane.ts"; import { appPermission } from "../../remote/permission.ts"; import { cachedWrite, createSession, deleteSession, loadSession, makeUser, PERM_READ_TTL, pruneExpired, SESSION_TTL, userForLogin, type Session } from "./sessions.ts"; +import { readSettingsSnapshot, withSettingsSnapshot, type SettingsSnapshot } from "../../settings-read.ts"; import { answering, handleMcp, mcpReply, writes as mcpWrites, type Msg as McpMsg, type Reply as McpReply } from "../mcp/index.ts"; import { loadToken, pruneTokens, type McpCaller } from "../mcp/tokens.ts"; import { sha256hex } from "./crypto.ts"; @@ -363,7 +364,7 @@ export async function createApp(opts: AppOptions & { routes: Route[] }) { } } - async function handleApi(req: IncomingMessage, res: ServerResponse, url: URL, nonce: string, session: Session): Promise { + async function handleApi(req: IncomingMessage, res: ServerResponse, url: URL, nonce: string, session: Session, snapshot?: Promise): Promise { const method = req.method; const out = (r: Res, cookies?: string[]) => send(res, nonce, { ...r, headers: { ...r.headers, [CSRF_HEADER]: session.csrf } }, cookies); @@ -388,13 +389,14 @@ export async function createApp(opts: AppOptions & { routes: Route[] }) { if (wait) return out({ status: 429, json: { error: "too many requests; wait a moment" }, headers: { "retry-after": String(wait) } }); } if (route.operator && session.role !== "operator") return out(apiError(403, "operators only")); - const r: Req = { + const run = async (): Promise => await route.handler(db, { method, path: url.pathname, params: params!, query: url.searchParams, form: new URLSearchParams(), json, user: makeUser(db, box, provider, session, writes, await githubIdentity(db) === "app"), scope: route.scoped && !writes ? scopeOf(req) : null, csrf: session.csrf, ip: clientIp(req), nonce, - }; - const res2 = await route.handler(db, r); + }); + // A read request takes its settings from one reading of the table, as a planner pass does. + const res2 = writes ? await run() : await withSettingsSnapshot(db, run, snapshot); // The writer sees its own change at once; other processes' writes arrive on the watcher's next read. if (writes) await live.poke(); return out(res2); @@ -595,8 +597,11 @@ export async function createApp(opts: AppOptions & { routes: Route[] }) { await pruneTokens(db); void vault.sweepRevocations().catch(() => {}); } - // A revoked session's token is revoked at once, not at the next hourly sweep; failures are retried by that sweep. - if (await db.get(db.k.selectFrom("user_token_revocations").select("id").where("attempts", "=", 0).limit(1))) void vault.sweepRevocations(true).catch(() => {}); + // A revoked session's token is revoked at once, not at the next hourly sweep; failures are retried by that sweep. The check + // runs alongside the session read; routes that return before it leave it running on its own. + const revocations = db.get(db.k.selectFrom("user_token_revocations").select("id").where("attempts", "=", 0).limit(1)) + .then((r) => { if (r) void vault.sweepRevocations(true).catch(() => {}); }); + revocations.catch(() => {}); // Dev auth lets anyone who reaches the port sign in as any login, so // a request that came through a proxy or under a public name is refused. if (config.devAuth && (req.headers["x-forwarded-for"] !== undefined || !isLoopbackHost(req.headers.host))) { @@ -627,7 +632,10 @@ export async function createApp(opts: AppOptions & { routes: Route[] }) { if (method === "GET" && url.pathname === DISCORD_TERMS_PATH) return send(res, nonce, { html: discordTermsPage(nonce, await contactOf(db)) }); // Public: the favicon and the preview image, which sign-in pages and link-preview crawlers load without a session. if (method === "GET" && PUBLIC_FILES.has(url.pathname)) return await sendWeb(res, nonce, url.pathname); - const session = await loadSession(db, cookies.get(SESSION_COOKIE)); + // A read request's settings snapshot is read with the session (handleApi). + const snapshot = method === "GET" && url.pathname.startsWith("/api/") && url.pathname !== "/api/live" ? readSettingsSnapshot(db) : undefined; + snapshot?.catch(() => {}); + const [session] = await Promise.all([loadSession(db, cookies.get(SESSION_COOKIE)), revocations, snapshot]); if (!session) { const wantsPage = method === "GET" && /text\/html/.test(String(req.headers.accept ?? "")); if (wantsPage) { @@ -640,7 +648,7 @@ export async function createApp(opts: AppOptions & { routes: Route[] }) { return send(res, nonce, { status: 401, json: { error: "sign-in required" } }); } if (method === "GET" && url.pathname === "/api/live") return await handleLive(req, res, nonce, session); - if (url.pathname.startsWith("/api/")) return await handleApi(req, res, url, nonce, session); + if (url.pathname.startsWith("/api/")) return await handleApi(req, res, url, nonce, session, snapshot); if (url.pathname === "/img") return await sendImage(req, res, url, session); // Every other address belongs to the React app, which routes on the client. if (method === "GET") return await sendWeb(res, nonce, url.pathname); diff --git a/src/fasttrack.ts b/src/fasttrack.ts index e3abf68db..bc78f1a35 100644 --- a/src/fasttrack.ts +++ b/src/fasttrack.ts @@ -174,13 +174,18 @@ export async function fastFirst(db: Db, repos: string[], top: (repo: string) => /** Work score of every ranked open item of the repo, with fast-tracked items raised above all others. */ export async function workScores(db: Db, repo: string): Promise> { - const out = new Map((await db.all(db.k.selectFrom("main.item_rank").select(["number", "score"]).where("repo", "=", repo))).map((r) => [r.number, r.score])); - for (const f of await db.all(db.k.selectFrom("main.fast_track as ft").select((eb) => ["ft.number", rowScoreExpr(eb, "ft").as("s")]).where("ft.repo", "=", repo))) out.set(f.number, f.s); + const [ranks, fast, fixes] = await Promise.all([ + db.all(db.k.selectFrom("main.item_rank").select(["number", "score"]).where("repo", "=", repo)), + db.all(db.k.selectFrom("main.fast_track as ft").select((eb) => ["ft.number", rowScoreExpr(eb, "ft").as("s")]).where("ft.repo", "=", repo)), + db.all(db.k.selectFrom("main.fast_track as ft") + .innerJoin("main.fix_attempts as fa", (j) => j.onRef("fa.repo", "=", "ft.repo").onRef("fa.number", "=", "ft.number")) + .select((eb) => ["fa.pr_url", rowScoreExpr(eb, "ft").as("s")]).$narrowType<{ pr_url: string }>() + .where("ft.repo", "=", repo).where("fa.pr_url", "is not", null)), + ]); + const out = new Map(ranks.map((r) => [r.number, r.score])); + for (const f of fast) out.set(f.number, f.s); // A fast-tracked issue's Fix PR takes the issue's place. - for (const f of await db.all(db.k.selectFrom("main.fast_track as ft") - .innerJoin("main.fix_attempts as fa", (j) => j.onRef("fa.repo", "=", "ft.repo").onRef("fa.number", "=", "ft.number")) - .select((eb) => ["fa.pr_url", rowScoreExpr(eb, "ft").as("s")]).$narrowType<{ pr_url: string }>() - .where("ft.repo", "=", repo).where("fa.pr_url", "is not", null))) { + for (const f of fixes) { const n = Number(/\/pull\/(\d+)$/.exec(f.pr_url)?.[1]); const own = out.get(n) ?? 0; // The higher score (heavier, then earlier addition) counts, like fastScoreSql. diff --git a/src/flow/summary.ts b/src/flow/summary.ts index 8f423ff93..eb5962484 100644 --- a/src/flow/summary.ts +++ b/src/flow/summary.ts @@ -6,6 +6,7 @@ import { countAll, type Counts } from "./count.ts"; import type { Db } from "../db/index.ts"; import type { SelectQueryBuilder } from "kysely"; import * as kx from "../db/kx.ts"; +import { setting } from "../settings-read.ts"; /** A row older than this is counted again even when nothing changed: the 24-hour windows move. */ export const MAX_AGE_MS = 10 * 60_000; @@ -14,7 +15,7 @@ const MARKS_KEY = "flow_summary_marks"; type Marks = { items: string; cls: number; stages: number; opus: number; merges: number; checks: string; plans?: string; global: string; vers?: Record }; const getMarks = async (db: Db): Promise => { - const v = (await db.get(db.k.selectFrom("main.settings").select("value").where("key", "=", MARKS_KEY)))?.value; + const v = await setting(db, MARKS_KEY); try { return v ? (JSON.parse(v) as Marks) : null; } catch { return null; } }; diff --git a/src/github/read.ts b/src/github/read.ts index 398c569bc..fc19952bb 100644 --- a/src/github/read.ts +++ b/src/github/read.ts @@ -10,6 +10,7 @@ import { DEFAULT_OWNER, OWNER } from "../owners.ts"; import { AppNotInstalledError, TOKEN_ENV, appChildEnv, installationToken } from "./install-token.ts"; import type { Db } from "../db/index.ts"; import { dbFor, dbTarget, isPgUrl, openDb } from "../db/open.ts"; +import { setting } from "../settings-read.ts"; export type ReadEnv = Record; export type ReadDeps = { db?: Db; mint?: (owner: string) => Promise; defaultOwner?: () => Promise }; @@ -60,7 +61,7 @@ async function retried(fn: () => Promise): Promise { } const settingOf = (db: Db): Promise => - retried(async () => (await db.get(db.k.selectFrom("main.settings").select("value").where("key", "=", "github_identity")))?.value ?? undefined); + retried(async () => (await setting(db, "github_identity")) ?? undefined); /** The identity setting as this process holds it, with the `settings` change counter it was read at (null: unknown). */ let held: { app: boolean; seq: number | null } | null = null; diff --git a/src/github/slugs.ts b/src/github/slugs.ts index 67f361476..ded1955e5 100644 --- a/src/github/slugs.ts +++ b/src/github/slugs.ts @@ -17,7 +17,7 @@ export const knownSlugs = async (db: Db): Promise => parseSlugs(await /** Records `slug` in the persisted list when it is new. */ export async function rememberSlug(db: Db, slug: string): Promise { // Read from the table, not a pass snapshot: another connection may have recorded a slug since the pass began. - const known = parseSlugs((await db.get(db.k.selectFrom("main.settings").select("value").where("key", "=", SLUGS_KEY)))?.value ?? undefined); + const known = parseSlugs((await setting(db, SLUGS_KEY)) ?? undefined); if (known.includes(slug)) return; await writeSetting(db, SLUGS_KEY, JSON.stringify([...known, slug])); } diff --git a/src/health-checks.ts b/src/health-checks.ts index a0438f06e..028cdfdeb 100644 --- a/src/health-checks.ts +++ b/src/health-checks.ts @@ -18,8 +18,8 @@ import { NO_TAKER_MS } from "./remote/takers.ts"; import { STATUS_FRESH_MS } from "./remote/helpers.ts"; import { manualExpr } from "./remote/manual-only.ts"; import { confidentialReadyAt, privateStepExpr } from "./build/tasks.ts"; -import { flatMapSeq } from "./async-seq.ts"; import type { Db } from "./db/index.ts"; +import { setting } from "./settings-read.ts"; /** Thresholds, in one place. */ export const THRESHOLDS = { @@ -74,7 +74,7 @@ const minutes = (ms: number): string => (ms < 90 * 60_000 ? `${Math.max(1, Math. const clip = (s: string, n: number): string => (s.length > n ? `${s.slice(0, n - 1)}…` : s); async function runnerCheck({ db, nowMs }: CheckCtx): Promise { - const hb = (await db.get(db.k.selectFrom("settings").select("value").where("key", "=", "runner_heartbeat")))?.value ?? null; + const hb = (await setting(db, "runner_heartbeat")) ?? null; const beat = hb ? Date.parse(hb) : NaN; if (!Number.isNaN(beat) && nowMs - beat <= THRESHOLDS.runnerStaleMs) return [ok("runner", "/pipeline")]; const text = Number.isNaN(beat) ? "The runner has not reported" : `The runner has not reported for ${minutes(nowMs - beat)}`; @@ -189,7 +189,7 @@ async function accountsCheck({ db, nowMs, probe }: CheckCtx): Promise { } async function rateCheck({ db, nowMs }: CheckCtx): Promise { - const get = async (k: string) => (await db.get(db.k.selectFrom("settings").select("value").where("key", "=", k)))?.value ?? null; + const get = async (k: string) => (await setting(db, k)) ?? null; const left = Number(await get("sync_rate_remaining")); const reset = Date.parse(await get("sync_rate_reset_at") ?? ""); // A reading from before the last reset says nothing about the new hour. @@ -237,8 +237,8 @@ async function appIdentityChecks({ db, probe }: CheckCtx): Promise { /** The last pass that binds contributors' account ids failed: the earlier PRs of the logins it did not bind count toward no tier until a pass succeeds. */ async function authorIdsCheck({ db }: CheckCtx): Promise { - const err = (await db.get(db.k.selectFrom("settings").select("value").where("key", "=", "author_ids_error")))?.value; - const passed = (await db.get(db.k.selectFrom("settings").select("value").where("key", "=", "author_ids_backfilled")))?.value; + const err = await setting(db, "author_ids_error"); + const passed = await setting(db, "author_ids_backfilled"); // A pass that succeeded after the error supersedes it. if (!err || (passed && passed >= (err.split(" ")[0] ?? ""))) return [ok("author-ids", "/contributors")]; const n = (await unboundLogins(db)).length; @@ -332,7 +332,8 @@ const SOURCES: ((ctx: CheckCtx) => Promise)[] = [runnerCheck, workerChe export async function computeChecks(db: Db, nowMs: number = Date.now(), probe = false): Promise { const mode = await inferenceMode(db); - return await flatMapSeq(SOURCES, async (f) => await f({ db, nowMs, probe, mode })); + // The checks do not depend on each other, so they run together; the list keeps the SOURCES order. + return (await Promise.all(SOURCES.map((f) => f({ db, nowMs, probe, mode })))).flat(); } /** The answer of GET /healthz/checks for staff: states, times and counts only; no repo, environment, account or error text. */ diff --git a/src/rank/position.ts b/src/rank/position.ts index d40b7a6f8..e64829593 100644 --- a/src/rank/position.ts +++ b/src/rank/position.ts @@ -30,11 +30,12 @@ export type Stages = Map; /** Work score of an item with fast-tracked ones raised, one lookup per repo. */ export function scoreLookup(db: Db): (repo: string, number: number) => Promise { - const by = new Map>(); + // The read in flight is kept, so lookups made together read each repo once. + const by = new Map>>(); return async (repo, number) => { let m = by.get(repo); - if (!m) by.set(repo, (m = await workScores(db, repo))); - return m.get(number); + if (!m) by.set(repo, (m = workScores(db, repo))); + return (await m).get(number); }; } diff --git a/src/settings-read.ts b/src/settings-read.ts index c1ec26140..ee5910bbb 100644 --- a/src/settings-read.ts +++ b/src/settings-read.ts @@ -18,18 +18,24 @@ const snapshotOf = (db: Db): Map | undefined => { * keep it current. Other contexts and connections (the runner thread, the dashboard) keep writing: the pass sees settings as * they were at its start, and applyProposals re-checks limits and blocks with fresh reads. */ -export async function withSettingsSnapshot(db: Db, fn: () => Promise): Promise { +export async function withSettingsSnapshot(db: Db, fn: () => Promise, read?: Promise): Promise { if (snapshotOf(db)) return await fn(); + return await pass.run({ db, map: await (read ?? readSettingsSnapshot(db)) }, fn); +} + +export type SettingsSnapshot = Map; + +/** One reading of the table for withSettingsSnapshot, so a caller can start it alongside its other reads. */ +export async function readSettingsSnapshot(db: Db): Promise { const rows = await db.all(db.k.selectFrom("main.settings").select(["key", "value"])); - return await pass.run({ db, map: new Map(rows.map((r) => [r.key, r.value])) }, fn); + return new Map(rows.map((r) => [r.key, r.value])); } /** Reads the table again for the snapshot of a pass on `db` (none: nothing), so a pass sees the settings of a read transaction it opens later. */ export async function rereadSettingsSnapshot(db: Db): Promise { const s = pass.getStore(); if (s?.db !== db) return; - const rows = await db.all(db.k.selectFrom("main.settings").select(["key", "value"])); - s.map = new Map(rows.map((r) => [r.key, r.value])); + s.map = await readSettingsSnapshot(db); } /** The stored value, undefined when the key has no row. */ diff --git a/src/settlers.ts b/src/settlers.ts index e727caf87..d480df21f 100644 --- a/src/settlers.ts +++ b/src/settlers.ts @@ -11,11 +11,12 @@ import type { Db } from "./db/index.ts"; import { nowParam } from "./db/portable.ts"; import * as kx from "./db/kx.ts"; import type { AliasableExpression, Expression, SqlBool } from "kysely"; +import { setting } from "./settings-read.ts"; export const MAINTAINER_WRITES_KEY = "maintainer_writes"; export const maintainerWritesOn = async (db: Db): Promise => - (await db.get(db.k.selectFrom("main.settings").select("value").where("key", "=", MAINTAINER_WRITES_KEY)))?.value === "1"; + (await setting(db, MAINTAINER_WRITES_KEY)) === "1"; /** Maintainers settle now where they have write access: `maintainer_writes` on and the app's identity (which is instance-wide, as `allAppIdentity` reads it). */ export const maintainersSettle = async (db: Db): Promise => await maintainerWritesOn(db) && await githubIdentity(db) === "app";