diff options
Diffstat (limited to 'src/db')
| -rw-r--r-- | src/db/migrations.rs | 293 | ||||
| -rw-r--r-- | src/db/mod.rs | 272 | ||||
| -rw-r--r-- | src/db/model.rs | 286 | ||||
| -rw-r--r-- | src/db/queries.rs | 808 |
4 files changed, 1659 insertions, 0 deletions
diff --git a/src/db/migrations.rs b/src/db/migrations.rs new file mode 100644 index 0000000..e0c1cb3 --- /dev/null +++ b/src/db/migrations.rs @@ -0,0 +1,293 @@ +//! 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, + pub name: &'static str, + pub sql: &'static str, +} + +const M_0001_CORE: &str = r#" +-- The single repo we publish. Exactly one row (DESIGN.md §9, decision 4). +CREATE TABLE repo ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + signing_key_id TEXT NOT NULL DEFAULT '', + path TEXT NOT NULL, + arch TEXT NOT NULL DEFAULT 'x86_64', + state TEXT NOT NULL DEFAULT 'active' +); + +CREATE TABLE settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); + +-- Append-only audit log (I10). Enforced by trigger below. +CREATE TABLE audit ( + id INTEGER PRIMARY KEY, + at TEXT NOT NULL, + actor_kind TEXT NOT NULL, -- human | policy | system + actor TEXT NOT NULL DEFAULT '', + action TEXT NOT NULL, + entity TEXT NOT NULL, + entity_id TEXT NOT NULL DEFAULT '', + detail_json TEXT NOT NULL DEFAULT '{}' +); + +-- The unit of subscription, detection, diffing and approval. +CREATE TABLE pkgbase ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE, + aur_url TEXT NOT NULL, + mirror_path TEXT, + aur_head TEXT, -- live mirror tip + current_accepted_release_id INTEGER, -- the single pointer everything reads + state TEXT NOT NULL DEFAULT 'tracked', + unpinable INTEGER NOT NULL DEFAULT 0, -- §16 pkgver() that ignores pins + created_at TEXT NOT NULL +); + +CREATE TABLE subscription ( + id INTEGER PRIMARY KEY, + repo_id INTEGER NOT NULL REFERENCES repo(id), + pkgbase TEXT NOT NULL, + aur_url TEXT NOT NULL, + maintainer TEXT, + state TEXT NOT NULL DEFAULT 'active', -- active|paused|orphaned|removed + next_check_at TEXT, + last_checked_at TEXT, + last_error TEXT, + poll_interval_secs INTEGER, -- per-source override (§19) + created_at TEXT NOT NULL, + UNIQUE (repo_id, pkgbase) +); +CREATE INDEX subscription_due ON subscription (state, next_check_at); + +-- An immutable pin of the AUR git repo for a pkgbase (§5.1a). +CREATE TABLE snapshot ( + id INTEGER PRIMARY KEY, + pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), + aur_commit TEXT NOT NULL, -- THE PIN + recipe_hash TEXT NOT NULL, + srcinfo_json TEXT NOT NULL, + files_json TEXT NOT NULL, + fetched_at TEXT NOT NULL, + UNIQUE (pkgbase_id, aur_commit) +); + +-- Fingerprint of the accepted dep set a build ran against (§10.1). +CREATE TABLE world_snapshot ( + id INTEGER PRIMARY KEY, + hash TEXT NOT NULL UNIQUE, + members_json TEXT NOT NULL, + created_at TEXT NOT NULL +); + +CREATE TABLE artifact ( + id INTEGER PRIMARY KEY, + digest TEXT NOT NULL UNIQUE, + size INTEGER NOT NULL, + path TEXT NOT NULL, + signature_path TEXT, + build_log_path TEXT, + source_archive_path TEXT, + created_at TEXT NOT NULL +); + +-- A detected, reviewable change. +CREATE TABLE candidate ( + id INTEGER PRIMARY KEY, + pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), + base_release_id INTEGER REFERENCES release(id), -- last ACCEPTED, never last seen + kind TEXT NOT NULL, -- new_version | first_introduction + snapshot_id INTEGER NOT NULL REFERENCES snapshot(id), + epoch TEXT NOT NULL DEFAULT '0', + pkgver TEXT NOT NULL, + pkgrel TEXT NOT NULL, + upstream_pins_json TEXT NOT NULL DEFAULT '[]', + source_digests_json TEXT NOT NULL DEFAULT '[]', + identity_hash TEXT NOT NULL, + diff_digest TEXT NOT NULL DEFAULT '', + revision INTEGER NOT NULL DEFAULT 0, + viewed_at TEXT, + risk_level TEXT NOT NULL DEFAULT 'none', + risk_signals_json TEXT NOT NULL DEFAULT '[]', + missing_deps_json TEXT NOT NULL DEFAULT '[]', + state TEXT NOT NULL, -- pending_review|approved|rejected|superseded|blocked + detected_at TEXT NOT NULL, + resolved_at TEXT, + UNIQUE (pkgbase_id, identity_hash) +); +CREATE INDEX candidate_by_pkgbase ON candidate (pkgbase_id, state); +CREATE INDEX candidate_pending_age ON candidate (state, detected_at); + +-- I7: at most one open review per pkgbase, as a database guarantee. +CREATE UNIQUE INDEX one_open_review_per_pkgbase + ON candidate (pkgbase_id) WHERE state = 'pending_review'; + +-- The immutable decision record (§7.2). +CREATE TABLE approval ( + id INTEGER PRIMARY KEY, + candidate_id INTEGER NOT NULL UNIQUE REFERENCES candidate(id), + base_release_id INTEGER REFERENCES release(id), + decided_at TEXT NOT NULL, + decision TEXT NOT NULL, -- approved | rejected + risk_level TEXT NOT NULL, + diff_digest TEXT NOT NULL, + identity_hash TEXT NOT NULL, + note TEXT +); + +-- An approved candidate that has been built & published. +CREATE TABLE release ( + id INTEGER PRIMARY KEY, + pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), + candidate_id INTEGER REFERENCES candidate(id), + approval_id INTEGER REFERENCES approval(id), + aur_commit TEXT NOT NULL, -- copied: provenance survives compaction + recipe_hash TEXT NOT NULL, + upstream_pins_json TEXT NOT NULL DEFAULT '[]', + source_digests_json TEXT NOT NULL DEFAULT '[]', + epoch TEXT NOT NULL DEFAULT '0', + pkgver TEXT NOT NULL, + pkgrel TEXT NOT NULL, + world_snapshot_id INTEGER REFERENCES world_snapshot(id), + state TEXT NOT NULL, -- published|withdrawn|failed_unbuilt + build_id TEXT, + published_at TEXT, + created_at TEXT NOT NULL +); +CREATE INDEX release_by_pkgbase ON release (pkgbase_id, state); + +-- `package` is the unit of the index and dependency resolution (§3). +CREATE TABLE package ( + id INTEGER PRIMARY KEY, + repo_id INTEGER NOT NULL REFERENCES repo(id), + release_id INTEGER NOT NULL REFERENCES release(id), + name TEXT NOT NULL, + arch TEXT NOT NULL, + version TEXT NOT NULL, + artifact_id INTEGER REFERENCES artifact(id), + state TEXT NOT NULL DEFAULT 'in_index' -- in_index | removed +); +CREATE INDEX package_by_name ON package (repo_id, name, state); +"#; + +const M_0002_BUILD: &str = r#" +CREATE TABLE build ( + id TEXT PRIMARY KEY, -- deterministic intent hash (§8.2) + pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), + candidate_id INTEGER REFERENCES candidate(id), + release_id INTEGER REFERENCES release(id), + kind TEXT NOT NULL, -- new_version | manual_rebuild + world_snapshot_id INTEGER REFERENCES world_snapshot(id), + build_profile TEXT NOT NULL, + state TEXT NOT NULL, -- queued|leased|running|blocked_missing_dep| + -- succeeded|failed|cancelled + blocked_on_json TEXT NOT NULL DEFAULT '[]', + current_step TEXT, + lease_owner TEXT, + lease_expires_at TEXT, + attempt INTEGER NOT NULL DEFAULT 0, + priority INTEGER NOT NULL DEFAULT 0, + cancel_requested INTEGER NOT NULL DEFAULT 0, + error TEXT, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); +CREATE INDEX build_queued ON build (state, priority DESC, created_at); +CREATE INDEX build_lease ON build (state, lease_expires_at); + +-- Step-level checkpoints: the mechanism behind I5. +CREATE TABLE build_step ( + build_id TEXT NOT NULL REFERENCES build(id), + step TEXT NOT NULL, + status TEXT NOT NULL, -- pending|running|succeeded|failed|interrupted|skipped + attempt INTEGER NOT NULL DEFAULT 0, + output_digest TEXT, + error TEXT, + started_at TEXT, + finished_at TEXT, + PRIMARY KEY (build_id, step) +); +"#; + +const M_0003_NOTICES: &str = r#" +-- "something changed but nothing is publishable" (§5.2, I11). +CREATE TABLE notice ( + id INTEGER PRIMARY KEY, + pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), + kind TEXT NOT NULL, -- pin_drift|recipe_drift|digest_drift|integrity_alert| + -- unpinable_pkgver|orphaned|deleted|renamed|downgrade + severity TEXT NOT NULL, -- info|warning|high + detail_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL, + acknowledged_at TEXT +); +CREATE INDEX notice_open ON notice (acknowledged_at, severity, created_at); + +CREATE TABLE source_cache ( + url TEXT NOT NULL, + digest TEXT NOT NULL, + size INTEGER NOT NULL, + fetched_at TEXT NOT NULL, + path TEXT NOT NULL, + PRIMARY KEY (url, digest) +); + +CREATE TABLE vcs_cache ( + url TEXT PRIMARY KEY, + head TEXT NOT NULL, + path TEXT NOT NULL, + fetched_at TEXT NOT NULL +); + +-- Derived, read-only: "approving this marks N packages stale" (§10.5). +-- Nothing consumes it automatically; it is a read-time aid only. +CREATE TABLE dep_edge ( + from_pkgbase TEXT NOT NULL, + to_pkgbase TEXT NOT NULL, + kind TEXT NOT NULL, + updated_at TEXT NOT NULL, + CHECK (kind IN ('depend','makedepends')), + PRIMARY KEY (from_pkgbase, to_pkgbase, kind) +); +"#; + +const M_0004_TRIGGERS: &str = r#" +-- I10: the audit log is append-only. +CREATE TRIGGER audit_no_update +BEFORE UPDATE ON audit +BEGIN + SELECT RAISE(ABORT, 'audit log is append-only: updates are forbidden'); +END; + +CREATE TRIGGER audit_no_delete +BEFORE DELETE ON audit +BEGIN + SELECT RAISE(ABORT, 'audit log is append-only: deletes are forbidden'); +END; +"#; + +pub static MIGRATIONS: &[Migration] = &[ + Migration { version: 1, name: "core", sql: M_0001_CORE }, + Migration { version: 2, name: "build", sql: M_0002_BUILD }, + Migration { version: 3, name: "notices", sql: M_0003_NOTICES }, + Migration { version: 4, name: "audit-triggers", sql: M_0004_TRIGGERS }, +]; + +/// Default settings seeded into `settings` (DESIGN.md §11). +pub const DEFAULT_SETTINGS: &[(&str, &str)] = &[ + ("max_concurrent_builds", "1"), + ("build_timeout", "5400"), + ("poll_interval", "86400"), + ("stage_b_cooldown", "86400"), + ("retention_versions", "3"), + ("dry_run", "0"), + ("review_budget_days", "14"), +]; diff --git a/src/db/mod.rs b/src/db/mod.rs new file mode 100644 index 0000000..c11bf5a --- /dev/null +++ b/src/db/mod.rs @@ -0,0 +1,272 @@ +//! 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. + +mod migrations; +mod model; +mod queries; + +pub use migrations::MIGRATIONS; +pub use model::*; +pub use queries::*; + +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +use crossbeam_channel::{bounded, unbounded, Sender}; +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( + path, + rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX, + ) + } else { + Connection::open(path) + } + .map_err(|e| Error::db(format!("open {}: {e}", path.display())))?; + configure(&conn, read_only)?; + Ok(conn) +} + +fn configure(conn: &Connection, read_only: bool) -> Result<()> { + conn.pragma_update(None, "journal_mode", "WAL") + .and_then(|_| conn.pragma_update(None, "busy_timeout", 5000)) + .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; + let current: u32 = conn + .pragma_query_value(None, "user_version", |r| r.get(0)) + .map_err(|e| Error::db(e.to_string()))?; + for m in migrations::MIGRATIONS { + if m.version > current { + let tx = conn + .transaction() + .map_err(|e| Error::db(e.to_string()))?; + tx.execute_batch(m.sql) + .map_err(|e| Error::db(format!("migration {} ({}): {e}", m.version, m.name)))?; + tx.pragma_update(None, "user_version", m.version) + .map_err(|e| Error::db(e.to_string()))?; + tx.commit().map_err(|e| Error::db(e.to_string()))?; + applied += 1; + } + } + if applied > 0 { + let mut stmt = conn + .prepare("INSERT OR IGNORE INTO settings (key, value) VALUES (?1, ?2)") + .map_err(|e| Error::db(e.to_string()))?; + for (k, v) in migrations::DEFAULT_SETTINGS { + let _ = stmt.execute(rusqlite::params![k, *v]); + } + } + Ok(applied) +} + +type BoxedCall = Box<dyn FnOnce(&mut Connection) + Send>; + +enum Msg { + Call(BoxedCall), + 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, + alive: Arc<AtomicBool>, +} + +impl Writer { + /// Spawn the writer actor thread. + pub fn start(path: &Path) -> Result<Self> { + let conn = open(path, false)?; + let (tx, rx) = unbounded::<Msg>(); + let alive = Arc::new(AtomicBool::new(true)); + let alive_thread = alive.clone(); + let thread_path = path.to_path_buf(); + std::thread::Builder::new() + .name("db-writer".into()) + .spawn(move || { + let mut conn = conn; + alive_thread.store(true, Ordering::SeqCst); + for msg in rx.iter() { + match msg { + Msg::Call(f) => f(&mut conn), + 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); + }) + .map_err(|e| Error::db(format!("spawn writer: {e}")))?; + Ok(Self { tx, path: thread_path, alive }) + } + + pub fn path(&self) -> &Path { + &self.path + } + + pub fn is_alive(&self) -> bool { + 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. + pub fn call<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T> + where + T: Send + 'static, + { + let (reply_tx, reply_rx) = bounded::<Result<T>>(1); + self.send(Box::new(move |conn| { + let _ = reply_tx.send(f(conn)); + }))?; + reply_rx + .recv() + .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. + pub fn tx<T>( + &self, + f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static, + ) -> Result<T> + where + T: Send + 'static, + { + self.call(move |conn| { + let mut tx = conn + .transaction_with_behavior(rusqlite::TransactionBehavior::Immediate) + .map_err(|e| Error::db(e.to_string()))?; + let out = f(&mut tx)?; + tx.commit().map_err(|e| Error::db(e.to_string()))?; + Ok(out) + }) + } + + /// Fire-and-forget write (audit rows, bookkeeping where the result is unused). + pub fn send(&self, f: BoxedCall) -> Result<()> { + if !self.is_alive() { + return Err(Error::db("writer actor gone")); + } + self.tx + .send(Msg::Call(f)) + .map_err(|_| Error::db("writer actor gone")) + } + + pub fn shutdown(&self) { + let _ = self.tx.send(Msg::Shutdown); + } +} + +/// 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. +pub struct Readers { + path: PathBuf, +} + +thread_local! { + static POOL: std::cell::RefCell<Vec<(PathBuf, Connection)>> = const { std::cell::RefCell::new(Vec::new()) }; +} + +impl Readers { + pub fn new(path: &Path) -> Self { + 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| { + let mut pool = pool.borrow_mut(); + if pool.iter().position(|(p, _)| p == &path).is_none() { + pool.push((path.clone(), open(&path, true)?)); + } + let idx = pool + .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). + let conn = &pool[idx].1; + f(conn) + }) + } +} + +/// A handle bundling the writer with a reader factory; passed around as `App`. +#[derive(Clone)] +pub struct Db { + pub writer: Arc<Writer>, + pub readers: Arc<Readers>, +} + +impl Db { + pub fn open(cfg: &Config) -> Result<Self> { + let path = cfg.db_path(); + migrate(&path)?; + Self::open_migrated(&path) + } + + pub fn open_migrated(path: &Path) -> Result<Self> { + Ok(Self { + writer: Arc::new(Writer::start(path)?), + readers: Arc::new(Readers::new(path)), + }) + } + + /// 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| { + conn.execute("VACUUM INTO ?1", rusqlite::params![dest_s]) + .map_err(|e| Error::db(e.to_string()))?; + Ok(()) + }) +} + +/// 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(); + wal.push("-wal"); + let wal_file = std::fs::metadata(&wal).map(|m| m.len()).unwrap_or(0); + (db_file, wal_file) +} diff --git a/src/db/model.rs b/src/db/model.rs new file mode 100644 index 0000000..599fc21 --- /dev/null +++ b/src/db/model.rs @@ -0,0 +1,286 @@ +//! 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. +#[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. + pub commit: String, +} + +/// 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 declared `SKIP` (or nothing) for this source. + pub skip_declared: bool, +} + +/// 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, + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, + pub upstream_pins: Vec<UpstreamPin>, + pub source_digests: Vec<SourceDigest>, +} + +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. + pub fn hash(&self) -> String { + hash::canonical_json(self) + } +} + +/// Candidate/review states (§7.1). +pub mod candidate_state { + pub const PENDING: &str = "pending_review"; + pub const APPROVED: &str = "approved"; + pub const REJECTED: &str = "rejected"; + pub const SUPERSEDED: &str = "superseded"; + pub const BLOCKED: &str = "blocked"; +} + +pub mod candidate_kind { + pub const NEW_VERSION: &str = "new_version"; + pub const FIRST_INTRODUCTION: &str = "first_introduction"; +} + +pub mod release_state { + pub const PUBLISHED: &str = "published"; + pub const WITHDRAWN: &str = "withdrawn"; + pub const FAILED_UNBUILT: &str = "failed_unbuilt"; +} + +pub mod build_state { + pub const QUEUED: &str = "queued"; + pub const LEASED: &str = "leased"; + pub const RUNNING: &str = "running"; + pub const BLOCKED_MISSING_DEP: &str = "blocked_missing_dep"; + pub const SUCCEEDED: &str = "succeeded"; + pub const FAILED: &str = "failed"; + pub const CANCELLED: &str = "cancelled"; +} + +pub mod step_state { + pub const PENDING: &str = "pending"; + pub const RUNNING: &str = "running"; + pub const SUCCEEDED: &str = "succeeded"; + pub const FAILED: &str = "failed"; + pub const INTERRUPTED: &str = "interrupted"; + pub const SKIPPED: &str = "skipped"; +} + +pub mod notice_kind { + pub const PIN_DRIFT: &str = "pin_drift"; + pub const RECIPE_DRIFT: &str = "recipe_drift"; + pub const DIGEST_DRIFT: &str = "digest_drift"; + pub const INTEGRITY_ALERT: &str = "integrity_alert"; + pub const UNPINABLE_PKGVER: &str = "unpinable_pkgver"; + pub const ORPHANED: &str = "orphaned"; + pub const DELETED: &str = "deleted"; + pub const RENAMED: &str = "renamed"; + pub const DOWNGRADE: &str = "downgrade"; +} + +pub mod subscription_state { + pub const ACTIVE: &str = "active"; + pub const PAUSED: &str = "paused"; + pub const ORPHANED: &str = "orphaned"; + pub const REMOVED: &str = "removed"; +} + +/// 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", + "chroot", + "sources", + "pkgver", + "build", + "collect", + "verify", + "ingest", + "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>, + /// `#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+`. + pub vcs: Option<String>, + /// True for files shipped inside the AUR repo (no scheme). + pub local: bool, +} + +impl SourceEntry { + pub fn is_vcs(&self) -> bool { + self.vcs.is_some() + } +} + +/// A parsed recipe: what `.SRCINFO` / `PKGBUILD` tell us. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct Recipe { + pub pkgbase: String, + pub pkgver: String, + pub pkgrel: String, + pub epoch: String, + pub pkgdesc: String, + pub url: String, + pub arch: Vec<String>, + pub license: Vec<String>, + pub groups: Vec<String>, + pub depends: Vec<String>, + pub makedepends: Vec<String>, + pub checkdepends: Vec<String>, + pub optdepends: Vec<String>, + pub provides: Vec<String>, + pub conflicts: Vec<String>, + pub source: Vec<String>, + pub sha256sums: Vec<String>, + pub b2sums: Vec<String>, + pub validpgpkeys: Vec<String>, + 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>, + /// 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, +} + +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) + } +} + +/// A source row as stored on a candidate/release. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ReleaseRow { + pub id: i64, + pub pkgbase_id: i64, + pub candidate_id: Option<i64>, + pub approval_id: Option<i64>, + pub aur_commit: String, + pub recipe_hash: String, + pub upstream_pins_json: String, + pub source_digests_json: String, + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, + pub world_snapshot_id: Option<i64>, + pub state: String, + pub published_at: Option<String>, +} + +impl ReleaseRow { + pub fn version(&self) -> String { + crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) + } + pub fn pins(&self) -> Vec<UpstreamPin> { + serde_json::from_str(&self.upstream_pins_json).unwrap_or_default() + } + pub fn digests(&self) -> Vec<SourceDigest> { + serde_json::from_str(&self.source_digests_json).unwrap_or_default() + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct CandidateRow { + pub id: i64, + pub pkgbase_id: i64, + pub base_release_id: Option<i64>, + pub kind: String, + pub snapshot_id: i64, + pub epoch: String, + pub pkgver: String, + pub pkgrel: String, + pub upstream_pins_json: String, + pub source_digests_json: String, + pub identity_hash: String, + pub diff_digest: String, + pub revision: i64, + pub viewed_at: Option<String>, + pub risk_level: String, + pub risk_signals_json: String, + pub missing_deps_json: String, + pub state: String, + pub detected_at: String, + pub resolved_at: Option<String>, + pub pkgbase: String, +} + +impl CandidateRow { + pub fn version(&self) -> String { + crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) + } + pub fn pins(&self) -> Vec<UpstreamPin> { + serde_json::from_str(&self.upstream_pins_json).unwrap_or_default() + } + pub fn digests(&self) -> Vec<SourceDigest> { + serde_json::from_str(&self.source_digests_json).unwrap_or_default() + } + pub fn risk_signals(&self) -> Vec<String> { + serde_json::from_str(&self.risk_signals_json).unwrap_or_default() + } + pub fn missing_deps(&self) -> Vec<String> { + serde_json::from_str(&self.missing_deps_json).unwrap_or_default() + } +} + +/// 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 new file mode 100644 index 0000000..b1f7e4d --- /dev/null +++ b/src/db/queries.rs @@ -0,0 +1,808 @@ +//! Typed query helpers. Everything that mutates goes through the writer actor; +//! everything that reads takes a `&Connection` from the reader pool. + +use rusqlite::{params, OptionalExtension, Row}; + +use crate::db::*; +use crate::error::{Error, Result}; +use crate::time; + +// ---------------------------------------------------------------- settings -- + +pub fn setting(db: &Db, key: &str) -> Result<Option<String>> { + db.read(|c| { + c.query_row("SELECT value FROM settings WHERE key = ?1", params![key], |r| r.get(0)) + .optional() + .map_err(Into::into) + }) +} + +pub fn setting_i64(db: &Db, key: &str, default: i64) -> i64 { + setting(db, key) + .ok() + .flatten() + .and_then(|v| v.parse().ok()) + .unwrap_or(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(); + let detail = detail.to_string(); + writer.tx(move |tx| { + tx.execute( + "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) + VALUES (?1,?2,?3,?4,?5,?6,?7)", + params![at, actor_kind, actor, action, entity, entity_id, detail], + )?; + Ok(()) + }) +} + +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<i64> { + 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<i64> { + 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<String>, + pub state: String, + pub next_check_at: Option<String>, + pub last_checked_at: Option<String>, + pub last_error: Option<String>, + pub poll_interval_secs: Option<i64>, +} + +fn row_to_sub(r: &Row<'_>) -> rusqlite::Result<Subscription> { + Ok(Subscription { + id: r.get(0)?, + pkgbase: r.get(1)?, + aur_url: r.get(2)?, + maintainer: r.get(3)?, + state: r.get(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<Vec<Subscription>> { + 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<Option<Subscription>> { + 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<i64> { + 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: &str) -> 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<Vec<Subscription>> { + 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<String>, + pub aur_head: Option<String>, + pub current_accepted_release_id: Option<i64>, + pub state: String, + pub unpinable: bool, +} + +fn row_to_pkgbase(r: &Row<'_>) -> rusqlite::Result<Pkgbase> { + 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<Option<Pkgbase>> { + 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<Option<Pkgbase>> { + 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<Vec<Pkgbase>> { + 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<i64>, + new_id: i64, +) -> Result<bool> { + 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<i64> { + 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<Option<SnapshotRow>> { + 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<Option<SnapshotRow>> { + 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<ReleaseRow> { + 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: r.get(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"; + +pub fn release_by_id(db: &Db, id: i64) -> Result<Option<ReleaseRow>> { + 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<Option<ReleaseRow>> { + 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<Vec<ReleaseRow>> { + 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<Vec<ReleaseRow>> { + 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<i64>, + pub pkgbase: String, +} + +pub fn index_packages(db: &Db) -> Result<Vec<PackageRow>> { + 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 + 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' + 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)?, + }) + })?; + 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<Option<String>> { + 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) + }) +} + +/// 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( + "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<std::collections::BTreeSet<String>> { + 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) + }) +} + +// ----------------------------------------------------------------- notice -- + +pub fn put_notice( + writer: &Writer, + pkgbase_id: i64, + kind: &str, + severity: &str, + detail: serde_json::Value, +) -> Result<i64> { + 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<Option<i64>> { + let (k, s, d) = (kind.to_string(), severity.to_string(), detail.to_string()); + let at = time::now(); + writer.tx(move |tx| { + let exists: Option<i64> = 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<String>, +} + +pub fn list_notices(db: &Db, include_acknowledged: bool) -> Result<Vec<NoticeRow>> { + 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<i64> { + 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<Vec<WorldMember>> { + 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<Vec<AuditRow>> { + 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) + }) +} + +// ------------------------------------------------------- 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( + "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<String>, Vec<String>)> { + 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)) + }) +} |
