//! 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::*; use crate::error::{Error, Result}; 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. `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. pub fn all_settings(db: &Db) -> Result> { db.read(|c| { let mut st = c.prepare("SELECT key, value FROM settings ORDER BY key")?; let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; Ok(rows.collect::<::rusqlite::Result>>()?) }) } pub fn setting(db: &Db, key: &str) -> Result> { db.read(|c| { c.query_row("SELECT value FROM settings WHERE key = ?1", params![key], |r| r.get(0)) .optional() .map_err(Into::into) }) } /// 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. pub fn setting_i64(db: &Db, key: &str, default: i64) -> i64 { match setting(db, key) { Ok(None) => default, Ok(Some(v)) => v.parse().unwrap_or_else(|_| { eprintln!("settings: {key}={v:?} is not an integer; using default {default}"); default }), Err(e) => { eprintln!("settings: could not read {key} ({e}); using default {default}"); default } } } pub fn set_setting(writer: &Writer, key: &str, value: &str) -> Result<()> { let v = value.to_string(); let k = key.to_string(); writer.tx(move |tx| { tx.execute( "INSERT INTO settings (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value", params![k, v], )?; Ok(()) }) } // ------------------------------------------------------------------- audit -- /// Append an audit row (I10). Every state transition funnels through here. pub fn audit( writer: &Writer, actor_kind: &str, actor: &str, action: &str, entity: &str, entity_id: &str, detail: serde_json::Value, ) -> Result<()> { let at = time::now(); let actor_kind = actor_kind.to_string(); let actor = actor.to_string(); let action = action.to_string(); let entity = entity.to_string(); let entity_id = entity_id.to_string(); writer.tx(move |tx| { audit_in( tx, &AuditEntry { at: &at, actor_kind: &actor_kind, actor: &actor, action: &action, entity: &entity, entity_id: &entity_id, detail, }, ) }) } /// An audit row to append inside someone else's transaction. /// /// 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. #[derive(Debug)] pub struct AuditEntry<'a> { pub at: &'a str, pub actor_kind: &'a str, pub actor: &'a str, pub action: &'a str, pub entity: &'a str, pub entity_id: &'a str, pub detail: serde_json::Value, } impl<'a> AuditEntry<'a> { /// A decision a named human made (§11: every approval is attributable). pub fn human( at: &'a str, actor: &'a str, action: &'a str, entity: &'a str, entity_id: &'a str, detail: serde_json::Value, ) -> Self { 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, entity: &'a str, entity_id: &'a str, detail: serde_json::Value, ) -> Self { Self { at, actor_kind: "system", actor: "", action, entity, entity_id, detail } } } /// Append an audit row inside a caller's transaction (I10). This is the variant /// every multi-statement mutation uses: the record of a decision commits with /// the decision or not at all, so there is no window where an audit row /// describes a change that was rolled back. pub fn audit_in(tx: &rusqlite::Transaction<'_>, e: &AuditEntry<'_>) -> Result<()> { tx.execute( "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) VALUES (?1,?2,?3,?4,?5,?6,?7)", params![e.at, e.actor_kind, e.actor, e.action, e.entity, e.entity_id, e.detail.to_string()], )?; Ok(()) } pub fn audit_system(writer: &Writer, action: &str, entity: &str, entity_id: &str, detail: serde_json::Value) -> Result<()> { audit(writer, "system", "", action, entity, entity_id, detail) } // -------------------------------------------------------------------- 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 { let (n, p, a, k) = (name.to_string(), path.to_string(), arch.to_string(), key.to_string()); writer.tx(move |tx| { tx.execute( "INSERT INTO repo (name, path, arch, signing_key_id) VALUES (?1,?2,?3,?4) ON CONFLICT(name) DO UPDATE SET path=excluded.path, arch=excluded.arch, signing_key_id=excluded.signing_key_id", params![n, p, a, k], )?; let id: i64 = tx.query_row("SELECT id FROM repo WHERE name = ?1", params![n], |r| r.get(0))?; Ok(id) }) } pub fn repo_id(db: &Db) -> Result { db.read(|c| { c.query_row("SELECT id FROM repo ORDER BY id LIMIT 1", [], |r| r.get(0)) .optional()? .ok_or_else(|| Error::not_found("no repo row; run `aur-build init`")) }) } // ------------------------------------------------------------- subscriptions -- #[derive(Debug, Clone)] pub struct Subscription { pub id: i64, pub pkgbase: String, pub aur_url: String, pub maintainer: Option, pub state: SubscriptionState, pub next_check_at: Option, pub last_checked_at: Option, pub last_error: Option, pub poll_interval_secs: Option, } fn row_to_sub(r: &Row<'_>) -> rusqlite::Result { Ok(Subscription { id: r.get(0)?, pkgbase: r.get(1)?, aur_url: r.get(2)?, maintainer: r.get(3)?, state: crate::db::state_col::(4, &r.get::<_, String>(4)?)?, next_check_at: r.get(5)?, last_checked_at: r.get(6)?, last_error: r.get(7)?, poll_interval_secs: r.get(8)?, }) } const SUB_COLS: &str = "id, pkgbase, aur_url, maintainer, state, next_check_at, last_checked_at, \ last_error, poll_interval_secs"; pub fn list_subscriptions(db: &Db) -> Result> { db.read(|c| { let mut stmt = c.prepare(&format!("SELECT {SUB_COLS} FROM subscription ORDER BY pkgbase"))?; let rows = stmt.query_map([], row_to_sub)?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } pub fn get_subscription(db: &Db, pkgbase: &str) -> Result> { db.read(|c| { c.query_row( &format!("SELECT {SUB_COLS} FROM subscription WHERE pkgbase = ?1"), params![pkgbase], row_to_sub, ) .optional() .map_err(Into::into) }) } /// Subscribe: creates the pkgbase row and an active subscription. Idempotent. pub fn subscribe(writer: &Writer, repo_id: i64, pkgbase: &str, aur_url: &str) -> Result { let (p, u) = (pkgbase.to_string(), aur_url.to_string()); let at = time::now(); writer.tx(move |tx| { tx.execute( "INSERT INTO pkgbase (name, aur_url, created_at) VALUES (?1,?2,?3) ON CONFLICT(name) DO UPDATE SET aur_url = excluded.aur_url", params![p, u, at], )?; tx.execute( "INSERT INTO subscription (repo_id, pkgbase, aur_url, state, next_check_at, created_at) VALUES (?1,?2,?3,'active',?4,?5) ON CONFLICT(repo_id, pkgbase) DO UPDATE SET state='active', aur_url=excluded.aur_url", params![repo_id, p, u, at.clone(), at], )?; Ok(1) }) } pub fn set_subscription_state(writer: &Writer, pkgbase: &str, state: SubscriptionState) -> Result<()> { let (p, s) = (pkgbase.to_string(), state.to_string()); writer.tx(move |tx| { tx.execute( "UPDATE subscription SET state=?1 WHERE pkgbase=?2", params![s, p], )?; Ok(()) }) } pub fn note_check(writer: &Writer, pkgbase: &str, next_check_at: &str, err: Option<&str>) -> Result<()> { let (p, n) = (pkgbase.to_string(), next_check_at.to_string()); let e = err.map(|s| s.to_string()); let at = time::now(); writer.tx(move |tx| { tx.execute( "UPDATE subscription SET last_checked_at=?1, next_check_at=?2, last_error=?3 WHERE pkgbase=?4", params![at, n, e, p], )?; Ok(()) }) } /// Subscriptions whose next check is due. pub fn due_subscriptions(db: &Db, now: &str) -> Result> { db.read(|c| { let mut stmt = c.prepare(&format!( "SELECT {SUB_COLS} FROM subscription WHERE state IN ('active','orphaned') AND (next_check_at IS NULL OR next_check_at <= ?1) ORDER BY next_check_at IS NULL DESC, next_check_at LIMIT 200" ))?; let rows = stmt.query_map(params![now], row_to_sub)?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } // ---------------------------------------------------------------- pkgbase -- #[derive(Debug, Clone)] pub struct Pkgbase { pub id: i64, pub name: String, pub aur_url: String, pub mirror_path: Option, pub aur_head: Option, pub current_accepted_release_id: Option, pub state: String, pub unpinable: bool, } fn row_to_pkgbase(r: &Row<'_>) -> rusqlite::Result { Ok(Pkgbase { id: r.get(0)?, name: r.get(1)?, aur_url: r.get(2)?, mirror_path: r.get(3)?, aur_head: r.get(4)?, current_accepted_release_id: r.get(5)?, state: r.get(6)?, unpinable: r.get::<_, i64>(7)? != 0, }) } const PKGBASE_COLS: &str = "id, name, aur_url, mirror_path, aur_head, \ current_accepted_release_id, state, unpinable"; pub fn get_pkgbase(db: &Db, name: &str) -> Result> { db.read(|c| { c.query_row( &format!("SELECT {PKGBASE_COLS} FROM pkgbase WHERE name = ?1"), params![name], row_to_pkgbase, ) .optional() .map_err(Into::into) }) } pub fn get_pkgbase_by_id(db: &Db, id: i64) -> Result> { db.read(|c| { c.query_row( &format!("SELECT {PKGBASE_COLS} FROM pkgbase WHERE id = ?1"), params![id], row_to_pkgbase, ) .optional() .map_err(Into::into) }) } pub fn list_pkgbases(db: &Db) -> Result> { db.read(|c| { let mut stmt = c.prepare(&format!("SELECT {PKGBASE_COLS} FROM pkgbase ORDER BY name"))?; let rows = stmt.query_map([], row_to_pkgbase)?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } pub fn set_aur_head(writer: &Writer, pkgbase_id: i64, head: &str, mirror: &str) -> Result<()> { let (h, m) = (head.to_string(), mirror.to_string()); writer.tx(move |tx| { tx.execute( "UPDATE pkgbase SET aur_head=?1, mirror_path=?2 WHERE id=?3", params![h, m, pkgbase_id], )?; Ok(()) }) } pub fn set_unpinable(writer: &Writer, pkgbase_id: i64, unpinable: bool) -> Result<()> { writer.tx(move |tx| { tx.execute( "UPDATE pkgbase SET unpinable=?1 WHERE id=?2", params![unpinable as i64, pkgbase_id], )?; Ok(()) }) } /// 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, expected: Option, new_id: i64, ) -> Result { writer.tx(move |tx| { let n = tx.execute( "UPDATE pkgbase SET current_accepted_release_id=?1 WHERE id=?2 AND current_accepted_release_id IS ?3", params![new_id, pkgbase_id, expected], )?; Ok(n == 1) }) } // ---------------------------------------------------------------- snapshot -- /// Insert-or-get a snapshot for (pkgbase, aur_commit). #[allow(clippy::too_many_arguments)] pub fn put_snapshot( writer: &Writer, pkgbase_id: i64, aur_commit: &str, recipe_hash: &str, srcinfo_json: &str, files_json: &str, ) -> Result { let (c, rh, si, fj) = ( aur_commit.to_string(), recipe_hash.to_string(), srcinfo_json.to_string(), files_json.to_string(), ); let at = time::now(); writer.tx(move |tx| { tx.execute( "INSERT INTO snapshot (pkgbase_id, aur_commit, recipe_hash, srcinfo_json, files_json, fetched_at) VALUES (?1,?2,?3,?4,?5,?6) ON CONFLICT(pkgbase_id, aur_commit) DO NOTHING", params![pkgbase_id, c, rh, si, fj, at], )?; tx.query_row( "SELECT id FROM snapshot WHERE pkgbase_id=?1 AND aur_commit=?2", params![pkgbase_id, c], |r| r.get(0), ) .map_err(Into::into) }) } #[derive(Debug, Clone)] pub struct SnapshotRow { pub id: i64, pub aur_commit: String, pub recipe_hash: String, pub srcinfo_json: String, pub files_json: String, } pub fn snapshot_by_commit(db: &Db, pkgbase_id: i64, commit: &str) -> Result> { db.read(|c| { c.query_row( "SELECT id, aur_commit, recipe_hash, srcinfo_json, files_json FROM snapshot WHERE pkgbase_id=?1 AND aur_commit=?2", params![pkgbase_id, commit], |r| { Ok(SnapshotRow { id: r.get(0)?, aur_commit: r.get(1)?, recipe_hash: r.get(2)?, srcinfo_json: r.get(3)?, files_json: r.get(4)?, }) }, ) .optional() .map_err(Into::into) }) } pub fn snapshot_by_id(db: &Db, id: i64) -> Result> { db.read(|c| { c.query_row( "SELECT id, aur_commit, recipe_hash, srcinfo_json, files_json FROM snapshot WHERE id=?1", params![id], |r| { Ok(SnapshotRow { id: r.get(0)?, aur_commit: r.get(1)?, recipe_hash: r.get(2)?, srcinfo_json: r.get(3)?, files_json: r.get(4)?, }) }, ) .optional() .map_err(Into::into) }) } // ---------------------------------------------------------------- release -- fn row_to_release(r: &Row<'_>) -> rusqlite::Result { Ok(ReleaseRow { id: r.get(0)?, pkgbase_id: r.get(1)?, candidate_id: r.get(2)?, approval_id: r.get(3)?, aur_commit: r.get(4)?, recipe_hash: r.get(5)?, upstream_pins_json: r.get(6)?, source_digests_json: r.get(7)?, epoch: r.get(8)?, pkgver: r.get(9)?, pkgrel: r.get(10)?, world_snapshot_id: r.get(11)?, state: crate::db::state_col::(12, &r.get::<_, String>(12)?)?, published_at: r.get(13)?, }) } const RELEASE_COLS: &str = "id, pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash, \ upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel, world_snapshot_id, state, published_at"; const RELEASE_COLS_R: &str = "r.id, r.pkgbase_id, r.candidate_id, r.approval_id, r.aur_commit, \ r.recipe_hash, r.upstream_pins_json, r.source_digests_json, r.epoch, r.pkgver, r.pkgrel, \ r.world_snapshot_id, r.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). /// /// 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. 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'", params![release_id], )?; if n == 0 { let state: Option = tx .query_row("SELECT state FROM release WHERE id=?1", params![release_id], |r| r.get(0)) .optional()?; return Err(match state.as_deref().map(ReleaseState::parse) { None => Error::not_found(format!("no release {release_id}")), Some(Some(s)) => Error::conflict(format!( "release {release_id} is {s}, not published: nothing to withdraw" )), Some(None) => Error::invalid(format!( "release {release_id} has a state outside the state machine: {:?}", state.unwrap_or_default() )), }); } tx.execute("UPDATE package SET state='removed' WHERE release_id=?1", params![release_id])?; Ok(()) } pub fn release_by_id(db: &Db, id: i64) -> Result> { db.read(|c| { c.query_row( &format!("SELECT {RELEASE_COLS} FROM release WHERE id = ?1"), params![id], row_to_release, ) .optional() .map_err(Into::into) }) } /// 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> { db.read(|c| { c.query_row( &format!( "SELECT {RELEASE_COLS_R} FROM release r JOIN pkgbase p ON p.current_accepted_release_id = r.id WHERE p.name = ?1 AND r.state = 'published'"), params![pkgbase], row_to_release, ) .optional() .map_err(Into::into) }) } pub fn releases_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result> { db.read(|c| { let sql = format!( "SELECT {RELEASE_COLS} FROM release WHERE pkgbase_id=?1 ORDER BY id DESC LIMIT ?2" ); let mut stmt = c.prepare(&sql)?; let rows = stmt.query_map(params![pkgbase_id, limit], row_to_release)?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } pub fn all_published_releases(db: &Db) -> Result> { db.read(|c| { let sql = format!( "SELECT {RELEASE_COLS} FROM release WHERE state='published' ORDER BY pkgbase_id, id DESC" ); let mut stmt = c.prepare(&sql)?; let rows = stmt.query_map([], row_to_release)?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } // ---------------------------------------------------------------- package -- #[derive(Debug, Clone)] pub struct PackageRow { pub id: i64, pub release_id: i64, pub name: String, pub arch: String, pub version: String, pub artifact_id: Option, pub pkgbase: String, /// Bytes of the packaged .pkg.tar.zst, so the index page can show a size. pub size: Option, pub published_at: Option, } pub fn index_packages(db: &Db) -> Result> { db.read(|c| { let mut stmt = c.prepare( "SELECT p.id, p.release_id, p.name, p.arch, p.version, p.artifact_id, b.name, a.size, r.published_at FROM package p JOIN release r ON r.id = p.release_id JOIN pkgbase b ON b.id = r.pkgbase_id LEFT JOIN artifact a ON a.id = p.artifact_id WHERE p.state = 'in_index' ORDER BY p.name", )?; let rows = stmt.query_map([], |r| { Ok(PackageRow { id: r.get(0)?, release_id: r.get(1)?, name: r.get(2)?, arch: r.get(3)?, version: r.get(4)?, artifact_id: r.get(5)?, pkgbase: r.get(6)?, size: r.get(7)?, published_at: r.get(8)?, }) })?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } /// Version of the package with this name currently in our index, if any. pub fn index_version(db: &Db, name: &str) -> Result> { db.read(|c| { c.query_row( "SELECT p.version FROM package p WHERE p.name=?1 AND p.state='in_index' ORDER BY p.id DESC LIMIT 1", params![name], |r| r.get(0), ) .optional() .map_err(Into::into) }) } /// 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. pub fn index_artifact(db: &Db, name: &str) -> Result> { db.read(|c| { c.query_row( "SELECT p.version, a.digest FROM package p JOIN artifact a ON a.id = p.artifact_id WHERE p.name=?1 AND p.state='in_index' ORDER BY p.id DESC LIMIT 1", params![name], |r| Ok((r.get(0)?, r.get(1)?)), ) .optional() .map_err(Into::into) }) } /// 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 { db.read(|c| { c.query_row( "SELECT 1 FROM package WHERE name=?1 AND state='in_index' LIMIT 1", params![name], |r| r.get::<_, i64>(0), ) .optional() .map(|o| o.is_some()) .map_err(Into::into) }) } /// All package names we publish (in_index), as a set. pub fn our_package_names(db: &Db) -> Result> { db.read(|c| { let mut stmt = c.prepare("SELECT DISTINCT name FROM package WHERE state='in_index'")?; let rows = stmt.query_map([], |r| r.get::<_, String>(0))?; let mut out = std::collections::BTreeSet::new(); for r in rows { out.insert(r?); } Ok(out) }) } /// 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> { let cid = match release.candidate_id { Some(c) => c, None => return Ok(None), }; db.read(move |c| { use rusqlite::OptionalExtension; Ok(c.query_row( "SELECT s.srcinfo_json FROM snapshot s JOIN candidate cnd ON cnd.snapshot_id = s.id WHERE cnd.id = ?1", params![cid], |r| r.get::<_, String>(0), ) .optional()? .and_then(|j| serde_json::from_str::(&j).ok())) }) } /// Recent builds for one pkgbase, newest first. pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result> { db.read(move |c| { let mut st = c.prepare( "SELECT id, pkgbase_id, candidate_id, release_id, kind, world_snapshot_id, build_profile, state, blocked_on_json, current_step, lease_owner, lease_expires_at, attempt, priority, cancel_requested, error 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>>().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`: the caller opens the // transaction, calls these in order, and bails if the compare-and-swap says the // world moved (I4). /// The on-disk path of an artifact, by id. pub fn artifact_path(db: &Db, id: i64) -> Result> { db.read(|c| { Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", params![id], |r| r.get::<_, String>(0)) .optional()?) }) } /// The artifact row for a content digest, if one exists. Two releases built from /// identical bytes share one artifact row — that is the point of the digest. pub fn artifact_id_by_digest_in(tx: &rusqlite::Transaction<'_>, digest: &str) -> Result> { 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> { tx.query_row( "SELECT current_accepted_release_id FROM pkgbase WHERE id=?1", params![pkgbase_id], |r| r.get::<_, Option>(0), ) .optional() .map(Option::flatten) .map_err(Into::into) } /// Compare-and-swap the accepted pointer inside a transaction. `false` means it /// was not where the caller thought it was, and the publish must not land. pub fn cas_accepted_release_in( tx: &rusqlite::Transaction<'_>, pkgbase_id: i64, new_release_id: i64, expected: Option, ) -> Result { let moved = tx.execute( "UPDATE pkgbase SET current_accepted_release_id=?1 WHERE id=?2 AND current_accepted_release_id IS ?3", params![new_release_id, pkgbase_id, expected], )?; Ok(moved == 1) } /// Retire whatever the index held for these names. The index holds exactly the /// accepted pointers, so this runs before the new rows go in. pub fn remove_index_packages_in(tx: &rusqlite::Transaction<'_>, names: &[String]) -> Result<()> { if names.is_empty() { return Ok(()); } let ph = names.iter().map(|_| "?").collect::>().join(","); let sql = format!("UPDATE package SET state='removed' WHERE state='in_index' AND name IN ({ph})"); let mut stmt = tx.prepare(&sql)?; stmt.execute(params_from_iter(names.iter().map(|n| n as &dyn rusqlite::ToSql)))?; Ok(()) } /// Retire one named package from the index (the §9 withdrawal path). pub fn remove_package_by_name_in(tx: &rusqlite::Transaction<'_>, repo_id: i64, name: &str) -> Result<()> { tx.execute( "UPDATE package SET state='removed' WHERE repo_id=?1 AND name=?2", params![repo_id, name], )?; Ok(()) } /// Everything a published release records. Borrowed because the caller is in the /// middle of a transaction and has the values on the stack. pub struct NewRelease<'a> { pub pkgbase_id: i64, pub candidate_id: Option, pub approval_id: Option, pub aur_commit: &'a str, pub recipe_hash: &'a str, pub upstream_pins_json: &'a str, pub source_digests_json: &'a str, pub epoch: &'a str, pub pkgver: &'a str, pub pkgrel: &'a str, pub world_snapshot_id: Option, 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 { tx.execute( "INSERT INTO release (pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash, upstream_pins_json, source_digests_json, epoch, pkgver, pkgrel, world_snapshot_id, state, build_id, published_at, created_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,'published',?12,?13,?13)", params![ r.pkgbase_id, r.candidate_id, r.approval_id, r.aur_commit, r.recipe_hash, r.upstream_pins_json, r.source_digests_json, r.epoch, r.pkgver, r.pkgrel, r.world_snapshot_id, r.build_id, at ], )?; Ok(tx.last_insert_rowid()) } /// Put one package into the index, pointing at the artifact with this digest. pub fn insert_package_in( tx: &rusqlite::Transaction<'_>, repo_id: i64, release_id: i64, name: &str, arch: &str, version: &str, digest: &str, ) -> Result<()> { let artifact_id = artifact_id_by_digest_in(tx, digest)?; tx.execute( "INSERT INTO package (repo_id, release_id, name, arch, version, artifact_id, state) VALUES (?1,?2,?3,?4,?5,?6,'in_index')", params![repo_id, release_id, name, arch, version, artifact_id], )?; Ok(()) } // ------------------------------------------------------------ staleness reads -- // // Staleness is derived on read (§10.2), and these are the reads it is derived // from. They return plain tuples: the *meaning* ("this dependency moved") is // `watch::staleness`'s business, the SQL is this module's. /// `(pkgbase, world members JSON)` for every published release, taken from the /// world snapshot its build recorded (§10.1). pub fn published_world_members(db: &Db) -> Result> { db.read(|c| { let mut st = c.prepare( "SELECT p.name, w.members_json FROM release r JOIN pkgbase p ON p.id = r.pkgbase_id JOIN build b ON b.id = r.build_id JOIN world_snapshot w ON w.id = b.world_snapshot_id WHERE r.state = 'published'", )?; let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; Ok(rows.collect::<::rusqlite::Result>>()?) }) } /// `(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> { db.read(|c| { let mut st = c.prepare( "SELECT p.name, r.pkgver, ( SELECT c.pkgver FROM candidate c WHERE c.pkgbase_id = r.pkgbase_id ORDER BY c.id DESC LIMIT 1) FROM release r JOIN pkgbase p ON p.current_accepted_release_id = r.id WHERE r.state = 'published'", )?; let rows = st.query_map([], |r| { Ok(( r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option>(2)?.unwrap_or_default(), )) })?; Ok(rows.collect::<::rusqlite::Result>>()?) }) } /// 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). /// /// 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. pub fn index_recipes(db: &Db) -> Result> { db.read(|c| { let mut stmt = c.prepare( "SELECT pk.name, s.srcinfo_json FROM package pk JOIN release r ON r.id = pk.release_id JOIN candidate cnd ON cnd.id = r.candidate_id JOIN snapshot s ON s.id = cnd.snapshot_id WHERE pk.state='in_index'", )?; let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } /// The note a reviewer left on an approval, empty when there was none. pub fn approval_note(db: &Db, approval_id: i64) -> Result { db.read(|c| { c.query_row("SELECT COALESCE(note,'') FROM approval WHERE id=?1", params![approval_id], |r| r.get::<_, String>(0)) .optional() .map(|o| o.unwrap_or_default()) .map_err(Into::into) }) } /// The snapshot a candidate was created from, for rendering its diff. pub fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Result> { db.read(|c| { Ok(c.query_row("SELECT snapshot_id FROM candidate WHERE id=?1", params![candidate_id], |r| r.get::<_, i64>(0)) .optional()?) }) } /// The poll interval configured for a subscription, as the scheduler already /// knows it (§5.1: one place decides how often a pkgbase is checked). pub fn subscription_poll_interval(db: &Db, pkgbase: &str) -> Result> { db.read(|c| { Ok(c.query_row( "SELECT poll_interval_secs FROM subscription WHERE pkgbase=?1", params![pkgbase], |r| r.get::<_, Option>(0), ) .optional()? .flatten()) }) } /// Record a fetched source in the content-addressed cache (§5.3). pub fn put_source_cache(writer: &Writer, url: &str, digest: &str, size: u64, path: &str) -> Result<()> { let (u, d, p) = (url.to_string(), digest.to_string(), path.to_string()); let at = time::now(); writer.tx(move |tx| { tx.execute( "INSERT INTO source_cache (url, digest, size, fetched_at, path) VALUES (?1,?2,?3,?4,?5) ON CONFLICT(url, digest) DO UPDATE SET fetched_at=excluded.fetched_at", params![u, d, size as i64, at, p], )?; Ok(()) }) } /// Where a cached source with this url+digest lives on disk. pub fn source_cache_path(db: &Db, url: &str, digest: &str) -> Result> { db.read(|c| { Ok(c.query_row( "SELECT path FROM source_cache WHERE url=?1 AND digest=?2", params![url, digest], |r| r.get::<_, String>(0), ) .optional()?) }) } /// An artifact produced by a build, ready to record. pub struct NewArtifact<'a> { pub digest: &'a str, pub size: i64, pub path: &'a str, pub signature_path: Option<&'a str>, pub build_log_path: Option<&'a str>, pub build_id: &'a str, pub at: &'a str, } /// Record an artifact produced by a build. Identical bytes are one row: the /// digest is the identity, and the row is re-stamped with the build that most /// recently produced them. pub fn insert_artifact_in(tx: &rusqlite::Transaction<'_>, a: &NewArtifact<'_>) -> Result<()> { tx.execute( "INSERT INTO artifact (digest, size, path, signature_path, build_log_path, build_id, created_at) VALUES (?1,?2,?3,?4,?5,?6,?7) ON CONFLICT(digest) DO UPDATE SET build_id=excluded.build_id", params![a.digest, a.size, a.path, a.signature_path, a.build_log_path, a.build_id, a.at], )?; Ok(()) } // --------------------------------------------------------- stage B cache -- /// Exact cache hit: same recipe, same upstream tips (§5.2). pub fn stage_b_cache_get(db: &Db, pkgbase_id: i64, recipe_hash: &str, tip_hash: &str) -> Result> { let (rh, th) = (recipe_hash.to_string(), tip_hash.to_string()); db.read(move |c| { use rusqlite::OptionalExtension; Ok(c.query_row( "SELECT epoch, pkgver, pkgrel, pins_json FROM stage_b_cache WHERE pkgbase_id=?1 AND recipe_hash=?2 AND tip_hash=?3", params![pkgbase_id, rh, th], |r| { Ok(( r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?, )) }, ) .optional()? .map(|(epoch, pkgver, pkgrel, pins_json)| StageBCacheRow { epoch, pkgver, pkgrel, pins: serde_json::from_str(&pins_json).unwrap_or_default(), })) }) } /// 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> { let cutoff = crate::time::secs_ago(cooldown_secs); db.read(move |c| { use rusqlite::OptionalExtension; Ok(c.query_row( "SELECT epoch, pkgver, pkgrel, pins_json FROM stage_b_cache WHERE pkgbase_id=?1 AND resolved_at > ?2 ORDER BY resolved_at DESC LIMIT 1", params![pkgbase_id, cutoff], |r| { Ok(( r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, String>(2)?, r.get::<_, String>(3)?, )) }, ) .optional()? .map(|(epoch, pkgver, pkgrel, pins_json)| StageBCacheRow { epoch, pkgver, pkgrel, pins: serde_json::from_str(&pins_json).unwrap_or_default(), })) }) } pub fn stage_b_cache_put( db: &Db, pkgbase_id: i64, recipe_hash: &str, tip_hash: &str, r: &StageBCacheRow, ) -> Result<()> { let (rh, th) = (recipe_hash.to_string(), tip_hash.to_string()); let (epoch, pkgver, pkgrel) = (r.epoch.clone(), r.pkgver.clone(), r.pkgrel.clone()); let pins = serde_json::to_string(&r.pins)?; let at = crate::time::now(); db.writer.tx(move |tx| { tx.execute( "INSERT INTO stage_b_cache (pkgbase_id, recipe_hash, tip_hash, epoch, pkgver, pkgrel, pins_json, resolved_at) VALUES (?1,?2,?3,?4,?5,?6,?7,?8) ON CONFLICT(pkgbase_id, recipe_hash, tip_hash) DO UPDATE SET epoch=excluded.epoch, pkgver=excluded.pkgver, pkgrel=excluded.pkgrel, pins_json=excluded.pins_json, resolved_at=excluded.resolved_at", params![pkgbase_id, rh, th, epoch, pkgver, pkgrel, pins, at], )?; Ok(()) }) } // ----------------------------------------------------------------- notice -- pub fn put_notice( writer: &Writer, pkgbase_id: i64, kind: &str, severity: &str, detail: serde_json::Value, ) -> Result { let (k, s, d) = (kind.to_string(), severity.to_string(), detail.to_string()); let at = time::now(); writer.tx(move |tx| { tx.execute( "INSERT INTO notice (pkgbase_id, kind, severity, detail_json, created_at) VALUES (?1,?2,?3,?4,?5)", params![pkgbase_id, k, s, d, at], )?; Ok(tx.last_insert_rowid()) }) } /// 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, kind: &str, severity: &str, detail: serde_json::Value, ) -> Result> { let (k, s, d) = (kind.to_string(), severity.to_string(), detail.to_string()); let at = time::now(); writer.tx(move |tx| { let exists: Option = tx .query_row( "SELECT id FROM notice WHERE pkgbase_id=?1 AND kind=?2 AND detail_json=?3 AND acknowledged_at IS NULL ORDER BY id DESC LIMIT 1", params![pkgbase_id, k, d], |r| r.get(0), ) .optional()?; if exists.is_some() { return Ok(None); } tx.execute( "INSERT INTO notice (pkgbase_id, kind, severity, detail_json, created_at) VALUES (?1,?2,?3,?4,?5)", params![pkgbase_id, k, s, d, at], )?; Ok(Some(tx.last_insert_rowid())) }) } #[derive(Debug, Clone)] pub struct NoticeRow { pub id: i64, pub pkgbase: String, pub kind: String, pub severity: String, pub detail_json: String, pub created_at: String, pub acknowledged_at: Option, } pub fn list_notices(db: &Db, include_acknowledged: bool) -> Result> { db.read(|c| { let sql = format!( "SELECT n.id, b.name, n.kind, n.severity, n.detail_json, n.created_at, n.acknowledged_at FROM notice n JOIN pkgbase b ON b.id = n.pkgbase_id {} ORDER BY (n.severity='high') DESC, n.created_at DESC LIMIT 500", if include_acknowledged { "" } else { "WHERE n.acknowledged_at IS NULL" } ); let mut stmt = c.prepare(&sql)?; let rows = stmt.query_map([], |r| { Ok(NoticeRow { id: r.get(0)?, pkgbase: r.get(1)?, kind: r.get(2)?, severity: r.get(3)?, detail_json: r.get(4)?, created_at: r.get(5)?, acknowledged_at: r.get(6)?, }) })?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } pub fn acknowledge_notice(writer: &Writer, id: i64) -> Result<()> { let at = time::now(); writer.tx(move |tx| { tx.execute( "UPDATE notice SET acknowledged_at=?1 WHERE id=?2", params![at, id], )?; Ok(()) }) } // --------------------------------------------------------- world snapshots -- pub fn put_world_snapshot(writer: &Writer, members: &[WorldMember]) -> Result { let mut sorted = members.to_vec(); sorted.sort(); sorted.dedup(); let hash = crate::hash::canonical_json(&sorted)?; let json = serde_json::to_string(&sorted)?; let at = time::now(); writer.tx(move |tx| { tx.execute( "INSERT INTO world_snapshot (hash, members_json, created_at) VALUES (?1,?2,?3) ON CONFLICT(hash) DO NOTHING", params![hash, json, at], )?; tx.query_row("SELECT id FROM world_snapshot WHERE hash=?1", params![hash], |r| r.get(0)) .map_err(Into::into) }) } pub fn world_members(db: &Db, id: i64) -> Result> { db.read(|c| { let s: String = c.query_row( "SELECT members_json FROM world_snapshot WHERE id=?1", params![id], |r| r.get(0), )?; Ok(json_or(&s, Vec::new())) }) } // ------------------------------------------------------------------ audit -- #[derive(Debug, Clone)] pub struct AuditRow { pub id: i64, pub at: String, pub actor_kind: String, pub actor: String, pub action: String, pub entity: String, pub entity_id: String, pub detail_json: String, } pub fn list_audit(db: &Db, limit: i64) -> Result> { db.read(|c| { let mut stmt = c.prepare( "SELECT id, at, actor_kind, actor, action, entity, entity_id, detail_json FROM audit ORDER BY id DESC LIMIT ?1", )?; let rows = stmt.query_map(params![limit], |r| { Ok(AuditRow { id: r.get(0)?, at: r.get(1)?, actor_kind: r.get(2)?, actor: r.get(3)?, action: r.get(4)?, entity: r.get(5)?, entity_id: r.get(6)?, detail_json: r.get(7)?, }) })?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } // -------------------------------------------------------------- metrics reads -- // // The metrics surface is derived from live state, never stored (§10.3: a // counter that is written is a counter that can drift out of truth). These are // the reads that derivation is made of, and they live here because the schema // they read lives here. /// The `count(*)` idiom in one place, so a metric cannot accidentally become a /// `count(*)` of a join. fn count_rows(db: &Db, sql: &str) -> Result { let sql = sql.to_string(); db.read(move |c| { c.query_row(&sql, [], |r| r.get::<_, i64>(0)) .map_err(|e| Error::db(e.to_string())) }) } /// `(state, count)` for every build state present. pub fn build_state_counts(db: &Db) -> Result> { db.read(|c| { let mut st = c.prepare("SELECT state, count(*) FROM build GROUP BY state ORDER BY state")?; let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } /// Seconds the oldest queued build has been waiting; 0 when the queue is empty. pub fn oldest_queued_age_secs(db: &Db, now: &str) -> Result { db.read(|c| { c.query_row( "SELECT julianday(?1) - julianday(min(created_at)) FROM build WHERE state='queued'", params![now], |r| r.get::<_, Option>(0), ) .map(|v| (v.unwrap_or(0.0) * 86400.0) as i64) .map(|v| v.max(0)) .map_err(|e| Error::db(e.to_string())) }) } /// How many candidates are waiting for a decision. pub fn count_pending_reviews(db: &Db) -> Result { 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> { db.read(|c| { let mut st = c.prepare("SELECT julianday(?1) - julianday(detected_at) FROM candidate WHERE state='pending_review'")?; let rows = st.query_map(params![now], |r| r.get::<_, Option>(0))?; let mut out = Vec::new(); for r in rows { out.push((r?.unwrap_or(0.0) * 86400.0) as i64); } Ok(out) }) } pub fn count_index_packages(db: &Db) -> Result { count_rows(db, "SELECT count(*) FROM package WHERE state='in_index'") } pub fn count_published_releases(db: &Db) -> Result { count_rows(db, "SELECT count(*) FROM release WHERE state='published'") } pub fn count_subscriptions(db: &Db) -> Result { count_rows(db, "SELECT count(*) FROM subscription") } pub fn count_unacknowledged_notices(db: &Db) -> Result { 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 { db.read(|c| { c.query_row( "SELECT COALESCE(sum(size),0) FROM artifact WHERE purged_at IS NULL", [], |r| r.get::<_, i64>(0), ) .map(|v| v.max(0) as u64) .map_err(|e| Error::db(e.to_string())) }) } /// Seconds since the last retention run, if there has been one. pub fn last_gc_age_secs(db: &Db, now: &str) -> Result> { let at = db.read(|c| { c.query_row("SELECT max(ran_at) FROM gc_run", [], |r| r.get::<_, Option>(0)) .map_err(|e| Error::db(e.to_string())) })?; Ok(at.and_then(|t| time::delta_secs(now, &t))) } /// Seconds since the last successful poll of any source, if there has been one. /// This is the metric that catches a watcher that stopped, which no log line /// will tell you about. pub fn last_poll_age_secs(db: &Db, now: &str) -> Result> { let at = db.read(|c| { c.query_row("SELECT max(last_checked_at) FROM subscription", [], |r| r.get::<_, Option>(0)) .map_err(|e| Error::db(e.to_string())) })?; Ok(at.and_then(|t| time::delta_secs(now, &t))) } // -------------------------------------------------------------- retention reads -- /// `(pkgbase id, current accepted release)` for every pkgbase, in id order. pub fn pkgbase_release_pointers(db: &Db) -> Result)>> { db.read(|c| { let mut st = c.prepare("SELECT id, current_accepted_release_id FROM pkgbase ORDER BY id")?; let rows = st.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Option>(1)?)))?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } /// Published release ids of one pkgbase, newest first. pub fn published_release_ids(db: &Db, pkgbase_id: i64) -> Result> { db.read(|c| { let mut st = c.prepare("SELECT id FROM release WHERE pkgbase_id=?1 AND state='published' ORDER BY id DESC")?; let rows = st.query_map(params![pkgbase_id], |r| r.get::<_, i64>(0))?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } /// Releases of one pkgbase that still back an `in_index` package. Retention must /// never evict these: the index is pointing at their bytes right now. pub fn serving_release_ids(db: &Db, pkgbase_id: i64) -> Result> { db.read(|c| { let mut st = c.prepare( "SELECT DISTINCT r.id FROM release r JOIN package p ON p.release_id=r.id WHERE r.pkgbase_id=?1 AND p.state='in_index' ORDER BY r.id DESC", )?; let rows = st.query_map(params![pkgbase_id], |r| r.get::<_, i64>(0))?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } /// The three paths one artifact row points at: the package, its signature and /// its build log. Any of them can be absent (an unsigned build, a log that was /// already purged). pub type ArtifactPaths = (Option, Option, Option); /// The artifact paths one release holds: package, signature, build log. pub fn release_artifact_paths(db: &Db, release_id: i64) -> Result> { db.read(|c| { let mut st = c.prepare( "SELECT a.path, a.signature_path, a.build_log_path FROM artifact a JOIN package p ON p.artifact_id = a.id WHERE p.release_id = ?1", )?; let rows = st.query_map(params![release_id], |r| { Ok((r.get::<_, Option>(0)?, r.get::<_, Option>(1)?, r.get::<_, Option>(2)?)) })?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } /// Mark a release and the artifacts behind it as purged, in one transaction. /// Half-marking them would leave the next retention pass believing the files are /// still retained. pub fn mark_release_purged(writer: &Writer, release_id: i64) -> Result<()> { let at = time::now(); writer.tx(move |tx| { tx.execute("UPDATE release SET purged_at=?1 WHERE id=?2", params![at, release_id])?; tx.execute( "UPDATE artifact SET purged_at=?1 WHERE purged_at IS NULL AND id IN (SELECT a.id FROM artifact a JOIN package p ON p.artifact_id=a.id WHERE p.release_id=?2)", params![at, release_id], )?; Ok(()) }) } /// Record a retention run, which is what the ops page and the `last_gc_age` /// metric read. pub fn record_gc_run(writer: &Writer, at: &str, kept: i64, evicted: i64, files_removed: i64, bytes_freed: i64, staging_swept: i64) -> Result<()> { let at = at.to_string(); writer.tx(move |tx| { tx.execute( "INSERT INTO gc_run (ran_at, releases_kept, releases_evicted, files_removed, bytes_freed, staging_swept) VALUES (?1,?2,?3,?4,?5,?6)", params![at, kept, evicted, files_removed, bytes_freed, staging_swept], )?; Ok(()) }) } // ------------------------------------------------------- invariant helpers -- /// I1: every artifact in a served repo index traces to an approval row. /// Returns offending package names; empty means the invariant holds. pub fn unapproved_index_entries(db: &Db) -> Result> { db.read(|c| { let mut stmt = c.prepare( "SELECT p.name FROM package p JOIN release r ON r.id = p.release_id WHERE p.state='in_index' AND (r.approval_id IS NULL OR NOT EXISTS (SELECT 1 FROM approval a WHERE a.id = r.approval_id AND a.decision='approved'))", )?; let rows = stmt.query_map([], |r| r.get::<_, String>(0))?; let mut out = Vec::new(); for r in rows { out.push(r?); } Ok(out) }) } /// 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, Vec)> { db.read(|c| { let mut orphans = Vec::new(); let mut stmt = c.prepare( "SELECT DISTINCT b.name FROM package p JOIN release r ON r.id = p.release_id JOIN pkgbase b ON b.id = r.pkgbase_id WHERE p.state='in_index' AND r.id NOT IN (SELECT current_accepted_release_id FROM pkgbase WHERE current_accepted_release_id IS NOT NULL)", )?; let rows = stmt.query_map([], |r| r.get::<_, String>(0))?; for r in rows { orphans.push(r?); } let mut missing = Vec::new(); let mut stmt = c.prepare( "SELECT b.name FROM pkgbase b JOIN subscription s ON s.pkgbase = b.name AND s.state IN ('active','orphaned') WHERE b.current_accepted_release_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM package p WHERE p.release_id = b.current_accepted_release_id AND p.state='in_index')", )?; let rows = stmt.query_map([], |r| r.get::<_, String>(0))?; for r in rows { missing.push(r?); } Ok((orphans, missing)) }) } /// 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`. #[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, } pub fn approved_but_unbuilt(db: &Db) -> Result> { 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. let mut stmt = c.prepare( "SELECT p.name, cnd.epoch, cnd.pkgver, cnd.pkgrel, ser.epoch, ser.pkgver, ser.pkgrel, COALESCE(b.error, ''), b.id FROM build b JOIN pkgbase p ON p.id = b.pkgbase_id LEFT JOIN candidate cnd ON cnd.id = b.candidate_id LEFT JOIN release ser ON ser.id = p.current_accepted_release_id AND ser.state='published' WHERE b.state = 'failed' AND b.candidate_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM release r WHERE r.candidate_id = b.candidate_id) AND b.id = (SELECT b2.id FROM build b2 WHERE b2.candidate_id = b.candidate_id ORDER BY b2.rowid DESC LIMIT 1) ORDER BY p.name", )?; let rows = stmt.query_map([], |r| { Ok(( r.get::<_, Option>(0)?, r.get::<_, Option>(1)?, r.get::<_, Option>(2)?, r.get::<_, Option>(3)?, r.get::<_, Option>(4)?, r.get::<_, Option>(5)?, r.get::<_, Option>(6)?, r.get::<_, String>(7)?, r.get::<_, String>(8)?, )) })?; let mut out = Vec::new(); for r in rows { 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(), )) } }; out.push(Unbuilt { pkgbase, approved: crate::pkgver::full_version(&ae.unwrap_or_default(), &av, &ar), serving: match (sv, sr) { (Some(v), Some(rel)) => { crate::pkgver::full_version(&se.unwrap_or_default(), &v, &rel) } _ => String::new(), }, error, build_id, }); } Ok(out) }) }