diff --git a/docs/operations.md b/docs/operations.md index 3620da9ef..299a16676 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -49,7 +49,7 @@ The runner drains `sync_requests` every 5 seconds while rows exist (`webhookTick - A login whose GitHub id was never bound (no dashboard sign-in yet) is refused, with the reason in the answer. - Otherwise the commenter's write permission on the repo is read from GitHub (as for conversation cards) and the item is added exactly as a line of **Queue items** on the Queue page (`queueAdd`, see docs/pipeline.md, Merge queue), as that login with its current role. Who may is queueAdd's rule, the one every person-started write uses (`settleRefusal` in `src/settlers.ts`): an operator with write access on the repo, or a maintainer with `maintainer_writes` on, the app identity and write access; anyone else is refused with its reason. A PR is pre-approved at its current head and fast-tracked with the weight (default 5); an issue is fast-tracked and its one open closing PR queued. Its refusals (outside the scope, no merge approval for the repo, a pre-approved merge already in progress, …) are the answer. Audit rows are queueAdd's own under the commenter's login with `via: "github"`, plus one `github-command` row. - The app answers in the same thread, naming the commenter: what was done and the item's fast-track place, or why not. The answer goes through `src/github/write.ts` (`ghComment`, audit action `github-command-reply`, note line "Automated reply") under a grant in the commenter's name; it needs no Comments approval, because a known person asked for it. A paced write is retried on the next pass; another failed answer is logged and not retried. -- A command waits until the item, and for an issue every open PR that closes it (the one Queue items would queue), was read from GitHub after the comment, by the webhook's re-read or by the poll when that re-read failed. `item_reads.synced_at` must be strictly after the command's time: a read stamped at the same instant may have started before it. So the command never pre-approves a head the mirror read before the comment. While no such read exists and none is queued (the re-read failed, or started within the comment's second, which the second-precision `synced_at` counts as before it), the command queues a re-read itself, at most once a minute (`tried_at`). A command that GitHub's permission read cannot settle is tried again after a minute (`tried_at`). Waiting commands cost no GitHub call and never keep newer ones out: a pass carries out at most 10 commands that call GitHub, oldest first among those that are due. One not carried out within an hour of the comment is dropped unanswered (`expired`). +- A command waits until the item, and for an issue every open PR that closes it (the one Queue items would queue), was read from GitHub after the comment, by the webhook's re-read or by the poll when that re-read failed. `item_reads.synced_at` must be strictly after the command's time: a read stamped at the same instant may have started before it. This is checked again after the permission read, right before `queueAdd`, with nothing waiting on I/O between that check and the pre-approval, because a read that started earlier (a reconcile) may have written an older snapshot meanwhile, which also sets the item's read time back. So the command never pre-approves a head the mirror read before the comment. While no such read exists and none is queued (the re-read failed, or started within the comment's second, which the second-precision `synced_at` counts as before it), the command queues a re-read itself, at most once a minute (`tried_at`). A command that GitHub's permission read cannot settle is tried again after a minute (`tried_at`). Waiting commands cost no GitHub call and never keep newer ones out: a pass carries out at most 10 commands that call GitHub, oldest first among those that are due. One not carried out within an hour of the comment is dropped unanswered (`expired`). The app's slug is `github_app_slug` in the secrets file; without the app there are no commands. The **Issue comment** event must be subscribed (it is in the list above). diff --git a/src/github/commands.ts b/src/github/commands.ts index 7812d31e8..2555c6bff 100644 --- a/src/github/commands.ts +++ b/src/github/commands.ts @@ -86,8 +86,10 @@ type Row = { comment_id: number; repo: string; number: number; pr: number; comma /** What carries out a queued merge-queue command: the Queue page's queueAdd, as the commenter. `canWrite`: GitHub's answer for `repo`, read just before. Injectable for tests. */ export type QueueFn = (db: DatabaseSync, o: { login: string; role: Role; canWrite: boolean; repo: string; item: string; weight: number | null }) => Promise; -const defaultQueue: QueueFn = async (db, o) => { - const { queueAdd } = await import("../dash/api/queue-page.ts"); +type QueuePage = typeof import("../dash/api/queue-page.ts"); + +/** queueAdd from a module loaded beforehand, so nothing but the handler's own checks runs between the freshness check and its write. */ +const queueVia = ({ queueAdd }: QueuePage): QueueFn => async (db, o) => { // The permission read covers the item's repo only; any other repo counts as no access. const has = async (repo: string): Promise => repo === o.repo && o.canWrite; const user = { login: o.login, role: o.role, canWrite: has, canRead: has }; @@ -121,22 +123,49 @@ function settle(db: DatabaseSync, r: Row, state: "done" | "refused" | "ignored" * (settleRefusal in src/settlers.ts) to the commenter's current role and the write permission read from GitHub now. This only settles what a * comment adds: who the commenter is. Returns false when GitHub could not tell the permission: the row stays queued. */ -async function carryOut(db: DatabaseSync, r: Row, deps: CommandDeps, now: Date): Promise { +async function carryOut(db: DatabaseSync, r: Row, deps: CommandDeps, now: Date, qp: QueuePage): Promise<"settled" | "retry" | "wait"> { const access = getAccess(db, r.login); const bound = (db.prepare("SELECT github_id FROM main.access WHERE login = ?").get(r.login) as { github_id: number | null } | undefined)?.github_id ?? null; // Not someone AutoCraft knows (no login, or the login now belongs to another GitHub account): no answer. - if (!access || (bound !== null && Number(bound) !== r.github_id)) { settle(db, r, "ignored", null, now); return true; } - if (bound === null) { settle(db, r, "refused", "sign in to the AutoCraft dashboard once first, so your GitHub account is bound to your login", now); return true; } + if (!access || (bound !== null && Number(bound) !== r.github_id)) { settle(db, r, "ignored", null, now); return "settled"; } + if (bound === null) { settle(db, r, "refused", "sign in to the AutoCraft dashboard once first, so your GitHub account is bound to your login", now); return "settled"; } const permission = deps.permission ?? (await import("../conversations/act.ts")).liveWrite; const p = await permission(deps.querier, r.repo, r.login).catch(() => "transient" as const); - if (p === "transient") return false; + if (p === "transient") return "retry"; + // Again after the permission read, which awaited GitHub: a read that started before the comment (a reconcile, say) may have + // written an older snapshot meanwhile, which also sets its item's read time back. From here to queueAdd's pre-approval nothing + // waits on I/O (the module is loaded, the permission is known), so no other write can come between this check and that one. + if (waitsForRead(db, r, now, qp)) return "wait"; try { - const label = await (deps.queue ?? defaultQueue)(db, { login: r.login, role: access.role, canWrite: p === "ok", repo: r.repo, item: refOf(r), weight: r.weight }); + const label = await (deps.queue ?? queueVia(qp))(db, { login: r.login, role: access.role, canWrite: p === "ok", repo: r.repo, item: refOf(r), weight: r.weight }); const f = fastPositions(db).get(refOf(r)); settle(db, r, "done", `${oneLine(label)}.${f ? ` Fast-tracked with weight ${f.weight}, ${f.position} of ${f.of}.` : ""}`, now); } catch (e) { settle(db, r, "refused", oneLine(String((e as Error)?.message ?? e)) || "it could not be queued", now); } + return "settled"; +} + +/** + * True while an item the command may pre-approve has no read from GitHub since the comment: the item, and for an issue the open PRs + * that close it (queueAdd queues the sole one). The read is the webhook's re-read, or the poll after a failed one; a request row + * that is gone proves nothing, since a failed re-read drops it too. It must have started strictly after the comment: `synced_at` is + * cut to the second, so one in the same instant may have started before it. For each stale item with no read queued it queues one, + * at most once a minute (tried_at), so the command does not wait for a poll that may never read it again. + */ +function waitsForRead(db: DatabaseSync, r: Row, now: Date, qp: QueuePage): boolean { + const readAt = db.prepare("SELECT synced_at FROM main.item_reads WHERE repo = ? AND number = ?"); + const stale = [r.number, ...(r.pr ? [] : qp.openPrsClosing(db, r.repo, r.number))].filter((n) => { + const read = (readAt.get(r.repo, n) as { synced_at: string } | undefined)?.synced_at; + return !read || Date.parse(read) <= Date.parse(r.requested_at); + }); + if (!stale.length) return false; + const ask = stale.filter((n) => !db.prepare("SELECT 1 FROM main.sync_requests WHERE repo = ? AND number = ?").get(r.repo, n)); + for (const n of ask) { + db.prepare("INSERT INTO main.sync_requests (repo, number, event, requested_at) VALUES (?, ?, 'issue_comment', ?) ON CONFLICT (repo, number) DO NOTHING") + .run(r.repo, n, now.toISOString().replace(/\.\d+Z$/, "Z")); + } + if (ask.length) db.prepare("UPDATE main.github_commands SET tried_at = ? WHERE comment_id = ?").run(now.toISOString(), r.comment_id); return true; } @@ -179,7 +208,7 @@ export async function drainCommands(db: DatabaseSync, deps: CommandDeps): Promis const rows = db.prepare(`SELECT comment_id, repo, number, pr, command, weight, login, github_id, requested_at, state, result FROM main.github_commands WHERE (state = 'queued' AND (tried_at IS NULL OR tried_at <= ?)) OR (state IN ('done', 'refused') AND reply IS NULL) ORDER BY requested_at`) .all(new Date(t0.getTime() - RETRY_MS).toISOString()) as Row[]; - const readAt = db.prepare("SELECT synced_at FROM main.item_reads WHERE repo = ? AND number = ?"); + const qp = await import("../dash/api/queue-page.ts"); let settled = 0, calls = 0; for (const r0 of rows) { if (calls >= (deps.limit ?? 10)) break; @@ -188,28 +217,12 @@ export async function drainCommands(db: DatabaseSync, deps: CommandDeps): Promis if (r.state === "queued") { if (now.getTime() - Date.parse(r.requested_at) > EXPIRE_MS) { settle(db, r, "expired", null, now); continue; } if (r.command !== "merge-queue") { settle(db, r, "ignored", null, now); continue; } - // Every item the command may pre-approve must have been read from GitHub since the comment (the webhook's re-read, or the - // poll after a failed one), so it is queued at its current head: the item, and for an issue the open PRs that close it (queueAdd - // queues the sole one). A request row that is gone proves nothing: a failed re-read drops it too. A read must have started - // strictly after the comment: `synced_at` is cut to the second, so one in the same instant may have started before it. - const { openPrsClosing } = await import("../dash/api/queue-page.ts"); - const stale = [r.number, ...(r.pr ? [] : openPrsClosing(db, r.repo, r.number))].filter((n) => { - const read = (readAt.get(r.repo, n) as { synced_at: string } | undefined)?.synced_at; - return !read || Date.parse(read) <= Date.parse(r.requested_at); - }); - if (stale.length) { - // No read since the comment (the re-read failed, or started within the comment's second): ask for one of each item that has - // none queued, at most once a minute (tried_at), so the command does not wait for a poll that may never read them again. - const ask = stale.filter((n) => !db.prepare("SELECT 1 FROM main.sync_requests WHERE repo = ? AND number = ?").get(r.repo, n)); - for (const n of ask) { - db.prepare("INSERT INTO main.sync_requests (repo, number, event, requested_at) VALUES (?, ?, 'issue_comment', ?) ON CONFLICT (repo, number) DO NOTHING") - .run(r.repo, n, now.toISOString().replace(/\.\d+Z$/, "Z")); - } - if (ask.length) db.prepare("UPDATE main.github_commands SET tried_at = ? WHERE comment_id = ?").run(now.toISOString(), r.comment_id); - continue; - } + // No GitHub call while an item waits for a read since the comment (see waitsForRead). + if (waitsForRead(db, r, now, qp)) continue; calls++; - if (!(await carryOut(db, r, deps, now))) { + const out = await carryOut(db, r, deps, now, qp); + if (out === "wait") continue; + if (out === "retry") { // GitHub could not tell the permission: retried after RETRY_MS; the expiry still counts from requested_at. db.prepare("UPDATE main.github_commands SET tried_at = ? WHERE comment_id = ?").run(now.toISOString(), r.comment_id); continue; diff --git a/test/github-commands.test.ts b/test/github-commands.test.ts index 9f64041ec..7f144e0e1 100644 --- a/test/github-commands.test.ts +++ b/test/github-commands.test.ts @@ -157,6 +157,19 @@ describe("drainCommands", () => { assert.equal(await drainCommands(w.db, deps(w, { exec: ghFake().exec, now: () => new Date(Date.parse(at) + 2 * 60_000) })), 1, "one millisecond later counts"); }); + test("an older read written while the permission is read from GitHub makes the command wait instead of queuing that head", async () => { + const w = fresh().pr(1); + deliver(w, payload({ body: `@${SLUG} merge queue` })); + w.db.exec("DELETE FROM sync_requests"); + readAt(w, 1, new Date(Date.now() + 1000)); + // A reconcile that started before the comment lands while the permission read waits on GitHub: it sets the read time back. + const permission = async () => { readAt(w, 1, new Date(Date.now() - 60_000)); return "ok" as const; }; + assert.equal(await drainCommands(w.db, { ...deps(w, { exec: ghFake().exec }), permission }), 0); + assert.equal(rows(w)[0]!.state, "queued"); + assert.equal(preapprovalOf(w.db, "app", 1), null, "the older snapshot is not pre-approved"); + assert.deepEqual(w.db.prepare("SELECT number FROM sync_requests").all().map((r) => ({ ...r })), [{ number: 1 }], "the item is read again"); + }); + test("on an issue, the PR that closes it must be read after the comment too before it is queued", async () => { const w = fresh().issue(3).pr(4); w.db.prepare("UPDATE items SET closing_issues = '[3]' WHERE repo = 'app' AND number = 4").run();