diff options
| author | aur-build <aur-build@localhost> | 2026-11-19 17:33:17 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-19 17:33:17 +0000 |
| commit | 4304b0f336ddba7b4ec6780795059ff2066d105b (patch) | |
| tree | 10edea744a1c2bf3fc363b4dc7f64abac8b1a0d3 /src/db | |
| parent | e757979f1a2afdbe7146066345bb9acd19d3b151 (diff) | |
| download | aur-build-4304b0f336ddba7b4ec6780795059ff2066d105b.tar.gz aur-build-4304b0f336ddba7b4ec6780795059ff2066d105b.zip | |
comments: keep only what the code cannot show
Stripped every comment that described what an item does, documented its
arguments or fields, or cited the design docs (§n, I-n, m-n, decision n).
2247 comments down to 83.
What survives: the section dividers that segment the large modules, the
secret-handling warnings, the agent wire-frame directions, and the few notes
without which the code they attach to reads as redundant, reorderable, or
unsound.
Diffstat (limited to 'src/db')
| -rw-r--r-- | src/db/approvals.rs | 6 | ||||
| -rw-r--r-- | src/db/builds.rs | 39 | ||||
| -rw-r--r-- | src/db/candidates.rs | 34 | ||||
| -rw-r--r-- | src/db/migrations.rs | 15 | ||||
| -rw-r--r-- | src/db/mod.rs | 35 | ||||
| -rw-r--r-- | src/db/model.rs | 91 | ||||
| -rw-r--r-- | src/db/queries.rs | 130 |
7 files changed, 0 insertions, 350 deletions
diff --git a/src/db/approvals.rs b/src/db/approvals.rs index b5a9b59..ececc32 100644 --- a/src/db/approvals.rs +++ b/src/db/approvals.rs @@ -3,7 +3,6 @@ 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>, @@ -15,7 +14,6 @@ pub struct Decision<'a> { 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, @@ -35,9 +33,6 @@ pub fn record_in(tx: &mut Transaction<'_>, d: &Decision<'_>) -> Result<i64> { 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, @@ -49,7 +44,6 @@ pub fn record_rejection_in(tx: &mut Transaction<'_>, candidate_id: i64, at: &str 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( diff --git a/src/db/builds.rs b/src/db/builds.rs index 8598dd3..de9e7fb 100644 --- a/src/db/builds.rs +++ b/src/db/builds.rs @@ -50,13 +50,10 @@ pub(crate) fn row_to_build(r: &rusqlite::Row<'_>) -> rusqlite::Result<BuildRow> }) } -/// Deterministic build id (§8.2): re-submitting the same intent is a no-op, -/// which is what makes manual rebuilds safe to enqueue carelessly. pub fn build_id(pkgbase: &str, identity_hash: &str, world_hash: &str, profile: &str) -> String { crate::hash::hex_str(&format!("{pkgbase}|{identity_hash}|{world_hash}|{profile}")) } -/// Enqueue a build intent. `INSERT OR IGNORE` on the deterministic id. #[allow(clippy::too_many_arguments)] pub fn enqueue( db: &Db, @@ -130,7 +127,6 @@ pub fn queued(db: &Db, limit: i64) -> Result<Vec<String>> { }) } -/// Claim a build for a worker: the lease is what makes a crash recoverable. pub fn claim(db: &Db, owner: &str, id: &str, lease_secs: i64) -> Result<bool> { let (owner, id) = (owner.to_string(), id.to_string()); let exp = time::secs_ahead(lease_secs); @@ -158,10 +154,6 @@ pub fn extend_lease(db: &Db, id: &str, lease_secs: i64) -> Result<()> { }) } -/// Reaper pass (§8.2): expired leases go back to the queue and their in-flight step -/// is marked interrupted, so the checkpoint decides where it resumes. -/// -/// Both `leased` and `running` are reaped: a mid-step death leaves a `running` row. pub fn reap_expired(db: &Db) -> Result<usize> { let now = time::now(); db.writer.tx(move |tx| { @@ -189,10 +181,6 @@ pub fn reap_expired(db: &Db) -> Result<usize> { }) } -/// The one way a build changes state, usable inside a transaction. -/// -/// The write is a compare-and-swap: only a row in one of `to`'s legal predecessor -/// states is updated, so a zombie worker whose lease was reaped gets an error. fn transition_in_tx( tx: &mut rusqlite::Transaction<'_>, id: &str, @@ -224,7 +212,6 @@ fn transition_in_tx( Ok(()) } -/// Move a build to `to`, refusing any transition [`BuildState`] forbids. pub fn set_state(db: &Db, id: &str, to: BuildState, error: Option<&str>) -> Result<()> { let id = id.to_string(); let error = error.map(|e| e.to_string()); @@ -242,10 +229,6 @@ pub fn block_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> { }) } -/// Requeue blocked builds whose blocking packages have since arrived (§10.4). -/// -/// Not "requeue everything that is blocked": the dispatcher calls this every pass, -/// and requeueing a build that will immediately block again burns a claim each tick. pub fn requeue_blocked(db: &Db) -> Result<usize> { let now = time::now(); db.writer.tx(move |tx| { @@ -256,8 +239,6 @@ pub fn requeue_blocked(db: &Db) -> Result<usize> { .collect::<rusqlite::Result<Vec<(String, String)>>>()?; out }; - // The index membership check is one query for the whole pass, not one per - // dependency of every blocked build (m-17), on the dispatcher's hot loop. let in_index: std::collections::HashSet<String> = { let mut stmt = tx.prepare("SELECT name FROM package WHERE state='in_index'")?; let names = stmt @@ -349,9 +330,6 @@ pub fn begin_step(db: &Db, build_id: &str, step: &str, attempt: i64) -> Result<( let (b, s) = (build_id.to_string(), step.to_string()); let at = time::now(); db.writer.tx(move |tx| { - // The `WHERE` is I5 with teeth: a step already checkpointed as done is - // frozen, so a resume that asks to re-run it cannot overwrite the record - // that told it to skip. The insert path is unaffected. let n = tx.execute( "INSERT INTO build_step (build_id, step, status, attempt, started_at) VALUES (?1,?2,'running',?3,?4) @@ -370,8 +348,6 @@ pub fn begin_step(db: &Db, build_id: &str, step: &str, attempt: i64) -> Result<( }) } -/// Record what a step produced. Refuses a transition [`StepState`] forbids — -/// above all, writing over a checkpoint a resume is relying on. pub fn finish_step( db: &Db, build_id: &str, @@ -416,7 +392,6 @@ pub fn finish_step( }) } -/// Builds in flight (leased or running), for the backpressure calculation. pub fn in_flight(db: &Db) -> Result<usize> { db.read(|c| { Ok(c.query_row( @@ -460,7 +435,6 @@ 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(()) @@ -532,9 +506,6 @@ pub fn current_state(c: &Connection, id: &str) -> Result<Option<BuildState>> { } } -/// Claim up to `limit` queued builds in one `BEGIN IMMEDIATE` transaction and -/// hand them to workers (§8.2). SQLite has no `SKIP LOCKED`, but with exactly one -/// writer the claim cannot race: the SELECT and the UPDATE are one transaction. pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Result<Vec<String>> { if limit == 0 { return Ok(Vec::new()); @@ -563,9 +534,6 @@ pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Resul }) } -/// A newer approved release for the same pkgbase makes an in-flight build -/// pointless (§8.2 cancellation). Workers notice at the next step boundary and -/// stop; nothing is killed mid-step, which is what keeps the checkpoints honest. pub fn cancel_superseded(db: &Db) -> Result<usize> { db.writer.tx(move |tx| { let n = tx.execute( @@ -578,17 +546,12 @@ pub fn cancel_superseded(db: &Db) -> Result<usize> { }) } -/// Put a build back on the queue after a transient failure, keeping the attempt -/// count so the retry cap can bite (§8.4). pub fn requeue_transient(db: &Db, id: &str) -> Result<()> { let id = id.to_string(); db.writer .tx(move |tx| transition_in_tx(tx, &id, BuildState::Queued, None)) } -/// Explicitly retry a failed build (§8.4): the failed step goes back to pending, -/// everything that succeeded stays checkpointed, and the attempt counter keeps -/// counting. pub fn retry(db: &Db, id: &str) -> Result<()> { let id = id.to_string(); db.writer.tx(move |tx| { @@ -597,8 +560,6 @@ pub fn retry(db: &Db, id: &str) -> Result<()> { WHERE build_id=?1 AND status IN ('failed','interrupted')", params![id], )?; - // The move itself goes through the machine, so requeueing a build that - // already published is refused with a reason. transition_in_tx(tx, &id, BuildState::Queued, None)?; tx.execute("UPDATE build SET cancel_requested=0 WHERE id=?1", params![id])?; Ok(()) diff --git a/src/db/candidates.rs b/src/db/candidates.rs index 631bf42..df145ac 100644 --- a/src/db/candidates.rs +++ b/src/db/candidates.rs @@ -4,7 +4,6 @@ use crate::db::{CandidateRow, CandidateState, Db}; use crate::error::{Error, Result}; use crate::time; -/// The columns `row_to_candidate` reads, spelled once (§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, \ @@ -36,7 +35,6 @@ fn row_to_candidate(r: &Row<'_>) -> rusqlite::Result<CandidateRow> { }) } -/// The fields a new candidate row carries, beyond its pkgbase and its base. #[derive(Debug, Clone)] pub struct NewCandidate { pub snapshot_id: i64, @@ -49,13 +47,11 @@ pub struct NewCandidate { } 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, @@ -65,8 +61,6 @@ pub struct OpenReview { } 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() } @@ -74,8 +68,6 @@ impl OpenReview { // ------------------------------------------------------------------ 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, @@ -83,9 +75,7 @@ pub struct ReviewSubject { pub state: CandidateState, 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, @@ -116,10 +106,6 @@ pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Opti .optional()?) } -/// Take a candidate out of the open state: approved, rejected or superseded. -/// -/// The write is a compare-and-swap on [`CandidateState`]: a decided review is never -/// re-decided, so an approval racing a rejection fails instead of overwriting. pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) -> Result<()> { let froms = CandidateState::predecessors(to); let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(","); @@ -144,8 +130,6 @@ pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) - 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<CandidateState>> { Ok(tx .query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| { @@ -160,7 +144,6 @@ pub fn identity_in(tx: &Transaction<'_>, id: i64) -> Result<Option<String>> { .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)) @@ -168,7 +151,6 @@ pub fn risk_level(db: &Db, id: i64) -> Result<Option<String>> { }) } -/// 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( @@ -187,8 +169,6 @@ pub fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result<Option<OpenRevie .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( @@ -212,14 +192,11 @@ pub fn collapse_in(tx: &mut Transaction<'_>, open: &OpenReview, nc: &NewCandidat Ok(revision) } -/// Freeze a reviewed candidate as `superseded` so a fresh review can open. pub fn supersede_in(tx: &Transaction<'_>, id: i64) -> Result<()> { let at = time::now(); resolve_in(tx, id, CandidateState::Superseded, &at) } -/// Has this exact identity been rejected before? If so the watcher stays quiet -/// until a human re-opens it (§7.1). pub fn rejected_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: &str) -> Result<bool> { Ok(tx .query_row( @@ -232,8 +209,6 @@ pub fn rejected_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: .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( @@ -246,7 +221,6 @@ pub fn recorded_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: .is_some()) } -/// Open a candidate row in `pending_review`. pub fn insert_in( tx: &mut Transaction<'_>, pkgbase_id: i64, @@ -277,7 +251,6 @@ pub fn insert_in( // ------------------------------------------------------------------ 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| { @@ -291,7 +264,6 @@ pub fn all(db: &Db) -> Result<Vec<CandidateRow>> { }) } -/// 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 \ @@ -316,7 +288,6 @@ pub fn by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> { }) } -/// 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 \ @@ -335,8 +306,6 @@ pub fn open_reviews_for(db: &Db, pkgbase_id: i64) -> Result<Vec<CandidateRow>> { // ---------------------------------------------------------------- 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| { @@ -348,8 +317,6 @@ pub fn mark_viewed(db: &Db, id: i64) -> Result<()> { }) } -/// §7.1: a rejection can be re-opened. The rejected row is retired 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| { @@ -364,7 +331,6 @@ pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> { }) } -/// 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)?; diff --git a/src/db/migrations.rs b/src/db/migrations.rs index b1954ab..18e9a4b 100644 --- a/src/db/migrations.rs +++ b/src/db/migrations.rs @@ -1,4 +1,3 @@ -/// One migration: version number + SQL body. pub struct Migration { pub version: u32, pub name: &'static str, @@ -268,17 +267,11 @@ BEGIN END; "#; -/// `artifact.build_id` lets the publish step find what `ingest` recorded without -/// re-scanning the disposable staging directory, so a worker that dies between -/// ingest and publish resumes cleanly (I5). const M_0005_ARTIFACT_BUILD: &str = r#" ALTER TABLE artifact ADD COLUMN build_id TEXT; CREATE INDEX artifact_by_build ON artifact (build_id); "#; -/// §7.2: the approval record is immutable. It is the only proof the system has -/// of *what a human actually looked at*, so editing it would let a later -/// attacker retarget a published artifact onto a clean review. const M_0006_APPROVAL_IMMUTABLE: &str = r#" CREATE TRIGGER approval_no_update BEFORE UPDATE ON approval @@ -293,9 +286,6 @@ BEGIN END; "#; -/// Stage B results, keyed on `(pkgbase, recipe_hash, upstream_tip)` (§5.2). -/// Re-resolving means cloning an upstream repo and running makepkg, so the answer -/// is worth keeping; the same key also implements the per-pkgbase cooldown. const M_0007_STAGE_B_CACHE: &str = r#" CREATE TABLE stage_b_cache ( pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), @@ -312,10 +302,6 @@ CREATE TABLE stage_b_cache ( CREATE INDEX stage_b_cache_by_pkgbase ON stage_b_cache (pkgbase_id, resolved_at); "#; -/// Retention (§15). The rows are never compacted — the schema exists so "which -/// bytes produced this installed package" stays answerable — but the bytes on disk -/// cannot be kept forever. So eviction is recorded rather than implied: the -/// artifact row keeps its digest, size and provenance and gains a `purged_at`. const M_0008_RETENTION: &str = r#" ALTER TABLE artifact ADD COLUMN purged_at TEXT; @@ -348,7 +334,6 @@ pub static MIGRATIONS: &[Migration] = &[ Migration { version: 8, name: "retention", sql: M_0008_RETENTION }, ]; -/// Default settings seeded into `settings` (DESIGN.md §11). pub const DEFAULT_SETTINGS: &[(&str, &str)] = &[ ("max_concurrent_builds", "1"), ("build_timeout", "5400"), diff --git a/src/db/mod.rs b/src/db/mod.rs index c271fe7..95833be 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -8,8 +8,6 @@ pub mod queries; pub use migrations::MIGRATIONS; pub use model::*; -/// Parse a state column into one of the state enums. A value the code does not -/// recognise fails the row instead of becoming a default. pub(crate) fn state_col<T: StateEnum>(col: usize, text: &str) -> rusqlite::Result<T> { T::parse(text).ok_or_else(|| { rusqlite::Error::FromSqlConversionFailure( @@ -35,7 +33,6 @@ use rusqlite::Connection; use crate::config::Config; use crate::error::{Error, Result}; -/// Open a connection with the pragmas every connection needs. fn open(path: &Path, read_only: bool) -> Result<Connection> { let conn = if read_only { Connection::open_with_flags( @@ -56,14 +53,12 @@ fn configure(conn: &Connection, read_only: bool) -> Result<()> { .and_then(|_| conn.pragma_update(None, "foreign_keys", "ON")) .map_err(|e| Error::db(e.to_string()))?; if !read_only { - // Durability of the approval trail is worth the fsync (§11a). conn.pragma_update(None, "synchronous", "FULL") .map_err(|e| Error::db(e.to_string()))?; } Ok(()) } -/// Apply pending migrations. Must run before the writer actor starts. pub fn migrate(path: &Path) -> Result<u32> { let mut conn = open(path, false)?; let mut applied = 0u32; @@ -101,9 +96,6 @@ enum Msg { Shutdown, } -/// Handle on the single writer thread. -/// -/// Cheap to clone; every clone talks to the same actor. pub struct Writer { tx: Sender<Msg>, path: PathBuf, @@ -111,7 +103,6 @@ pub struct Writer { } impl Writer { - /// Spawn the writer actor thread. pub fn start(path: &Path) -> Result<Self> { let conn = open(path, false)?; let (tx, rx) = unbounded::<Msg>(); @@ -129,7 +120,6 @@ impl Writer { Msg::Shutdown => break, } } - // Best-effort WAL checkpoint on the way out. let _ = conn.pragma_update(None, "wal_checkpoint", "TRUNCATE"); alive_thread.store(false, Ordering::SeqCst); }) @@ -145,13 +135,6 @@ impl Writer { self.alive.load(Ordering::SeqCst) } - /// Run `f` on the write connection and wait for its result. No transaction - /// may span a build step: `f` should be short. - /// - /// `pub(crate)`, not `pub`: the schema has one owner, this module (§6 M-1). - /// 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, @@ -165,7 +148,6 @@ impl Writer { .map_err(|_| Error::db("writer actor gone"))? } - /// Run `f` inside a single `BEGIN IMMEDIATE` transaction. pub(crate) fn tx<T>( &self, f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static, @@ -183,7 +165,6 @@ impl Writer { }) } - /// Fire-and-forget write (audit rows, bookkeeping where the result is unused). pub(crate) fn send(&self, f: BoxedCall) -> Result<()> { if !self.is_alive() { return Err(Error::db("writer actor gone")); @@ -198,10 +179,6 @@ impl Writer { } } -/// The raw-SQL door, open only for the test harness (§6 M-9). A fixture -/// sometimes has to reach a state the typed API only reaches through several -/// steps, but that is not a reason to leave the door unlocked in the binary an -/// operator runs. #[cfg(feature = "test-support")] impl Writer { pub fn tx_for_tests<T>( @@ -222,9 +199,6 @@ impl Writer { } } -/// Thread-local read-only connection pool: one connection per thread per -/// database file. HTTP handlers and watchers use this; they never touch the -/// write connection. pub struct Readers { path: PathBuf, } @@ -238,7 +212,6 @@ impl Readers { Self { path: path.to_path_buf() } } - /// Run `f` against this thread's read-only connection. pub fn with<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> { let path = self.path.clone(); POOL.with(|pool| { @@ -258,7 +231,6 @@ impl Readers { } } -/// A handle bundling the writer with a reader factory; passed around as `App`. #[derive(Clone)] pub struct Db { pub writer: Arc<Writer>, @@ -279,13 +251,11 @@ impl Db { }) } - /// Convenience: read-only query against the shared reader pool. pub fn read<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> { self.readers.with(f) } } -/// Consistent snapshot for backups: `VACUUM INTO`, never `cp` of a live WAL db. pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> { let dest_s = dest.display().to_string(); writer.call(move |conn| { @@ -295,11 +265,6 @@ pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> { }) } -/// The schema version a database file reports. A backup that does not answer -/// with a migrated schema is a file, not a backup. -/// -/// Opened read-write and untouched by the connection pragmas: a WAL database -/// cannot even be opened read-only. 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())))?; diff --git a/src/db/model.rs b/src/db/model.rs index 84701d1..5afb793 100644 --- a/src/db/model.rs +++ b/src/db/model.rs @@ -2,24 +2,15 @@ use serde::{Deserialize, Serialize}; use crate::hash; -/// One resolved upstream VCS source (DESIGN.md §3). The commit SHA alone is -/// sufficient: a git commit transitively commits to its tree, and a gitlink in -/// that tree commits to any submodule's commit. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct UpstreamPin { pub index: usize, pub url: String, - /// The ref we asked for: `HEAD`, a tag, or an explicit commit. pub ref_: String, pub branch: Option<String>, - /// The pin. pub commit: String, } -/// A row of the Stage B cache (§5.2): the version resolution produced, with the -/// pins it was computed from. This lives with the schema because the table does — -/// the persistence layer must not name a type from the module that owns VCS -/// probing (§6 M-6). #[derive(Debug, Clone)] pub struct StageBCacheRow { pub epoch: String, @@ -34,40 +25,28 @@ impl StageBCacheRow { } } -/// A source entry with the digest *we* computed, regardless of what the -/// PKGBUILD declares (§5.3). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SourceDigest { pub index: usize, pub url: String, - /// `static` | `vcs` | `local` pub kind: String, - /// sha256, or the resolved VCS commit for vcs sources. pub digest: String, pub size: u64, - /// True when the PKGBUILD gave us no checksum to trust — `SKIP`, a malformed - /// digest, or nothing at all. It means that and nothing else (m-19): a `-git` - /// source has no checksum by design because the *pin* is the integrity. Ask - /// [`SourceDigest::is_vcs`] which mechanism protects an entry. pub skip_declared: bool, } impl SourceDigest { - /// True when this entry's integrity comes from a resolved commit rather than a - /// content hash. pub fn is_vcs(&self) -> bool { matches!(self.kind.as_str(), "vcs" | "git" | "svn" | "hg" | "bzr") } } -/// A member of a world snapshot: one of *our* packages the build ran against. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] pub struct WorldMember { pub pkgbase: String, pub version: String, } -/// The identity tuple of a candidate (§3). Every element is part of the key. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Identity { pub aur_commit: String, @@ -79,30 +58,18 @@ pub struct Identity { } impl Identity { - /// The hash that makes I3 a fact: two byte-identical inputs never produce two - /// candidates, and any change to what becomes a byte in the artifact produces a - /// new one. This is the value an approval must echo; a value that cannot be - /// serialized is an error rather than a digest, because a shared fallback - /// digest would be the one way two identities could collide by accident. pub fn hash(&self) -> crate::error::Result<String> { Ok(format!("sha256:{}", hash::hex(hash::canonical_json(self)?.as_bytes()))) } } -/// The review state machine (§7.1). A decision must never be overwritten by -/// accident — an approval that silently replaced a rejection would break I2 and -/// I3 without any symptom — so the states are an enum and -/// [`crate::db::candidates::resolve_in`] refuses a move the machine forbids. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum CandidateState { - /// The only state a reviewer can act on. PendingReview, Approved, Rejected, - /// A newer review of the same pkgbase took its place (§7.1). Superseded, - /// Not approved because something it needs is missing (§10.4). Blocked, } @@ -133,7 +100,6 @@ impl CandidateState { *self == CandidateState::PendingReview } - /// Re-writing the state a row already has is a no-op, not a move. pub fn can_transition(&self, to: CandidateState) -> bool { use CandidateState::*; if *self == to { @@ -141,7 +107,6 @@ impl CandidateState { } match self { PendingReview => matches!(to, Approved | Rejected | Superseded | Blocked), - // A decided review is only ever frozen, never re-decided (§7.1). Approved | Rejected => to == Superseded, Blocked => matches!(to, PendingReview | Approved | Rejected), Superseded => false, @@ -168,14 +133,11 @@ pub mod candidate_kind { pub const FIRST_INTRODUCTION: &str = "first_introduction"; } -/// The release state machine (§9). #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ReleaseState { Published, - /// Taken out of the index (§9 withdrawal); the row stays (§15). Withdrawn, - /// Approved, but the build never produced it: the old version still serves. FailedUnbuilt, } @@ -198,7 +160,6 @@ impl ReleaseState { ReleaseState::ALL.iter().copied().find(|r| r.as_str() == s) } - /// Withdrawal is the only move a release makes on its own. pub fn can_transition(&self, to: ReleaseState) -> bool { use ReleaseState::*; if *self == to { @@ -217,11 +178,7 @@ impl std::fmt::Display for ReleaseState { } } -/// What the state enums below have in common: a closed set of column values, -/// parsed where a row is read, so `db::state_col` can fail an unknown state -/// instead of defaulting it. pub trait StateEnum: Copy + Sized { - /// The name of the machine, for the error message. const KIND: &'static str; fn parse(text: &str) -> Option<Self>; fn as_str(&self) -> &'static str; @@ -247,17 +204,11 @@ impl_state_enum!(StepState, "build step"); impl_state_enum!(ReleaseState, "release"); impl_state_enum!(SubscriptionState, "subscription"); -/// The build state machine (§7.1, §8.2). A state is one of these seven, it is -/// parsed where a row is read, and `can_transition` is the only way a write -/// happens. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum BuildState { Queued, - /// Claimed by a worker with a lease (§8.2). Leased, - /// A step is executing. Running, - /// Waiting for packages another build must publish first (§10.4). BlockedMissingDep, Succeeded, Failed, @@ -275,8 +226,6 @@ impl BuildState { BuildState::Cancelled, ]; - /// The text in the `state` column — a spelling the reaper, dispatcher and UI - /// all speak. pub fn as_str(&self) -> &'static str { match self { BuildState::Queued => "queued", @@ -289,14 +238,10 @@ impl BuildState { } } - /// An unrecognised state is `None`, and the row boundary turns that into an - /// error: a state we cannot name is one we must not act on. pub fn parse(s: &str) -> Option<BuildState> { BuildState::ALL.iter().copied().find(|b| b.as_str() == s) } - /// Nothing happens to a finished build by itself; only an explicit human - /// requeue or resume moves it again. pub fn is_terminal(&self) -> bool { matches!( self, @@ -304,32 +249,22 @@ impl BuildState { ) } - /// Writing the state a row already has is always allowed: the step loop - /// re-asserts `Running` at every step boundary (§8.3). Everything else is - /// refused by [`crate::db::builds::set_state`], and the refusals are the point: - /// nothing revives a `Succeeded` build, and a build reaped back to `Queued` - /// cannot be completed by the zombie worker that lost its lease. pub fn can_transition(&self, to: BuildState) -> bool { use BuildState::*; if *self == to { return true; } match self { - // The dispatcher claims queued builds; `aur-build run <id>` runs one - // in the foreground without a lease. Queued => matches!(to, Leased | Running | BlockedMissingDep | Cancelled), Leased => matches!(to, Running | Queued | BlockedMissingDep | Succeeded | Failed | Cancelled), Running => matches!(to, Queued | BlockedMissingDep | Succeeded | Failed | Cancelled), BlockedMissingDep => matches!(to, Queued | Cancelled), - // A failed build is resumed on the same row — that is I5 (§8.4). Failed => matches!(to, Queued | Running), Cancelled => to == Queued, Succeeded => false, } } - /// Every state that may legally move to `to` — the `WHERE state IN (...)` - /// that makes a state write a compare-and-swap. pub fn predecessors(to: BuildState) -> Vec<&'static str> { BuildState::ALL .iter() @@ -354,9 +289,6 @@ impl std::fmt::Display for BuildState { } } -/// The step checkpoint state machine (§8.3, I5). The checkpoint row is what a -/// resumed build reads to decide what not to redo, so a completed checkpoint is -/// frozen. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum StepState { @@ -364,7 +296,6 @@ pub enum StepState { Running, Succeeded, Failed, - /// Killed mid-step; the reaper writes this so the resume re-runs it (§8.2). Interrupted, Skipped, } @@ -394,8 +325,6 @@ impl StepState { StepState::ALL.iter().copied().find(|st| st.as_str() == text) } - /// I5: the resume skips a step in one of these two states, so nothing may - /// move it again. pub fn is_done(&self) -> bool { matches!(self, StepState::Succeeded | StepState::Skipped) } @@ -407,8 +336,6 @@ impl StepState { } match self { Pending => matches!(to, Running | Succeeded | Failed | Interrupted | Skipped), - // `Running → Pending` is the blocked path: the step did not happen, - // so the checkpoint goes back to waiting. Running => matches!(to, Pending | Succeeded | Failed | Interrupted | Skipped), Failed | Interrupted => matches!(to, Pending | Running), Succeeded | Skipped => false, @@ -442,13 +369,11 @@ pub mod notice_kind { pub const DOWNGRADE: &str = "downgrade"; } -/// Whether a pkgbase is being watched (§4.1, §12). #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum SubscriptionState { Active, Paused, - /// The pkgbase left AUR; the watcher stopped looking (§12). Orphaned, Removed, } @@ -474,8 +399,6 @@ impl SubscriptionState { SubscriptionState::ALL.iter().copied().find(|st| st.as_str() == text) } - /// Pause and resume are the only moves the UI makes; orphaned and removed - /// are facts about the pkgbase, reported once. pub fn can_transition(&self, to: SubscriptionState) -> bool { use SubscriptionState::*; if *self == to { @@ -496,8 +419,6 @@ impl std::fmt::Display for SubscriptionState { } } -/// The pipeline steps (§8.1). Order matters: a build resumes at the first step -/// in this list without a `succeeded` row. pub const BUILD_STEPS: &[&str] = &[ "materialize", "plan", @@ -511,20 +432,15 @@ pub const BUILD_STEPS: &[&str] = &[ "publish", ]; -/// A `source=()` entry after parsing. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SourceEntry { pub index: usize, - /// The URL as written, minus the filename fragment. pub url: String, - /// Explicit filename (`::name` / `::` prefix handling). pub filename: Option<String>, pub commit: Option<String>, pub tag: Option<String>, pub branch: Option<String>, - /// Set when the url is prefixed `git+`, `svn+`, `hg+`, `bzr+`. pub vcs: Option<String>, - /// True for files shipped inside the AUR repo (no scheme). pub local: bool, } @@ -534,7 +450,6 @@ impl SourceEntry { } } -/// A parsed recipe: what `.SRCINFO` / `PKGBUILD` tell us. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Recipe { pub pkgbase: String, @@ -559,15 +474,11 @@ pub struct Recipe { pub options: Vec<String>, pub backup: Vec<String>, pub install: Option<String>, - /// Names of the binary packages this pkgbase emits (split pkgbases have N). pub pkgnames: Vec<String>, pub pkg_depends: Vec<(String, Vec<String>)>, - /// Raw PKGBUILD text, for display and diffing. pub pkgbuild: String, pub srcinfo: Option<String>, - /// True if `--skippgpcheck` appears in the PKGBUILD. pub skipgpcheck: bool, - /// Derived from `source`, so not serialized. #[serde(skip, default)] pub source_entries: Vec<SourceEntry>, } @@ -578,7 +489,6 @@ impl Recipe { } } -/// A source row as stored on a candidate/release. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ReleaseRow { pub id: i64, @@ -652,7 +562,6 @@ impl CandidateRow { } } -/// Parse a JSON column with a fallback, so one bad row never takes down a page. pub fn json_or<T: serde::de::DeserializeOwned>(s: &str, fallback: T) -> T { serde_json::from_str(s).unwrap_or(fallback) } diff --git a/src/db/queries.rs b/src/db/queries.rs index 924051d..583676b 100644 --- a/src/db/queries.rs +++ b/src/db/queries.rs @@ -6,10 +6,6 @@ use crate::time; // ---------------------------------------------------------------- settings -- -/// Every setting, for the settings page. -/// -/// Row-error policy, applied everywhere in `db` (m-9): a row that cannot be read -/// fails the query rather than being dropped silently. pub fn all_settings(db: &Db) -> Result<Vec<(String, String)>> { db.read(|c| { let mut st = c.prepare("SELECT key, value FROM settings ORDER BY key")?; @@ -26,13 +22,6 @@ pub fn setting(db: &Db, key: &str) -> Result<Option<String>> { }) } -/// An integer setting, or `default`. -/// -/// The policy, stated once (m-9): a *missing* setting is normal — the default is -/// the answer. A setting present but unparseable, or a read that failed, is not, -/// and silently returning the default would hide an operator's typo. Both still -/// fall back, because refusing to start over a tuning knob is worse — but they -/// fall back out loud. pub fn setting_i64(db: &Db, key: &str, default: i64) -> i64 { match setting(db, key) { Ok(None) => default, @@ -62,7 +51,6 @@ pub fn set_setting(writer: &Writer, key: &str, value: &str) -> Result<()> { // ------------------------------------------------------------------- audit -- -/// Append an audit row (I10). Every state transition funnels through here. pub fn audit( writer: &Writer, actor_kind: &str, @@ -94,9 +82,6 @@ pub fn audit( }) } -/// An audit row to append inside someone else's transaction. Build one with -/// [`AuditEntry::human`] or [`AuditEntry::system`]: `actor_kind` is a closed set -/// and the timestamp is not the caller's to improvise (§6 m-4). #[derive(Debug)] pub struct AuditEntry<'a> { pub at: &'a str, @@ -109,7 +94,6 @@ pub struct AuditEntry<'a> { } impl<'a> AuditEntry<'a> { - /// A decision a named human made (§11: every approval is attributable). pub fn human( at: &'a str, actor: &'a str, @@ -121,7 +105,6 @@ impl<'a> AuditEntry<'a> { Self { at, actor_kind: "human", actor, action, entity, entity_id, detail } } - /// Something the server did by itself: a publish, a requeue, a watcher tick. pub fn system( at: &'a str, action: &'a str, @@ -133,8 +116,6 @@ impl<'a> AuditEntry<'a> { } } -/// Append an audit row inside a caller's transaction (I10), so the record of a -/// decision commits with the decision or not at all. 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) @@ -150,7 +131,6 @@ pub fn audit_system(writer: &Writer, action: &str, entity: &str, entity_id: &str // -------------------------------------------------------------------- repo -- -/// Ensure the single repo row exists (decision 4: exactly one). pub fn ensure_repo(writer: &Writer, name: &str, path: &str, arch: &str, key: &str) -> Result<i64> { let (n, p, a, k) = (name.to_string(), path.to_string(), arch.to_string(), key.to_string()); writer.tx(move |tx| { @@ -229,7 +209,6 @@ pub fn get_subscription(db: &Db, pkgbase: &str) -> Result<Option<Subscription>> }) } -/// Subscribe: creates the pkgbase row and an active subscription. Idempotent. pub fn subscribe(writer: &Writer, repo_id: i64, pkgbase: &str, aur_url: &str) -> Result<i64> { let (p, u) = (pkgbase.to_string(), aur_url.to_string()); let at = time::now(); @@ -274,7 +253,6 @@ pub fn note_check(writer: &Writer, pkgbase: &str, next_check_at: &str, err: Opti }) } -/// Subscriptions whose next check is due. pub fn due_subscriptions(db: &Db, now: &str) -> Result<Vec<Subscription>> { db.read(|c| { let mut stmt = c.prepare(&format!( @@ -378,8 +356,6 @@ pub fn set_unpinable(writer: &Writer, pkgbase_id: i64, unpinable: bool) -> Resul }) } -/// Compare-and-swap the accepted-release pointer (§16: concurrent approvals). -/// Returns Ok(true) when the swap happened. pub fn cas_accepted_release( writer: &Writer, pkgbase_id: i64, @@ -398,7 +374,6 @@ pub fn cas_accepted_release( // ---------------------------------------------------------------- snapshot -- -/// Insert-or-get a snapshot for (pkgbase, aur_commit). #[allow(clippy::too_many_arguments)] pub fn put_snapshot( writer: &Writer, @@ -509,12 +484,6 @@ 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"; -/// Take a release out of the served index (§9, decision 23), in the caller's -/// transaction so the removal and the audit row explaining it are one fact. -/// -/// Refuses a release that is not currently published (m-10): re-withdrawing used -/// to report success and rewrite nothing. The write is a compare-and-swap on -/// `state='published'`, and the refusal names the state that was actually there. pub fn withdraw_release_in(tx: &rusqlite::Transaction<'_>, release_id: i64) -> Result<()> { let n = tx.execute( "UPDATE release SET state='withdrawn' WHERE id=?1 AND state='published'", @@ -551,8 +520,6 @@ pub fn release_by_id(db: &Db, id: i64) -> Result<Option<ReleaseRow>> { }) } -/// The accepted release of a pkgbase, by name. `None` for a pkgbase that has -/// never been accepted — the case that makes `first_introduction` special (§7.1b). pub fn accepted_release(db: &Db, pkgbase: &str) -> Result<Option<ReleaseRow>> { db.read(|c| { c.query_row( @@ -609,7 +576,6 @@ pub struct PackageRow { pub version: String, pub artifact_id: Option<i64>, pub pkgbase: String, - /// Bytes of the packaged .pkg.tar.zst, so the index page can show a size. pub size: Option<i64>, pub published_at: Option<String>, } @@ -647,7 +613,6 @@ pub fn index_packages(db: &Db) -> Result<Vec<PackageRow>> { }) } -/// Version of the package with this name currently in our index, if any. pub fn index_version(db: &Db, name: &str) -> Result<Option<String>> { db.read(|c| { c.query_row( @@ -661,9 +626,6 @@ pub fn index_version(db: &Db, name: &str) -> Result<Option<String>> { }) } -/// The exact artifact we serve for a package name: `(version, digest)`. This is -/// what a build's lease manifest pins — the dependency arrives as these bytes or -/// the build fails closed (§8). pub fn index_artifact(db: &Db, name: &str) -> Result<Option<(String, String)>> { db.read(|c| { c.query_row( @@ -678,8 +640,6 @@ pub fn index_artifact(db: &Db, name: &str) -> Result<Option<(String, String)>> { }) } -/// Is `name` one of the packages we publish? Used to filter world snapshots -/// down to our own packages (§10.1). pub fn is_ours(db: &Db, name: &str) -> Result<bool> { db.read(|c| { c.query_row( @@ -693,7 +653,6 @@ pub fn is_ours(db: &Db, name: &str) -> Result<bool> { }) } -/// All package names we publish (in_index), as a set. pub fn our_package_names(db: &Db) -> Result<std::collections::BTreeSet<String>> { db.read(|c| { let mut stmt = c.prepare("SELECT DISTINCT name FROM package WHERE state='in_index'")?; @@ -706,9 +665,6 @@ pub fn our_package_names(db: &Db) -> Result<std::collections::BTreeSet<String>> }) } -/// The recipe the accepted release was actually built from, by walking -/// release -> candidate -> snapshot. Risk scoring compares against this, which -/// is why "last seen" can never leak into a review (§6, I2). pub fn accepted_recipe(db: &Db, release: &ReleaseRow) -> Result<Option<Recipe>> { let cid = match release.candidate_id { Some(c) => c, @@ -728,7 +684,6 @@ pub fn accepted_recipe(db: &Db, release: &ReleaseRow) -> Result<Option<Recipe>> }) } -/// Recent builds for one pkgbase, newest first. pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<crate::db::builds::BuildRow>> { db.read(move |c| { let mut st = c.prepare( @@ -738,18 +693,12 @@ pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<cr FROM build WHERE pkgbase_id=?1 ORDER BY rowid DESC LIMIT ?2", )?; let rows = st.query_map(params![pkgbase_id, limit], crate::db::builds::row_to_build)?; - // A row we cannot read is an error, not a build that quietly disappears - // from the package page. rows.collect::<::rusqlite::Result<Vec<_>>>().map_err(Into::into) }) } // ------------------------------------------------------------ publish writes -- -// -// Publishing is the one externally visible step, so every statement it needs is -// here and the *decision* stays in `pipeline::publish` (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)) @@ -757,15 +706,12 @@ pub fn artifact_path(db: &Db, id: i64) -> Result<Option<String>> { }) } -/// 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", @@ -777,8 +723,6 @@ pub fn accepted_pointer_in(tx: &rusqlite::Transaction<'_>, pkgbase_id: i64) -> R .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, @@ -792,8 +736,6 @@ pub fn cas_accepted_release_in( 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(()); @@ -805,7 +747,6 @@ pub fn remove_index_packages_in(tx: &rusqlite::Transaction<'_>, names: &[String] 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", @@ -814,8 +755,6 @@ pub fn remove_package_by_name_in(tx: &rusqlite::Transaction<'_>, repo_id: i64, n 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>, @@ -831,7 +770,6 @@ pub struct NewRelease<'a> { 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, @@ -857,7 +795,6 @@ pub fn insert_release_in(tx: &mut rusqlite::Transaction<'_>, r: &NewRelease<'_>, 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, @@ -877,12 +814,7 @@ pub fn insert_package_in( } // ------------------------------------------------------------ staleness reads -- -// -// Staleness is derived on read (§10.2). These return plain tuples: the *meaning* -// 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( @@ -898,8 +830,6 @@ pub fn published_world_members(db: &Db) -> Result<Vec<(String, String)>> { }) } -/// `(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( @@ -922,12 +852,6 @@ pub fn served_vs_offered_pkgvers(db: &Db) -> Result<Vec<(String, String, String) }) } -/// Every in-index package's recipe JSON, as (name, srcinfo_json) — what each -/// dependency list actually said. -/// -/// One query, not one per package (m-17): `watch::staleness::dependents_of` -/// wants the whole table, and asking per name was an N+1 on a path that runs -/// after every publish. pub fn index_recipes(db: &Db) -> Result<Vec<(String, String)>> { db.read(|c| { let mut stmt = c.prepare( @@ -946,7 +870,6 @@ pub fn index_recipes(db: &Db) -> Result<Vec<(String, String)>> { }) } -/// 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)) @@ -956,7 +879,6 @@ pub fn approval_note(db: &Db, approval_id: i64) -> Result<String> { }) } -/// 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)) @@ -964,8 +886,6 @@ pub fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Result<Option<i64>> }) } -/// 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( @@ -978,7 +898,6 @@ pub fn subscription_poll_interval(db: &Db, pkgbase: &str) -> Result<Option<i64>> }) } -/// 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(); @@ -992,7 +911,6 @@ pub fn put_source_cache(writer: &Writer, url: &str, digest: &str, size: u64, pat }) } -/// 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( @@ -1004,7 +922,6 @@ pub fn source_cache_path(db: &Db, url: &str, digest: &str) -> Result<Option<Stri }) } -/// An artifact produced by a build, ready to record. pub struct NewArtifact<'a> { pub digest: &'a str, pub size: i64, @@ -1015,9 +932,6 @@ pub struct NewArtifact<'a> { 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) @@ -1030,7 +944,6 @@ pub fn insert_artifact_in(tx: &rusqlite::Transaction<'_>, a: &NewArtifact<'_>) - // --------------------------------------------------------- stage B cache -- -/// Exact cache hit: same recipe, same upstream tips (§5.2). pub fn stage_b_cache_get(db: &Db, pkgbase_id: i64, recipe_hash: &str, tip_hash: &str) -> Result<Option<StageBCacheRow>> { let (rh, th) = (recipe_hash.to_string(), tip_hash.to_string()); db.read(move |c| { @@ -1058,7 +971,6 @@ pub fn stage_b_cache_get(db: &Db, pkgbase_id: i64, recipe_hash: &str, tip_hash: }) } -/// The most recent answer for this pkgbase, if it is inside the cooldown window. pub fn stage_b_recent(db: &Db, pkgbase_id: i64, cooldown_secs: i64) -> Result<Option<StageBCacheRow>> { let cutoff = crate::time::secs_ago(cooldown_secs); db.read(move |c| { @@ -1132,8 +1044,6 @@ pub fn put_notice( }) } -/// Suppress a notice if an identical unacknowledged one already exists, so a -/// watcher polling daily does not spam the same alert. pub fn put_notice_once( writer: &Writer, pkgbase_id: i64, @@ -1290,11 +1200,7 @@ 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). -/// 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| { @@ -1303,7 +1209,6 @@ fn count_rows(db: &Db, sql: &str) -> Result<i64> { }) } -/// `(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")?; @@ -1316,7 +1221,6 @@ pub fn build_state_counts(db: &Db) -> Result<Vec<(String, i64)>> { }) } -/// 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( @@ -1330,12 +1234,10 @@ pub fn oldest_queued_age_secs(db: &Db, now: &str) -> Result<i64> { }) } -/// 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'")?; @@ -1364,7 +1266,6 @@ 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( @@ -1377,7 +1278,6 @@ pub fn artifact_bytes_served(db: &Db) -> Result<u64> { }) } -/// 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)) @@ -1386,8 +1286,6 @@ pub fn last_gc_age_secs(db: &Db, now: &str) -> Result<Option<i64>> { Ok(at.and_then(|t| time::delta_secs(now, &t))) } -/// Seconds since the last successful poll of any source. This is the metric that -/// catches a watcher that stopped. 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)) @@ -1398,7 +1296,6 @@ pub fn last_poll_age_secs(db: &Db, now: &str) -> Result<Option<i64>> { // -------------------------------------------------------------- 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")?; @@ -1411,7 +1308,6 @@ pub fn pkgbase_release_pointers(db: &Db) -> Result<Vec<(i64, Option<i64>)>> { }) } -/// 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")?; @@ -1424,8 +1320,6 @@ pub fn published_release_ids(db: &Db, pkgbase_id: i64) -> Result<Vec<i64>> { }) } -/// 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( @@ -1441,12 +1335,8 @@ pub fn serving_release_ids(db: &Db, pkgbase_id: i64) -> Result<Vec<i64>> { }) } -/// 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( @@ -1464,9 +1354,6 @@ pub fn release_artifact_paths(db: &Db, release_id: i64) -> Result<Vec<ArtifactPa }) } -/// 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| { @@ -1480,8 +1367,6 @@ pub fn mark_release_purged(writer: &Writer, release_id: i64) -> Result<()> { }) } -/// 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| { @@ -1496,8 +1381,6 @@ pub fn record_gc_run(writer: &Writer, at: &str, kept: i64, evicted: i64, files_r // ------------------------------------------------------- invariant helpers -- -/// I1: every artifact in a served repo index traces to an approval row. -/// Returns offending package names; empty means the invariant holds. pub fn unapproved_index_entries(db: &Db) -> Result<Vec<String>> { db.read(|c| { let mut stmt = c.prepare( @@ -1515,8 +1398,6 @@ pub fn unapproved_index_entries(db: &Db) -> Result<Vec<String>> { }) } -/// I8: the set of packages in the index is exactly the set of -/// `current_accepted_release` pointers for active subscriptions. pub fn index_pkgbase_drift(db: &Db) -> Result<(Vec<String>, Vec<String>)> { db.read(|c| { let mut orphans = Vec::new(); @@ -1548,15 +1429,10 @@ pub fn index_pkgbase_drift(db: &Db) -> Result<(Vec<String>, Vec<String>)> { }) } -/// An approved change whose build failed and never reached the index (§8.4). A -/// human said yes, the build died, and the index is quietly still serving the -/// previous version; surfacing that is the whole point. #[derive(Debug, Clone)] pub struct Unbuilt { pub pkgbase: String, - /// The version that was approved but never published. pub approved: String, - /// The version the index actually serves, empty if nothing is served. pub serving: String, pub error: String, pub build_id: String, @@ -1564,9 +1440,6 @@ pub struct Unbuilt { pub fn approved_but_unbuilt(db: &Db) -> Result<Vec<Unbuilt>> { db.read(|c| { - // The version strings are assembled in Rust by `pkgver::full_version`, - // not by a CASE expression here (m-18): a second copy of the - // epoch-omission rule in SQL is a second rule that can disagree. let mut stmt = c.prepare( "SELECT p.name, cnd.epoch, cnd.pkgver, cnd.pkgrel, @@ -1603,9 +1476,6 @@ pub fn approved_but_unbuilt(db: &Db) -> Result<Vec<Unbuilt>> { let (pkgbase, ae, av, ar, se, sv, sr, error, build_id) = r?; let (pkgbase, av, ar) = match (pkgbase, av, ar) { (Some(p), Some(v), Some(rel)) => (p, v, rel), - // The join guarantees a pkgbase, and a failed build with a - // candidate always has one; a missing version means the schema - // was violated, so say so rather than show a blank. _ => { return Err(crate::error::Error::Db( "failed build row without a candidate version".into(), |
