diff options
Diffstat (limited to 'src/db')
| -rw-r--r-- | src/db/approvals.rs | 8 | ||||
| -rw-r--r-- | src/db/builds.rs | 40 | ||||
| -rw-r--r-- | src/db/candidates.rs | 24 | ||||
| -rw-r--r-- | src/db/migrations.rs | 23 | ||||
| -rw-r--r-- | src/db/mod.rs | 73 | ||||
| -rw-r--r-- | src/db/model.rs | 152 | ||||
| -rw-r--r-- | src/db/queries.rs | 95 |
7 files changed, 130 insertions, 285 deletions
diff --git a/src/db/approvals.rs b/src/db/approvals.rs index f04d641..b5a9b59 100644 --- a/src/db/approvals.rs +++ b/src/db/approvals.rs @@ -1,11 +1,3 @@ -//! 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; diff --git a/src/db/builds.rs b/src/db/builds.rs index 072836b..8598dd3 100644 --- a/src/db/builds.rs +++ b/src/db/builds.rs @@ -1,5 +1,3 @@ -//! Build queue rows: deterministic ids, leases, step checkpoints (§8.1, §8.2). - use rusqlite::{params, Connection, OptionalExtension}; use crate::db::{BuildState, Db, StepState}; @@ -160,12 +158,10 @@ 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. +/// 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 worker sets `running` as soon as it -/// starts a step, so a process that dies mid-step leaves a `running` row, not a -/// `leased` one. Reaping only `leased` would strand every real crash. +/// 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| { @@ -195,10 +191,8 @@ 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 currently in one of `to`'s legal -/// predecessor states is updated, so two workers cannot both land a terminal -/// state, and a zombie worker whose lease was reaped gets an error instead of -/// silently rewriting a build that has since been handed to somebody else. +/// 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, @@ -248,13 +242,10 @@ pub fn block_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> { }) } -/// Re-check blocked builds whenever a publish lands (§10.4). /// 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 is a busy loop -/// that burns a claim and a plan step each tick. A build only goes back on the -/// queue when every name it is waiting for is actually in the index now. +/// 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| { @@ -265,9 +256,8 @@ 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): the old shape was an N+1 - // whose N grew with the backlog, and it ran on the dispatcher's hot loop. + // 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 @@ -544,8 +534,7 @@ 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 the same -/// transaction, so no other claimer can see a row in between. +/// 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()); @@ -597,9 +586,9 @@ pub fn requeue_transient(db: &Db, id: &str) -> Result<()> { .tx(move |tx| transition_in_tx(tx, &id, BuildState::Queued, None)) } -/// Explicitly retry a failed build (§8.4). This is a human decision, not a -/// policy: the failed step is put back to pending so it runs again, everything -/// that succeeded stays checkpointed, and the attempt counter keeps counting. +/// 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| { @@ -609,8 +598,7 @@ pub fn retry(db: &Db, id: &str) -> Result<()> { params![id], )?; // The move itself goes through the machine, so requeueing a build that - // already published is refused with a reason instead of silently - // re-queueing a row whose every step is checkpointed as done. + // 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 63c089f..631bf42 100644 --- a/src/db/candidates.rs +++ b/src/db/candidates.rs @@ -1,22 +1,10 @@ -//! 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, CandidateState, 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). +/// 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, \ @@ -130,10 +118,8 @@ pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Opti /// 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 — or a stale worker -/// resolving a review that has since been superseded — fails instead of -/// silently overwriting what a human did. +/// 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(","); @@ -233,7 +219,7 @@ pub fn supersede_in(tx: &Transaction<'_>, id: i64) -> Result<()> { } /// Has this exact identity been rejected before? If so the watcher stays quiet -/// until a human re-opens it (§7.1: "do not nag"). +/// 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( @@ -362,7 +348,7 @@ pub fn mark_viewed(db: &Db, id: i64) -> Result<()> { }) } -/// §7.1: a rejection can be re-opened. We retire the rejected row so it stops +/// §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(); diff --git a/src/db/migrations.rs b/src/db/migrations.rs index 9e60132..b1954ab 100644 --- a/src/db/migrations.rs +++ b/src/db/migrations.rs @@ -1,9 +1,3 @@ -//! Hand-rolled `user_version` migration stepper (DESIGN.md §4, "Migrations"). -//! -//! Each entry is applied inside its own transaction and bumps -//! `PRAGMA user_version`. Migrations must never be edited after they ship; add -//! a new one instead. - /// One migration: version number + SQL body. pub struct Migration { pub version: u32, @@ -300,9 +294,8 @@ 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, because a fresh tip inside the window reuses the old answer. +/// 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), @@ -319,14 +312,10 @@ CREATE TABLE stage_b_cache ( CREATE INDEX stage_b_cache_by_pkgbase ON stage_b_cache (pkgbase_id, resolved_at); "#; -/// Retention (§15, open question 21). The rows are never compacted — the whole -/// point of the schema is that "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`, which says "these bytes existed, and were -/// dropped from the store at T" instead of silently pretending they are still -/// there. A `cp` of the store and a database that disagrees about what is on disk -/// is the failure mode this avoids. +/// 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; diff --git a/src/db/mod.rs b/src/db/mod.rs index 403ced2..c271fe7 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -1,13 +1,3 @@ -//! SQLite access (DESIGN.md §11a). -//! -//! The app is multi-threaded and SQLite has one writer at a time, so there is -//! exactly **one writer thread** owning the write connection. Everything that -//! mutates is sent to it over a channel as a closure and answered with a -//! `Result`. That makes "who can write" a compile-time fact (only [`Writer`] -//! hands out `&mut`-equivalent access) and removes `SQLITE_BUSY` from the -//! 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; @@ -18,11 +8,8 @@ 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: a build in a state we cannot name must not be listed, claimed, or -/// rendered as if it were in one we could. +/// 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( @@ -158,17 +145,13 @@ 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. - /// Use [`Writer::tx`] for atomic multi-statement mutations. + /// 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 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)`, 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, @@ -182,8 +165,7 @@ impl Writer { .map_err(|_| Error::db("writer actor gone"))? } - /// Run `f` inside a single `BEGIN IMMEDIATE` transaction on the write - /// connection. This is how every multi-statement mutation is expressed. + /// Run `f` inside a single `BEGIN IMMEDIATE` transaction. pub(crate) fn tx<T>( &self, f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static, @@ -216,17 +198,12 @@ 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. +/// 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 { - /// 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, @@ -237,7 +214,6 @@ impl Writer { 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, @@ -246,10 +222,9 @@ impl Writer { } } -/// Thread-local read-only connection pool. -/// -/// One connection per thread per database file, opened read-only. HTTP handlers -/// and watchers use this; they never touch the write connection. +/// 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, } @@ -275,9 +250,8 @@ impl Readers { .iter() .position(|(p, _)| p == &path) .ok_or_else(|| Error::db("reader pool lost entry"))?; - // Safety of the borrow: we only ever use one connection at a time - // per thread and `f` cannot re-enter this function for the same pool - // (it receives &Connection, not &Readers). + // We only ever use one connection at a time per thread, and `f` + // receives &Connection rather than &Readers, so it cannot re-enter. let conn = &pool[idx].1; f(conn) }) @@ -321,13 +295,11 @@ 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. +/// 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: 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). +/// 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())))?; @@ -335,7 +307,6 @@ pub fn schema_version(path: &Path) -> Result<i64> { .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); let mut wal = db.writer.path().as_os_str().to_os_string(); diff --git a/src/db/model.rs b/src/db/model.rs index 3fa2840..84701d1 100644 --- a/src/db/model.rs +++ b/src/db/model.rs @@ -1,35 +1,25 @@ -//! Row types and small value objects that appear in JSON columns. - use serde::{Deserialize, Serialize}; use crate::hash; -/// One resolved upstream VCS source (DESIGN.md §3, "Three things to pin"). -/// -/// 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. +/// 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 { - /// Index into the PKGBUILD `source=()` array. pub index: usize, pub url: String, /// The ref we asked for: `HEAD`, a tag, or an explicit commit. pub ref_: String, - /// Branch the ref resolved to, when known. pub branch: Option<String>, - /// Resolved commit SHA. This is the pin. + /// The pin. pub commit: String, } -/// A row of the Stage B cache (§5.2): the version that resolution produced, -/// with the pins it was computed from. -/// -/// This lives with the schema because the table lives here — the persistence -/// layer must not name a type from the module that owns VCS probing, which is -/// the dependency pointing the wrong way (§6 M-6). `watch::upstream::StageB` -/// is this plus `cached`, and that extra field is the reason the two are not -/// the same type: "was this answer a cache hit?" is a fact about the resolution -/// that just happened, not a column. +/// 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, @@ -55,20 +45,16 @@ pub struct SourceDigest { /// 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 for this source — - /// `SKIP`, a malformed digest, or nothing at all. - /// - /// It means that and nothing else (m-19). It used to be hardcoded `true` for - /// VCS entries, where it reads as a warning the recipe never earned: a - /// `-git` source has no checksum by design because the *pin* is the - /// integrity. Ask [`SourceDigest::is_vcs`] when you need to know which of - /// the two mechanisms protects an entry. + /// 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. + /// 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") } @@ -93,35 +79,28 @@ 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. - /// - /// A digest of the canonical JSON of the identity tuple. This is the value - /// an approval must echo: two candidates share an `identity_hash` only if - /// every pin, digest and version in them is identical. A value that cannot - /// be serialized is an error rather than a digest — a shared fallback digest - /// would be the one way two identities could collide by accident. + /// 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 candidate is what a human decides on, and the decision is the one thing in -/// this system that must never be overwritten by accident: an approval that -/// silently replaced a rejection, or a superseded review resurrected, would -/// break I2 and I3 without any symptom. So the states are an enum, and +/// 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 { - /// Open: nobody has decided yet. The only state a reviewer can act on. + /// The only state a reviewer can act on. PendingReview, Approved, Rejected, - /// Frozen: a newer review of the same pkgbase took its place (§7.1). + /// A newer review of the same pkgbase took its place (§7.1). Superseded, /// Not approved because something it needs is missing (§10.4). Blocked, @@ -150,13 +129,11 @@ impl CandidateState { CandidateState::ALL.iter().copied().find(|c| c.as_str() == s) } - /// The state a reviewer can still act on. pub fn is_open(&self) -> bool { *self == CandidateState::PendingReview } - /// May a candidate in this state be written to `to`? Re-writing the state it - /// already has is a no-op, not a move. + /// 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 { @@ -195,7 +172,6 @@ pub mod candidate_kind { #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ReleaseState { - /// In the served index. Published, /// Taken out of the index (§9 withdrawal); the row stays (§15). Withdrawn, @@ -222,8 +198,7 @@ impl ReleaseState { ReleaseState::ALL.iter().copied().find(|r| r.as_str() == s) } - /// Withdrawal is the only move a release makes on its own; a failed-unbuilt - /// release is a record of an attempt, and a published one is live. + /// Withdrawal is the only move a release makes on its own. pub fn can_transition(&self, to: ReleaseState) -> bool { use ReleaseState::*; if *self == to { @@ -243,8 +218,8 @@ 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. `db::state_col` uses this to fail a row whose -/// state the code does not know instead of defaulting it. +/// 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; @@ -272,17 +247,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). -/// -/// This used to be seven `&str` constants and a `set_state(&str)` that wrote any -/// string a caller invented, so the machine existed only as `WHERE state IN -/// (...)` clauses scattered across six modules — nothing could tell you that -/// `succeeded → running` is nonsense. The enum is the machine: 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. +/// 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 { - /// Approved and waiting for a worker. Queued, /// Claimed by a worker with a lease (§8.2). Leased, @@ -306,8 +275,8 @@ impl BuildState { BuildState::Cancelled, ]; - /// The text in the `state` column. The spelling is part of the schema: the - /// reaper, the dispatcher and the UI all speak it. + /// 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", @@ -320,17 +289,14 @@ impl BuildState { } } - /// The only way in from the database text. An unrecognised state is `None`, - /// and the row boundary turns that into an error rather than a silent - /// fallback: a state we cannot name is a state we must not act on. + /// 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. `Succeeded` is final — - /// the release is published and the row is history (§15). `Failed` and - /// `Cancelled` end a worker's involvement, and only an explicit human - /// requeue or resume moves them again ([`BuildState::can_transition`]). + /// 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, @@ -338,17 +304,11 @@ impl BuildState { ) } - /// May a row in this state be written to `to`? - /// - /// Writing the state a row already has is always allowed: it is a no-op, not - /// a move. The step loop re-asserts `Running` at every step boundary (§8.3), - /// and re-running a finished build must stay harmless rather than turn into - /// an error. - /// - /// 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 — that refusal is the alarm. + /// 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 { @@ -356,16 +316,13 @@ impl BuildState { } match self { // The dispatcher claims queued builds; `aur-build run <id>` runs one - // in the foreground without a lease, so `Running` is legal from here - // too. A dependency can be discovered before a worker ever starts. + // 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 (the step - // checkpoints say where to continue) and §8.4's human requeue. + // A failed build is resumed on the same row — that is I5 (§8.4). Failed => matches!(to, Queued | Running), - // §8.4: requeue is a human decision, not a policy. Cancelled => to == Queued, Succeeded => false, } @@ -381,7 +338,6 @@ impl BuildState { .collect() } - /// The states the queue considers "in flight" for metrics and the index. pub fn active() -> &'static [BuildState] { &[ BuildState::Queued, @@ -398,11 +354,9 @@ 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 the rule that matters is that a completed checkpoint is frozen: a step -/// recorded `succeeded` or `skipped` is never re-run and never rewritten. +/// 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 { @@ -441,7 +395,7 @@ impl StepState { } /// I5: the resume skips a step in one of these two states, so nothing may - /// move it again — a checkpoint that can be rewritten is not a checkpoint. + /// move it again. pub fn is_done(&self) -> bool { matches!(self, StepState::Succeeded | StepState::Skipped) } @@ -565,13 +519,10 @@ pub struct SourceEntry { pub url: String, /// Explicit filename (`::name` / `::` prefix handling). pub filename: Option<String>, - /// `#commit=` fragment. pub commit: Option<String>, - /// `#tag=` fragment. pub tag: Option<String>, - /// `#branch=` fragment. pub branch: Option<String>, - /// VCS kind if the url is prefixed `git+`, `svn+`, `hg+`, `bzr+`. + /// 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, @@ -610,21 +561,18 @@ pub struct Recipe { pub install: Option<String>, /// Names of the binary packages this pkgbase emits (split pkgbases have N). pub pkgnames: Vec<String>, - /// Per-package depends, for split pkgbases. pub pkg_depends: Vec<(String, Vec<String>)>, /// Raw PKGBUILD text, for display and diffing. pub pkgbuild: String, - /// Raw .SRCINFO text when it was present. pub srcinfo: Option<String>, /// True if `--skippgpcheck` appears in the PKGBUILD. pub skipgpcheck: bool, - /// Parsed `source=()` entries. Derived from `source`, so not serialized. + /// Derived from `source`, so not serialized. #[serde(skip, default)] pub source_entries: Vec<SourceEntry>, } impl Recipe { - /// `epoch:pkgver-pkgrel` as displayed to consumers. pub fn full_version(&self) -> String { crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) } diff --git a/src/db/queries.rs b/src/db/queries.rs index fe0518f..924051d 100644 --- a/src/db/queries.rs +++ b/src/db/queries.rs @@ -1,6 +1,3 @@ -//! Typed query helpers. Everything that mutates goes through the writer actor; -//! everything that reads takes a `&Connection` from the reader pool. - use rusqlite::{params, params_from_iter, OptionalExtension, Row}; use crate::db::*; @@ -12,9 +9,7 @@ use crate::time; /// Every setting, for the settings page. /// /// Row-error policy, applied everywhere in `db` (m-9): a row that cannot be read -/// fails the query. `filter_map(|r| r.ok())` used to drop such rows silently, -/// which is fine for a page that merely looks incomplete and fatal for the -/// callers that decide what to reap, what to claim, and what is stale. +/// 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")?; @@ -34,12 +29,10 @@ 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, and every knob in `settings` has one. A setting that is present -/// but unparseable, or a read that failed outright, is not normal, and silently -/// returning the default would hide an operator's typo behind a config that -/// looks applied. Both still fall back — these are tuning knobs, and refusing to -/// start over `stage_b_cooldown = 86400x` is worse than using the default — but -/// they fall back out loud. +/// 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, @@ -101,14 +94,9 @@ pub fn audit( }) } -/// An audit row to append inside someone else's transaction. -/// -/// Build one with [`AuditEntry::human`] or [`AuditEntry::system`] rather than -/// by writing the literal: `actor_kind` is a closed set and the timestamp is -/// not the caller's to improvise (§6 m-4). Three review sites had each -/// hand-built this struct, and their `detail` shapes drifted until the log -/// could not answer, for two of the three, which candidate bytes the decision -/// was about. +/// 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, @@ -145,10 +133,8 @@ impl<'a> AuditEntry<'a> { } } -/// 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. +/// 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) @@ -523,16 +509,12 @@ 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. -/// Take a release out of the served index (§9, decision 23). +/// 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, so an operator who clicked twice — or -/// withdrew a release that had never been live — got a green result and no -/// explanation. The write is a compare-and-swap on `state='published'`, and the -/// refusal names the state that was actually there. +/// 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'", @@ -679,10 +661,9 @@ pub fn index_version(db: &Db, name: &str) -> Result<Option<String>> { }) } -/// The exact artifact we serve for a package name: `(version, digest)` of the -/// in-index row's artifact. This is what a build's lease manifest pins — the -/// dependency arrives as these bytes or the build fails closed (§8, -/// provisioning); nothing about it is re-resolved at build time. +/// 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( @@ -766,9 +747,7 @@ 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). +// 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>> { @@ -899,9 +878,8 @@ pub fn insert_package_in( // ------------------------------------------------------------ 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. +// 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). @@ -944,13 +922,12 @@ pub fn served_vs_offered_pkgvers(db: &Db) -> Result<Vec<(String, String, String) }) } -/// The `srcinfo_json` of the recipe the index's copy of a package was built -/// from — what its dependency list actually said. -/// Every in-index package's recipe JSON, as (name, srcinfo_json). +/// 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: asking for each package by name was an N+1 whose N is -/// the size of the index, on a code path that runs after every publish. +/// 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( @@ -1314,10 +1291,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: 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 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. @@ -1412,9 +1386,8 @@ 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, if there has been one. -/// This is the metric that catches a watcher that stopped, which no log line -/// will tell you about. +/// 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)) @@ -1575,10 +1548,9 @@ pub fn index_pkgbase_drift(db: &Db) -> Result<(Vec<String>, Vec<String>)> { }) } -/// An approved change whose build failed and which therefore never reached the -/// index (§8.4). This is the state that must never look healthy: a human said -/// yes, the build died, and the index is quietly still serving the previous -/// version. Surfacing it is the whole point of `approved_but_unbuilt`. +/// 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, @@ -1593,9 +1565,8 @@ 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): the epoch-omitted form is a rule - // of ours, and a second copy of it in SQL is a second rule that can - // disagree with the first. + // 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, |
