diff options
Diffstat (limited to 'tests/ops.rs')
| -rw-r--r-- | tests/ops.rs | 381 |
1 files changed, 381 insertions, 0 deletions
diff --git a/tests/ops.rs b/tests/ops.rs new file mode 100644 index 0000000..305976e --- /dev/null +++ b/tests/ops.rs @@ -0,0 +1,381 @@ +//! Retention, metrics and backups (§15). +//! +//! These are the features that only get tested when something goes wrong, which +//! is why they are specified here as behaviour rather than as functions that +//! exist. The load-bearing claims: retention never evicts a byte the index is +//! serving, it treats a package and its log and its sources as one unit, and it +//! never deletes the history that explains the bytes. Metrics are computed from +//! live state, so they cannot drift. Backups are `VACUUM INTO`, so they restore. + +mod common; + +use std::path::{Path, PathBuf}; + +use aur_build::ops; +use aur_build::pipeline; +use aur_build::review::{candidates, diff}; +use common::*; + +fn approve_and_build(env: &Env, name: &str) { + aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap(); + let c = candidates::pending_candidates(&env.db).unwrap().remove(0); + let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); + let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); + aur_build::review::approve::approve(&env.db, "t", c.id, &c.identity_hash, &dd, None).unwrap(); + let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); + let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); + pipeline::run(&env.cfg, &env.db, &id).unwrap(); +} + +/// Publish the same pkgbase N times, each at a higher version. +fn publish_versions(env: &Env, fx: &Fixture, name: &str, n: usize) { + approve_and_build(env, name); + for i in 1..n { + fx.bump(&[("pkgver", &format!("1.{i}"))]); + approve_and_build(env, name); + } +} + +fn artifact_paths(env: &Env) -> Vec<PathBuf> { + env.db + .read(|c| { + let mut st = c.prepare("SELECT path FROM artifact ORDER BY id")?; + let rows = st.query_map([], |r| r.get::<_, String>(0))?; + let mut out = Vec::new(); + for r in rows { + out.push(PathBuf::from(r?)); + } + Ok::<_, aur_build::Error>(out) + }) + .unwrap() +} + +#[test] +fn retention_keeps_the_newest_n_versions_and_never_deletes_a_row() { + let (env, fx) = env_with_fixture("plain-make"); + publish_versions(&env, &fx, "plain-make", 5); + let before = artifact_paths(&env); + assert_eq!(before.len(), 5, "five published versions"); + for p in &before { + assert!(p.exists(), "every published artifact should be on disk: {}", p.display()); + } + + let report = ops::retention(&env.cfg, &env.db, Some(2)).unwrap(); + assert_eq!(report.releases_evicted, 3, "5 versions, keep 2: {report:?}"); + assert!(report.files_removed >= 3, "each evicted release removes its package: {report:?}"); + + // The newest two survive; the older three lose their bytes. + let kept: Vec<PathBuf> = env + .db + .read(|c| { + let mut st = c.prepare("SELECT path FROM artifact WHERE purged_at IS NULL ORDER BY id")?; + let rows = st.query_map([], |r| r.get::<_, String>(0))?; + let mut out = Vec::new(); + for r in rows { + out.push(PathBuf::from(r?)); + } + Ok::<_, aur_build::Error>(out) + }) + .unwrap(); + assert_eq!(kept.len(), 2, "exactly the keep window survives: {kept:?}"); + for p in &kept { + assert!(p.exists(), "a retained artifact must still be on disk: {}", p.display()); + } + for p in before.iter().rev().skip(2) { + assert!(!p.exists(), "an evicted artifact should be gone: {}", p.display()); + } + + // Nothing was forgotten: the rows are all still there, marked as purged + // rather than removed, so "which bytes produced this" stays answerable as + // history even once the bytes are gone. + assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(5)); + assert_eq!(env.query_i64("SELECT count(*) FROM artifact", &[]), Some(5)); + assert_eq!( + env.query_i64("SELECT count(*) FROM artifact WHERE purged_at IS NOT NULL", &[]), + Some(3) + ); + assert_eq!( + env.query_i64("SELECT count(*) FROM release WHERE purged_at IS NOT NULL", &[]), + Some(3) + ); + // And the run itself is on the record. + assert_eq!(env.query_i64("SELECT count(*) FROM gc_run", &[]), Some(1)); + assert!(env.query_i64("SELECT count(*) FROM audit WHERE action='retention'", &[]) == Some(1)); +} + +#[test] +fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() { + let (env, fx) = env_with_fixture("plain-make"); + publish_versions(&env, &fx, "plain-make", 4); + let oldest = env + .db + .read(|c| { + Ok(c.query_row( + "SELECT id FROM release WHERE state='published' ORDER BY id LIMIT 1", + [], + |r| r.get::<_, i64>(0), + )?) + }) + .unwrap(); + let files = ops::release_files(&env.cfg, &env.db, oldest).unwrap(); + // Compare against what the database says the release holds, rather than + // guessing from filename shapes: the store is content-addressed, so the + // package file is a bare hex name and "does it look like a package" is not + // a question the path can answer. + let held: Vec<(Option<String>, Option<String>, Option<String>)> = env + .db + .read(|c| { + let mut st = c.prepare( + "SELECT a.path, a.signature_path, a.build_log_path FROM artifact a + JOIN package p ON p.artifact_id = a.id WHERE p.release_id = ?1", + )?; + let rows = st.query_map(rusqlite::params![oldest], |r| { + Ok((r.get::<_, Option<String>>(0)?, r.get::<_, Option<String>>(1)?, r.get::<_, Option<String>>(2)?)) + })?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok::<_, aur_build::Error>(out) + }) + .unwrap(); + assert_eq!(held.len(), 1, "one artifact for this release: {held:?}"); + let (pkg, sig, log) = &held[0]; + for (what, p) in [("package", pkg), ("signature", sig), ("build log", log)] { + let p = p.as_ref().unwrap_or_else(|| panic!("the release should hold a {what}")); + assert!( + files.iter().any(|f| f == Path::new(p)), + "release_files must include the {what} ({p}): {files:?}" + ); + assert!(Path::new(p).exists(), "the {what} should exist before eviction"); + } + + // Eviction removes them together. A package whose log is gone but whose bytes + // remain is the worst outcome: full price, no explanation. + ops::retention(&env.cfg, &env.db, Some(1)).unwrap(); + let still_there: Vec<&PathBuf> = files.iter().filter(|f| f.exists()).collect(); + assert!( + still_there.is_empty(), + "evicting a release must take its log and signature with it: {still_there:?}" + ); +} + +#[test] +fn retention_never_evicts_the_version_the_index_is_serving() { + // The interesting case: the accepted release is *not* the newest one, because + // the newest build has not happened yet. A naive "keep the newest N" would + // delete the bytes the index is pointing at. + let (env, fx) = env_with_fixture("plain-make"); + publish_versions(&env, &fx, "plain-make", 2); + let served = env + .db + .read(|c| { + Ok(c.query_row( + "SELECT a.path FROM artifact a JOIN package p ON p.artifact_id=a.id WHERE p.state='in_index'", + [], + |r| r.get::<_, String>(0), + )?) + }) + .unwrap(); + let served_release = env + .db + .read(|c| { + Ok(c.query_row( + "SELECT p.release_id FROM package p WHERE p.state='in_index' LIMIT 1", + [], + |r| r.get::<_, i64>(0), + )?) + }) + .unwrap(); + + // Publish a third version, then pretend the index still serves the first by + // withdrawing the newer ones from the index. + env.exec("UPDATE package SET state='removed' WHERE state='in_index'", &[]); + env.exec( + "UPDATE package SET state='in_index' WHERE release_id=?1", + &[P::I(served_release)], + ); + let report = ops::retention(&env.cfg, &env.db, Some(1)).unwrap(); + assert!(report.releases_evicted >= 1, "something should have been evicted: {report:?}"); + assert!( + Path::new(&served).exists(), + "retention deleted the artifact the index is serving: {served}" + ); +} + +#[test] +fn staging_dirs_are_swept_only_when_their_build_is_finished() { + let (env, fx) = env_with_fixture("plain-make"); + approve_and_build(&env, "plain-make"); + + // An old dir belonging to a finished build: disposable. + let done = env.cfg.staging_dir().join("finished-build"); + // An old dir with no build row at all: left over from a crash. + let orphan = env.cfg.staging_dir().join("no-such-build"); + // An old dir whose build is still running: NOT disposable, however old it is. + let live = env.cfg.staging_dir().join("live-build"); + for d in [&done, &orphan, &live] { + std::fs::create_dir_all(d).unwrap(); + std::fs::write(d.join("pkg.tar.zst"), vec![b'x'; 4096]).unwrap(); + backdate(d, 7200); + } + env.exec( + "INSERT INTO build (id, pkgbase_id, candidate_id, kind, build_profile, state, attempt, created_at, updated_at) + VALUES ('live-build', 1, 1, 'new_version', 'default', 'running', 1, '2020-01-01T00:00:00Z', '2020-01-01T00:00:00Z')", + &[], + ); + let _ = fx; + + let (swept, freed) = ops::sweep_staging(&env.cfg, &env.db, ops::STAGING_GRACE_SECS).unwrap(); + assert_eq!(swept, 2, "the finished and the orphaned dir go; the running one stays"); + assert_eq!(freed, 8192, "two dirs of 4 KiB each"); + assert!(!done.exists(), "a finished build's staging is disposable"); + assert!(!orphan.exists(), "a staging dir with no build row is abandoned"); + assert!(live.exists(), "a long-running build is not an abandoned one"); +} + +#[test] +fn metrics_reports_the_operating_numbers_in_prometheus_format() { + let (env, fx) = env_with_fixture("plain-make"); + approve_and_build(&env, "plain-make"); + // Leave one review unapproved so there is review debt to measure. + fx.bump(&[("pkgver", "9.9")]); + aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); + // And a queued build that has never run, so queue depth is not vacuously zero. + let c = candidates::pending_candidates(&env.db).unwrap().remove(0); + let _ = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c); + + let m = ops::metrics(&env.cfg, &env.db).unwrap(); + let text = m.to_prometheus(); + + // Every family the contract names, and each one parseable as a Prometheus + // sample: `name{labels} value`, preceded by its TYPE line. + for family in [ + "aurbuild_queue_depth", + "aurbuild_pending_review_candidates", + "aurbuild_pending_review_age_seconds_bucket", + "aurbuild_build_success_rate", + "aurbuild_sqlite_wal_size_bytes", + "aurbuild_builds_total", + "aurbuild_index_packages", + "aurbuild_stale_releases", + ] { + assert!(text.contains(family), "missing metric {family}: {text}"); + } + for line in text.lines().filter(|l| !l.starts_with('#')) { + let tail = line.rsplit(' ').next().unwrap_or(""); + assert!( + tail.parse::<f64>().is_ok(), + "not a prometheus sample: {line:?}" + ); + } + for line in text.lines().filter(|l| l.starts_with("# TYPE")) { + let name = line.split_whitespace().nth(2).unwrap(); + assert!( + text.contains(&format!("{name} ")) || text.contains(&format!("{name}{{")), + "family {name} declared but never sampled" + ); + } + + assert_eq!(m.queue_depth, 1, "one queued build"); + assert_eq!(m.pending_review, 1, "one review waiting"); + assert_eq!(m.review_ages.len(), 1); + assert_eq!(m.succeeded, 1); + assert_eq!(m.failed, 0); + assert!((m.build_success_rate() - 1.0).abs() < 1e-9); + assert!(m.db_bytes > 0, "the database file has a size"); + assert!( + text.contains("aurbuild_pending_review_age_seconds_bucket{le=\"+Inf\"} 1"), + "histograms need a +Inf bucket: {text}" + ); + assert!(text.contains("aurbuild_pending_review_age_seconds_count 1")); + assert!(text.contains("aurbuild_pending_review_age_seconds_sum")); +} + +#[test] +fn a_fresh_install_reports_a_clean_sheet_not_a_division_by_zero() { + // A brand-new install has no builds at all. Success rate has to be something + // an alert rule can read, not NaN and not 0% (which would page). + let env = Env::new(); + let m = ops::metrics(&env.cfg, &env.db).unwrap(); + assert_eq!(m.succeeded + m.failed, 0); + assert!((m.build_success_rate() - 1.0).abs() < 1e-9, "no builds yet should read as healthy"); + assert!(m.to_prometheus().contains("aurbuild_up 1")); +} + +#[test] +fn the_http_metrics_endpoint_serves_scrapeable_text() { + let web = Web::new("plain-make"); + let page = web.get("/metrics"); + assert_eq!(page.status, 200); + assert!(page.body.contains("# TYPE aurbuild_queue_depth gauge")); + assert!(page.body.contains("aurbuild_sqlite_wal_size_bytes")); + // No session needed: a scraper cannot log in. Check it with a bare socket. + let (headers, body) = web.raw_get("/metrics"); + assert!(body.contains("aurbuild_up 1"), "metrics should be reachable unauthenticated"); + let ct = headers + .iter() + .find(|(k, _)| k.eq_ignore_ascii_case("content-type")) + .map(|(_, v)| v.clone()) + .unwrap_or_default(); + assert!(ct.starts_with("text/plain"), "a scraper wants text/plain, got {ct}"); +} + +#[test] +fn backup_is_a_consistent_single_file_that_reopens_and_matches() { + let (env, _fx) = env_with_fixture("plain-make"); + approve_and_build(&env, "plain-make"); + let dest = env.root().join("backup/aur-build.db"); + let out = ops::backup(&env.db, &dest).unwrap(); + assert_eq!(out, dest); + + // A single file: `VACUUM INTO` produces a compacted database with no WAL, so + // the backup is one object that can be copied while the server keeps running. + assert!(dest.exists()); + assert!(!Path::new(&format!("{}-wal", dest.display())).exists(), "a backup must not need a sidecar"); + assert!(!Path::new(&format!("{}-shm", dest.display())).exists()); + + // It is a real database with the same schema and the same crown jewel: the + // approval trail. + let probe = rusqlite::Connection::open(&dest).unwrap(); + let version: i64 = probe.query_row("PRAGMA user_version", [], |r| r.get(0)).unwrap(); + assert!(version >= 8, "the snapshot carries the migrated schema, got {version}"); + let approvals: i64 = probe.query_row("SELECT count(*) FROM approval", [], |r| r.get(0)).unwrap(); + assert_eq!(approvals, 1, "the approval history is the reason backups exist"); + let releases: i64 = probe.query_row("SELECT count(*) FROM release", [], |r| r.get(0)).unwrap(); + assert_eq!(releases, 1); + drop(probe); + + // The live database is untouched and still in WAL mode — the backup did not + // checkpoint it out from under the running server. + let mode: String = env + .db + .read(|c| Ok(c.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))?)) + .unwrap(); + assert_eq!(mode.to_lowercase(), "wal", "the live db should still be WAL"); + assert!(env.query_i64("SELECT count(*) FROM approval", &[]) == Some(1)); +} + +#[test] +fn backup_refuses_to_overwrite_an_existing_snapshot() { + // A backup that silently replaces last week's backup is not a backup; it is a + // way of losing the only copy on the day you need it. + let (env, _fx) = env_with_fixture("plain-make"); + approve_and_build(&env, "plain-make"); + let dest = env.root().join("snap.db"); + ops::backup(&env.db, &dest).unwrap(); + let second = ops::backup(&env.db, &dest); + assert!(second.is_err(), "overwriting an existing backup must be refused"); + assert!(dest.exists(), "the refusal must not have truncated the existing file"); + assert!(std::fs::metadata(&dest).unwrap().len() > 0); +} + +/// Set a directory's mtime into the past, so the grace period can be exercised +/// without sleeping for an hour. +fn backdate(path: &Path, secs: u64) { + let old = std::time::SystemTime::now() - std::time::Duration::from_secs(secs); + for f in std::fs::read_dir(path).into_iter().flatten().flatten() { + let _ = std::fs::File::open(f.path()).and_then(|f| f.set_modified(old)); + } + let _ = std::fs::File::open(path).and_then(|f| f.set_modified(old)); +} |
