diff --git a/src/github/user-lane.ts b/src/github/user-lane.ts index 3ceee5926..650537463 100644 --- a/src/github/user-lane.ts +++ b/src/github/user-lane.ts @@ -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 { - 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 { - 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 { * (a database read only: the network checks happen when the write runs). */ export async function initExecState(db: Db, id: string): Promise { - 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 { - 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 { - 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 { - 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 => - !!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 { 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"; } diff --git a/src/github/vault.ts b/src/github/vault.ts index 5a2222e58..8cfa7f52f 100644 --- a/src/github/vault.ts +++ b/src/github/vault.ts @@ -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; } } diff --git a/src/github/webhooks.ts b/src/github/webhooks.ts index 8c82a3f84..e700c6b66 100644 --- a/src/github/webhooks.ts +++ b/src/github/webhooks.ts @@ -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 { 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 { 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 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 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; diff --git a/src/github/write.ts b/src/github/write.ts index 26068b60c..c2a4f700a 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -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 { - 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((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 => (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 => { 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, 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; }); } diff --git a/test/api.test.ts b/test/api.test.ts index 79d018dcd..242c2b397 100644 --- a/test/api.test.ts +++ b/test/api.test.ts @@ -122,7 +122,7 @@ async function signedIn(login: string): Promise { const actionableIds = async () => (await actionable(db)).map((d) => d.id); const auditCount = async (action: string, login: string) => - (await db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action = ? AND login = ?").get(action, login) as { n: number }).n; + (await db.get(db.k.selectFrom("audit").select((eb) => eb.fn.countAll().as("n")).where("action", "=", action).where("login", "=", login)))!.n; describe("api", () => { test("without a session every endpoint answers 401 JSON", async () => { @@ -203,7 +203,7 @@ describe("api", () => { await c.post(dpath(P1, "/answer"), { answer: "small" }, 403); await c.post(dpath(P1, "/undo"), undefined, 403); } - const audits = async () => (await db.prepare("SELECT COUNT(*) AS n FROM audit WHERE login = 'viewer1'").get() as { n: number }).n; + const audits = async () => (await db.get(db.k.selectFrom("audit").select((eb) => eb.fn.countAll().as("n")).where("login", "=", "viewer1")))!.n; const before = await audits(); await viewer.post(dpath(P1, "/feedback"), { option: "plugin", text: `viewer ${MARKER}` }, 403); await viewer.post(dpath(P1, "/feedback"), { text: `viewer ${MARKER}` }, 403); diff --git a/test/app-lane.test.ts b/test/app-lane.test.ts index bc1d66e11..6adf60b56 100644 --- a/test/app-lane.test.ts +++ b/test/app-lane.test.ts @@ -12,6 +12,7 @@ import type { GuardedItem, GuardedRepo } from "../src/core/guard.ts"; import type { ExecOpts } from "../src/fixup/git.ts"; import { SCRATCH } from "./scratch.ts"; import { connectDb } from "../src/db/open.ts"; +import * as kx from "../src/db/kx.ts"; const BOX = "ghp_box_account_token"; const APP = "ghs_installation_token"; @@ -22,7 +23,7 @@ const note = { by: "fixed" } as never; test("app identity: the installation token is the whole child environment; legacy and user grants are untouched", async () => { mkdirSync(SCRATCH, { recursive: true }); const db = await connectDb(join(SCRATCH, `app-lane-${process.pid}.db`)); - await db.prepare("INSERT OR IGNORE INTO tracked_repos (name) VALUES ('lane')").run(); + await db.run(db.k.insertInto("tracked_repos").values({ name: "lane" }).onConflict((oc) => oc.doNothing())); process.env.GITHUB_TOKEN = BOX; process.env.GH_TOKEN = BOX; let mintFails = false; @@ -58,6 +59,6 @@ test("app identity: the installation token is the whole child environment; legac assert.equal(r.code, 1); assert.match(r.stderr, /not installed on storytold/); assert.equal(seen.length, 0); - const row = await db.prepare("SELECT details FROM audit WHERE action = 'act-comment' ORDER BY rowid DESC LIMIT 1").get() as { details: string }; - assert.equal(JSON.parse(row.details).state, "failed"); + const row = (await db.get(db.k.selectFrom("audit").select("details").where("action", "=", "act-comment").orderBy(kx.rowid("audit"), "desc").limit(1)))!; + assert.equal(JSON.parse(row.details!).state, "failed"); }); diff --git a/test/github-commands.test.ts b/test/github-commands.test.ts index c3373f82e..03bafc173 100644 --- a/test/github-commands.test.ts +++ b/test/github-commands.test.ts @@ -10,6 +10,7 @@ import { preapprovalOf } from "../src/preapproval/index.ts"; import { OPERATOR, world, type World } from "./world-db.ts"; import { validating } from "./gql.ts"; import type { AppPermission } from "../src/remote/permission.ts"; +import * as kx from "../src/db/kx.ts"; const SLUG = "autocraft-bot"; const SECRET = "hook-secret"; @@ -18,7 +19,7 @@ const OP_ID = 101; let current: World | null = null; const fresh = async (off: Parameters[0] = []): Promise => { const w = (current = await (await world()).repo(off)); - await w.db.prepare("UPDATE access SET github_id = ? WHERE login = ?").run(OP_ID, OPERATOR); + await w.db.run(w.db.k.updateTable("access").set({ github_id: OP_ID }).where("login", "=", OPERATOR)); return w; }; afterEach(() => current?.close()); @@ -50,7 +51,7 @@ const stillThere = (w: World) => async (_repo: string, id: number): Promise async (_q: unknown, _repo: string, n: number): Promise => - ({ head: (await w.db.prepare("SELECT head_oid FROM items WHERE repo = 'app' AND number = ?").get(n) as { head_oid: string }).head_oid, opened: "2020-01-01T00:00:00Z", changed: false }); + ({ head: (await w.db.get(w.db.k.selectFrom("items").select("head_oid").where("repo", "=", "app").where("number", "=", n)))!.head_oid!, opened: "2020-01-01T00:00:00Z", changed: false }); const WRITE: AppPermission = { kind: "ok", permission: "write" }; const FAILED: AppPermission = { kind: "error", why: "GitHub permission check failed: HTTP 502" }; const PERMS: Record<"ok" | "no" | "transient", AppPermission> = { ok: WRITE, no: { kind: "ok", permission: "read" }, transient: FAILED }; @@ -62,7 +63,7 @@ const readAt = async (w: World, number: number, at: Date) => await w.db.prepare("INSERT INTO item_reads (repo, number, synced_at) VALUES ('app', ?, ?) ON CONFLICT (repo, number) DO UPDATE SET synced_at = excluded.synced_at").run(number, at.toISOString()); /** Drains after the re-reads: every commanded item was read just now. */ const drained = async (w: World, o: Parameters[1] = {}) => { - await w.db.script("DELETE FROM sync_requests"); + await w.db.run(w.db.k.deleteFrom("sync_requests")); for (const { number } of await w.db.prepare("SELECT DISTINCT number FROM github_commands").all() as { number: number }[]) await readAt(w, number, new Date(Date.now() + 1000)); return drainCommands(w.db, deps(w, o)); }; @@ -112,7 +113,7 @@ describe("webhook", () => { assert.deepEqual(await rows(w), [{ comment_id: 5000, number: 1, pr: 1, weight: 7, login: OPERATOR, state: "queued", result: null, reply: null }]); const cols = (await w.db.prepare("SELECT name FROM pragma_table_info('github_commands')").all() as { name: string }[]).map((c) => c.name); assert.ok(!cols.includes("body"), "the comment's text has no column"); - assert.deepEqual((await w.db.prepare("SELECT number FROM sync_requests").all()).map((r) => ({ ...r })), [{ number: 1 }], "the item is still re-read"); + assert.deepEqual((await w.db.all(w.db.k.selectFrom("sync_requests").select("number"))).map((r) => ({ ...r })), [{ number: 1 }], "the item is still re-read"); }); }); @@ -130,10 +131,11 @@ describe("drainCommands", () => { assert.equal(gh.posted.length, 1); assert.deepEqual(gh.posted[0]!.args.slice(0, 5), ["pr", "comment", "1", "--repo", "storytold/app"]); assert.match(gh.posted[0]!.body, /^_Automated reply_\n\n@op Added to the merge queue; .*Fast-tracked with weight 7, 1 of 1\.$/); - const audit = await w.db.prepare("SELECT action, login, details FROM audit WHERE action IN ('preapproval', 'fasttrack-add', 'github-command', 'github-command-reply') ORDER BY rowid").all() as { action: string; login: string; details: string }[]; + const audit = await w.db.all(w.db.k.selectFrom("audit").select(["action", "login", "details"]) + .where("action", "in", ["preapproval", "fasttrack-add", "github-command", "github-command-reply"]).orderBy(kx.rowid("audit"))); assert.deepEqual(audit.map((a) => [a.action, a.login]), [["preapproval", OPERATOR], ["fasttrack-add", OPERATOR], ["github-command", OPERATOR], ["github-command-reply", OPERATOR]]); - assert.equal(JSON.parse(audit[1]!.details).via, "github"); - assert.equal(JSON.parse(audit[3]!.details).state, "done"); + assert.equal(JSON.parse(audit[1]!.details!).via, "github"); + assert.equal(JSON.parse(audit[3]!.details!).state, "done"); assert.equal(await drained(w, { exec: gh.exec }), 0, "nothing is left"); assert.equal(gh.posted.length, 1); }); @@ -144,12 +146,12 @@ describe("drainCommands", () => { await deliver(w, payload({ body: `@${SLUG} merge queue` })); const gh = ghFake(); assert.equal(await drainCommands(w.db, deps(w, { exec: gh.exec })), 0, "the re-read is still queued"); - await w.db.script("DELETE FROM sync_requests"); + await w.db.run(w.db.k.deleteFrom("sync_requests")); assert.equal(await drainCommands(w.db, deps(w, { exec: gh.exec })), 0, "the request is gone but the last read is older than the comment"); assert.equal((await rows(w))[0]!.state, "queued"); assert.equal(await preapprovalOf(w.db, "app", 1), null); - assert.deepEqual((await w.db.prepare("SELECT number FROM sync_requests").all()).map((r) => ({ ...r })), [{ number: 1 }], "the command asks for a new read"); - await w.db.script("DELETE FROM sync_requests"); + assert.deepEqual((await w.db.all(w.db.k.selectFrom("sync_requests").select("number"))).map((r) => ({ ...r })), [{ number: 1 }], "the command asks for a new read"); + await w.db.run(w.db.k.deleteFrom("sync_requests")); await readAt(w, 1, new Date(Date.now() + 1000)); assert.equal(await drainCommands(w.db, deps(w, { exec: gh.exec })), 0, "it looks again a minute after asking"); const later = new Date(Date.now() + 2 * 60_000); @@ -160,7 +162,7 @@ describe("drainCommands", () => { test("a read stamped at the comment's own instant does not count: it may have started before it", async () => { const w = await (await fresh()).pr(1); await deliver(w, payload({ body: `@${SLUG} merge queue` })); - await w.db.script("DELETE FROM sync_requests"); + await w.db.run(w.db.k.deleteFrom("sync_requests")); const at = (await w.db.prepare("SELECT requested_at FROM github_commands").get() as { requested_at: string }).requested_at; await readAt(w, 1, new Date(at)); assert.equal(await drainCommands(w.db, deps(w, { exec: ghFake().exec })), 0); @@ -172,28 +174,28 @@ describe("drainCommands", () => { test("an older read written while the permission is read from GitHub makes the command wait instead of queuing that head", async () => { const w = await (await fresh()).pr(1); await deliver(w, payload({ body: `@${SLUG} merge queue` })); - await w.db.script("DELETE FROM sync_requests"); + await w.db.run(w.db.k.deleteFrom("sync_requests")); await 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 () => { await readAt(w, 1, new Date(Date.now() - 60_000)); return WRITE; }; assert.equal(await drainCommands(w.db, { ...deps(w, { exec: ghFake().exec }), permission }), 0); assert.equal((await rows(w))[0]!.state, "queued"); assert.equal(await preapprovalOf(w.db, "app", 1), null, "the older snapshot is not pre-approved"); - assert.deepEqual((await w.db.prepare("SELECT number FROM sync_requests").all()).map((r) => ({ ...r })), [{ number: 1 }], "the item is read again"); + assert.deepEqual((await w.db.all(w.db.k.selectFrom("sync_requests").select("number"))).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 = await (await (await fresh()).issue(3)).pr(4); - await w.db.prepare("UPDATE items SET closing_issues = '[3]' WHERE repo = 'app' AND number = 4").run(); + await w.db.run(w.db.k.updateTable("items").set({ closing_issues: "[3]" }).where("repo", "=", "app").where("number", "=", 4)); await readAt(w, 4, new Date(Date.now() - 60_000)); await deliver(w, payload({ body: `@${SLUG} merge queue`, number: 3, pr: false })); - await w.db.script("DELETE FROM sync_requests"); + await w.db.run(w.db.k.deleteFrom("sync_requests")); await readAt(w, 3, new Date(Date.now() + 1000)); assert.equal(await drainCommands(w.db, deps(w, { exec: ghFake().exec })), 0, "the issue is fresh, its closing PR is not"); - assert.deepEqual((await w.db.prepare("SELECT number FROM sync_requests").all()).map((r) => ({ ...r })), [{ number: 4 }], "the PR is read again"); + assert.deepEqual((await w.db.all(w.db.k.selectFrom("sync_requests").select("number"))).map((r) => ({ ...r })), [{ number: 4 }], "the PR is read again"); assert.equal(await preapprovalOf(w.db, "app", 4), null); await readAt(w, 4, new Date(Date.now() + 1000)); - await w.db.script("DELETE FROM sync_requests"); + await w.db.run(w.db.k.deleteFrom("sync_requests")); assert.equal(await drainCommands(w.db, deps(w, { exec: ghFake().exec, now: () => new Date(Date.now() + 2 * 60_000) })), 1); assert.equal((await preapprovalOf(w.db, "app", 4))?.state, "review"); }); @@ -203,7 +205,7 @@ describe("drainCommands", () => { await deliver(w, payload({ body: `@${SLUG} merge queue`, number: 1, comment: 7001 })); await deliver(w, payload({ body: `@${SLUG} merge queue`, number: 2, comment: 7002 })); await deliver(w, payload({ body: `@${SLUG} merge queue`, number: 3, comment: 7003 })); - await w.db.script("DELETE FROM sync_requests"); + await w.db.run(w.db.k.deleteFrom("sync_requests")); await readAt(w, 2, new Date(Date.now() + 1000)); await readAt(w, 3, new Date(Date.now() + 1000)); // #1 is not read yet; #2's permission cannot be told; with one GitHub call per drain #3 still gets its turn next. @@ -230,7 +232,7 @@ describe("drainCommands", () => { test("Queue items' rule decides: a maintainer without maintainer writes and an operator without write access are refused; a viewer or a login never bound gets no answer", async () => { const w = await (await fresh()).pr(1); - await w.db.prepare("INSERT INTO access (login, role, github_id) VALUES ('maint', 'maintainer', 202), ('view', 'viewer', 404), ('newop', 'operator', NULL)").run(); + await w.db.run(w.db.k.insertInto("access").values([{ login: "maint", role: "maintainer", github_id: 202 }, { login: "view", role: "viewer", github_id: 404 }, { login: "newop", role: "operator", github_id: null }])); await deliver(w, payload({ body: `@${SLUG} merge queue`, login: "maint", id: 202 })); await deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5001, login: "view", id: 404 })); await deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5002, login: "newop", id: 303 })); @@ -244,13 +246,14 @@ describe("drainCommands", () => { assert.equal(bodies.length, 2); assert.match(bodies[0]!, /@maint Not added to the merge queue: only an operator, or a maintainer with write access where the app acts for them, queues items on app\.$/); assert.match(bodies[1]!, /@op Not added to the merge queue: no write access to storytold\/app/); - assert.equal((await w.db.prepare("SELECT github_id FROM access WHERE login = 'newop'").get() as { github_id: number | null }).github_id, null, "a comment never binds an id"); + assert.equal((await w.db.get(w.db.k.selectFrom("access").select("github_id").where("login", "=", "newop")))!.github_id, null, "a comment never binds an id"); }); test("a maintainer who settles decisions on the repo queues, as with Queue items; without write access they do not", async () => { const w = await (await (await fresh()).pr(1)).pr(2); - await w.db.prepare("INSERT INTO access (login, role, github_id) VALUES ('maint', 'maintainer', 202)").run(); - await w.db.prepare("INSERT OR REPLACE INTO settings (key, value) VALUES ('maintainer_writes', '1'), ('github_identity', 'app')").run(); + await w.db.run(w.db.k.insertInto("access").values({ login: "maint", role: "maintainer", github_id: 202 })); + await w.db.run(w.db.k.insertInto("settings").values([{ key: "maintainer_writes", value: "1" }, { key: "github_identity", value: "app" }]) + .onConflict((oc) => oc.column("key").doUpdateSet(kx.excluded(["value"])))); await deliver(w, payload({ body: `@${SLUG} merge queue`, login: "maint", id: 202, number: 2, comment: 6000 })); await drained(w, { exec: ghFake().exec, perm: "no" }); assert.equal((await rows(w))[0]!.state, "refused"); @@ -299,7 +302,7 @@ describe("drainCommands", () => { test("due retries do not keep a command that was never tried out, also with drains minutes apart", async () => { const w = await (await (await (await fresh()).pr(1)).pr(2)).pr(3); for (const n of [1, 2, 3]) await deliver(w, payload({ body: `@${SLUG} merge queue`, number: n, comment: 8000 + n })); - await w.db.script("DELETE FROM sync_requests"); + await w.db.run(w.db.k.deleteFrom("sync_requests")); for (const n of [1, 2, 3]) await readAt(w, n, new Date(Date.now() + 1000)); // One GitHub call per drain, drains two minutes apart, so a retry is due again at every drain. GitHub cannot tell the // permission for the first two calls. Oldest first alone would retry #1 at every drain and never reach #3. @@ -316,20 +319,20 @@ describe("drainCommands", () => { test("the role and binding are read again after the permission read: a demoted or rebound commenter queues nothing", async () => { const w = await (await (await fresh()).pr(1)).pr(2); await deliver(w, payload({ body: `@${SLUG} merge queue`, number: 1, comment: 9001 })); - await w.db.script("DELETE FROM sync_requests"); + await w.db.run(w.db.k.deleteFrom("sync_requests")); await readAt(w, 1, new Date(Date.now() + 1000)); const gh = ghFake(); // Demoted to a maintainer, who does not settle here, while GitHub answers. - await drainCommands(w.db, { ...deps(w, { exec: gh.exec }), permission: async () => { await w.db.prepare("UPDATE access SET role = 'maintainer' WHERE login = ?").run(OPERATOR); return WRITE; } }); + await drainCommands(w.db, { ...deps(w, { exec: gh.exec }), permission: async () => { await w.db.run(w.db.k.updateTable("access").set({ role: "maintainer" }).where("login", "=", OPERATOR)); return WRITE; } }); assert.equal((await rows(w))[0]!.state, "refused"); assert.equal(await preapprovalOf(w.db, "app", 1), null); assert.match(gh.posted[0]!.body, /@op Not added to the merge queue: only an operator, or a maintainer/); // The login is bound to another GitHub account while GitHub answers: no pre-approval and no answer. - await w.db.prepare("UPDATE access SET role = 'operator' WHERE login = ?").run(OPERATOR); + await w.db.run(w.db.k.updateTable("access").set({ role: "operator" }).where("login", "=", OPERATOR)); await deliver(w, payload({ body: `@${SLUG} merge queue`, number: 2, comment: 9002 })); - await w.db.script("DELETE FROM sync_requests"); + await w.db.run(w.db.k.deleteFrom("sync_requests")); await readAt(w, 2, new Date(Date.now() + 1000)); - await drainCommands(w.db, { ...deps(w, { exec: gh.exec }), permission: async () => { await w.db.prepare("UPDATE access SET github_id = 999 WHERE login = ?").run(OPERATOR); return WRITE; } }); + await drainCommands(w.db, { ...deps(w, { exec: gh.exec }), permission: async () => { await w.db.run(w.db.k.updateTable("access").set({ github_id: 999 }).where("login", "=", OPERATOR)); return WRITE; } }); assert.equal((await rows(w))[1]!.state, "ignored"); assert.equal(await preapprovalOf(w.db, "app", 2), null); assert.equal(gh.posted.length, 1); @@ -351,7 +354,7 @@ describe("drainCommands", () => { // 59 minutes when the drain starts, 61 once the permission read is back. let at = Date.now() + 59 * 60_000; const permission = async () => { at = Date.now() + 61 * 60_000; return WRITE; }; - await w.db.script("DELETE FROM sync_requests"); + await w.db.run(w.db.k.deleteFrom("sync_requests")); await readAt(w, 1, new Date(Date.now() + 1000)); await drainCommands(w.db, { ...deps(w, { exec: gh.exec, now: () => new Date(at) }), permission }); assert.deepEqual((await rows(w)).map((r) => r.state), ["expired"]); @@ -397,7 +400,7 @@ describe("comment-time checks", () => { const w = await (await (await (await fresh()).pr(1)).pr(2)).pr(3); for (const n of [1, 2, 3]) await deliver(w, payload({ body: `@${SLUG} merge queue`, number: n, comment: 6000 + n })); const gh = ghFake(); - const head = async (n: number) => (await w.db.prepare("SELECT head_oid FROM items WHERE repo = 'app' AND number = ?").get(n) as { head_oid: string }).head_oid; + const head = async (n: number) => (await w.db.get(w.db.k.selectFrom("items").select("head_oid").where("repo", "=", "app").where("number", "=", n)))!.head_oid!; const pr = async (_q: unknown, _repo: string, n: number): Promise => n === 1 ? { head: await head(1), opened: "2020-01-01T00:00:00Z", changed: true } : { head: n === 2 ? "f".repeat(40) : await head(3), opened: "2020-01-01T00:00:00Z", changed: false }; await drained(w, { exec: gh.exec, pr }); @@ -410,7 +413,7 @@ describe("comment-time checks", () => { test("on an issue, a closing PR opened or pushed to after the comment is named, not queued", async () => { const w = await (await (await fresh()).issue(3)).pr(4); - await w.db.prepare("UPDATE items SET closing_issues = '[3]' WHERE repo = 'app' AND number = 4").run(); + await w.db.run(w.db.k.updateTable("items").set({ closing_issues: "[3]" }).where("repo", "=", "app").where("number", "=", 4)); await deliver(w, payload({ body: `@${SLUG} merge queue`, number: 3, pr: false })); const gh = ghFake(); await readAt(w, 4, new Date(Date.now() + 1000)); @@ -437,7 +440,7 @@ describe("comment-time checks", () => { test("a quiet PR: a maintainer's command is refused without an answer, an operator's is carried out without one", async () => { const w = await (await fresh()).pr(1); - await w.db.prepare("INSERT INTO access (login, role, github_id) VALUES ('maint', 'maintainer', 202)").run(); + await w.db.run(w.db.k.insertInto("access").values({ login: "maint", role: "maintainer", github_id: 202 })); await w.db.prepare(`INSERT INTO security_findings (repo, number, scan_id, area, title, severity, state, refs, reach, impact, fingerprint, fix_pr, created_at, updated_at) VALUES ('app', 1, 1, 'a', 't', 'high', 'landing', '[]', 'r', 'i', 'f', 1, '2020-01-01T00:00:00Z', '2020-01-01T00:00:00Z')`).run(); await deliver(w, payload({ body: `@${SLUG} merge queue`, login: "maint", id: 202, comment: 5001 })); @@ -451,7 +454,7 @@ describe("comment-time checks", () => { test("an unexpected error is answered with a fixed text; a refused person's answer needs the repo's comment approval", async () => { const w = await (await fresh(["comment"])).pr(1); - await w.db.prepare("INSERT INTO access (login, role, github_id) VALUES ('maint', 'maintainer', 202)").run(); + await w.db.run(w.db.k.insertInto("access").values({ login: "maint", role: "maintainer", github_id: 202 })); await deliver(w, payload({ body: `@${SLUG} merge queue`, comment: 5001 })); await deliver(w, payload({ body: `@${SLUG} merge queue`, login: "maint", id: 202, comment: 5002 })); const gh = ghFake(); diff --git a/test/guard.test.ts b/test/guard.test.ts index 616945302..af74d01bd 100644 --- a/test/guard.test.ts +++ b/test/guard.test.ts @@ -50,8 +50,8 @@ test("refuses a merge without a live read, and when GitHub's head moved", async test("refuses when an operator's Hold answer arrived", async () => { const db = await fresh([{ n: 1 }]); const id = mergeDecisionId("app", 1, "sha1"); - await db.prepare("INSERT INTO decisions (id, kind, repo, number, items, question, options, facts, asked_at, answer, answered_by, answered_at) VALUES (?, 'merge', 'app', 1, '[]', 'q', '[]', ?, ?, 'hold', 'op', ?)") - .run(id, JSON.stringify(["head commit sha1"]), T, T); + await db.run(db.k.insertInto("decisions").values({ id, kind: "merge", repo: "app", number: 1, items: "[]", question: "q", options: "[]", facts: JSON.stringify(["head commit sha1"]), + asked_at: T, answer: "hold", answered_by: "op", answered_at: T })); assert.match(why(await guard(db, ref, MERGE, OP, live())), /plan no longer has merge/); }); @@ -113,8 +113,8 @@ test("the merge command gets the reviewed head, and the built-in command refuses /** Item 1 with an operator's close answer to a scope decision. */ async function closeAnswered(): Promise { const db = await fresh([{ n: 1 }]); - await db.prepare("INSERT INTO decisions (id, kind, repo, number, items, question, options, facts, asked_at, answer, answered_by, answered_at) VALUES ('d1', 'scope', 'app', 1, ?, 'q', '[]', '[]', ?, 'close', 'op', ?)") - .run(JSON.stringify([{ repo: "app", number: 1 }]), T, T); + await db.run(db.k.insertInto("decisions").values({ id: "d1", kind: "scope", repo: "app", number: 1, items: JSON.stringify([{ repo: "app", number: 1 }]), question: "q", options: "[]", facts: "[]", + asked_at: T, answer: "close", answered_by: "op", answered_at: T })); return db; } const CLOSE = { kind: "act", bucket: "scope", decisionId: "d1" } as const; @@ -124,7 +124,7 @@ test("an item write needs the comment approval and an answer that still closes t assert.match(why(await guardItem(db, ref, CLOSE, OP)), /Comments in app are not approved/); await setCommentApproval(db, "op", "app", true); assert.ok(ok(await guardItem(db, ref, CLOSE, OP))); - await db.prepare("UPDATE decisions SET answer = 'hold' WHERE id = 'd1'").run(); + await db.run(db.k.updateTable("decisions").set({ answer: "hold" }).where("id", "=", "d1")); assert.match(why(await guardItem(db, ref, CLOSE, OP)), /plan no longer has act:scope/); }); diff --git a/test/identity.test.ts b/test/identity.test.ts index 96c361f26..50d364fc0 100644 --- a/test/identity.test.ts +++ b/test/identity.test.ts @@ -12,6 +12,7 @@ import type { GuardedItem } from "../src/core/guard.ts"; import type { Querier } from "../src/mirror.ts"; import { SCRATCH } from "./scratch.ts"; import { connectDb } from "../src/db/open.ts"; +import * as kx from "../src/db/kx.ts"; const grant = (as: string): GuardedItem => ({ scope: "item", action: { kind: "act" }, repo: "app", number: 7, as }) as unknown as GuardedItem; const q: Querier = { query: async () => ({}) } as unknown as Querier; @@ -19,9 +20,10 @@ const q: Querier = { query: async () => ({}) } as unknown as Querier; test("a decision answered by someone maps to that login, anything else to the app", async () => { mkdirSync(SCRATCH, { recursive: true }); const db = await connectDb(join(SCRATCH, `identity-${process.pid}.db`)); - const ins = db.prepare("INSERT INTO decisions (id, kind, question, options, asked_at, answer, answered_by) VALUES (?, 'close', 'q', '[]', 't', ?, ?)"); - await ins.run("d1", "yes", "example-user"); - await ins.run("d2", null, "example-user"); + const ins = (id: string, answer: string | null) => db.run(db.k.insertInto("decisions") + .values({ id, kind: "close", question: "q", options: "[]", asked_at: "t", answer, answered_by: "example-user" })); + await ins("d1", "yes"); + await ins("d2", null); assert.equal(await identityOfDecision(db, "d1"), "user:example-user"); assert.equal(await identityOfDecision(db, "d2"), "app"); assert.equal(await identityOfDecision(db, "missing"), "app"); @@ -34,10 +36,10 @@ test("a decision answered by someone maps to that login, anything else to the ap test("the audit row records legacy until the identity is switched, then the grant's identity", async () => { mkdirSync(SCRATCH, { recursive: true }); const db = await connectDb(join(SCRATCH, `identity-audit-${process.pid}.db`)); - await db.prepare("INSERT OR IGNORE INTO tracked_repos (name) VALUES ('app')").run(); + await db.run(db.k.insertInto("tracked_repos").values({ name: "app" }).onConflict((oc) => oc.doNothing())); const w = { db, login: "act", mint: async () => "ghs_test", appClient: () => q }; const item = { repo: "app", number: 7, id: "I_1", pr: false }; - const last = async () => JSON.parse((await db.prepare("SELECT details FROM audit WHERE action = 'act-close' ORDER BY rowid DESC LIMIT 1").get() as { details: string }).details) as { identity: string }; + const last = async () => JSON.parse((await db.get(db.k.selectFrom("audit").select("details").where("action", "=", "act-close").orderBy(kx.rowid("audit"), "desc").limit(1)))!.details!) as { identity: string }; assert.equal(await githubIdentity(db), "box"); await closeItem(w, grant("user:example-user"), q, item); assert.equal((await last()).identity, "legacy"); @@ -68,7 +70,7 @@ test("every audited write in write.ts takes its identity from a grant", () => { test("commits are authored by the app's bot user on an app-lane repo and by the box account on a legacy one", async () => { mkdirSync(SCRATCH, { recursive: true }); const db = await connectDb(join(SCRATCH, `identity-commit-${process.pid}.db`)); - await db.prepare("INSERT INTO tracked_repos (name) VALUES ('app')").run(); + await db.run(db.k.insertInto("tracked_repos").values({ name: "app" })); const box = async () => ({ login: "box", email: "1+box@users.noreply.github.com" }); const deps = { slug: () => "demo-app", botId: async () => 42 }; assert.deepEqual(await commitIdentity(db, "app", box, deps), { name: "box", login: "box", email: "1+box@users.noreply.github.com" }); @@ -79,7 +81,7 @@ test("commits are authored by the app's bot user on an app-lane repo and by the test("switching to the app is refused with the uncovered repos listed, and a switch ends the sessions", async () => { mkdirSync(SCRATCH, { recursive: true }); const db = await connectDb(join(SCRATCH, `identity-switch-${process.pid}.db`)); - await db.prepare("INSERT INTO tracked_repos (name) VALUES ('covered'), ('outside')").run(); + await db.run(db.k.insertInto("tracked_repos").values([{ name: "covered" }, { name: "outside" }])); const mint = async (_owner: string, repo: string) => { if (repo === "outside") throw new RepoNotInInstallationError("o", repo); return "t"; }; await assert.rejects(setGithubIdentityChecked(db, "op", "app", { registered: () => false, mint }), (e: unknown) => e instanceof IdentityRefused && e.repos.length === 0); await assert.rejects(setGithubIdentityChecked(db, "op", "app", { registered: () => true, mint }), (e: unknown) => e instanceof IdentityRefused && e.repos.join() === "outside" && /outside/.test(e.message)); @@ -87,8 +89,8 @@ test("switching to the app is refused with the uncovered repos listed, and a swi // A GitHub failure is "could not confirm", not "not covered". const flaky = async () => { throw Object.assign(new AppError("GET /x: HTTP 502"), { status: 502 }); }; await assert.rejects(setGithubIdentityChecked(db, "op", "app", { registered: () => true, mint: flaky }), (e: unknown) => e instanceof IdentityRefused && e.transient); - await db.prepare("DELETE FROM tracked_repos WHERE name = 'outside'").run(); - await db.prepare("INSERT INTO sessions (id_hash, login, csrf, created_at, last_seen, expires_at) VALUES ('h', 'op', 'c', ?, ?, ?)").run(new Date().toISOString(), new Date().toISOString(), new Date(Date.now() + 1e6).toISOString()); + await db.run(db.k.deleteFrom("tracked_repos").where("name", "=", "outside")); + await db.run(db.k.insertInto("sessions").values({ id_hash: "h", login: "op", csrf: "c", created_at: new Date().toISOString(), last_seen: new Date().toISOString(), expires_at: new Date(Date.now() + 1e6).toISOString() })); assert.equal(await setGithubIdentityChecked(db, "op", "app", { registered: () => true, mint }), true); - assert.equal((await db.prepare("SELECT COUNT(*) AS n FROM sessions").get() as { n: number }).n, 0); + assert.equal((await db.get(db.k.selectFrom("sessions").select((eb) => eb.fn.countAll().as("n"))))!.n, 0); }); diff --git a/test/raw-sql-not-converted.txt b/test/raw-sql-not-converted.txt index 58a21aae4..cd0af18e6 100644 --- a/test/raw-sql-not-converted.txt +++ b/test/raw-sql-not-converted.txt @@ -273,13 +273,9 @@ src/github/read.ts src/github/slugs.ts -src/github/user-lane.ts -src/github/vault.ts -src/github/webhooks.ts -src/github/write.ts src/health-checks.ts diff --git a/test/user-lane.test.ts b/test/user-lane.test.ts index 593b0df59..d266afc07 100644 --- a/test/user-lane.test.ts +++ b/test/user-lane.test.ts @@ -7,6 +7,7 @@ import { setGithubIdentity } from "../src/github/identity.ts"; import { plannedItems } from "../src/core/select-items.ts"; import { authFailure, retryWaiting, type LaneDeps } from "../src/github/user-lane.ts"; import { OPERATOR, world, type World } from "./world-db.ts"; +import * as kx from "../src/db/kx.ts"; const quiet = () => {}; let current: World | null = null; @@ -18,7 +19,7 @@ const askedAndAnswered = async (w: World) => { await w.answerDecision(asked.asked[0]!, "close"); return asked.asked[0]!; }; -const execOf = async (w: World, id: string) => (await w.rows("SELECT exec_state AS s, exec_reason AS r FROM decisions WHERE id = ?", id))[0] as { s: string | null; r: string | null }; +const execOf = async (w: World, id: string) => (await w.db.get(w.db.k.selectFrom("decisions").select(["exec_state as s", "exec_reason as r"]).where("id", "=", id)))!; test("legacy repos close as before; an app repo without the operator's token waits and writes nothing, then closes as the operator after a sign-in", async () => { // legacy: the box transports close it and no state is recorded @@ -58,10 +59,10 @@ test("legacy repos close as before; an app repo without the operator's token wai assert.equal(w.gh.writes.length, 0, "still nothing through the box's transports"); assert.ok(queries.includes("close") && !queries.includes("comment"), `the person's transports made the close only: ${queries.join(",")}`); assert.deepEqual(appQueries, ["comment"], "the comment before the close is the app's"); - const row = (await w.rows("SELECT details FROM audit WHERE action = 'act-close'"))[0] as { details: string }; - assert.equal((JSON.parse(row.details) as { identity: string }).identity, `user:${OPERATOR}`); - const crow = (await w.rows("SELECT details FROM audit WHERE action = 'act-comment'"))[0] as { details: string }; - assert.equal((JSON.parse(crow.details) as { identity: string }).identity, "app"); + const row = (await w.db.get(w.db.k.selectFrom("audit").select("details").where("action", "=", "act-close").orderBy(kx.rowid("audit")).limit(1)))!; + assert.equal((JSON.parse(row.details!) as { identity: string }).identity, `user:${OPERATOR}`); + const crow = (await w.db.get(w.db.k.selectFrom("audit").select("details").where("action", "=", "act-comment").orderBy(kx.rowid("audit")).limit(1)))!; + assert.equal((JSON.parse(crow.details!) as { identity: string }).identity, "app"); }); test("a waiting decision is no act work: the run counts nothing and the planner plans no act for it", async () => { diff --git a/test/vault.test.ts b/test/vault.test.ts index 8104776cf..faf8f219b 100644 --- a/test/vault.test.ts +++ b/test/vault.test.ts @@ -54,7 +54,7 @@ test("a refresh GitHub rejects marks the row and answers needs-sign-in, never an const v = new Vault(db, box, provider); v.waitMs = 0; assert.deepEqual(await v.userToken("example-user"), { ok: false, needsSignIn: true, why: "refresh-failed" }); - assert.equal((await db.prepare("SELECT status FROM user_tokens").get() as { status: string }).status, "refresh-failed"); + assert.equal((await db.get(db.k.selectFrom("user_tokens").select("status")))!.status, "refresh-failed"); provider.rejectRefresh = false; assert.equal((await v.userToken("example-user")).ok, false); assert.equal(provider.refreshes, 0); @@ -69,11 +69,11 @@ test("removing a login deletes its token row and the sweep revokes the grant at await addLogin(db, "op", "example-user", "viewer", null); const t = await signIn("example-user", 8 * 3_600_000); await removeLogin(db, "op", "example-user"); - assert.equal(await db.prepare("SELECT 1 FROM user_tokens").get(), undefined); + assert.equal(await db.get(db.k.selectFrom("user_tokens").select("login")), undefined); const v = new Vault(db, box, provider); assert.equal(await v.sweepRevocations(), 1); assert.deepEqual(provider.revokedGrants, [t.access]); - assert.equal(await db.prepare("SELECT 1 FROM user_token_revocations").get(), undefined); + assert.equal(await db.get(db.k.selectFrom("user_token_revocations").select("id")), undefined); }); test("revoking one session revokes only its token and keeps the login's newer sign-in", async () => { @@ -91,6 +91,6 @@ test("revoking one session revokes only its token and keeps the login's newer si assert.equal(provider.revoked.length, 1); assert.notEqual(provider.revoked[0], a.access); assert.equal((await v.userToken("example-user")).ok, true); - assert.equal(openTokens(box, (await db.prepare("SELECT token_enc FROM user_tokens").get() as { token_enc: string }).token_enc, "user_tokens:example-user")?.access, b.access); - assert.equal(await db.prepare("SELECT 1 FROM user_token_revocations").get(), undefined); + assert.equal(openTokens(box, (await db.get(db.k.selectFrom("user_tokens").select("token_enc")))!.token_enc, "user_tokens:example-user")?.access, b.access); + assert.equal(await db.get(db.k.selectFrom("user_token_revocations").select("id")), undefined); }); diff --git a/test/webhooks.test.ts b/test/webhooks.test.ts index 0e0fb781d..cc3a4e4ee 100644 --- a/test/webhooks.test.ts +++ b/test/webhooks.test.ts @@ -12,15 +12,15 @@ import { connectDb } from "../src/db/open.ts"; const SECRET = "hook-secret"; async function scratch() { const db = await connectDb(join(mkdtempSync(join(SCRATCH, "hook-")), "m.db")); - await db.script("DELETE FROM tracked_repos"); - await db.script("INSERT INTO tracked_repos VALUES ('a','t','x', 1)"); + await db.run(db.k.deleteFrom("tracked_repos")); + await db.run(db.k.insertInto("tracked_repos").values({ name: "a", added_by: "t", added_at: "x", pipeline: 1 })); return db; } const deliver = async (db: Awaited>, event: string, payload: unknown, sign = true) => { const raw = Buffer.from(JSON.stringify(payload)); return await handleDelivery(db, SECRET, { event, ...(sign ? { signature: signatureOf(SECRET, raw) } : {}) }, raw, safeEqual); }; -const queued = async (db: Awaited>) => (await db.prepare("SELECT repo, number FROM sync_requests ORDER BY number").all()).map((r) => ({ ...r })); +const queued = async (db: Awaited>) => (await db.all(db.k.selectFrom("sync_requests").select(["repo", "number"]).orderBy("number"))).map((r) => ({ ...r })); test("a signed delivery queues one row per item, a bad or missing signature and an untracked repo queue nothing", async () => { const db = await scratch(); @@ -39,7 +39,7 @@ test("a signed delivery queues one row per item, a bad or missing signature and const suite = (action: string, prs: unknown[], sha = "s1") => ({ action, repository: { full_name: "storytold/a", name: "a", id: 1 }, check_suite: { head_sha: sha, pull_requests: prs } }); assert.equal((await deliver(db, "check_suite", suite("requested", [{ number: 13, base: { repo: { id: 1 } } }]))).status, 202); assert.equal((await deliver(db, "check_suite", suite("completed", [{ number: 12, base: { repo: { id: 1 } } }, { number: 99, base: { repo: { id: 2 } } }]))).status, 202); - await db.script("INSERT INTO items (repo, number, kind, state, head_oid) VALUES ('a', 14, 'pr', 'OPEN', 'fork-sha')"); + await db.run(db.k.insertInto("items").values({ repo: "a", number: 14, kind: "pr", state: "OPEN", head_oid: "fork-sha" })); assert.equal((await deliver(db, "check_suite", suite("completed", [], "fork-sha"))).status, 202); assert.deepEqual(await queued(db), [{ repo: "a", number: 7 }, { repo: "a", number: 8 }, { repo: "a", number: 12 }, { repo: "a", number: 14 }]); }); diff --git a/test/write-pacing.test.ts b/test/write-pacing.test.ts index 4a5687767..53996c5d8 100644 --- a/test/write-pacing.test.ts +++ b/test/write-pacing.test.ts @@ -21,7 +21,7 @@ async function setup(as: string, repoIdentity = "app", failing = false) { const g = { scope: "item", repo: "app1", number: 1, as } as unknown as Grant; const post = () => commentOn(w, g, q, "act-comment", { repo: "app1", number: 1, id: "x" }, { kind: "none" } as never, "hi"); const closeIt = () => closeItem(w, g as never, q, { repo: "app1", number: 1, id: "x", pr: false }); - const rows = async () => (await db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action IN ('act-comment', 'act-close')").get() as { n: number }).n; + const rows = async () => (await db.get(db.k.selectFrom("audit").select((eb) => eb.fn.countAll().as("n")).where("action", "in", ["act-comment", "act-close"])))!.n; return { w, post, closeIt, rows, sleeps, advance: (ms: number) => { t += ms; } }; }