From fd3ecf91686b11feea078531baeddb60e6941116 Mon Sep 17 00:00:00 2001 From: aur-build Date: Tue, 17 Nov 2026 20:59:57 +0000 Subject: feat: SQLite schema, migrations, single writer actor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The §11 data model as four migrations, plus the §11a concurrency model: one writer thread owning the write connection (mutations arrive as closures over a crossbeam channel, so SQLITE_BUSY is not part of the design) and thread-local read-only connections under WAL. Invariants that are database guarantees rather than conventions: I7 partial unique index -> at most one pending_review per pkgbase I3 UNIQUE(pkgbase_id, identity_hash) -> no duplicate candidates I10 audit table rejects UPDATE and DELETE by trigger §16 current_accepted_release_id moves only by compare-and-swap Also: vercmp + dependency-string parsing (ALPM algorithm, no libalpm), hash helpers including recipe_hash over the whole AUR tree, the clock helper that stamps every write, and the config/root layout. Part of P0 (DESIGN.md §17). --- tests/common/mod.rs | 177 ++++++++++++++++++++++++++++++++++++++ tests/db.rs | 239 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 416 insertions(+) create mode 100644 tests/common/mod.rs create mode 100644 tests/db.rs (limited to 'tests') diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 0000000..4cf78ec --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,177 @@ +//! Shared test scaffolding: an isolated server root in a tempdir with a migrated +//! database and a running writer actor. + +#![allow(dead_code)] + +use std::path::{Path, PathBuf}; + +use aur_build::config::Config; +use aur_build::db::{self, Db}; + +pub struct Env { + pub tmp: tempfile::TempDir, + pub cfg: Config, + pub db: Db, +} + +impl Env { + pub fn new() -> Self { + let tmp = tempfile::tempdir().expect("tempdir"); + let cfg = Config { + root: tmp.path().to_path_buf(), + signing_key_id: "TESTKEY".into(), + ..Config::default() + }; + cfg.ensure_dirs().expect("ensure_dirs"); + db::migrate(&cfg.db_path()).expect("migrate"); + let db = Db::open_migrated(&cfg.db_path()).expect("open db"); + let rid = db::ensure_repo( + &db.writer, + &cfg.repo_name, + &cfg.repo_arch_dir().display().to_string(), + &cfg.arch, + &cfg.signing_key_id, + ) + .expect("repo row"); + assert!(rid > 0); + Self { tmp, cfg, db } + } + + pub fn root(&self) -> &Path { + self.tmp.path() + } + + pub fn path(&self, p: &str) -> PathBuf { + self.tmp.path().join(p) + } + + /// Insert a pkgbase + active subscription and return the pkgbase id. + pub fn subscribe(&self, name: &str) -> i64 { + let rid = db::repo_id(&self.db).unwrap(); + let url = format!("file://{}/aur/{}.git", self.root().display(), name); + db::subscribe(&self.db.writer, rid, name, &url).unwrap(); + db::get_pkgbase(&self.db, name).unwrap().unwrap().id + } + + /// Drop a row back in via raw SQL (tests need to construct states the API + /// only reaches through several steps). + pub fn exec(&self, sql: &str, params: &[P]) -> usize { + let sql = sql.to_string(); + let params: Vec

= params.to_vec(); + self.db + .writer + .tx(move |tx| { + let refs: Vec<&dyn rusqlite::ToSql> = params + .iter() + .map(|p| match p { + P::I(i) => i as &dyn rusqlite::ToSql, + P::S(s) => s as &dyn rusqlite::ToSql, + }) + .collect(); + Ok(tx.execute(&sql, rusqlite::params_from_iter(refs.iter()))?) + }) + .unwrap() + } + + pub fn query_i64(&self, sql: &str, params: &[P]) -> Option { + let sql = sql.to_string(); + let params: Vec

= params.to_vec(); + self.db + .read(move |c| { + let refs: Vec<&dyn rusqlite::ToSql> = params + .iter() + .map(|p| match p { + P::I(i) => i as &dyn rusqlite::ToSql, + P::S(s) => s as &dyn rusqlite::ToSql, + }) + .collect(); + use rusqlite::OptionalExtension; + Ok(c.query_row(&sql, rusqlite::params_from_iter(refs.iter()), |r| r.get::<_, i64>(0)) + .optional()?) + }) + .unwrap() + } +} + +/// A test parameter. Owned so it can cross the writer-actor channel. +#[derive(Debug, Clone)] +pub enum P { + I(i64), + S(String), +} + +impl From for P { + fn from(i: i64) -> Self { + P::I(i) + } +} +impl From<&str> for P { + fn from(s: &str) -> Self { + P::S(s.to_string()) + } +} +impl From for P { + fn from(s: String) -> Self { + P::S(s) + } +} + +/// Shorthand for building a parameter slice. +pub fn params(v: Vec>) -> Vec

