Convert the GitHub user lane, vault, webhooks and write statements to Kysely

This commit is contained in:
aiongg committed 2026-11-21 22:55:04 +00:00
1 parent a88b4f543f
commit 07bd3e0e3e
14 files changed
+139 -114

No files matched your search

+22 -13
View File
@@ -16,7 +16,7 @@ import { exec as defaultExec, type Exec } from "../fixup/git.ts";
import { Client, GithubError, Transient, type Querier } from "../mirror.ts";
import { slugOf } from "../owners.ts";
import type { Db } from "../db/index.ts";
import { ciEq } from "../db/portable.ts";
import * as kx from "../db/kx.ts";
export type ExecState = "pending" | "waiting-token" | "waiting-permission" | "done" | "failed";
export const WAITING: readonly ExecState[] = ["waiting-token", "waiting-permission"];
@@ -26,12 +26,15 @@ export const noWriteReason = (repo: string): string => `You have no write access
/** Sets the state shown on the decision. Writes nothing when it is already that, so the planner is not woken for nothing. */
export async function setExecState(db: Db, id: string, state: ExecState, reason: string | null = null): Promise<void> {
await db.prepare("UPDATE main.decisions SET exec_state = ?, exec_reason = ? WHERE id = ? AND exec_state IS DISTINCT FROM 'disputed' AND (exec_state IS DISTINCT FROM ? OR exec_reason IS DISTINCT FROM ?)").run(state, reason, id, state, reason);
await db.run(db.k.updateTable("main.decisions").set({ exec_state: state, exec_reason: reason }).where("id", "=", id)
.where("exec_state", "is distinct from", "disputed")
.where((eb) => eb.or([eb("exec_state", "is distinct from", state), eb("exec_reason", "is distinct from", reason)])));
}
/** Decisions the pipeline applied are done. */
export async function markExecDone(db: Db): Promise<void> {
await db.prepare("UPDATE main.decisions SET exec_state = 'done', exec_reason = NULL WHERE applied_at IS NOT NULL AND exec_state IS NOT NULL AND exec_state <> 'done'").run();
await db.run(db.k.updateTable("main.decisions").set({ exec_state: "done", exec_reason: null })
.where("applied_at", "is not", null).where("exec_state", "is not", null).where("exec_state", "<>", "done"));
}
/**
@@ -39,28 +42,33 @@ export async function markExecDone(db: Db): Promise<void> {
* (a database read only: the network checks happen when the write runs).
*/
export async function initExecState(db: Db, id: string): Promise<void> {
const d = await db.prepare("SELECT repo, answered_by FROM main.decisions WHERE id = ? AND answer IS NOT NULL AND applied_at IS NULL").get(id) as { repo: string | null; answered_by: string | null } | undefined;
const d = await db.get(db.k.selectFrom("main.decisions").select(["repo", "answered_by"]).where("id", "=", id)
.where("answer", "is not", null).where("applied_at", "is", null));
if (!d?.repo || !d.answered_by || await githubIdentity(db) !== "app") return;
const has = await db.prepare("SELECT 1 FROM main.user_tokens WHERE login = ? AND status = 'ok'").get(d.answered_by);
const has = await db.get(db.k.selectFrom("main.user_tokens").select("login").where("login", "=", d.answered_by).where("status", "=", "ok"));
if (has) await setExecState(db, id, "pending");
else await setExecState(db, id, "waiting-token", SIGN_IN_REASON);
}
/** Puts the waiting (and, for one decision, failed) decisions back to pending so the stages take them up again. Returns how many changed. */
export async function retryWaiting(db: Db, login?: string): Promise<number> {
const r = await db.prepare(`UPDATE main.decisions SET exec_state = 'pending', exec_reason = NULL
WHERE exec_state IN ('waiting-token', 'waiting-permission') AND applied_at IS NULL AND answer IS NOT NULL AND (CAST(? AS TEXT) IS NULL OR ${ciEq(db, "answered_by", "?")})`).run(login ?? null, login ?? null);
const r = await db.run(db.k.updateTable("main.decisions").set({ exec_state: "pending", exec_reason: null })
.where("exec_state", "in", ["waiting-token", "waiting-permission"]).where("applied_at", "is", null).where("answer", "is not", null)
.$if(login != null, (q) => q.where((eb) => kx.ciEq(db, "answered_by", eb.val(login!)))));
return Number(r.changes);
}
/** Act's tries of a decision start again: a target it stopped after repeated failures is planned once more. Used when the answer is undone, given again, kept after a dispute, or retried. */
export async function resetActTries(db: Db, id: string): Promise<void> {
await db.prepare("UPDATE main.actions SET state = CASE WHEN state = 'stopped' THEN 'failed' ELSE state END, attempts = 0 WHERE decision_id = ? AND state IN ('stopped', 'failed')").run(id);
await db.run(db.k.updateTable("main.actions")
.set((eb) => ({ state: eb.case().when("state", "=", "stopped").then("failed").else(eb.ref("state")).end(), attempts: 0 }))
.where("decision_id", "=", id).where("state", "in", ["stopped", "failed"]));
}
export async function retryDecision(db: Db, id: string): Promise<boolean> {
const r = await db.prepare(`UPDATE main.decisions SET exec_state = 'pending', exec_reason = NULL
WHERE id = ? AND exec_state IN ('waiting-token', 'waiting-permission', 'failed') AND applied_at IS NULL AND answer IS NOT NULL`).run(id);
const r = await db.run(db.k.updateTable("main.decisions").set({ exec_state: "pending", exec_reason: null })
.where("id", "=", id).where("exec_state", "in", ["waiting-token", "waiting-permission", "failed"])
.where("applied_at", "is", null).where("answer", "is not", null));
if (Number(r.changes) > 0) await resetActTries(db, id);
return Number(r.changes) > 0;
}
@@ -165,7 +173,8 @@ export async function resolveLane(deps: LaneDeps, login: string, repos: string[]
const NOT_APP_REASON = "This answer was given by a maintainer and can only be carried out as that person: the repo does not use the app identity";
const answeredByMaintainer = async (db: Db, decisionId: string): Promise<boolean> =>
!!await db.prepare("SELECT 1 FROM main.decisions d JOIN main.access a ON a.login = d.answered_by WHERE d.id = ? AND a.role = 'maintainer'").get(decisionId);
!!await db.get(db.k.selectFrom("main.decisions as d").innerJoin("main.access as a", "a.login", "d.answered_by").select("d.id")
.where("d.id", "=", decisionId).where("a.role", "=", "maintainer"));
/**
* The lane for the operator who answered `decisionId`, or null when every repo is on the box account (`legacy`): the
@@ -177,7 +186,7 @@ export async function laneForDecision(db: Db, deps: LaneDeps | undefined, decisi
if (app.length < repos.length && await answeredByMaintainer(db, decisionId)) return { state: "waiting-permission", reason: NOT_APP_REASON };
if (!app.length) return null;
// A decision that waits stays put until its operator signs in or someone retries it: no network call per run.
const row = await db.prepare("SELECT exec_state, exec_reason FROM main.decisions WHERE id = ?").get(decisionId) as { exec_state: string | null; exec_reason: string | null } | undefined;
const row = await db.get(db.k.selectFrom("main.decisions").select(["exec_state", "exec_reason"]).where("id", "=", decisionId));
if (row && (row.exec_state === "waiting-token" || row.exec_state === "waiting-permission")) return { state: row.exec_state, reason: row.exec_reason ?? SIGN_IN_REASON };
const who = await identityOfDecision(db, decisionId);
if (who === "app") return { state: "waiting-token", reason: SIGN_IN_REASON };
@@ -193,7 +202,7 @@ export async function laneForOperator(db: Db, deps: LaneDeps | undefined, login:
/** A decision that waits for its operator's token or access, or whose answer is disputed: the stages leave it out of their work until it is retried or the dispute is settled. */
export async function isWaiting(db: Db, decisionId: string | null | undefined): Promise<boolean> {
if (!decisionId) return false;
const r = await db.prepare("SELECT exec_state FROM main.decisions WHERE id = ?").get(decisionId) as { exec_state: string | null } | undefined;
const r = await db.get(db.k.selectFrom("main.decisions").select("exec_state").where("id", "=", decisionId));
return r?.exec_state === "waiting-token" || r?.exec_state === "waiting-permission" || r?.exec_state === "disputed";
}
+8 -6
View File
@@ -101,11 +101,13 @@ export class Vault {
if (this.#sweeping) return 0;
this.#sweeping = true;
try {
const rows = await this.#db.prepare(`SELECT id, login, token_enc, kind, aad, attempts FROM user_token_revocations ${fresh ? "WHERE attempts = 0 " : ""}ORDER BY id`)
.all() as { id: number; login: string; token_enc: string; kind: string; aad: string | null; attempts: number }[];
const rows = await this.#db.all(this.#db.k.selectFrom("user_token_revocations")
.select(["id", "login", "token_enc", "kind", "aad", "attempts"])
.$if(fresh, (q) => q.where("attempts", "=", 0)).orderBy("id"));
for (const r of rows) {
// Claim the attempt first: a concurrent sweep (another process) that read the same row changes nothing here and skips it.
if ((await this.#db.prepare("UPDATE user_token_revocations SET attempts = attempts + 1 WHERE id = ? AND attempts = ?").run(r.id, r.attempts)).changes !== 1) continue;
if ((await this.#db.run(this.#db.k.updateTable("user_token_revocations").set((eb) => ({ attempts: eb("attempts", "+", 1) }))
.where("id", "=", r.id).where("attempts", "=", r.attempts))).changes !== 1) continue;
let done = false;
try {
done = await this.#revokeRow(r);
@@ -113,10 +115,10 @@ export class Vault {
console.error(`revocation for ${r.login}: ${(e as Error).message}`);
}
if (done) {
await this.#db.prepare("DELETE FROM user_token_revocations WHERE id = ?").run(r.id);
await this.#db.run(this.#db.k.deleteFrom("user_token_revocations").where("id", "=", r.id));
} else if (r.attempts + 1 >= MAX_REVOKE_ATTEMPTS) {
console.error(`revocation for ${r.login}: given up after ${r.attempts + 1} failed attempts`);
await this.#db.prepare("DELETE FROM user_token_revocations WHERE id = ?").run(r.id);
await this.#db.run(this.#db.k.deleteFrom("user_token_revocations").where("id", "=", r.id));
}
}
return rows.length;
@@ -156,7 +158,7 @@ export class Vault {
if (!access) return false;
await revoke(access);
}
if (sameSignIn) await this.#db.prepare("DELETE FROM user_tokens WHERE login = ?").run(r.login);
if (sameSignIn) await this.#db.run(this.#db.k.deleteFrom("user_tokens").where("login", "=", r.login));
return true;
}
}
+11 -7
View File
@@ -6,6 +6,7 @@ import { queueCommand } from "./commands.ts";
import { ONE_QUERY, Transient, writeItemNode, type Querier } from "../mirror.ts";
import { ownerOf } from "../owners.ts";
import type { Db } from "../db/index.ts";
import * as kx from "../db/kx.ts";
export const WEBHOOK_PATH = "/webhooks/github";
export const WEBHOOK_BODY_LIMIT = 1024 * 1024;
@@ -28,7 +29,7 @@ async function trackedName(db: Db, payload: Obj): Promise<string | null> {
if (i < 1) return null;
const owner = full.slice(0, i);
const name = full.slice(i + 1);
if (!await db.prepare("SELECT 1 FROM main.tracked_repos WHERE name = ?").get(name)) return null;
if (!await db.get(db.k.selectFrom("main.tracked_repos").select("name").where("name", "=", name))) return null;
return ownerOf(name).toLowerCase() === owner.toLowerCase() ? name : null;
}
@@ -53,7 +54,8 @@ export async function itemNumbers(db: Db, repo: string, event: string, payload:
if (own.length || listed.length) return own;
const sha = body.head_sha;
if (typeof sha !== "string" || !sha) return [];
return (await db.prepare("SELECT number FROM main.items WHERE repo = ? AND kind = 'pr' AND state = 'OPEN' AND head_oid = ?").all(repo, sha) as { number: number }[]).map((r) => r.number);
return (await db.all(db.k.selectFrom("main.items").select("number").where("repo", "=", repo).where("kind", "=", "pr")
.where("state", "=", "OPEN").where("head_oid", "=", sha))).map((r) => r.number);
}
default: return [];
}
@@ -73,9 +75,10 @@ export async function queueDelivery(db: Db, event: string, payload: unknown, now
const numbers = await itemNumbers(db, repo, event, p);
if (!numbers.length) return 0;
const at = now.toISOString().replace(/\.\d+Z$/, "Z");
const ins = db.prepare(`INSERT INTO main.sync_requests (repo, number, event, requested_at) VALUES (?, ?, ?, ?)
ON CONFLICT (repo, number) DO UPDATE SET event = excluded.event, requested_at = excluded.requested_at`);
for (const n of numbers) await ins.run(repo, n, event, at);
for (const n of numbers) {
await db.run(db.k.insertInto("main.sync_requests").values({ repo, number: n, event, requested_at: at })
.onConflict((oc) => oc.columns(["repo", "number"]).doUpdateSet(kx.excluded(["event", "requested_at"]))));
}
return numbers.length;
}
@@ -106,11 +109,12 @@ const ABANDON_MS = 6 * 3600_000;
*/
export async function drainSyncRequests(db: Db, client: Querier, opts: { limit?: number; reserve?: number; now?: Date; log?: (l: string) => void } = {}): Promise<number> {
const now = opts.now ?? new Date();
const rows = await db.prepare("SELECT repo, number, requested_at FROM main.sync_requests ORDER BY requested_at LIMIT ?").all(opts.limit ?? 20) as { repo: string; number: number; requested_at: string }[];
const rows = await db.all(db.k.selectFrom("main.sync_requests").select(["repo", "number", "requested_at"])
.orderBy("requested_at").limit(opts.limit ?? 20));
let done = 0;
for (const r of rows) {
// Arrived after this row was read: left for the next drain.
const gone = async (): Promise<void> => void await db.prepare("DELETE FROM main.sync_requests WHERE repo = ? AND number = ? AND requested_at = ?").run(r.repo, r.number, r.requested_at);
const gone = async (): Promise<void> => void await db.run(db.k.deleteFrom("main.sync_requests").where("repo", "=", r.repo).where("number", "=", r.number).where("requested_at", "=", r.requested_at));
if (now.getTime() - Date.parse(r.requested_at) > ABANDON_MS) { await gone(); continue; }
// Never wait out a rate limit here; the poll has its own handling.
if (client.remaining !== null && client.remaining < (opts.reserve ?? 1000)) break;
+23 -16
View File
@@ -25,7 +25,7 @@ import { createHash } from "node:crypto";
import { giveaway } from "../security/rules.ts";
import { filterSeq, forEachSeq } from "../async-seq.ts";
import type { Db } from "../db/index.ts";
import { inList, jsonNum, jsonText, jsonValid } from "../db/portable.ts";
import * as kx from "../db/kx.ts";
import { openDb } from "../db/open.ts";
export { GITHUB_ACTIONS } from "./actions.ts";
@@ -161,11 +161,12 @@ function paceOwner(identity: string, target: string, owner?: string): string {
/** How long a write of `action` by `identity` on `owner`'s key waits for the budget now (0: it may start). Reads only. */
async function keyWait(db: Db, action: string, identity: string, owner: string, now: number): Promise<number> {
const d = `CASE WHEN ${jsonValid(db, "details")} THEN details END`;
const rows = await db.prepare(
`SELECT at, ${jsonText(db, d, "$.state")} AS state, ${jsonText(db, d, "$.error")} AS error FROM audit
WHERE at >= ? AND ${jsonText(db, d, "$.identity")} = ? AND ${jsonText(db, d, "$.paceOwner")} = ? ORDER BY at, rowid`,
).all(new Date(now - 3_600_000).toISOString(), identity, owner) as { at: string; state: string | null; error: string | null }[];
const valid = (eb: kx.AnyEb) => eb.case().when(kx.jsonValid(db, "details")).then(eb.ref("details")).end();
const rows = await db.all(db.k.selectFrom("audit")
.select((eb) => ["at", kx.jsonText(db, valid(eb), "$.state").as("state"), kx.jsonText(db, valid(eb), "$.error").as("error")])
.where("at", ">=", new Date(now - 3_600_000).toISOString())
.where((eb) => eb.and([eb(kx.jsonText(db, valid(eb), "$.identity"), "=", identity), eb(kx.jsonText(db, valid(eb), "$.paceOwner"), "=", owner)]))
.orderBy("at").orderBy(kx.rowid("audit")));
const times = rows.map((r) => Date.parse(r.at));
const inMinute = times.filter((t) => t > now - 60_000);
const share = BULK_ACTIONS.has(action) ? BULK_SHARE : 1;
@@ -196,8 +197,9 @@ export async function pipelineWriteWait(db: Db, action: string, repo: string, no
async function tryBegin(w: Writer, action: string, target: string, details: Details, now: number, ownerArg?: string): Promise<{ id: number } | { wait: number }> {
const identity = String(details.identity ?? "");
const owner = paceOwner(identity, target, ownerArg);
const insert = async (d: Details): Promise<number> => Number((await w.db.prepare("INSERT INTO audit (at, login, action, target, details) VALUES (?, ?, ?, ?, ?) RETURNING rowid")
.get(new Date(now).toISOString(), w.login, action, target, JSON.stringify(d)) as { rowid: number }).rowid);
const insert = async (d: Details): Promise<number> => (await w.db.get(w.db.k.insertInto("audit")
.values({ at: new Date(now).toISOString(), login: w.login, action, target, details: JSON.stringify(d) })
.returning(kx.rowid("audit").as("rowid"))))!.rowid;
const started = { ...details, state: "started" };
if (identity.startsWith("user:")) return { id: await insert(started) };
return await w.db.write(async () => {
@@ -290,7 +292,7 @@ async function begin(w: Writer, action: string, target: string, details: Details
if ("id" in r) {
// Checked and tracked in one turn of the event loop: stopWrites either waits for this write, or it is not made.
const id = r.id;
if (stoppedWhy !== null) return await park(async () => { await w.db.prepare("DELETE FROM audit WHERE rowid = ?").run(id); await beforePark?.(); });
if (stoppedWhy !== null) return await park(async () => { await w.db.run(w.db.k.deleteFrom("audit").where(kx.rowid("audit"), "=", id)); await beforePark?.(); });
track(id);
return id;
}
@@ -305,10 +307,10 @@ async function finish(w: Writer, id: number, details: Details, error?: string, o
// The pacing key's owner, set by begin(), stays on the row.
try {
await w.db.write(async () => {
const row = await w.db.prepare("SELECT details FROM audit WHERE rowid = ?").get(id) as { details: string | null } | undefined;
const row = await w.db.get(w.db.k.selectFrom("audit").select("details").where(kx.rowid("audit"), "=", id));
let owner: unknown = null;
try { owner = (JSON.parse(row?.details ?? "null") as { paceOwner?: unknown } | null)?.paceOwner ?? null; } catch { /* no owner */ }
await w.db.prepare("UPDATE audit SET details = ? WHERE rowid = ?").run(JSON.stringify(owner === null ? d : { ...d, paceOwner: owner }), id);
await w.db.run(w.db.k.updateTable("audit").set({ details: JSON.stringify(owner === null ? d : { ...d, paceOwner: owner }) }).where(kx.rowid("audit"), "=", id));
});
} finally {
if (owes) owed++;
@@ -339,9 +341,14 @@ async function madeBefore(w: Writer, action: string, target: string, keys: strin
if (job === null) return null;
const run = await resumedRun(w.db, job);
if (!run) return null;
const rows = await w.db.prepare(`SELECT rowid AS id, details FROM audit WHERE target = ? AND action = ? AND at < ? AND ${jsonNum(w.db, "details", "$.jobId")} = ?
AND ${inList(w.db, jsonText(w.db, "details", "$.writeKey"))} AND ${jsonText(w.db, "details", "$.state")} IN ('done', 'started') ORDER BY rowid DESC`)
.all(target, action, run.startedAt, job, JSON.stringify(keys)) as { id: number; details: string }[];
const rows = await w.db.all(w.db.k.selectFrom("audit").select([kx.rowid("audit").as("id"), "details"]).$narrowType<{ details: string }>()
.where("target", "=", target).where("action", "=", action).where("at", "<", run.startedAt)
.where((eb) => eb.and([
eb(kx.jsonNum(w.db, "details", "$.jobId"), "=", job),
kx.inList(w.db, kx.jsonText(w.db, "details", "$.writeKey"), keys),
eb(kx.jsonText(w.db, "details", "$.state"), "in", ["done", "started"]),
]))
.orderBy(kx.rowid("audit"), "desc"));
const done = rows.find((r) => (JSON.parse(r.details) as Details).state === "done");
if (done) return { done: JSON.parse(done.details) as Details };
return rows.length ? { unknown: Number(rows[0]!.id) } : null;
@@ -552,7 +559,7 @@ export async function addLabels(w: Writer, q: Querier, repo: string, items: Labe
const unsent = async (): Promise<void> => {
for (const id of ids) {
untrack(id);
await w.db.prepare("DELETE FROM audit WHERE rowid = ?").run(id);
await w.db.run(w.db.k.deleteFrom("audit").where(kx.rowid("audit"), "=", id));
}
};
try {
@@ -805,7 +812,7 @@ export function pushOwnBranch(w: Writer, g: Grant, git: Pick<Git, "git">, action
// A new branch has no PR yet: its outcome is matched to the PR by commit once the PR's checks arrive.
return pushed(w, g, git, action, o.number === undefined ? `${o.repo}:${o.branch}` : refOf(o.repo, o.number), o, "--force", details, { repo: o.repo, number: null }, asBox).then(async (r) => {
// Without this row the pipeline's own PR at this commit is not counted as its own (a person is asked), so a failed write only holds it.
if (r.code === 0) try { await w.db.prepare("INSERT OR IGNORE INTO main.own_commits (repo, sha, action, at) VALUES (?, ?, ?, ?)").run(o.repo, o.sha, action, new Date().toISOString()); } catch (e) { console.error(`own commit not recorded: ${oneLine(String((e as Error).message ?? e))}`); }
if (r.code === 0) try { await w.db.run(w.db.k.insertInto("main.own_commits").values({ repo: o.repo, sha: o.sha, action, at: new Date().toISOString() }).onConflict((oc) => oc.doNothing())); } catch (e) { console.error(`own commit not recorded: ${oneLine(String((e as Error).message ?? e))}`); }
return r;
});
}