summaryrefslogtreecommitdiffstats
path: root/src/db
diff options
context:
space:
mode:
authoraur-build <aur-build@localhost>2026-11-18 15:20:13 +0000
committeraur-build <aur-build@localhost>2026-11-18 15:20:13 +0000
commit933c637de34095f1ea1ab88b02626bbf22eec7f4 (patch)
treeee7bd3d7a2b18163c0fdbe061ef53a73b74907ab /src/db
parent7946e9ffc48748992f051ada15bec772b16a585d (diff)
downloadaur-build-933c637de34095f1ea1ab88b02626bbf22eec7f4.tar.gz
aur-build-933c637de34095f1ea1ab88b02626bbf22eec7f4.zip
db: the schema gets an owner — every statement moves into db/, and the writer stops handing out connections
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.
Diffstat (limited to 'src/db')
-rw-r--r--src/db/approvals.rs70
-rw-r--r--src/db/builds.rs11
-rw-r--r--src/db/candidates.rs388
-rw-r--r--src/db/mod.rs63
-rw-r--r--src/db/queries.rs544
5 files changed, 1059 insertions, 17 deletions
diff --git a/src/db/approvals.rs b/src/db/approvals.rs
new file mode 100644
index 0000000..f04d641
--- /dev/null
+++ b/src/db/approvals.rs
@@ -0,0 +1,70 @@
+//! The approval table: the record of a human decision, and the only thing that
+//! makes a candidate publishable (§7.1a, I1).
+//!
+//! An approval row is what an index entry must trace back to. The rules about
+//! *when* one may be written — same identity, same diff, same base — are domain
+//! logic in `review::approve`; what lives here is the SQL, so the schema has one
+//! owner (§6 M-1).
+
+use rusqlite::{params, OptionalExtension, Transaction};
+
+use crate::db::Db;
+use crate::error::Result;
+
+/// A human decision about one candidate, ready to record.
+pub struct Decision<'a> {
+ pub candidate_id: i64,
+ pub base_release_id: Option<i64>,
+ pub at: &'a str,
+ pub decision: &'a str,
+ pub risk_level: &'a str,
+ pub diff_digest: &'a str,
+ pub identity_hash: &'a str,
+ pub note: Option<&'a str>,
+}
+
+/// Record a decision on a candidate and return the approval row's id.
+pub fn record_in(tx: &mut Transaction<'_>, d: &Decision<'_>) -> Result<i64> {
+ tx.execute(
+ "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level,
+ diff_digest, identity_hash, note)
+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8)",
+ params![
+ d.candidate_id,
+ d.base_release_id,
+ d.at,
+ d.decision,
+ d.risk_level,
+ d.diff_digest,
+ d.identity_hash,
+ d.note
+ ],
+ )?;
+ Ok(tx.last_insert_rowid())
+}
+
+/// Record a rejection by copying the candidate's own row into the approval
+/// table. The decision has to describe the bytes that *were* rejected, so it is
+/// read from the row rather than repeated by the caller (§7.1).
+pub fn record_rejection_in(tx: &mut Transaction<'_>, candidate_id: i64, at: &str, identity_hash: &str, note: &str) -> Result<()> {
+ tx.execute(
+ "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level,
+ diff_digest, identity_hash, note)
+ SELECT id, base_release_id, ?1, 'rejected', risk_level, diff_digest, ?2, ?3
+ FROM candidate WHERE id=?4",
+ params![at, identity_hash, note, candidate_id],
+ )?;
+ Ok(())
+}
+
+/// The decision recorded against a candidate, if one was.
+pub fn for_candidate(db: &Db, candidate_id: i64) -> Result<Option<(i64, String)>> {
+ db.read(|c| {
+ Ok(c.query_row(
+ "SELECT id, decision FROM approval WHERE candidate_id=?1",
+ params![candidate_id],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .optional()?)
+ })
+}
diff --git a/src/db/builds.rs b/src/db/builds.rs
index 3770746..5c4d1d4 100644
--- a/src/db/builds.rs
+++ b/src/db/builds.rs
@@ -395,12 +395,15 @@ pub fn touch(db: &Db, id: &str) -> Result<()> {
})
}
+/// Record which release a build produced, inside the publish transaction.
+pub fn set_release_in(tx: &rusqlite::Transaction<'_>, id: &str, release_id: i64) -> Result<()> {
+ tx.execute("UPDATE build SET release_id=?1 WHERE id=?2", params![release_id, id])?;
+ Ok(())
+}
+
pub fn set_release(db: &Db, id: &str, release_id: i64) -> Result<()> {
let id = id.to_string();
- db.writer.tx(move |tx| {
- tx.execute("UPDATE build SET release_id=?1 WHERE id=?2", params![release_id, id])?;
- Ok(())
- })
+ db.writer.tx(move |tx| set_release_in(tx, &id, release_id))
}
pub fn set_world(db: &Db, id: &str, world_id: i64) -> Result<()> {
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<CandidateRow> {
+ 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<String>,
+ 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<i64>,
+ /// What the pkgbase accepts now — the other half of the I2 check.
+ pub current_base_release_id: Option<i64>,
+ pub risk_level: String,
+ pub pkgbase: String,
+}
+
+pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Option<ReviewSubject>> {
+ 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<Option<String>> {
+ 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<Option<String>> {
+ 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<Option<String>> {
+ 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<Option<OpenReview>> {
+ 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<i64> {
+ 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<bool> {
+ 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<bool> {
+ 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<i64>,
+ kind: &str,
+ nc: &NewCandidate,
+) -> Result<i64> {
+ 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<Vec<CandidateRow>> {
+ 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<Vec<CandidateRow>> {
+ 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<Option<CandidateRow>> {
+ 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<Vec<CandidateRow>> {
+ 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(())
+ })
+}
diff --git a/src/db/mod.rs b/src/db/mod.rs
index b810453..2cf766b 100644
--- a/src/db/mod.rs
+++ b/src/db/mod.rs
@@ -8,7 +8,9 @@
//! design entirely. Readers are thread-local, read-only connections; WAL lets
//! them proceed concurrently with the writer.
+pub mod approvals;
pub mod builds;
+pub mod candidates;
pub mod migrations;
pub mod model;
pub mod queries;
@@ -139,9 +141,16 @@ impl Writer {
/// Run `f` on the write connection and wait for its result.
///
- /// No transaction may span a build step: `f` should be short. Use
- /// [`Writer::tx`] for atomic multi-statement mutations.
- pub fn call<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T>
+ /// No transaction may span a build step: `f` should be short.
+ /// Use [`Writer::tx`] for atomic multi-statement mutations.
+ ///
+ /// `pub(crate)`, not `pub`: the schema is the system's most protected asset
+ /// and it has one owner, this module (§6 M-1). Code outside `db/` asks for a
+ /// typed query instead of writing SQL. `pub(crate)` is what keeps the
+ /// *crate's* users (the integration tests, the shim binaries) out; inside
+ /// the crate the convention is enforced by `tests/schema_ownership.rs`,
+ /// which fails the build if a SQL statement appears outside `src/db/`.
+ pub(crate) fn call<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T>
where
T: Send + 'static,
{
@@ -156,7 +165,7 @@ impl Writer {
/// Run `f` inside a single `BEGIN IMMEDIATE` transaction on the write
/// connection. This is how every multi-statement mutation is expressed.
- pub fn tx<T>(
+ pub(crate) fn tx<T>(
&self,
f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static,
) -> Result<T>
@@ -174,7 +183,7 @@ impl Writer {
}
/// Fire-and-forget write (audit rows, bookkeeping where the result is unused).
- pub fn send(&self, f: BoxedCall) -> Result<()> {
+ pub(crate) fn send(&self, f: BoxedCall) -> Result<()> {
if !self.is_alive() {
return Err(Error::db("writer actor gone"));
}
@@ -188,6 +197,36 @@ impl Writer {
}
}
+/// The raw-SQL door, open only for the test harness (§6 M-9).
+///
+/// A fixture sometimes has to put the database in a state the typed API only
+/// reaches through several steps — a release published without a build, a
+/// pointer moved out from under a review. That is a reason to have a door, not
+/// a reason to leave it unlocked in the binary an operator runs, so it exists
+/// only under the `test-support` feature, which nothing but this crate's own
+/// dev-dependency enables.
+#[cfg(feature = "test-support")]
+impl Writer {
+ /// Run `f` in a transaction. Test fixtures only.
+ pub fn tx_for_tests<T>(
+ &self,
+ f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static,
+ ) -> Result<T>
+ where
+ T: Send + 'static,
+ {
+ self.tx(f)
+ }
+
+ /// Run `f` on the write connection. Test fixtures only.
+ pub fn call_for_tests<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T>
+ where
+ T: Send + 'static,
+ {
+ self.call(f)
+ }
+}
+
/// Thread-local read-only connection pool.
///
/// One connection per thread per database file, opened read-only. HTTP handlers
@@ -263,6 +302,20 @@ pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> {
})
}
+/// The schema version a database file reports. A backup that does not open and
+/// answer with a migrated schema is a file, not a backup, and the only way to
+/// find that out is to ask it.
+///
+/// Opened read-write and untouched by the connection pragmas: the point is to
+/// read one number from a file we are not going to modify, and a WAL database
+/// cannot even be opened read-only (it needs its sidecar).
+pub fn schema_version(path: &Path) -> Result<i64> {
+ let conn = rusqlite::Connection::open(path)
+ .map_err(|e| Error::db(format!("{} does not open: {e}", path.display())))?;
+ conn.query_row("PRAGMA user_version", [], |r| r.get(0))
+ .map_err(|e| Error::db(format!("{} has no schema version: {e}", path.display())))
+}
+
/// WAL size + checkpoint lag, surfaced on the Ops page and in metrics.
pub fn wal_stats(db: &Db) -> (u64, u64) {
let db_file = std::fs::metadata(db.writer.path()).map(|m| m.len()).unwrap_or(0);
diff --git a/src/db/queries.rs b/src/db/queries.rs
index ca73e5f..ffb2520 100644
--- a/src/db/queries.rs
+++ b/src/db/queries.rs
@@ -1,7 +1,7 @@
//! Typed query helpers. Everything that mutates goes through the writer actor;
//! everything that reads takes a `&Connection` from the reader pool.
-use rusqlite::{params, OptionalExtension, Row};
+use rusqlite::{params, params_from_iter, OptionalExtension, Row};
use crate::db::*;
use crate::error::{Error, Result};
@@ -65,17 +65,47 @@ pub fn audit(
let action = action.to_string();
let entity = entity.to_string();
let entity_id = entity_id.to_string();
- let detail = detail.to_string();
writer.tx(move |tx| {
- tx.execute(
- "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json)
- VALUES (?1,?2,?3,?4,?5,?6,?7)",
- params![at, actor_kind, actor, action, entity, entity_id, detail],
- )?;
- Ok(())
+ audit_in(
+ tx,
+ &AuditEntry {
+ at: &at,
+ actor_kind: &actor_kind,
+ actor: &actor,
+ action: &action,
+ entity: &entity,
+ entity_id: &entity_id,
+ detail,
+ },
+ )
})
}
+/// An audit row to append inside someone else's transaction.
+#[derive(Debug)]
+pub struct AuditEntry<'a> {
+ pub at: &'a str,
+ pub actor_kind: &'a str,
+ pub actor: &'a str,
+ pub action: &'a str,
+ pub entity: &'a str,
+ pub entity_id: &'a str,
+ pub detail: serde_json::Value,
+}
+
+/// Append an audit row inside a caller's transaction (I10). This is the variant
+/// every multi-statement mutation uses: the record of a decision commits with
+/// the decision or not at all, so there is no window where an audit row
+/// describes a change that was rolled back.
+pub fn audit_in(tx: &rusqlite::Transaction<'_>, e: &AuditEntry<'_>) -> Result<()> {
+ tx.execute(
+ "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json)
+ VALUES (?1,?2,?3,?4,?5,?6,?7)",
+ params![e.at, e.actor_kind, e.actor, e.action, e.entity, e.entity_id, e.detail.to_string()],
+ )?;
+ Ok(())
+}
+
pub fn audit_system(writer: &Writer, action: &str, entity: &str, entity_id: &str, detail: serde_json::Value) -> Result<()> {
audit(writer, "system", "", action, entity, entity_id, detail)
}
@@ -441,6 +471,15 @@ const RELEASE_COLS_R: &str = "r.id, r.pkgbase_id, r.candidate_id, r.approval_id,
r.recipe_hash, r.upstream_pins_json, r.source_digests_json, r.epoch, r.pkgver, r.pkgrel, \
r.world_snapshot_id, r.state, r.published_at";
+/// Withdraw a published release and remove the packages it served (§9
+/// `repo-remove`, decision 23). Runs in the caller's transaction so the removal
+/// and the audit row that explains it are one fact.
+pub fn withdraw_release_in(tx: &rusqlite::Transaction<'_>, release_id: i64) -> Result<()> {
+ tx.execute("UPDATE release SET state='withdrawn' WHERE id=?1", params![release_id])?;
+ tx.execute("UPDATE package SET state='removed' WHERE release_id=?1", params![release_id])?;
+ Ok(())
+}
+
pub fn release_by_id(db: &Db, id: i64) -> Result<Option<ReleaseRow>> {
db.read(|c| {
c.query_row(
@@ -635,6 +674,286 @@ pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<cr
})
}
+// ------------------------------------------------------------ publish writes --
+//
+// Publishing is the one externally visible step, so every statement it needs is
+// here and the *decision* stays in `pipeline::publish`: the caller opens the
+// transaction, calls these in order, and bails if the compare-and-swap says the
+// world moved (I4).
+
+/// The on-disk path of an artifact, by id.
+pub fn artifact_path(db: &Db, id: i64) -> Result<Option<String>> {
+ db.read(|c| {
+ Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", params![id], |r| r.get::<_, String>(0))
+ .optional()?)
+ })
+}
+
+/// The artifact row for a content digest, if one exists. Two releases built from
+/// identical bytes share one artifact row — that is the point of the digest.
+pub fn artifact_id_by_digest_in(tx: &rusqlite::Transaction<'_>, digest: &str) -> Result<Option<i64>> {
+ Ok(tx
+ .query_row("SELECT id FROM artifact WHERE digest=?1", params![digest], |r| r.get::<_, i64>(0))
+ .optional()?)
+}
+
+/// The pkgbase's accepted pointer, read inside a transaction: the CAS baseline.
+pub fn accepted_pointer_in(tx: &rusqlite::Transaction<'_>, pkgbase_id: i64) -> Result<Option<i64>> {
+ tx.query_row(
+ "SELECT current_accepted_release_id FROM pkgbase WHERE id=?1",
+ params![pkgbase_id],
+ |r| r.get::<_, Option<i64>>(0),
+ )
+ .optional()
+ .map(Option::flatten)
+ .map_err(Into::into)
+}
+
+/// Compare-and-swap the accepted pointer inside a transaction. `false` means it
+/// was not where the caller thought it was, and the publish must not land.
+pub fn cas_accepted_release_in(
+ tx: &rusqlite::Transaction<'_>,
+ pkgbase_id: i64,
+ new_release_id: i64,
+ expected: Option<i64>,
+) -> Result<bool> {
+ let moved = tx.execute(
+ "UPDATE pkgbase SET current_accepted_release_id=?1 WHERE id=?2 AND current_accepted_release_id IS ?3",
+ params![new_release_id, pkgbase_id, expected],
+ )?;
+ Ok(moved == 1)
+}
+
+/// Retire whatever the index held for these names. The index holds exactly the
+/// accepted pointers, so this runs before the new rows go in.
+pub fn remove_index_packages_in(tx: &rusqlite::Transaction<'_>, names: &[String]) -> Result<()> {
+ if names.is_empty() {
+ return Ok(());
+ }
+ let ph = names.iter().map(|_| "?").collect::<Vec<_>>().join(",");
+ let sql = format!("UPDATE package SET state='removed' WHERE state='in_index' AND name IN ({ph})");
+ let mut stmt = tx.prepare(&sql)?;
+ stmt.execute(params_from_iter(names.iter().map(|n| n as &dyn rusqlite::ToSql)))?;
+ Ok(())
+}
+
+/// Retire one named package from the index (the §9 withdrawal path).
+pub fn remove_package_by_name_in(tx: &rusqlite::Transaction<'_>, repo_id: i64, name: &str) -> Result<()> {
+ tx.execute(
+ "UPDATE package SET state='removed' WHERE repo_id=?1 AND name=?2",
+ params![repo_id, name],
+ )?;
+ Ok(())
+}
+
+/// Everything a published release records. Borrowed because the caller is in the
+/// middle of a transaction and has the values on the stack.
+pub struct NewRelease<'a> {
+ pub pkgbase_id: i64,
+ pub candidate_id: Option<i64>,
+ pub approval_id: Option<i64>,
+ pub aur_commit: &'a str,
+ pub recipe_hash: &'a str,
+ pub upstream_pins_json: &'a str,
+ pub source_digests_json: &'a str,
+ pub epoch: &'a str,
+ pub pkgver: &'a str,
+ pub pkgrel: &'a str,
+ pub world_snapshot_id: Option<i64>,
+ pub build_id: &'a str,
+}
+
+/// Insert the release row and return its id.
+pub fn insert_release_in(tx: &mut rusqlite::Transaction<'_>, r: &NewRelease<'_>, at: &str) -> Result<i64> {
+ tx.execute(
+ "INSERT INTO release (pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash,
+ upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel,
+ world_snapshot_id, state, build_id, published_at, created_at)
+ VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,'published',?12,?13,?13)",
+ params![
+ r.pkgbase_id,
+ r.candidate_id,
+ r.approval_id,
+ r.aur_commit,
+ r.recipe_hash,
+ r.upstream_pins_json,
+ r.source_digests_json,
+ r.epoch,
+ r.pkgver,
+ r.pkgrel,
+ r.world_snapshot_id,
+ r.build_id,
+ at
+ ],
+ )?;
+ Ok(tx.last_insert_rowid())
+}
+
+/// Put one package into the index, pointing at the artifact with this digest.
+pub fn insert_package_in(
+ tx: &rusqlite::Transaction<'_>,
+ repo_id: i64,
+ release_id: i64,
+ name: &str,
+ arch: &str,
+ version: &str,
+ digest: &str,
+) -> Result<()> {
+ let artifact_id = artifact_id_by_digest_in(tx, digest)?;
+ tx.execute(
+ "INSERT INTO package (repo_id, release_id, name, arch, version, artifact_id, state)
+ VALUES (?1,?2,?3,?4,?5,?6,'in_index')",
+ params![repo_id, release_id, name, arch, version, artifact_id],
+ )?;
+ Ok(())
+}
+
+// ------------------------------------------------------------ staleness reads --
+//
+// Staleness is derived on read (§10.2), and these are the reads it is derived
+// from. They return plain tuples: the *meaning* ("this dependency moved") is
+// `watch::staleness`'s business, the SQL is this module's.
+
+/// `(pkgbase, world members JSON)` for every published release, taken from the
+/// world snapshot its build recorded (§10.1).
+pub fn published_world_members(db: &Db) -> Result<Vec<(String, String)>> {
+ db.read(|c| {
+ let mut st = c.prepare(
+ "SELECT p.name, w.members_json
+ FROM release r
+ JOIN pkgbase p ON p.id = r.pkgbase_id
+ JOIN build b ON b.id = r.build_id
+ JOIN world_snapshot w ON w.id = b.world_snapshot_id
+ WHERE r.state = 'published'",
+ )?;
+ let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
+ Ok(rows.filter_map(|r| r.ok()).collect::<Vec<_>>())
+ })
+}
+
+/// `(pkgbase, served pkgver, newest candidate pkgver)` for every accepted
+/// release — the pair the downgrade check compares (§10.2).
+pub fn served_vs_offered_pkgvers(db: &Db) -> Result<Vec<(String, String, String)>> {
+ db.read(|c| {
+ let mut st = c.prepare(
+ "SELECT p.name, r.pkgver, (
+ SELECT c.pkgver FROM candidate c
+ WHERE c.pkgbase_id = r.pkgbase_id
+ ORDER BY c.id DESC LIMIT 1)
+ FROM release r
+ JOIN pkgbase p ON p.current_accepted_release_id = r.id
+ WHERE r.state = 'published'",
+ )?;
+ let rows = st.query_map([], |r| {
+ Ok((
+ r.get::<_, String>(0)?,
+ r.get::<_, String>(1)?,
+ r.get::<_, Option<String>>(2)?.unwrap_or_default(),
+ ))
+ })?;
+ Ok(rows.filter_map(|r| r.ok()).collect::<Vec<_>>())
+ })
+}
+
+/// The `srcinfo_json` of the recipe the index's copy of a package was built
+/// from — what its dependency list actually said.
+pub fn recipe_json_of_index_package(db: &Db, name: &str) -> Result<Option<String>> {
+ db.read(|c| {
+ Ok(c.query_row(
+ "SELECT s.srcinfo_json FROM package pk
+ JOIN release r ON r.id = pk.release_id
+ JOIN candidate cnd ON cnd.id = r.candidate_id
+ JOIN snapshot s ON s.id = cnd.snapshot_id
+ WHERE pk.name = ?1 AND pk.state='in_index'",
+ params![name],
+ |r| r.get::<_, String>(0),
+ )
+ .optional()?)
+ })
+}
+
+/// The note a reviewer left on an approval, empty when there was none.
+pub fn approval_note(db: &Db, approval_id: i64) -> Result<String> {
+ db.read(|c| {
+ c.query_row("SELECT COALESCE(note,'') FROM approval WHERE id=?1", params![approval_id], |r| r.get::<_, String>(0))
+ .optional()
+ .map(|o| o.unwrap_or_default())
+ .map_err(Into::into)
+ })
+}
+
+/// The snapshot a candidate was created from, for rendering its diff.
+pub fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Result<Option<i64>> {
+ db.read(|c| {
+ Ok(c.query_row("SELECT snapshot_id FROM candidate WHERE id=?1", params![candidate_id], |r| r.get::<_, i64>(0))
+ .optional()?)
+ })
+}
+
+/// The poll interval configured for a subscription, as the scheduler already
+/// knows it (§5.1: one place decides how often a pkgbase is checked).
+pub fn subscription_poll_interval(db: &Db, pkgbase: &str) -> Result<Option<i64>> {
+ db.read(|c| {
+ Ok(c.query_row(
+ "SELECT poll_interval_secs FROM subscription WHERE pkgbase=?1",
+ params![pkgbase],
+ |r| r.get::<_, Option<i64>>(0),
+ )
+ .optional()?
+ .flatten())
+ })
+}
+
+/// Record a fetched source in the content-addressed cache (§5.3).
+pub fn put_source_cache(writer: &Writer, url: &str, digest: &str, size: u64, path: &str) -> Result<()> {
+ let (u, d, p) = (url.to_string(), digest.to_string(), path.to_string());
+ let at = time::now();
+ writer.tx(move |tx| {
+ tx.execute(
+ "INSERT INTO source_cache (url, digest, size, fetched_at, path) VALUES (?1,?2,?3,?4,?5)
+ ON CONFLICT(url, digest) DO UPDATE SET fetched_at=excluded.fetched_at",
+ params![u, d, size as i64, at, p],
+ )?;
+ Ok(())
+ })
+}
+
+/// Where a cached source with this url+digest lives on disk.
+pub fn source_cache_path(db: &Db, url: &str, digest: &str) -> Result<Option<String>> {
+ db.read(|c| {
+ Ok(c.query_row(
+ "SELECT path FROM source_cache WHERE url=?1 AND digest=?2",
+ params![url, digest],
+ |r| r.get::<_, String>(0),
+ )
+ .optional()?)
+ })
+}
+
+/// An artifact produced by a build, ready to record.
+pub struct NewArtifact<'a> {
+ pub digest: &'a str,
+ pub size: i64,
+ pub path: &'a str,
+ pub signature_path: Option<&'a str>,
+ pub build_log_path: Option<&'a str>,
+ pub build_id: &'a str,
+ pub at: &'a str,
+}
+
+/// Record an artifact produced by a build. Identical bytes are one row: the
+/// digest is the identity, and the row is re-stamped with the build that most
+/// recently produced them.
+pub fn insert_artifact_in(tx: &rusqlite::Transaction<'_>, a: &NewArtifact<'_>) -> Result<()> {
+ tx.execute(
+ "INSERT INTO artifact (digest, size, path, signature_path, build_log_path, build_id, created_at)
+ VALUES (?1,?2,?3,?4,?5,?6,?7)
+ ON CONFLICT(digest) DO UPDATE SET build_id=excluded.build_id",
+ params![a.digest, a.size, a.path, a.signature_path, a.build_log_path, a.build_id, a.at],
+ )?;
+ Ok(())
+}
+
// --------------------------------------------------------- stage B cache --
/// Exact cache hit: same recipe, same upstream tips (§5.2).
@@ -898,6 +1217,215 @@ pub fn list_audit(db: &Db, limit: i64) -> Result<Vec<AuditRow>> {
})
}
+// -------------------------------------------------------------- metrics reads --
+//
+// The metrics surface is derived from live state, never stored (§10.3: a
+// counter that is written is a counter that can drift out of truth). These are
+// the reads that derivation is made of, and they live here because the schema
+// they read lives here.
+
+/// The `count(*)` idiom in one place, so a metric cannot accidentally become a
+/// `count(*)` of a join.
+fn count_rows(db: &Db, sql: &str) -> Result<i64> {
+ let sql = sql.to_string();
+ db.read(move |c| {
+ c.query_row(&sql, [], |r| r.get::<_, i64>(0))
+ .map_err(|e| Error::db(e.to_string()))
+ })
+}
+
+/// `(state, count)` for every build state present.
+pub fn build_state_counts(db: &Db) -> Result<Vec<(String, i64)>> {
+ db.read(|c| {
+ let mut st = c.prepare("SELECT state, count(*) FROM build GROUP BY state ORDER BY state")?;
+ let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+/// Seconds the oldest queued build has been waiting; 0 when the queue is empty.
+pub fn oldest_queued_age_secs(db: &Db, now: &str) -> Result<i64> {
+ db.read(|c| {
+ c.query_row(
+ "SELECT julianday(?1) - julianday(min(created_at)) FROM build WHERE state='queued'",
+ params![now],
+ |r| r.get::<_, Option<f64>>(0),
+ )
+ .map(|v| (v.unwrap_or(0.0) * 86400.0) as i64)
+ .map(|v| v.max(0))
+ .map_err(|e| Error::db(e.to_string()))
+ })
+}
+
+/// How many candidates are waiting for a decision.
+pub fn count_pending_reviews(db: &Db) -> Result<i64> {
+ count_rows(db, "SELECT count(*) FROM candidate WHERE state='pending_review'")
+}
+
+/// Age in seconds of every pending review; the caller sorts them.
+pub fn pending_review_ages_secs(db: &Db, now: &str) -> Result<Vec<i64>> {
+ db.read(|c| {
+ let mut st = c.prepare("SELECT julianday(?1) - julianday(detected_at) FROM candidate WHERE state='pending_review'")?;
+ let rows = st.query_map(params![now], |r| r.get::<_, Option<f64>>(0))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push((r?.unwrap_or(0.0) * 86400.0) as i64);
+ }
+ Ok(out)
+ })
+}
+
+pub fn count_index_packages(db: &Db) -> Result<i64> {
+ count_rows(db, "SELECT count(*) FROM package WHERE state='in_index'")
+}
+
+pub fn count_published_releases(db: &Db) -> Result<i64> {
+ count_rows(db, "SELECT count(*) FROM release WHERE state='published'")
+}
+
+pub fn count_subscriptions(db: &Db) -> Result<i64> {
+ count_rows(db, "SELECT count(*) FROM subscription")
+}
+
+pub fn count_unacknowledged_notices(db: &Db) -> Result<i64> {
+ count_rows(db, "SELECT count(*) FROM notice WHERE acknowledged_at IS NULL")
+}
+
+/// Bytes of artifact still on disk. Purged rows are history, not usage.
+pub fn artifact_bytes_served(db: &Db) -> Result<u64> {
+ db.read(|c| {
+ c.query_row(
+ "SELECT COALESCE(sum(size),0) FROM artifact WHERE purged_at IS NULL",
+ [],
+ |r| r.get::<_, i64>(0),
+ )
+ .map(|v| v.max(0) as u64)
+ .map_err(|e| Error::db(e.to_string()))
+ })
+}
+
+/// Seconds since the last retention run, if there has been one.
+pub fn last_gc_age_secs(db: &Db, now: &str) -> Result<Option<i64>> {
+ let at = db.read(|c| {
+ c.query_row("SELECT max(ran_at) FROM gc_run", [], |r| r.get::<_, Option<String>>(0))
+ .map_err(|e| Error::db(e.to_string()))
+ })?;
+ Ok(at.and_then(|t| time::delta_secs(now, &t)))
+}
+
+/// Seconds since the last successful poll of any source, if there has been one.
+/// This is the metric that catches a watcher that stopped, which no log line
+/// will tell you about.
+pub fn last_poll_age_secs(db: &Db, now: &str) -> Result<Option<i64>> {
+ let at = db.read(|c| {
+ c.query_row("SELECT max(last_checked_at) FROM subscription", [], |r| r.get::<_, Option<String>>(0))
+ .map_err(|e| Error::db(e.to_string()))
+ })?;
+ Ok(at.and_then(|t| time::delta_secs(now, &t)))
+}
+
+// -------------------------------------------------------------- retention reads --
+
+/// `(pkgbase id, current accepted release)` for every pkgbase, in id order.
+pub fn pkgbase_release_pointers(db: &Db) -> Result<Vec<(i64, Option<i64>)>> {
+ db.read(|c| {
+ let mut st = c.prepare("SELECT id, current_accepted_release_id FROM pkgbase ORDER BY id")?;
+ let rows = st.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Option<i64>>(1)?)))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+/// Published release ids of one pkgbase, newest first.
+pub fn published_release_ids(db: &Db, pkgbase_id: i64) -> Result<Vec<i64>> {
+ db.read(|c| {
+ let mut st = c.prepare("SELECT id FROM release WHERE pkgbase_id=?1 AND state='published' ORDER BY id DESC")?;
+ let rows = st.query_map(params![pkgbase_id], |r| r.get::<_, i64>(0))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+/// Releases of one pkgbase that still back an `in_index` package. Retention must
+/// never evict these: the index is pointing at their bytes right now.
+pub fn serving_release_ids(db: &Db, pkgbase_id: i64) -> Result<Vec<i64>> {
+ db.read(|c| {
+ let mut st = c.prepare(
+ "SELECT DISTINCT r.id FROM release r JOIN package p ON p.release_id=r.id
+ WHERE r.pkgbase_id=?1 AND p.state='in_index' ORDER BY r.id DESC",
+ )?;
+ let rows = st.query_map(params![pkgbase_id], |r| r.get::<_, i64>(0))?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+/// The three paths one artifact row points at: the package, its signature and
+/// its build log. Any of them can be absent (an unsigned build, a log that was
+/// already purged).
+pub type ArtifactPaths = (Option<String>, Option<String>, Option<String>);
+
+/// The artifact paths one release holds: package, signature, build log.
+pub fn release_artifact_paths(db: &Db, release_id: i64) -> Result<Vec<ArtifactPaths>> {
+ db.read(|c| {
+ let mut st = c.prepare(
+ "SELECT a.path, a.signature_path, a.build_log_path FROM artifact a
+ JOIN package p ON p.artifact_id = a.id WHERE p.release_id = ?1",
+ )?;
+ let rows = st.query_map(params![release_id], |r| {
+ Ok((r.get::<_, Option<String>>(0)?, r.get::<_, Option<String>>(1)?, r.get::<_, Option<String>>(2)?))
+ })?;
+ let mut out = Vec::new();
+ for r in rows {
+ out.push(r?);
+ }
+ Ok(out)
+ })
+}
+
+/// Mark a release and the artifacts behind it as purged, in one transaction.
+/// Half-marking them would leave the next retention pass believing the files are
+/// still retained.
+pub fn mark_release_purged(writer: &Writer, release_id: i64) -> Result<()> {
+ let at = time::now();
+ writer.tx(move |tx| {
+ tx.execute("UPDATE release SET purged_at=?1 WHERE id=?2", params![at, release_id])?;
+ tx.execute(
+ "UPDATE artifact SET purged_at=?1 WHERE purged_at IS NULL AND id IN
+ (SELECT a.id FROM artifact a JOIN package p ON p.artifact_id=a.id WHERE p.release_id=?2)",
+ params![at, release_id],
+ )?;
+ Ok(())
+ })
+}
+
+/// Record a retention run, which is what the ops page and the `last_gc_age`
+/// metric read.
+pub fn record_gc_run(writer: &Writer, at: &str, kept: i64, evicted: i64, files_removed: i64, bytes_freed: i64, staging_swept: i64) -> Result<()> {
+ let at = at.to_string();
+ writer.tx(move |tx| {
+ tx.execute(
+ "INSERT INTO gc_run (ran_at, releases_kept, releases_evicted, files_removed, bytes_freed, staging_swept)
+ VALUES (?1,?2,?3,?4,?5,?6)",
+ params![at, kept, evicted, files_removed, bytes_freed, staging_swept],
+ )?;
+ Ok(())
+ })
+}
+
// ------------------------------------------------------- invariant helpers --
/// I1: every artifact in a served repo index traces to an approval row.