From 933c637de34095f1ea1ab88b02626bbf22eec7f4 Mon Sep 17 00:00:00 2001 From: aur-build Date: Wed, 18 Nov 2026 15:20:13 +0000 Subject: =?UTF-8?q?db:=20the=20schema=20gets=20an=20owner=20=E2=80=94=20ev?= =?UTF-8?q?ery=20statement=20moves=20into=20db/,=20and=20the=20writer=20st?= =?UTF-8?q?ops=20handing=20out=20connections?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Twelve modules outside `db/` contained hand-rolled SQL — 22 statements in `ops.rs`, 17 in `approve.rs`, 15 in `candidates.rs`, 11 in `publish.rs`, and a dozen more scattered through `watch`, `pipeline`, `http` — which meant the blast radius of a schema change was "any module", and `db/` was a directory rather than a boundary. The audit trail alone was defined in four places with three different detail payloads. Every statement now lives in `db/`. New modules `db::candidates` and `db::approvals` own their tables (including the 21-column candidate select, spelled once as `CANDIDATE_COLS` instead of four times); `db::queries` gains the metrics reads, the retention reads and writes, the publish writes (`insert_release_in`, `cas_accepted_release_in`, `remove_index_packages_in`), the staleness reads and the source-cache lookups; `db::builds` gains `set_release_in`. Where a mutation is a *decision* — the collapse rules, the approval gate, the publish compare-and-swap — the decision stays where it was and the statements are called through the transaction handle, so the atomicity is unchanged and only the SQL moved. `audit_in` is the in-transaction audit append, and `audit` is now a wrapper over it: a decision and its audit row commit together or not at all, which is what I10 actually claims. Enforcement is two-layered, because one layer is a lie. `Writer::call`, `tx` and `send` are `pub(crate)`, which keeps the crate's *users* out — the integration tests and the shim binaries — but `pub(crate)` is crate-wide, so on its own it would not stop `approve.rs` from writing SQL tomorrow. The layer that does is `tests/schema_ownership.rs`: it walks `src/` and fails the build if a statement literal or a rusqlite statement call appears outside `src/db/`. It was checked against a deliberate violation. The test harness still needs to construct states no typed API reaches, so the raw door exists but only under the `test-support` feature, which nothing but this crate's own dev-dependency enables; a production binary cannot see it. --- src/db/candidates.rs | 388 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 388 insertions(+) create mode 100644 src/db/candidates.rs (limited to 'src/db/candidates.rs') diff --git a/src/db/candidates.rs b/src/db/candidates.rs new file mode 100644 index 0000000..e41fb94 --- /dev/null +++ b/src/db/candidates.rs @@ -0,0 +1,388 @@ +//! The candidate table: its row shape, its column list, and every statement +//! that touches it (§7.1). +//! +//! The *rules* about candidates — collapse into the open review, supersede once +//! a human has looked, never re-raise a rejection — are domain logic and live +//! in `review::candidates`. What lives here is SQL, so that the schema has one +//! owner (§6 M-1). The `_in` functions take a transaction handle so a caller +//! can compose several of them into one atomic decision; the decision itself +//! stays with the caller. + +use rusqlite::{params, OptionalExtension, Row, Transaction}; + +use crate::db::{CandidateRow, Db}; +use crate::error::{Error, Result}; +use crate::time; + +/// The columns `row_to_candidate` reads, spelled once. Every other table in +/// this module already works this way; the candidate select was simply copied +/// four times for long enough to be noticed (§6 m-3). +const CANDIDATE_COLS: &str = "c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, \ + c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, c.diff_digest, \ + c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, c.missing_deps_json, c.state, \ + c.detected_at, c.resolved_at, b.name"; + +fn row_to_candidate(r: &Row<'_>) -> rusqlite::Result { + Ok(CandidateRow { + id: r.get(0)?, + pkgbase_id: r.get(1)?, + base_release_id: r.get(2)?, + kind: r.get(3)?, + snapshot_id: r.get(4)?, + epoch: r.get(5)?, + pkgver: r.get(6)?, + pkgrel: r.get(7)?, + upstream_pins_json: r.get(8)?, + source_digests_json: r.get(9)?, + identity_hash: r.get(10)?, + diff_digest: r.get(11)?, + revision: r.get(12)?, + viewed_at: r.get(13)?, + risk_level: r.get(14)?, + risk_signals_json: r.get(15)?, + missing_deps_json: r.get(16)?, + state: r.get(17)?, + detected_at: r.get(18)?, + resolved_at: r.get(19)?, + pkgbase: r.get(20)?, + }) +} + +/// The fields a new candidate row carries, beyond its pkgbase and its base. +#[derive(Debug, Clone)] +pub struct NewCandidate { + pub snapshot_id: i64, + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, + pub upstream_pins_json: String, + pub source_digests_json: String, + pub identity_hash: String, +} + +impl NewCandidate { + /// The `epoch:pkgver-pkgrel` this candidate would publish. + pub fn version(&self) -> String { + crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) + } +} + +/// The open review of a pkgbase — as much of it as the collapse rules need. +#[derive(Debug, Clone)] +pub struct OpenReview { + pub id: i64, + pub identity_hash: String, + pub viewed_at: Option, + pub revision: i64, +} + +impl OpenReview { + /// Has a human opened this review yet? That timestamp is what decides + /// whether a newer detection collapses or supersedes (§7.1). + pub fn viewed(&self) -> bool { + self.viewed_at.is_some() + } +} + +// ------------------------------------------------------------------ in-tx -- + +/// Everything the approval gate has to look at to decide, read in one statement +/// so the check cannot straddle two snapshots of the database. +#[derive(Debug, Clone)] +pub struct ReviewSubject { + pub id: i64, + pub pkgbase_id: i64, + pub state: String, + pub identity_hash: String, + pub diff_digest: String, + /// The release this review was opened against (I2). + pub base_release_id: Option, + /// What the pkgbase accepts now — the other half of the I2 check. + pub current_base_release_id: Option, + pub risk_level: String, + pub pkgbase: String, +} + +pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result> { + Ok(tx + .query_row( + "SELECT c.id, c.pkgbase_id, c.state, c.identity_hash, c.diff_digest, c.base_release_id, + p.current_accepted_release_id, c.risk_level, p.name + FROM candidate c JOIN pkgbase p ON p.id = c.pkgbase_id + WHERE c.id = ?1", + params![candidate_id], + |r| { + Ok(ReviewSubject { + id: r.get(0)?, + pkgbase_id: r.get(1)?, + state: r.get(2)?, + identity_hash: r.get(3)?, + diff_digest: r.get(4)?, + base_release_id: r.get(5)?, + current_base_release_id: r.get(6)?, + risk_level: r.get(7)?, + pkgbase: r.get(8)?, + }) + }, + ) + .optional()?) +} + +/// Take a candidate out of the open state: approved, rejected or superseded. +pub fn resolve_in(tx: &Transaction<'_>, id: i64, state: &str, at: &str) -> Result<()> { + tx.execute("UPDATE candidate SET state=?1, resolved_at=?2 WHERE id=?3", params![state, at, id])?; + Ok(()) +} + +/// A candidate's state, read inside a transaction (the reject path needs it +/// before it writes). +pub fn state_in(tx: &Transaction<'_>, id: i64) -> Result> { + Ok(tx + .query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| r.get::<_, String>(0)) + .optional()?) +} + +pub fn identity_in(tx: &Transaction<'_>, id: i64) -> Result> { + Ok(tx + .query_row("SELECT identity_hash FROM candidate WHERE id=?1", params![id], |r| r.get::<_, String>(0)) + .optional()?) +} + +/// The risk level recorded at review time, if the candidate exists. +pub fn risk_level(db: &Db, id: i64) -> Result> { + db.read(|c| { + Ok(c.query_row("SELECT risk_level FROM candidate WHERE id=?1", params![id], |r| r.get::<_, String>(0)) + .optional()?) + }) +} + +/// The pkgbase's open review, if it has one (I7: at most one). +pub fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result> { + Ok(tx + .query_row( + "SELECT id, identity_hash, viewed_at, revision FROM candidate + WHERE pkgbase_id=?1 AND state='pending_review'", + params![pkgbase_id], + |r| { + Ok(OpenReview { + id: r.get(0)?, + identity_hash: r.get(1)?, + viewed_at: r.get(2)?, + revision: r.get(3)?, + }) + }, + ) + .optional()?) +} + +/// Write a newer detection into the open review: same row, same base, one more +/// revision, and the stale diff rendering dropped so it cannot be approved. +pub fn collapse_in(tx: &mut Transaction<'_>, open: &OpenReview, nc: &NewCandidate) -> Result { + let revision = open.revision + 1; + tx.execute( + "UPDATE candidate SET snapshot_id=?1, epoch=?2, pkgver=?3, pkgrel=?4, + upstream_pins_json=?5, source_digests_json=?6, identity_hash=?7, + revision=?8, detected_at=?9, diff_digest='' + WHERE id=?10", + params![ + nc.snapshot_id, + nc.epoch, + nc.pkgver, + nc.pkgrel, + nc.upstream_pins_json, + nc.source_digests_json, + nc.identity_hash, + revision, + time::now(), + open.id + ], + )?; + Ok(revision) +} + +/// Freeze a reviewed candidate as `superseded` so a fresh review can open. +pub fn supersede_in(tx: &Transaction<'_>, id: i64) -> Result<()> { + tx.execute( + "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2", + params![time::now(), id], + )?; + Ok(()) +} + +/// Has this exact identity been rejected before? If so the watcher stays quiet +/// until a human re-opens it (§7.1: "do not nag"). +pub fn rejected_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: &str) -> Result { + Ok(tx + .query_row( + "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 AND state='rejected' + ORDER BY id DESC LIMIT 1", + params![pkgbase_id, identity_hash], + |r| r.get::<_, i64>(0), + ) + .optional()? + .is_some()) +} + +/// Has this identity been recorded at all — approved, superseded, anything? +/// Then the detection said nothing new. +pub fn recorded_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: &str) -> Result { + Ok(tx + .query_row( + "SELECT id FROM candidate WHERE pkgbase_id=?1 AND identity_hash=?2 + ORDER BY id DESC LIMIT 1", + params![pkgbase_id, identity_hash], + |r| r.get::<_, i64>(0), + ) + .optional()? + .is_some()) +} + +/// Open a candidate row in `pending_review`. +pub fn insert_in( + tx: &mut Transaction<'_>, + pkgbase_id: i64, + base: Option, + kind: &str, + nc: &NewCandidate, +) -> Result { + tx.execute( + "INSERT INTO candidate (pkgbase_id, base_release_id, kind, snapshot_id, epoch, pkgver, pkgrel, + upstream_pins_json, source_digests_json, identity_hash, state, detected_at) + VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,'pending_review',?11)", + params![ + pkgbase_id, + base, + kind, + nc.snapshot_id, + nc.epoch, + nc.pkgver, + nc.pkgrel, + nc.upstream_pins_json, + nc.source_digests_json, + nc.identity_hash, + time::now() + ], + )?; + Ok(tx.last_insert_rowid()) +} + +// ------------------------------------------------------------------ reads -- + +/// Every candidate regardless of state, newest first (`aur-build reviews --all`). +pub fn all(db: &Db) -> Result> { + let sql = format!("SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id ORDER BY c.detected_at DESC LIMIT 500"); + db.read(move |c| { + let mut stmt = c.prepare(&sql)?; + let rows = stmt.query_map([], row_to_candidate)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +/// The reviews waiting for a decision, riskiest first. +pub fn pending(db: &Db) -> Result> { + let sql = format!( + "SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id \ + WHERE c.state='pending_review' ORDER BY (c.risk_level='high') DESC, c.detected_at" + ); + db.read(move |c| { + let mut stmt = c.prepare(&sql)?; + let rows = stmt.query_map([], row_to_candidate)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +pub fn by_id(db: &Db, id: i64) -> Result> { + let sql = format!("SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id WHERE c.id=?1"); + db.read(move |c| { + Ok(c.query_row(&sql, params![id], row_to_candidate) + .optional()?) + }) +} + +/// Open reviews for a pkgbase (usually zero or one, by I7). +pub fn open_reviews_for(db: &Db, pkgbase_id: i64) -> Result> { + let sql = format!( + "SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id \ + WHERE c.pkgbase_id=?1 AND c.state='pending_review'" + ); + db.read(move |c| { + let mut stmt = c.prepare(&sql)?; + let rows = stmt.query_map(params![pkgbase_id], row_to_candidate)?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok(out) + }) +} + +// ---------------------------------------------------------------- writes -- + +/// Mark a candidate `viewed` the first time a human opens it. That timestamp is +/// what decides whether a later detection collapses or supersedes (§7.1). +pub fn mark_viewed(db: &Db, id: i64) -> Result<()> { + let at = time::now(); + db.writer.tx(move |tx| { + tx.execute( + "UPDATE candidate SET viewed_at=?1 WHERE id=?2 AND viewed_at IS NULL", + params![at, id], + )?; + Ok(()) + }) +} + +/// §7.1: a rejection can be re-opened. We retire the rejected row so it stops +/// suppressing the identity, and the next detection opens a fresh review. +pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> { + let at = time::now(); + db.writer.tx(move |tx| { + let n = tx.execute( + "UPDATE candidate SET state='superseded', resolved_at=?1 WHERE id=?2 AND state='rejected'", + params![at, id], + )?; + if n == 0 { + return Err(Error::conflict("candidate is not rejected")); + } + Ok(()) + }) +} + +/// Record the risk assessment computed at review time. +pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()> { + let lvl = level.to_string(); + let sig = serde_json::to_string(signals)?; + db.writer.tx(move |tx| { + tx.execute( + "UPDATE candidate SET risk_level=?1, risk_signals_json=?2 WHERE id=?3", + params![lvl, sig, id], + )?; + Ok(()) + }) +} + +pub fn set_missing_deps(db: &Db, id: i64, missing: &[String]) -> Result<()> { + let m = serde_json::to_string(missing)?; + db.writer.tx(move |tx| { + tx.execute( + "UPDATE candidate SET missing_deps_json=?1 WHERE id=?2", + params![m, id], + )?; + Ok(()) + }) +} + +pub fn set_diff_digest(db: &Db, id: i64, digest: &str) -> Result<()> { + let d = digest.to_string(); + db.writer.tx(move |tx| { + tx.execute("UPDATE candidate SET diff_digest=?1 WHERE id=?2", params![d, id])?; + Ok(()) + }) +} -- cgit v1.2.3