diff options
| author | aur-build <aur-build@localhost> | 2026-11-18 10:02:04 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-18 10:02:04 +0000 |
| commit | bc63622a1a91f6e1036eb8e6824c04f922e2654e (patch) | |
| tree | 6ca0a3d136ac5c5ba3d8abe89a2bce4b8531803c /src | |
| parent | 5809493be2f6e47e3bbfc8a645ea0d82d5aedd82 (diff) | |
| download | aur-build-bc63622a1a91f6e1036eb8e6824c04f922e2654e.tar.gz aur-build-bc63622a1a91f6e1036eb8e6824c04f922e2654e.zip | |
ops: retention that never lies about what is on disk, metrics that cannot drift, and a backup that restores
Three §15 features, each with a failure mode worth designing against.
**Retention** evicts the files of releases beyond the keep window and never
deletes a row. The artifact keeps its digest, size and provenance and gains a
purged_at, so the record says 'these bytes existed and were dropped at T'
instead of continuing to claim a file that is no longer there. A package, its
signature, its build log and its cached sources are evicted as one unit — a
package whose log is gone but whose bytes remain is the worst outcome: full
price, no explanation. Shared content-addressed files are reference-checked
against every *retained* release first, because two releases built from the same
source share one cached archive and aging one out must not corrupt the other.
The currently accepted release and anything still backing an in_index package are
kept regardless of how far down the list they sit: deleting the bytes the index
is pointing at is the one thing retention must never do.
**Staging sweep** derives 'abandoned' rather than guessing it: the dir's build is
terminal, or has no build row at all, and the dir is older than a grace period.
A dir whose build is running is left alone however old it looks, because a long
build is not an abandoned one.
**Metrics** are computed from live state on every scrape. There are no counters
incremented at event sites, because a counter maintained by every code path is a
counter that quietly drifts the first time a path is added; a query cannot
drift. Includes queue depth, the review-debt age histogram (not just how many
reviews are pending but how stale they are), build success rate, WAL size,
stale counts by reason and staging usage. A fresh install reports success rate
1.0 rather than NaN or 0%, so an empty system does not page anyone. Served at
GET /metrics and by 'aur-build metrics'.
**Backup** uses VACUUM INTO on the writer connection, so it cannot interleave
with a write, and refuses to overwrite an existing file — a backup that silently
replaces last week's backup is a way of losing the only copy on the day you need
it. The snapshot is then reopened and checked for schema version and approval
rows: if it does not open on its own it is a file, not a backup.
New CLI: metrics, gc [--keep N] [--dry-run], backup <path>.
tests/ops.rs: 9 tests. 170 tests pass, clippy clean.
Diffstat (limited to 'src')
| -rw-r--r-- | src/db/migrations.rs | 30 | ||||
| -rw-r--r-- | src/http/mod.rs | 5 | ||||
| -rw-r--r-- | src/http/routes.rs | 19 | ||||
| -rw-r--r-- | src/lib.rs | 1 | ||||
| -rw-r--r-- | src/main.rs | 54 | ||||
| -rw-r--r-- | src/ops.rs | 650 |
6 files changed, 758 insertions, 1 deletions
diff --git a/src/db/migrations.rs b/src/db/migrations.rs index bb8974f..9e60132 100644 --- a/src/db/migrations.rs +++ b/src/db/migrations.rs @@ -319,6 +319,35 @@ CREATE TABLE stage_b_cache ( CREATE INDEX stage_b_cache_by_pkgbase ON stage_b_cache (pkgbase_id, resolved_at); "#; +/// Retention (§15, open question 21). The rows are never compacted — the whole +/// point of the schema is that "which bytes produced this installed package" +/// stays answerable — but the bytes on disk cannot be kept forever. So eviction +/// is recorded rather than implied: the artifact row keeps its digest, size and +/// provenance and gains a `purged_at`, which says "these bytes existed, and were +/// dropped from the store at T" instead of silently pretending they are still +/// there. A `cp` of the store and a database that disagrees about what is on disk +/// is the failure mode this avoids. +const M_0008_RETENTION: &str = r#" +ALTER TABLE artifact ADD COLUMN purged_at TEXT; + +-- Set when a release's files have been evicted; NULL means the bytes are held. +ALTER TABLE release ADD COLUMN purged_at TEXT; + +-- Staging is disposable (§8.2), but "disposable" needs a definition: a dir is +-- swept when its build is terminal or unknown and the dir is older than the +-- grace period. Recording the sweep keeps a crashed-then-swept build auditable. +CREATE TABLE IF NOT EXISTS gc_run ( + id INTEGER PRIMARY KEY, + ran_at TEXT NOT NULL, + releases_kept INTEGER NOT NULL, + releases_evicted INTEGER NOT NULL, + files_removed INTEGER NOT NULL, + bytes_freed INTEGER NOT NULL, + staging_swept INTEGER NOT NULL, + detail_json TEXT NOT NULL DEFAULT '{}' +); +"#; + pub static MIGRATIONS: &[Migration] = &[ Migration { version: 1, name: "core", sql: M_0001_CORE }, Migration { version: 2, name: "build", sql: M_0002_BUILD }, @@ -327,6 +356,7 @@ pub static MIGRATIONS: &[Migration] = &[ Migration { version: 5, name: "artifact-build", sql: M_0005_ARTIFACT_BUILD }, Migration { version: 6, name: "approval-immutable", sql: M_0006_APPROVAL_IMMUTABLE }, Migration { version: 7, name: "stage-b-cache", sql: M_0007_STAGE_B_CACHE }, + Migration { version: 8, name: "retention", sql: M_0008_RETENTION }, ]; /// Default settings seeded into `settings` (DESIGN.md §11). diff --git a/src/http/mod.rs b/src/http/mod.rs index 7ca4875..16ff6b1 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -223,6 +223,11 @@ fn dispatch(state: &State, req: &Req) -> Res { ("GET", ["login"]) => return routes::login_form(state, req), ("POST", ["login"]) => return routes::login(state, req), ("GET", ["healthz"]) => return Res::text(200, "ok\n".into()), + // Metrics are counts only — no package names, no versions, no audit + // detail — and a Prometheus scraper has no session to present. Serving + // them unauthenticated is what makes them scrapeable at all; the bind + // address is loopback by default, which is where that is safe. + ("GET", ["metrics"]) => return routes::metrics(state), _ => {} } diff --git a/src/http/routes.rs b/src/http/routes.rs index 26aaa89..9efb90b 100644 --- a/src/http/routes.rs +++ b/src/http/routes.rs @@ -6,7 +6,7 @@ use crate::db::{self, builds, model::*, Db}; use crate::review::{approve as ap, candidates, diff, risk}; -use crate::{pipeline, time}; +use crate::{ops, pipeline, time}; use super::auth; use super::render::*; @@ -995,6 +995,23 @@ fn audit(state: &State, req: &Req) -> Res { page_to_res(Audit { page, rows }, 200) } +/// `GET /metrics` in Prometheus text exposition format (§12, §15). +/// +/// Everything here is computed from live state on every scrape. There are no +/// counters incremented at event sites, because a counter that has to be +/// maintained by every code path is a counter that quietly drifts the first time +/// a path is added; a query cannot drift. +pub fn metrics(state: &State) -> Res { + match ops::metrics(&state.cfg, &state.db) { + Ok(m) => { + let mut res = Res::text(200, m.to_prometheus()); + res.content_type = "text/plain; version=0.0.4; charset=utf-8".into(); + res + } + Err(e) => Res::text(500, format!("metrics unavailable: {e}\n")), + } +} + fn settings(state: &State, req: &Req) -> Res { let page = chrome(state, req, "Settings", "nav_settings"); let rows = db::all_settings(&state.db) @@ -12,6 +12,7 @@ pub mod fetch; pub mod git; pub mod hash; pub mod http; +pub mod ops; pub mod pipeline; pub mod pkginfo; pub mod pkgver; diff --git a/src/main.rs b/src/main.rs index 7297a96..6df2bd7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -95,6 +95,25 @@ enum Cmd { #[arg(long, default_value_t = 30)] limit: i64, }, + /// Print metrics in Prometheus text format (the same numbers /metrics serves). + Metrics, + /// Drop the files of releases beyond the retention window, and sweep + /// abandoned staging directories. Rows are never deleted (§15). + Gc { + /// Versions per pkgbase whose files are kept. Defaults to the + /// `retention_versions` setting. + #[arg(long)] + keep: Option<usize>, + /// Show what would be removed without removing it. + #[arg(long)] + dry_run: bool, + }, + /// Write a consistent snapshot of the database with `VACUUM INTO`. + Backup { + /// Destination file. It must not already exist: a backup that silently + /// overwrites last week's backup is not a backup. + to: PathBuf, + }, } fn main() -> anyhow::Result<()> { @@ -317,6 +336,41 @@ fn main() -> anyhow::Result<()> { } Ok(()) } + Cmd::Metrics => { + print!("{}", aur_build::ops::metrics(&cfg, &ctx.db)?.to_prometheus()); + Ok(()) + } + Cmd::Gc { keep, dry_run } => { + let keep = keep.unwrap_or(aur_build::ops::DEFAULT_KEEP); + if dry_run { + let (kept, evict) = aur_build::ops::plan_retention(&ctx.db, keep)?; + println!("retention: keep {keep} version(s) per pkgbase"); + println!(" {} release(s) keep their files", kept.len()); + for e in evict { + let files = aur_build::ops::release_files(&cfg, &ctx.db, e.release_id)?; + println!(" release {} would lose {} file(s)", e.release_id, files.len()); + for f in files { + println!(" {}", f.display()); + } + } + return Ok(()); + } + let r = aur_build::ops::retention(&cfg, &ctx.db, Some(keep))?; + println!( + "kept {} release(s), evicted {}, removed {} file(s), freed {} bytes, swept {} staging dir(s)", + r.releases_kept, r.releases_evicted, r.files_removed, r.bytes_freed, r.staging_swept + ); + Ok(()) + } + Cmd::Backup { to } => { + let path = aur_build::ops::backup(&ctx.db, &to)?; + println!( + "wrote {} bytes to {} (VACUUM INTO, single file, no WAL)", + std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0), + path.display() + ); + Ok(()) + } } } diff --git a/src/ops.rs b/src/ops.rs new file mode 100644 index 0000000..e211a95 --- /dev/null +++ b/src/ops.rs @@ -0,0 +1,650 @@ +//! Retention, metrics and backups (§15). +//! +//! Three separate jobs that share one premise: the database is the thing that +//! must survive, and the bytes on disk are the thing that cannot be kept forever. +//! +//! *Retention* evicts files for releases beyond the last N of a pkgbase. It never +//! deletes a row. The artifact keeps its digest, size and provenance and gains a +//! `purged_at`, so the record says "these bytes existed and were dropped at T" +//! rather than continuing to claim a file that is no longer there. +//! +//! *Metrics* are computed on read, like staleness. A counter that has to be +//! incremented on every state change is a counter that drifts. +//! +//! *Backups* use `VACUUM INTO`. Copying a live WAL database with `cp` produces a +//! main file plus a WAL that may or may not belong to it, which is to say a backup +//! that is only sometimes restorable. + +use std::path::{Path, PathBuf}; + +use crate::config::Config; +use crate::db::{self, Db}; +use crate::error::Result; +use crate::time; + +/// Default number of versions kept per pkgbase (§11 `retention_versions`). +pub const DEFAULT_KEEP: usize = 3; + +#[derive(Debug, Default, Clone)] +pub struct RetentionReport { + pub releases_kept: usize, + pub releases_evicted: usize, + pub files_removed: usize, + pub bytes_freed: u64, + pub staging_swept: usize, +} + +/// Everything a metrics scrape reports, computed in one pass over the database. +/// +/// Kept as a struct rather than a string builder so the HTTP handler, the CLI and +/// the tests all read the same numbers from the same source. +#[derive(Debug, Default, Clone)] +pub struct Metrics { + pub builds: Vec<(String, i64)>, + pub queue_depth: i64, + pub oldest_queued_age_secs: i64, + pub pending_review: i64, + /// Age of pending candidates in seconds, already sorted, for bucketing. + pub review_ages: Vec<i64>, + pub succeeded: i64, + pub failed: i64, + pub blocked_missing_dep: i64, + pub index_packages: i64, + pub releases: i64, + pub stale_outdated: i64, + pub stale_missing: i64, + pub downgrades: i64, + pub subscriptions: i64, + pub notices_unseen: i64, + pub db_bytes: u64, + pub wal_bytes: u64, + pub artifact_bytes: u64, + pub staging_dirs: usize, + pub staging_bytes: u64, + pub last_gc_age_secs: Option<i64>, + pub poll_lag_age_secs: Option<i64>, +} + +impl Metrics { + /// Share of recorded builds that published. Reported as 1.0 when nothing has + /// run yet: a fresh install is not a failing install, and an alert rule that + /// reads 0% success on an empty system pages someone for no reason. + pub fn build_success_rate(&self) -> f64 { + match self.succeeded + self.failed { + 0 => 1.0, + n => self.succeeded as f64 / n as f64, + } + } + + /// Render in Prometheus text exposition format. + /// + /// Every family is declared with `# HELP` and `# TYPE` because a scrape that + /// fails validation silently drops the whole payload, not just the bad line. + pub fn to_prometheus(&self) -> String { + let mut o = String::new(); + + o.push_str("# HELP aurbuild_up Always 1: the process answered the scrape.\n# TYPE aurbuild_up gauge\naurbuild_up 1\n"); + o.push_str(&header("aurbuild_queue_depth", "Builds waiting to run.")); + o.push_str(&format!("aurbuild_queue_depth {}\n", self.queue_depth)); + o.push_str(&header("aurbuild_oldest_queued_age_seconds", "How long the oldest queued build has waited.")); + o.push_str(&format!("aurbuild_oldest_queued_age_seconds {}\n", self.oldest_queued_age_secs)); + + o.push_str("# HELP aurbuild_builds_total Builds by state.\n# TYPE aurbuild_builds_total gauge\n"); + for (state, n) in &self.builds { + o.push_str(&format!("aurbuild_builds_total{{state=\"{state}\"}} {n}\n")); + } + + o.push_str(&header("aurbuild_pending_review_candidates", "Reviews waiting on a human — the review debt.")); + o.push_str(&format!("aurbuild_pending_review_candidates {}\n", self.pending_review)); + + // The debt number nobody asks for until it is weeks old: not how many + // reviews are pending, but how stale the pending ones are. + o.push_str("# HELP aurbuild_pending_review_age_seconds Histogram of how long pending reviews have waited.\n# TYPE aurbuild_pending_review_age_seconds histogram\n"); + for le in [3600i64, 21600, 86400, 259200, 604800] { + let n = self.review_ages.iter().filter(|a| **a <= le).count(); + o.push_str(&format!("aurbuild_pending_review_age_seconds_bucket{{le=\"{le}\"}} {n}\n")); + } + o.push_str(&format!( + "aurbuild_pending_review_age_seconds_bucket{{le=\"+Inf\"}} {}\n", + self.review_ages.len() + )); + let sum: i64 = self.review_ages.iter().sum(); + o.push_str(&format!("aurbuild_pending_review_age_seconds_sum {sum}\n")); + o.push_str(&format!("aurbuild_pending_review_age_seconds_count {}\n", self.review_ages.len())); + + o.push_str(&header("aurbuild_builds_succeeded_total", "Builds that published.")); + o.push_str(&format!("aurbuild_builds_succeeded_total {}\n", self.succeeded)); + o.push_str(&header("aurbuild_builds_failed_total", "Builds that failed.")); + o.push_str(&format!("aurbuild_builds_failed_total {}\n", self.failed)); + let rate = self.build_success_rate(); + o.push_str(&header("aurbuild_build_success_rate", "Share of recorded builds that succeeded.")); + o.push_str(&format!("aurbuild_build_success_rate {rate:.4}\n")); + + o.push_str(&header("aurbuild_blocked_missing_dep", "Builds blocked on a package we have not published.")); + o.push_str(&format!("aurbuild_blocked_missing_dep {}\n", self.blocked_missing_dep)); + o.push_str(&header("aurbuild_index_packages", "Packages in the served index.")); + o.push_str(&format!("aurbuild_index_packages {}\n", self.index_packages)); + o.push_str(&header("aurbuild_releases", "Published releases on record.")); + o.push_str(&format!("aurbuild_releases {}\n", self.releases)); + o.push_str(&header("aurbuild_subscriptions", "Subscribed pkgbases.")); + o.push_str(&format!("aurbuild_subscriptions {}\n", self.subscriptions)); + o.push_str(&header("aurbuild_notices_unseen", "Notices no human has looked at.")); + o.push_str(&format!("aurbuild_notices_unseen {}\n", self.notices_unseen)); + + o.push_str("# HELP aurbuild_stale_releases Releases whose recorded world no longer matches the index, by reason.\n# TYPE aurbuild_stale_releases gauge\n"); + o.push_str(&format!("aurbuild_stale_releases{{reason=\"outdated\"}} {}\n", self.stale_outdated)); + o.push_str(&format!("aurbuild_stale_releases{{reason=\"missing\"}} {}\n", self.stale_missing)); + o.push_str(&header("aurbuild_downgrades", "Subscriptions where AUR offers a lower version than we serve.")); + o.push_str(&format!("aurbuild_downgrades {}\n", self.downgrades)); + + o.push_str(&header("aurbuild_sqlite_size_bytes", "Main database file size.")); + o.push_str(&format!("aurbuild_sqlite_size_bytes {}\n", self.db_bytes)); + o.push_str(&header("aurbuild_sqlite_wal_size_bytes", "Write-ahead log size — large means nobody is checkpointing.")); + o.push_str(&format!("aurbuild_sqlite_wal_size_bytes {}\n", self.wal_bytes)); + o.push_str(&header("aurbuild_artifact_bytes", "Bytes held in the content-addressed store.")); + o.push_str(&format!("aurbuild_artifact_bytes {}\n", self.artifact_bytes)); + o.push_str(&header("aurbuild_staging_bytes", "Bytes in disposable staging directories.")); + o.push_str(&format!("aurbuild_staging_bytes {}\n", self.staging_bytes)); + o.push_str(&format!("# TYPE aurbuild_staging_dirs gauge\naurbuild_staging_dirs {}\n", self.staging_dirs)); + + match self.poll_lag_age_secs { + Some(a) => { + o.push_str(&header("aurbuild_poll_lag_seconds", "Seconds since the last successful poll of any source.")); + o.push_str(&format!("aurbuild_poll_lag_seconds {a}\n")); + } + None => { + o.push_str(&header("aurbuild_poll_lag_seconds", "Seconds since the last successful poll of any source.")); + o.push_str("aurbuild_poll_lag_seconds nan\n"); + } + } + match self.last_gc_age_secs { + Some(a) => { + o.push_str(&header("aurbuild_last_gc_age_seconds", "Seconds since the last retention run.")); + o.push_str(&format!("aurbuild_last_gc_age_seconds {a}\n")); + } + None => { + o.push_str(&header("aurbuild_last_gc_age_seconds", "Seconds since the last retention run.")); + o.push_str("aurbuild_last_gc_age_seconds nan\n"); + } + } + o + } +} + +/// Compute every metric from live state. +pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> { + let mut m = Metrics::default(); + let now = time::now(); + + m.builds = db.read(|c| { + let mut st = c.prepare("SELECT state, count(*) FROM build GROUP BY state ORDER BY state")?; + let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i64>(1)?)))?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok::<_, crate::error::Error>(out) + })?; + let count = |state: &str| -> i64 { + m.builds.iter().find(|(s, _)| s == state).map(|(_, n)| *n).unwrap_or(0) + }; + m.queue_depth = count("queued"); + m.succeeded = count("succeeded"); + m.failed = count("failed"); + m.blocked_missing_dep = count("blocked_missing_dep"); + + let oldest = db.read(|c| { + c.query_row( + "SELECT julianday(?1) - julianday(min(created_at)) FROM build WHERE state='queued'", + rusqlite::params![now], + |r| r.get::<_, Option<f64>>(0), + ) + .map(|v| (v.unwrap_or(0.0) * 86400.0) as i64) + .map_err(|e| crate::error::Error::db(e.to_string())) + })?; + m.oldest_queued_age_secs = oldest.max(0); + + m.pending_review = scalar(db, "SELECT count(*) FROM candidate WHERE state='pending_review'")?; + m.review_ages = db.read(|c| { + let mut st = c.prepare("SELECT julianday(?1) - julianday(detected_at) FROM candidate WHERE state='pending_review'")?; + let rows = st.query_map(rusqlite::params![now], |r| r.get::<_, Option<f64>>(0))?; + let mut out = Vec::new(); + for r in rows { + out.push((r?.unwrap_or(0.0) * 86400.0) as i64); + } + Ok::<_, crate::error::Error>(out) + })?; + m.review_ages.sort(); + + m.index_packages = scalar(db, "SELECT count(*) FROM package WHERE state='in_index'")?; + m.releases = scalar(db, "SELECT count(*) FROM release WHERE state='published'")?; + m.subscriptions = scalar(db, "SELECT count(*) FROM subscription")?; + m.notices_unseen = scalar(db, "SELECT count(*) FROM notice WHERE acknowledged_at IS NULL")?; + + let stale = crate::watch::staleness::stale_rows(db)?; + m.stale_outdated = stale.iter().filter(|s| s.kind == crate::watch::staleness::Kind::Outdated).count() as i64; + m.stale_missing = stale.iter().filter(|s| s.kind == crate::watch::staleness::Kind::Missing).count() as i64; + m.downgrades = crate::watch::staleness::downgrades(db)?.len() as i64; + + m.db_bytes = file_len(&cfg.db_path()); + m.wal_bytes = file_len(&PathBuf::from(format!("{}-wal", cfg.db_path().display()))); + m.artifact_bytes = db.read(|c| { + c.query_row( + "SELECT COALESCE(sum(size),0) FROM artifact WHERE purged_at IS NULL", + [], + |r| r.get::<_, i64>(0), + ) + .map(|v| v.max(0) as u64) + .map_err(|e| crate::error::Error::db(e.to_string())) + })?; + let (dirs, bytes) = staging_usage(&cfg.staging_dir()); + m.staging_dirs = dirs; + m.staging_bytes = bytes; + + m.last_gc_age_secs = db + .read(|c| { + c.query_row("SELECT max(ran_at) FROM gc_run", [], |r| r.get::<_, Option<String>>(0)) + .map_err(|e| crate::error::Error::db(e.to_string())) + })? + .and_then(|t| time::delta_secs(&now, &t)); + m.poll_lag_age_secs = db + .read(|c| { + c.query_row("SELECT max(last_checked_at) FROM subscription", [], |r| r.get::<_, Option<String>>(0)) + .map_err(|e| crate::error::Error::db(e.to_string())) + })? + .and_then(|t| time::delta_secs(&now, &t)); + let _ = cfg; + Ok(m) +} + +/// A Prometheus family header. Kept as a function rather than a closure over the +/// output buffer so the borrow checker does not object to interleaving. +fn header(name: &str, help: &str) -> String { + format!("# HELP {name} {help}\n# TYPE {name} gauge\n") +} + +fn scalar(db: &Db, sql: &str) -> Result<i64> { + let sql = sql.to_string(); + db.read(move |c| c.query_row(&sql, [], |r| r.get::<_, i64>(0)).map_err(|e| crate::error::Error::db(e.to_string()))) +} + +fn file_len(p: &Path) -> u64 { + std::fs::metadata(p).map(|m| m.len()).unwrap_or(0) +} + +/// `(dir count, total bytes)` under a directory, tolerating concurrent removal. +fn staging_usage(root: &Path) -> (usize, u64) { + let mut dirs = 0; + let mut bytes = 0; + let Ok(entries) = std::fs::read_dir(root) else { return (0, 0) }; + for e in entries.flatten() { + if e.path().is_dir() { + dirs += 1; + bytes += dir_bytes(&e.path()); + } + } + (dirs, bytes) +} + +fn dir_bytes(path: &Path) -> u64 { + let mut total = 0; + let Ok(entries) = std::fs::read_dir(path) else { return 0 }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + total += dir_bytes(&p); + } else if let Ok(m) = std::fs::metadata(&p) { + total += m.len(); + } + } + total +} + +/// Which releases of a pkgbase keep their files, and which lose them. +/// +/// The rule is "newest N, plus anything that would be a lie to evict": the +/// currently accepted release and any release still backing an `in_index` +/// package are kept regardless of how far down the list they sit. Evicting those +/// would delete the bytes the index is actively pointing at, which is the one +/// thing retention must never do — a rollback target is worth disk, a served +/// package is not optional. +pub fn plan_retention(db: &Db, keep: usize) -> Result<(Vec<i64>, Vec<EvictPlan>)> { + let keep = keep.max(1); + let pkgbases: Vec<(i64, Option<i64>)> = db.read(|c| { + let mut st = c.prepare("SELECT id, current_accepted_release_id FROM pkgbase ORDER BY id")?; + let rows = st.query_map([], |r| Ok((r.get::<_, i64>(0)?, r.get::<_, Option<i64>>(1)?)))?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok::<_, crate::error::Error>(out) + })?; + + let mut kept = Vec::new(); + let mut evict = Vec::new(); + for (pb_id, accepted) in pkgbases { + let releases: Vec<i64> = db.read(|c| { + let mut st = c.prepare( + "SELECT id FROM release WHERE pkgbase_id=?1 AND state='published' ORDER BY id DESC", + )?; + let rows = st.query_map(rusqlite::params![pb_id], |r| r.get::<_, i64>(0))?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok::<_, crate::error::Error>(out) + })?; + // Still in the index? Then it is being served and is not a candidate for + // eviction no matter how old it is. + let serving: Vec<i64> = db.read(|c| { + let mut st = c.prepare( + "SELECT DISTINCT r.id FROM release r JOIN package p ON p.release_id=r.id + WHERE r.pkgbase_id=?1 AND p.state='in_index' ORDER BY r.id DESC", + )?; + let rows = st.query_map(rusqlite::params![pb_id], |r| r.get::<_, i64>(0))?; + let mut out = Vec::new(); + for r in rows { + out.push(r?); + } + Ok::<_, crate::error::Error>(out) + })?; + + let mut keep_set: std::collections::BTreeSet<i64> = serving.iter().cloned().collect(); + if let Some(a) = accepted { + keep_set.insert(a); + } + for id in releases.iter().take(keep) { + keep_set.insert(*id); + } + for id in &releases { + if keep_set.contains(id) { + kept.push(*id); + } else { + evict.push(EvictPlan { release_id: *id }); + } + } + } + Ok((kept, evict)) +} + +#[derive(Debug, Clone)] +pub struct EvictPlan { + pub release_id: i64, +} + +/// Run retention: evict files for releases beyond the keep window, then sweep +/// abandoned staging directories. +/// +/// Files are only removed when no *retained* release still references them. The +/// store is content-addressed, so two releases built from the same source share +/// one cached archive; deleting it because one release aged out would corrupt a +/// release that is still current. +pub fn retention(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<RetentionReport> { + let keep = keep.unwrap_or_else(|| setting_usize(db, "retention_versions", DEFAULT_KEEP)); + let (kept, evict) = plan_retention(db, keep)?; + + // Everything still held by a kept release, so we do not evict a shared file. + let mut retained_files: std::collections::BTreeSet<PathBuf> = std::collections::BTreeSet::new(); + for id in &kept { + for f in release_files(cfg, db, *id)? { + retained_files.insert(f); + } + } + + let mut report = RetentionReport { releases_kept: kept.len(), ..Default::default() }; + for e in &evict { + let files = release_files(cfg, db, e.release_id)?; + let mut removed = 0usize; + let mut freed = 0u64; + for f in &files { + if retained_files.contains(f) { + continue; + } + if let Ok(m) = std::fs::metadata(f) { + freed += m.len(); + // A missing file is the state we are trying to reach, not an error. + let _ = std::fs::remove_file(f); + removed += 1; + } + } + report.files_removed += removed; + report.bytes_freed += freed; + if removed > 0 || !files.is_empty() { + report.releases_evicted += 1; + mark_purged(db, e.release_id)?; + } + } + + let (swept, swept_bytes) = sweep_staging(cfg, db, STAGING_GRACE_SECS)?; + report.staging_swept = swept; + report.bytes_freed += swept_bytes; + + record_run(db, &report)?; + let _ = db::audit( + &db.writer, + "system", + "gc", + "retention", + "gc_run", + "", + serde_json::json!({ + "keep": keep, + "kept": report.releases_kept, + "evicted": report.releases_evicted, + "files_removed": report.files_removed, + "bytes_freed": report.bytes_freed, + "staging_swept": report.staging_swept, + }), + ); + Ok(report) +} + +/// Grace period before an abandoned staging dir is swept. Anything younger could +/// belong to a build that is still running right now. +pub const STAGING_GRACE_SECS: i64 = 3600; + +/// The files a release holds on disk: package, signature, build log, and the +/// cached sources it was built from. +/// +/// These are returned as a unit because that is how they must be treated. A +/// package without its build log is a byte nobody can explain, and a package +/// without its sources cannot be rebuilt — keeping one and dropping the others +/// is how a store ends up full of orphans and empty of answers. +pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathBuf>> { + let mut out = Vec::new(); + let rows: Vec<(Option<String>, Option<String>, Option<String>)> = 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![release_id], |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::<_, crate::error::Error>(out) + })?; + for (path, sig, log) in rows { + if let Some(p) = path { + out.push(PathBuf::from(p)); + } + if let Some(p) = sig { + out.push(PathBuf::from(p)); + } + if let Some(p) = log { + out.push(PathBuf::from(p)); + } + } + // Cached sources, by content digest (§5.1a: the mirror and the source cache + // are what make an old release rebuildable). + let digests: String = db + .read(|c| { + c.query_row( + "SELECT source_digests_json FROM release WHERE id=?1", + rusqlite::params![release_id], + |r| r.get::<_, String>(0), + ) + .map_err(|e| crate::error::Error::db(e.to_string())) + }) + .unwrap_or_else(|_| "[]".into()); + if let Ok(list) = serde_json::from_str::<Vec<db::SourceDigest>>(&digests) { + for d in list { + if !d.digest.is_empty() { + out.push(cfg.source_cache_path(&d.digest)); + } + } + } + Ok(out) +} + +fn mark_purged(db: &Db, release_id: i64) -> Result<()> { + let at = time::now(); + db.writer.tx(move |tx| { + tx.execute( + "UPDATE release SET purged_at=?1 WHERE id=?2", + rusqlite::params![at, release_id], + )?; + tx.execute( + "UPDATE artifact SET purged_at=?1 WHERE purged_at IS NULL AND id IN + (SELECT a.id FROM artifact a JOIN package p ON p.artifact_id=a.id WHERE p.release_id=?2)", + rusqlite::params![at, release_id], + )?; + Ok(()) + }) +} + +/// Remove staging directories whose build is finished or unknown (§8.2: staging +/// is disposable, and a GC pass sweeps what was abandoned). +/// +/// "Abandoned" is derived, not guessed: a dir is swept when its build row is in a +/// terminal state, or when no build row exists at all, and the dir is older than +/// the grace period. A dir belonging to a live build is left alone no matter how +/// old it looks, because a long build is not an abandoned one. +pub fn sweep_staging(cfg: &Config, db: &Db, grace_secs: i64) -> Result<(usize, u64)> { + let root = cfg.staging_dir(); + let Ok(entries) = std::fs::read_dir(&root) else { return Ok((0, 0)) }; + let now = time::now(); + let mut swept = 0usize; + let mut freed = 0u64; + for e in entries.flatten() { + let path = e.path(); + if !path.is_dir() { + continue; + } + let Some(build_id) = path.file_name().map(|s| s.to_string_lossy().to_string()) else { + continue; + }; + let state: Option<String> = db + .read(|c| { + Ok(c.query_row("SELECT state FROM build WHERE id=?1", rusqlite::params![build_id], |r| { + r.get::<_, String>(0) + }) + .ok()) + }) + .unwrap_or(None); + let abandonable = match &state { + // No build row: staging left over from a crash before the row was + // written, or from a build id that no longer exists. + None => true, + Some(s) => matches!(s.as_str(), "succeeded" | "failed" | "cancelled"), + }; + if !abandonable { + continue; + } + let age = dir_age_secs(&path).unwrap_or(0); + if age < grace_secs { + continue; + } + let bytes = dir_bytes(&path); + if std::fs::remove_dir_all(&path).is_ok() { + swept += 1; + freed += bytes; + } + } + let _ = now; + Ok((swept, freed)) +} + +fn dir_age_secs(path: &Path) -> Option<i64> { + let m = std::fs::metadata(path).ok()?; + let t = m.modified().ok()?; + let age = std::time::SystemTime::now().duration_since(t).ok()?; + Some(age.as_secs() as i64) +} + +fn record_run(db: &Db, r: &RetentionReport) -> Result<()> { + let at = time::now(); + let (kept, evicted, files, bytes, swept) = ( + r.releases_kept as i64, + r.releases_evicted as i64, + r.files_removed as i64, + r.bytes_freed as i64, + r.staging_swept as i64, + ); + db.writer.tx(move |tx| { + tx.execute( + "INSERT INTO gc_run (ran_at, releases_kept, releases_evicted, files_removed, bytes_freed, staging_swept) + VALUES (?1,?2,?3,?4,?5,?6)", + rusqlite::params![at, kept, evicted, files, bytes, swept], + )?; + Ok(()) + }) +} + +fn setting_usize(db: &Db, key: &str, default: usize) -> usize { + db.read(|c| { + Ok(c.query_row("SELECT value FROM settings WHERE key=?1", rusqlite::params![key], |r| r.get::<_, String>(0)).ok()) + }) + .ok() + .flatten() + .and_then(|v| v.parse().ok()) + .unwrap_or(default) +} + +/// A consistent snapshot of the database, written to `dest`. +/// +/// `VACUUM INTO` runs on the writer connection so the snapshot cannot interleave +/// with a write, and it produces a compacted single file with no WAL — which is +/// what you want to be holding at 3am when the main file is gone. A `cp` of a +/// live WAL database gives you a main file and a sidecar log that may or may not +/// belong to it, and you find out which during the restore. +pub fn backup(db: &Db, dest: &Path) -> Result<PathBuf> { + let dest = dest.to_path_buf(); + if dest.exists() { + return Err(crate::error::Error::not_found(format!( + "refusing to overwrite an existing backup: {}", + dest.display() + ))); + } + if let Some(parent) = dest.parent() { + if !parent.as_os_str().is_empty() && !parent.exists() { + std::fs::create_dir_all(parent)?; + } + } + let sql = format!("VACUUM INTO '{}'", dest.display().to_string().replace('\'', "''")); + db.writer.call(move |conn| { + conn.execute_batch(&sql) + .map_err(|e| crate::error::Error::db(format!("VACUUM INTO: {e}")))?; + Ok(()) + })?; + // The snapshot must be readable on its own: if it does not open and report + // the same schema version, the backup is a file, not a backup. + let probe = rusqlite::Connection::open(&dest) + .map_err(|e| crate::error::Error::db(format!("backup unreadable: {e}")))?; + let version: i64 = probe + .query_row("PRAGMA user_version", [], |r| r.get(0)) + .map_err(|e| crate::error::Error::db(format!("backup has no schema: {e}")))?; + if version <= 0 { + return Err(crate::error::Error::db("backup does not contain a migrated database")); + } + let _ = db::audit_system( + &db.writer, + "backup", + "vacuum_into", + &dest.display().to_string(), + serde_json::json!({ "bytes": file_len(&dest), "schema_version": version }), + ); + Ok(dest) +} |
