summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/config.rs201
-rw-r--r--src/db/migrations.rs293
-rw-r--r--src/db/mod.rs272
-rw-r--r--src/db/model.rs286
-rw-r--r--src/db/queries.rs808
-rw-r--r--src/error.rs70
-rw-r--r--src/hash.rs78
-rw-r--r--src/lib.rs14
-rw-r--r--src/pkgver/mod.rs273
-rw-r--r--src/time.rs69
10 files changed, 2364 insertions, 0 deletions
diff --git a/src/config.rs b/src/config.rs
new file mode 100644
index 0000000..44b110c
--- /dev/null
+++ b/src/config.rs
@@ -0,0 +1,201 @@
+//! Filesystem layout and runtime configuration.
+//!
+//! Everything the server owns lives under one root directory so a test can point
+//! the whole application at a `tempdir` and get an isolated instance. The heavy
+//! bytes (packages, logs, mirrors) live on the filesystem and are referenced by
+//! path from the DB (DESIGN.md §11a).
+
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+
+/// Runtime configuration. Persisted as `<root>/config.json`.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(default)]
+pub struct Config {
+ /// Root directory holding db, mirrors, caches, store, repo and logs.
+ pub root: PathBuf,
+ /// Name of the single pacman repo we publish (DESIGN.md §9, decision 4).
+ pub repo_name: String,
+ /// Architecture, fixed to x86_64 by decision 17.
+ pub arch: String,
+ /// GPG key id used to sign packages *and* the database (decision 22).
+ pub signing_key_id: String,
+ /// Address the HTTP UI binds to. Default is loopback only (§14).
+ pub bind: String,
+ /// Shared credential for the UI. Single user, one credential, no user table.
+ pub password: String,
+ /// Public base URL used in consumer-facing snippets.
+ pub base_url: String,
+ /// devtools build profile (§8.3).
+ pub build_profile: String,
+ /// Path to the git executable.
+ pub git_bin: String,
+ /// Path to the makepkg executable.
+ pub makepkg_bin: String,
+ /// Path to makechrootpkg.
+ pub makechrootpkg_bin: String,
+ /// Path to mkarchroot.
+ pub mkarchroot_bin: String,
+ /// Path to repo-add.
+ pub repo_add_bin: String,
+ /// Path to gpg.
+ pub gpg_bin: String,
+ /// Unprivileged user that runs PKGBUILD code (§14). Empty = current user.
+ pub build_user: String,
+ /// Directory prepended to PATH for child processes. The test harness puts
+ /// the toolchain shims here (§16a).
+ pub path_prepend: Option<PathBuf>,
+}
+
+impl Default for Config {
+ fn default() -> Self {
+ Self {
+ root: PathBuf::from("/var/lib/aur-build"),
+ repo_name: "aur-build".into(),
+ arch: "x86_64".into(),
+ signing_key_id: String::new(),
+ bind: "127.0.0.1:8484".into(),
+ password: String::new(),
+ base_url: "http://127.0.0.1:8484".into(),
+ build_profile: "extra-x86_64".into(),
+ git_bin: "git".into(),
+ makepkg_bin: "makepkg".into(),
+ makechrootpkg_bin: "makechrootpkg".into(),
+ mkarchroot_bin: "mkarchroot".into(),
+ repo_add_bin: "repo-add".into(),
+ gpg_bin: "gpg".into(),
+ build_user: String::new(),
+ path_prepend: None,
+ }
+ }
+}
+
+impl Config {
+ pub fn load(root: &Path) -> anyhow::Result<Self> {
+ let p = root.join("config.json");
+ if !p.exists() {
+ anyhow::bail!("no config at {}; run `aur-build init`", p.display());
+ }
+ let s = std::fs::read_to_string(&p)?;
+ let mut cfg: Config = serde_json::from_str(&s)?;
+ // root inside the config file is relative to the config's directory
+ // unless it is absolute; that keeps a moved tree usable.
+ if !cfg.root.is_absolute() {
+ cfg.root = root.join(&cfg.root);
+ }
+ Ok(cfg)
+ }
+
+ pub fn save(&self) -> anyhow::Result<()> {
+ std::fs::create_dir_all(&self.root)?;
+ std::fs::write(
+ self.root.join("config.json"),
+ serde_json::to_string_pretty(self)? + "\n",
+ )?;
+ Ok(())
+ }
+
+ /// Create the directory tree the server needs. Idempotent.
+ pub fn ensure_dirs(&self) -> anyhow::Result<()> {
+ for d in [
+ self.root.clone(),
+ self.mirrors_dir(),
+ self.vcs_cache_dir(),
+ self.source_cache_dir(),
+ self.staging_dir(),
+ self.store_dir(),
+ self.log_dir(),
+ self.repo_dir(),
+ self.chroot_dir(),
+ ] {
+ std::fs::create_dir_all(d)?;
+ }
+ std::fs::create_dir_all(self.repo_arch_dir())?;
+ Ok(())
+ }
+
+ pub fn db_path(&self) -> PathBuf {
+ self.root.join("aur-build.db")
+ }
+ /// Local AUR git mirrors, one clone per pkgbase (§5.1). Load-bearing, not a
+ /// cache: it is what makes historical releases rebuildable (§5.1a).
+ pub fn mirrors_dir(&self) -> PathBuf {
+ self.root.join("mirrors")
+ }
+ pub fn mirror_path(&self, pkgbase: &str) -> PathBuf {
+ self.mirrors_dir().join(format!("{pkgbase}.git"))
+ }
+ /// Persistent upstream VCS clones (§5.2 cost control).
+ pub fn vcs_cache_dir(&self) -> PathBuf {
+ self.root.join("vcs_cache")
+ }
+ pub fn vcs_cache_path(&self, url: &str) -> PathBuf {
+ let h = crate::hash::short(url.as_bytes(), 16);
+ self.vcs_cache_dir().join(format!("{}-{}.git", slug(url), h))
+ }
+ /// Content-addressed download cache reused by the build (§5.3).
+ pub fn source_cache_dir(&self) -> PathBuf {
+ self.root.join("source_cache")
+ }
+ pub fn source_cache_path(&self, digest: &str) -> PathBuf {
+ self.source_cache_dir().join(&digest[..2.min(digest.len())]).join(digest)
+ }
+ /// Disposable per-build workspace (§8.2).
+ pub fn staging_dir(&self) -> PathBuf {
+ self.root.join("staging")
+ }
+ pub fn staging_build_dir(&self, build_id: &str) -> PathBuf {
+ self.staging_dir().join(build_id)
+ }
+ /// Content-addressed artifact store.
+ pub fn store_dir(&self) -> PathBuf {
+ self.root.join("store")
+ }
+ pub fn store_path(&self, digest: &str) -> PathBuf {
+ self.store_dir().join(&digest[..2.min(digest.len())]).join(digest)
+ }
+ pub fn log_dir(&self) -> PathBuf {
+ self.root.join("logs")
+ }
+ pub fn build_log_path(&self, build_id: &str) -> PathBuf {
+ self.log_dir().join(format!("{build_id}.log"))
+ }
+ /// The served repo tree: `<repo>/<name>/os/<arch>/` (§9).
+ pub fn repo_dir(&self) -> PathBuf {
+ self.root.join("repo")
+ }
+ pub fn repo_arch_dir(&self) -> PathBuf {
+ self.repo_dir()
+ .join(&self.repo_name)
+ .join("os")
+ .join(&self.arch)
+ }
+ pub fn repo_db_name(&self) -> String {
+ format!("{}.db", self.repo_name)
+ }
+ /// Warm chroot seeds, one per profile (§8.3).
+ pub fn chroot_dir(&self) -> PathBuf {
+ self.root.join("chroot")
+ }
+ pub fn chroot_seed(&self, profile: &str) -> PathBuf {
+ self.chroot_dir().join(profile)
+ }
+}
+
+/// Filesystem-safe slug for a URL, used in cache filenames.
+pub fn slug(url: &str) -> String {
+ url.chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() {
+ c.to_ascii_lowercase()
+ } else {
+ '-'
+ }
+ })
+ .collect::<String>()
+ .trim_matches('-')
+ .chars()
+ .take(32)
+ .collect()
+}
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))
+ })
+}
diff --git a/src/error.rs b/src/error.rs
new file mode 100644
index 0000000..a60843c
--- /dev/null
+++ b/src/error.rs
@@ -0,0 +1,70 @@
+//! Error type shared across the application.
+
+use std::fmt;
+
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ #[error("io: {0}")]
+ Io(#[from] std::io::Error),
+ #[error("json: {0}")]
+ Json(#[from] serde_json::Error),
+ #[error("sqlite: {0}")]
+ Db(String),
+ #[error("sqlite: {0}")]
+ Sqlite(#[from] rusqlite::Error),
+ #[error("git: {0}")]
+ Git(String),
+ #[error("http fetch: {0}")]
+ Http(String),
+ #[error("child process {cmd}: {detail}")]
+ Subprocess { cmd: String, detail: String },
+ /// A fail-closed assertion. Everything that guards "we build what we reviewed"
+ /// raises this: recipe_hash mismatch, pkgver mismatch, missing approval.
+ #[error("assertion failed: {0}")]
+ FailClosed(String),
+ #[error("not found: {0}")]
+ NotFound(String),
+ #[error("conflict: {0}")]
+ Conflict(String),
+ #[error("invalid: {0}")]
+ Invalid(String),
+ #[error("blocked: {0}")]
+ Blocked(String),
+ #[error("{0}")]
+ Other(String),
+}
+
+impl Error {
+ pub fn db(s: impl fmt::Display) -> Self {
+ Error::Db(s.to_string())
+ }
+ pub fn git(s: impl fmt::Display) -> Self {
+ Error::Git(s.to_string())
+ }
+ pub fn fail_closed(s: impl fmt::Display) -> Self {
+ Error::FailClosed(s.to_string())
+ }
+ pub fn not_found(s: impl fmt::Display) -> Self {
+ Error::NotFound(s.to_string())
+ }
+ pub fn conflict(s: impl fmt::Display) -> Self {
+ Error::Conflict(s.to_string())
+ }
+ pub fn invalid(s: impl fmt::Display) -> Self {
+ Error::Invalid(s.to_string())
+ }
+ pub fn blocked(s: impl fmt::Display) -> Self {
+ Error::Blocked(s.to_string())
+ }
+ pub fn other(s: impl fmt::Display) -> Self {
+ Error::Other(s.to_string())
+ }
+
+ /// True when a retry could plausibly help (network, mirror 5xx). Deterministic
+ /// build failures must not auto-retry (§8.4).
+ pub fn is_transient(&self) -> bool {
+ matches!(self, Error::Http(_) | Error::Io(_))
+ }
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
diff --git a/src/hash.rs b/src/hash.rs
new file mode 100644
index 0000000..5243520
--- /dev/null
+++ b/src/hash.rs
@@ -0,0 +1,78 @@
+//! Hashing helpers. `sha256` hex strings are the currency of identity and
+//! provenance throughout the system (DESIGN.md §3, §5.3).
+
+use sha2::{Digest, Sha256};
+use std::io::{self, Read, Write};
+
+pub const EMPTY: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
+
+pub fn hex(bytes: &[u8]) -> String {
+ let mut h = Sha256::new();
+ h.update(bytes);
+ hex::encode(h.finalize())
+}
+
+pub fn hex_str(s: &str) -> String {
+ hex(s.as_bytes())
+}
+
+/// First `n` hex chars — enough for display, not for identity.
+pub fn short(bytes: &[u8], n: usize) -> String {
+ let h = hex(bytes);
+ h[..n.min(h.len())].to_string()
+}
+
+/// Stream-hash a reader, optionally teeing every byte into `sink`.
+///
+/// Used to hash a download while writing it into the source cache, so the
+/// bandwidth is paid for once (§5.3 "stream-hash, don't buffer").
+pub fn digest_reader<R: Read>(mut r: R, mut sink: Option<&mut dyn Write>) -> io::Result<(String, u64)> {
+ let mut h = Sha256::new();
+ let mut buf = vec![0u8; 64 * 1024];
+ let mut total = 0u64;
+ loop {
+ let n = r.read(&mut buf)?;
+ if n == 0 {
+ break;
+ }
+ h.update(&buf[..n]);
+ if let Some(s) = sink.as_mut() {
+ s.write_all(&buf[..n])?;
+ }
+ total += n as u64;
+ }
+ Ok((hex::encode(h.finalize()), total))
+}
+
+pub fn digest_file(path: &std::path::Path) -> io::Result<(String, u64)> {
+ let f = std::fs::File::open(path)?;
+ let mut br = io::BufReader::new(f);
+ digest_reader(&mut br, None)
+}
+
+/// Hash of a canonical, sorted list of `(path, blob_hash)` pairs.
+///
+/// This is `recipe_hash` (DESIGN.md §3): a digest over *every* file in the AUR
+/// snapshot tree — PKGBUILD, .SRCINFO, *.install and any shipped patches or
+/// assets — because a patch file shipped in the AUR repo is part of the recipe
+/// and is a classic silent-change vector.
+pub fn recipe_hash(entries: &[(String, String)]) -> String {
+ let mut sorted: Vec<&(String, String)> = entries.iter().collect();
+ sorted.sort_unstable_by(|a, b| a.0.cmp(&b.0));
+ let mut h = Sha256::new();
+ for (path, blob) in &sorted {
+ h.update(path.as_bytes());
+ h.update([0u8]);
+ h.update(blob.as_bytes());
+ h.update([0u8]);
+ }
+ hex::encode(h.finalize())
+}
+
+/// Canonical JSON used for identity digests. Key order in serde_json maps is
+/// not stable across object construction, so we serialize through a
+/// `BTreeMap`-preserving path: callers pass already-canonical values (arrays of
+/// objects with a fixed field order) and we hash the compact rendering.
+pub fn canonical_json<T: serde::Serialize>(v: &T) -> String {
+ serde_json::to_string(v).unwrap_or_else(|_| "{}".into())
+}
diff --git a/src/lib.rs b/src/lib.rs
index 77aa7d7..f87c598 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -1 +1,15 @@
//! AUR Build Server — see DESIGN.md.
+//!
+//! One process, many threads, no async. The write path is: watcher detects a
+//! change → candidate → human approval → build pipeline → atomic publish into a
+//! signed pacman repo. Nothing reaches a consumer without an approval row
+//! behind it (I1).
+
+pub mod config;
+pub mod db;
+pub mod error;
+pub mod hash;
+pub mod pkgver;
+pub mod time;
+
+pub use error::{Error, Result};
diff --git a/src/pkgver/mod.rs b/src/pkgver/mod.rs
new file mode 100644
index 0000000..a940dc0
--- /dev/null
+++ b/src/pkgver/mod.rs
@@ -0,0 +1,273 @@
+//! Version comparison and dependency-string parsing.
+//!
+//! Hand-written rather than bound to libalpm (DESIGN.md §4). The algorithm is
+//! the ALPM one and is fully specified: compare epoch numerically, then compare
+//! `pkgver` chunk-wise, then `pkgrel` chunk-wise. A chunk is a maximal run of
+//! digits or a maximal run of non-digits; non-alphanumeric characters are
+//! ignored. A numeric chunk always sorts before an alphabetic chunk, so `1.5`
+//! < `1.5a` and `1.1` < `1.a`.
+
+use std::cmp::Ordering;
+use std::fmt;
+
+/// `epoch:pkgver-pkgrel` as pacman displays it, with the epoch omitted when 0.
+pub fn full_version(epoch: &str, pkgver: &str, pkgrel: &str) -> String {
+ let e = epoch.trim();
+ if e.is_empty() || e == "0" {
+ format!("{pkgver}-{pkgrel}")
+ } else {
+ format!("{e}:{pkgver}-{pkgrel}")
+ }
+}
+
+/// Parse a full `epoch:pkgver-pkgrel` string back into its parts.
+pub fn split_full_version(v: &str) -> (String, String, String) {
+ let (epoch, rest) = match v.split_once(':') {
+ Some((e, r)) => (e.to_string(), r.to_string()),
+ None => ("0".to_string(), v.to_string()),
+ };
+ match rest.rsplit_once('-') {
+ Some((pv, pr)) => (epoch, pv.to_string(), pr.to_string()),
+ None => (epoch, rest, "1".to_string()),
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Version {
+ pub epoch: String,
+ pub pkgver: String,
+ pub pkgrel: String,
+}
+
+impl fmt::Display for Version {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", full_version(&self.epoch, &self.pkgver, &self.pkgrel))
+ }
+}
+
+impl Version {
+ pub fn parse(v: &str) -> Self {
+ let (epoch, pkgver, pkgrel) = split_full_version(v);
+ Self { epoch, pkgver, pkgrel }
+ }
+ pub fn cmp_full(&self, other: &Version) -> Ordering {
+ compare(self.epoch_as_i64(), &self.pkgver, &self.pkgrel, other.epoch_as_i64(), &other.pkgver, &other.pkgrel)
+ }
+ pub fn epoch_as_i64(&self) -> i64 {
+ self.epoch.trim().parse().unwrap_or(0)
+ }
+ pub fn display(&self) -> String {
+ self.to_string()
+ }
+}
+
+/// Compare `epoch:pkgver-pkgrel` triples the way pacman does.
+pub fn compare(
+ epoch_a: i64,
+ pkgver_a: &str,
+ pkgrel_a: &str,
+ epoch_b: i64,
+ pkgver_b: &str,
+ pkgrel_b: &str,
+) -> Ordering {
+ match epoch_a.cmp(&epoch_b) {
+ Ordering::Equal => {}
+ o => return o,
+ }
+ match vercmp_string(pkgver_a, pkgver_b) {
+ Ordering::Equal => vercmp_string(pkgrel_a, pkgrel_b),
+ o => o,
+ }
+}
+
+/// Compare two full version strings (`1.2.3-1`, `1:2-3`).
+pub fn vercmp(a: &str, b: &str) -> Ordering {
+ let va = Version::parse(a);
+ let vb = Version::parse(b);
+ va.cmp_full(&vb)
+}
+
+#[derive(Debug, PartialEq, Eq)]
+enum Chunk<'a> {
+ Num(u128),
+ Alpha(&'a str),
+}
+
+/// Split into maximal digit / alpha runs, ignoring everything else.
+fn chunks(s: &str) -> Vec<Chunk<'_>> {
+ let b = s.as_bytes();
+ let mut out = Vec::new();
+ let mut i = 0;
+ while i < b.len() {
+ let c = b[i] as char;
+ if c.is_ascii_digit() {
+ let start = i;
+ while i < b.len() && (b[i] as char).is_ascii_digit() {
+ i += 1;
+ }
+ // Leading zeros are not significant.
+ let digits = s[start..i].trim_start_matches('0');
+ out.push(Chunk::Num(digits.parse::<u128>().unwrap_or(0)));
+ } else if c.is_ascii_alphabetic() {
+ let start = i;
+ while i < b.len() && (b[i] as char).is_ascii_alphabetic() {
+ i += 1;
+ }
+ out.push(Chunk::Alpha(&s[start..i]));
+ } else {
+ i += 1;
+ }
+ }
+ out
+}
+
+/// ALPM's `vercmp_string`: chunk-wise comparison where digits precede letters.
+pub fn vercmp_string(a: &str, b: &str) -> Ordering {
+ let ca = chunks(a);
+ let cb = chunks(b);
+ let mut i = 0;
+ loop {
+ match (ca.get(i), cb.get(i)) {
+ (None, None) => return Ordering::Equal,
+ (None, Some(Chunk::Num(_))) => return Ordering::Less,
+ (None, Some(Chunk::Alpha(_))) => return Ordering::Greater,
+ (Some(Chunk::Num(_)), None) => return Ordering::Greater,
+ (Some(Chunk::Alpha(_)), None) => return Ordering::Less,
+ (Some(x), Some(y)) => {
+ let o = match (x, y) {
+ (Chunk::Num(x), Chunk::Num(y)) => x.cmp(y),
+ (Chunk::Alpha(x), Chunk::Alpha(y)) => x.cmp(y),
+ // A numeric chunk is always older than an alphabetic one.
+ (Chunk::Num(_), Chunk::Alpha(_)) => Ordering::Less,
+ (Chunk::Alpha(_), Chunk::Num(_)) => Ordering::Greater,
+ };
+ if o != Ordering::Equal {
+ return o;
+ }
+ i += 1;
+ }
+ }
+ }
+}
+
+/// True if `new` is a downgrade relative to `current` (§16: maintainer reverted).
+pub fn is_downgrade(current: &str, new: &str) -> bool {
+ vercmp(current, new) == Ordering::Greater
+}
+
+/// True if `new` is exactly equal to `current` in the pacman sense.
+pub fn same_version(current: &str, new: &str) -> bool {
+ vercmp(current, new) == Ordering::Equal
+}
+
+// ------------------------------------------------------------- dep strings --
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum DepOp {
+ /// `foo`
+ Any,
+ /// `foo=1.2`
+ Eq,
+ /// `foo>=1.2`
+ Ge,
+ /// `foo<=1.2`
+ Le,
+ /// `foo>1.2`
+ Gt,
+ /// `foo<1.2`
+ Lt,
+}
+
+impl fmt::Display for DepOp {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.write_str(match self {
+ DepOp::Any => "",
+ DepOp::Eq => "=",
+ DepOp::Ge => ">=",
+ DepOp::Le => "<=",
+ DepOp::Gt => ">",
+ DepOp::Lt => "<",
+ })
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Dep {
+ pub name: String,
+ pub op: DepOp,
+ pub version: Option<String>,
+}
+
+impl Dep {
+ /// Parse one dependency string, e.g. `python>=3.11`, `gcc`, `foo=1.2-3`.
+ ///
+ /// Returns `None` for an empty or malformed string rather than failing the
+ /// whole recipe: a weird `optdepends` line must not break detection.
+ pub fn parse(s: &str) -> Option<Dep> {
+ let s = s.trim();
+ if s.is_empty() {
+ return None;
+ }
+ // optdepends carry a `: description` suffix.
+ let s = match s.split_once(':') {
+ Some((head, _desc)) if !head.contains(['>', '<', '=']) => head,
+ _ => s,
+ };
+ for (tok, op) in [
+ (">=", DepOp::Ge),
+ ("<=", DepOp::Le),
+ ("=", DepOp::Eq),
+ (">", DepOp::Gt),
+ ("<", DepOp::Lt),
+ ] {
+ if let Some((name, ver)) = s.split_once(tok) {
+ let name = name.trim();
+ if name.is_empty() {
+ return None;
+ }
+ return Some(Dep {
+ name: name.to_string(),
+ op,
+ version: Some(ver.trim().to_string()),
+ });
+ }
+ }
+ Some(Dep { name: s.trim().to_string(), op: DepOp::Any, version: None })
+ }
+
+ /// The bare package name, which is what we resolve against our index.
+ pub fn name(&self) -> &str {
+ &self.name
+ }
+
+ /// Does a candidate version satisfy this constraint?
+ pub fn satisfied_by(&self, version: &str) -> bool {
+ match self.op {
+ DepOp::Any => true,
+ DepOp::Eq => vercmp(version, self.version.as_deref().unwrap_or("0")) == Ordering::Equal,
+ DepOp::Ge => vercmp(version, self.version.as_deref().unwrap_or("0")) != Ordering::Less,
+ DepOp::Le => vercmp(version, self.version.as_deref().unwrap_or("0")) != Ordering::Greater,
+ DepOp::Gt => vercmp(version, self.version.as_deref().unwrap_or("0")) == Ordering::Greater,
+ DepOp::Lt => vercmp(version, self.version.as_deref().unwrap_or("0")) == Ordering::Less,
+ }
+ }
+}
+
+impl fmt::Display for Dep {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match &self.version {
+ Some(v) => write!(f, "{}{}{}", self.name, self.op, v),
+ None => write!(f, "{}", self.name),
+ }
+ }
+}
+
+/// Parse a whole `depends=()` style list, dropping unparseable entries.
+pub fn parse_deps(list: &[String]) -> Vec<Dep> {
+ list.iter().filter_map(|s| Dep::parse(s)).collect()
+}
+
+/// Strip a `name=version` constraint down to the name, for index resolution.
+pub fn dep_names(list: &[String]) -> Vec<String> {
+ parse_deps(list).into_iter().map(|d| d.name).collect()
+}
diff --git a/src/time.rs b/src/time.rs
new file mode 100644
index 0000000..69fbc3c
--- /dev/null
+++ b/src/time.rs
@@ -0,0 +1,69 @@
+//! Clock helpers.
+//!
+//! DESIGN.md §16: "use DB time (`strftime` at write) for all ordering and audit
+//! stamps". We store timestamps as UTC ISO-8601 with second resolution so that
+//! lexicographic ordering equals chronological ordering, and every write path
+//! funnels through [`now`] so a test can pin the clock.
+
+use chrono::{DateTime, SecondsFormat, TimeZone, Utc};
+
+/// Current time as a canonical DB timestamp: `2026-11-17T20:43:24Z`.
+pub fn now() -> String {
+ // A test may pin the clock (see `pin`); production reads the real clock.
+ if let Some(pinned) = pinned() {
+ return pinned;
+ }
+ fmt(Utc::now())
+}
+
+fn fmt(t: DateTime<Utc>) -> String {
+ t.to_rfc3339_opts(SecondsFormat::Secs, true)
+}
+
+fn pinned() -> Option<String> {
+ CLOCK.with(|c| c.borrow().clone())
+}
+
+thread_local! {
+ static CLOCK: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
+}
+
+/// Pin the clock for the current thread (tests only). Returns the previous value.
+pub fn pin(ts: &str) -> Option<String> {
+ CLOCK.with(|c| {
+ let mut slot = c.borrow_mut();
+ (*slot).replace(ts.to_string())
+ })
+}
+
+/// Unpin the clock for the current thread.
+pub fn unpin() {
+ CLOCK.with(|c| *c.borrow_mut() = None);
+}
+
+/// Parse a DB timestamp back into a `DateTime<Utc>`.
+pub fn parse(ts: &str) -> Option<DateTime<Utc>> {
+ DateTime::parse_from_rfc3339(ts)
+ .ok()
+ .map(|d| d.with_timezone(&Utc))
+ .or_else(|| {
+ chrono::NaiveDateTime::parse_from_str(ts, "%Y-%m-%d %H:%M:%S")
+ .ok()
+ .map(|n| Utc.from_utc_datetime(&n))
+ })
+}
+
+/// Whole seconds between two timestamps (`b - a`), or `None` if unparseable.
+pub fn delta_secs(a: &str, b: &str) -> Option<i64> {
+ Some(parse(b)?.signed_duration_since(parse(a)?).num_seconds())
+}
+
+/// A timestamp `secs` seconds in the past, canonical format.
+pub fn secs_ago(secs: i64) -> String {
+ fmt(Utc::now() - chrono::Duration::seconds(secs))
+}
+
+/// A timestamp `secs` seconds in the future, canonical format.
+pub fn secs_ahead(secs: i64) -> String {
+ fmt(Utc::now() + chrono::Duration::seconds(secs))
+}