{ + v.into_iter().map(Into::into).collect() +} + +impl Drop for Env { + fn drop(&mut self) { + self.db.writer.shutdown(); + } +} + +/// A minimal PKGBUILD for tests that need recipe bytes without a fixture dir. +pub fn pkgbuild(pkgbase: &str, pkgver: &str, pkgrel: &str, extra: &str) -> String { + format!( + "pkgbase={pkgbase}\npkgver={pkgver}\npkgrel={pkgrel}\npkgdesc=test\narch=(x86_64)\nurl=https://example.invalid\nlicense=(MIT)\n{extra}\nbuild() {{ :\n}}\npackage_{pkgbase}() {{ :\n}}\n" + ) +} + +/// Build a throwaway git repo with the given files and return its path. +pub fn make_git_repo(dir: &Path, files: &[(&str, &str)], msg: &str) -> String { + std::fs::create_dir_all(dir).unwrap(); + git(dir, &["init", "-q", "-b", "master"]); + git(dir, &["config", "user.email", "t@example.invalid"]); + git(dir, &["config", "user.name", "t"]); + for (name, body) in files { + let p = dir.join(name); + if let Some(parent) = p.parent() { + std::fs::create_dir_all(parent).unwrap(); + } + std::fs::write(p, body).unwrap(); + } + git(dir, &["add", "-A"]); + git(dir, &["commit", "-q", "-m", msg]); + git(dir, &["rev-parse", "HEAD"]) +} + +pub fn git_add_commit(dir: &Path, files: &[(&str, &str)], msg: &str) -> String { + for (name, body) in files { + std::fs::write(dir.join(name), body).unwrap(); + } + git(dir, &["add", "-A"]); + git(dir, &["commit", "-q", "-m", msg]); + git(dir, &["rev-parse", "HEAD"]) +} + +pub fn git(dir: &Path, args: &[&str]) -> String { + let out = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .output() + .expect("git"); + assert!( + out.status.success(), + "git {args:?} failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() +} diff --git a/tests/db.rs b/tests/db.rs new file mode 100644 index 0000000..60c9256 --- /dev/null +++ b/tests/db.rs @@ -0,0 +1,239 @@ +//! Schema and writer-actor tests (DESIGN.md §11, §11a). +//! +//! These are the parts of the §2 invariant set that are database guarantees +//! rather than code conventions. + +mod common; + +use common::{params, Env, P}; +use rusqlite::params; + +use aur_build::db; + +fn insert_snapshot(env: &Env, pkgbase_id: i64, commit: &str) -> i64 { + db::put_snapshot( + &env.db.writer, + pkgbase_id, + commit, + &format!("rh-{commit}"), + "{}", + "[]", + ) + .unwrap() +} + +fn insert_candidate(env: &Env, pkgbase_id: i64, snap_id: i64, identity: &str, state: &str) { + env.exec( + "INSERT INTO candidate (pkgbase_id, kind, snapshot_id, pkgver, pkgrel, identity_hash, state, detected_at) + VALUES (?1,'new_version',?2,'1.0','1',?3,?4,'2026-01-01T00:00:00Z')", + &[P::I(pkgbase_id), P::I(snap_id), P::S(identity.into()), P::S(state.into())], + ); +} + +#[test] +fn migrations_apply_from_empty_and_are_idempotent() { + let env = Env::new(); + let v = env + .db + .read(|c| { + Ok(c.pragma_query_value(None, "user_version", |r| r.get::<_, u32>(0))?) + }) + .unwrap(); + assert_eq!(v, 4, "all four migrations applied"); + // Re-running migration over an existing DB is a no-op, not an error. + assert_eq!(db::migrate(&env.cfg.db_path()).unwrap(), 0); + let journal: String = env + .db + .read(|c| Ok(c.pragma_query_value(None, "journal_mode", |r| r.get(0))?)) + .unwrap(); + assert_eq!(journal.to_lowercase(), "wal", "WAL mode (§11a)"); +} + +#[test] +fn default_settings_are_seeded() { + let env = Env::new(); + assert_eq!(db::setting_i64(&env.db, "max_concurrent_builds", 0), 1); + assert_eq!(db::setting_i64(&env.db, "poll_interval", 0), 86400); + assert_eq!(db::setting_i64(&env.db, "retention_versions", 0), 3); + db::set_setting(&env.db.writer, "retention_versions", "5").unwrap(); + assert_eq!(db::setting_i64(&env.db, "retention_versions", 0), 5); +} + +/// I7: a pkgbase has at most one open review, enforced by a partial unique index. +#[test] +fn i7_second_open_review_is_rejected_by_the_database() { + let env = Env::new(); + let pb = env.subscribe("foo"); + let snap = insert_snapshot(&env, pb, "aaaa"); + insert_candidate(&env, pb, snap, "id-1", "pending_review"); + let snap2 = insert_snapshot(&env, pb, "bbbb"); + let err = std::panic::catch_unwind(|| { + insert_candidate(&env, pb, snap2, "id-2", "pending_review"); + }); + assert!(err.is_err(), "second pending_review must fail"); + + // A terminal state frees the slot again. + insert_candidate(&env, pb, snap2, "id-2", "rejected"); + let n: Option = env.query_i64( + "SELECT count(*) FROM candidate WHERE pkgbase_id=?1", + ¶ms(vec![pb]), + ); + assert_eq!(n, Some(2)); +} + +/// Same identity for the same pkgbase must never create a second candidate (I3). +#[test] +fn candidate_identity_is_unique_per_pkgbase() { + let env = Env::new(); + let pb = env.subscribe("foo"); + let s1 = insert_snapshot(&env, pb, "aaaa"); + let s2 = insert_snapshot(&env, pb, "bbbb"); + insert_candidate(&env, pb, s1, "same", "rejected"); + let res = std::panic::catch_unwind(|| insert_candidate(&env, pb, s2, "same", "pending_review")); + assert!(res.is_err(), "UNIQUE(pkgbase_id, identity_hash) must hold"); +} + +/// I10: every state transition is recorded, and the log cannot be rewritten. +#[test] +fn audit_log_is_append_only() { + let env = Env::new(); + db::audit_system(&env.db.writer, "test", "pkgbase", "1", serde_json::json!({"k": 1})).unwrap(); + let id = env + .query_i64("SELECT id FROM audit ORDER BY id DESC LIMIT 1", &[]) + .unwrap(); + assert!( + std::panic::catch_unwind(|| env + .exec("UPDATE audit SET action='x' WHERE id=?1", ¶ms(vec![id]))) + .is_err(), + "audit UPDATE must be refused by trigger" + ); + assert!( + std::panic::catch_unwind(|| env.exec("DELETE FROM audit WHERE id=?1", ¶ms(vec![id]))).is_err(), + "audit DELETE must be refused by trigger" + ); + // Inserts keep working. + db::audit_system(&env.db.writer, "test2", "pkgbase", "1", serde_json::json!({})).unwrap(); +} + +/// §16: concurrent approvals on the same pkgbase are a guarded compare-and-swap. +#[test] +fn accepted_release_pointer_is_compared_and_swapped() { + let env = Env::new(); + let pb = env.subscribe("foo"); + let snap = insert_snapshot(&env, pb, "aaaa"); + insert_candidate(&env, pb, snap, "id-1", "approved"); + let rel = env + .db + .writer + .tx(move |tx| { + tx.execute( + "INSERT INTO release (pkgbase_id, aur_commit, recipe_hash, pkgver, pkgrel, state, created_at) + VALUES (?1,'aaaa','rh','1.0','1','published','2026-01-01T00:00:00Z')", + params![pb], + )?; + Ok(tx.last_insert_rowid()) + }) + .unwrap(); + // First swap from NULL wins, second loses. + assert!(db::cas_accepted_release(&env.db.writer, pb, None, rel).unwrap()); + assert!(!db::cas_accepted_release(&env.db.writer, pb, None, rel).unwrap()); + assert_eq!( + db::get_pkgbase(&env.db, "foo").unwrap().unwrap().current_accepted_release_id, + Some(rel) + ); +} + +/// §11a: WAL lets readers proceed concurrently with the writer. +#[test] +fn many_readers_do_not_block_the_writer() { + let env = std::sync::Arc::new(Env::new()); + let pb = env.subscribe("foo"); + let snap = insert_snapshot(&env, pb, "aaaa"); + insert_candidate(&env, pb, snap, "id-1", "pending_review"); + + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let mut readers = Vec::new(); + for _ in 0..8 { + let db = env.db.clone(); + let stop = stop.clone(); + readers.push( + std::thread::Builder::new() + .name("reader".into()) + .spawn(move || { + let mut n = 0u64; + while !stop.load(std::sync::atomic::Ordering::SeqCst) { + let c = db::setting_i64(&db, "max_concurrent_builds", 0); + assert_eq!(c, 1); + n += 1; + } + n + }) + .unwrap(), + ); + } + // Write while they read: none of these may fail with SQLITE_BUSY. + for i in 0..200 { + db::set_setting(&env.db.writer, &format!("k{i}"), "1").unwrap(); + } + stop.store(true, std::sync::atomic::Ordering::SeqCst); + let total: u64 = readers.into_iter().map(|h| h.join().unwrap()).sum(); + assert!(total > 0, "readers made progress during writes"); +} + +#[test] +fn world_snapshot_dedupes_by_hash() { + let env = Env::new(); + let m = |b: &str, v: &str| db::WorldMember { pkgbase: b.into(), version: v.into() }; + let a = db::put_world_snapshot(&env.db.writer, &[m("foo", "1-1"), m("bar", "2-1")]).unwrap(); + // Order-insensitive: same set, same snapshot. + let b = db::put_world_snapshot(&env.db.writer, &[m("bar", "2-1"), m("foo", "1-1")]).unwrap(); + assert_eq!(a, b); + let members = db::world_members(&env.db, a).unwrap(); + assert_eq!(members.len(), 2); + assert_eq!(members[0].pkgbase, "bar", "members are stored sorted"); +} + +#[test] +fn duplicate_open_notices_are_suppressed() { + let env = Env::new(); + let pb = env.subscribe("foo"); + let detail = serde_json::json!({"old": "a", "new": "b"}); + assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", detail.clone()) + .unwrap() + .is_some()); + assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", detail.clone()) + .unwrap() + .is_none()); + // Acknowledging lets a fresh one through. + let id = env + .query_i64("SELECT id FROM notice ORDER BY id DESC LIMIT 1", &[]) + .unwrap(); + db::acknowledge_notice(&env.db.writer, id).unwrap(); + assert!(db::put_notice_once(&env.db.writer, pb, "pin_drift", "info", detail) + .unwrap() + .is_some()); +} + +#[test] +fn i1_query_flags_index_entries_without_approval() { + let env = Env::new(); + let pb = env.subscribe("foo"); + // A published release with no approval row: exactly the thing I1 forbids. + let rel = env + .db + .writer + .tx(move |tx| { + tx.execute( + "INSERT INTO release (pkgbase_id, aur_commit, recipe_hash, pkgver, pkgrel, state, created_at) + VALUES (?1,'aaaa','rh','1.0','1','published','2026-01-01T00:00:00Z')", + params![pb], + )?; + Ok(tx.last_insert_rowid()) + }) + .unwrap(); + env.exec( + "INSERT INTO package (repo_id, release_id, name, arch, version, state) VALUES (1,?1,'foo','x86_64','1.0-1','in_index')", + ¶ms(vec![rel]), + ); + assert_eq!(db::unapproved_index_entries(&env.db).unwrap(), vec!["foo".to_string()]); +} -- cgit v1.2.3