summaryrefslogtreecommitdiffstats
path: root/src/ops.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/ops.rs')
-rw-r--r--src/ops.rs85
1 files changed, 25 insertions, 60 deletions
diff --git a/src/ops.rs b/src/ops.rs
index fd644c3..612db78 100644
--- a/src/ops.rs
+++ b/src/ops.rs
@@ -1,20 +1,3 @@
-//! 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;
@@ -37,7 +20,7 @@ pub struct RetentionReport {
/// 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.
+/// the tests read the same numbers from the same source.
#[derive(Debug, Default, Clone)]
pub struct Metrics {
pub builds: Vec<(String, i64)>,
@@ -67,8 +50,8 @@ pub struct Metrics {
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.
+ /// run yet: an alert rule reading 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,
@@ -76,10 +59,9 @@ impl Metrics {
}
}
- /// 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.
+ /// Render in Prometheus text exposition format. Every family is declared with
+ /// `# HELP` and `# TYPE`, because a scrape that fails validation drops the
+ /// whole payload.
pub fn to_prometheus(&self) -> String {
let mut o = String::new();
@@ -97,8 +79,7 @@ impl Metrics {
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.
+ // 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();
@@ -214,8 +195,7 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> {
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.
+/// A Prometheus family header.
fn header(name: &str, help: &str) -> String {
format!("# HELP {name} {help}\n# TYPE {name} gauge\n")
}
@@ -254,12 +234,7 @@ fn dir_bytes(path: &Path) -> u64 {
/// 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.
+/// The rule is "newest N, plus anything that would be a lie to evict".
pub fn plan_retention(db: &Db, keep: usize) -> Result<(Vec<i64>, Vec<EvictPlan>)> {
let keep = keep.max(1);
let pkgbases = db::pkgbase_release_pointers(db)?;
@@ -268,8 +243,7 @@ pub fn plan_retention(db: &Db, keep: usize) -> Result<(Vec<i64>, Vec<EvictPlan>)
let mut evict = Vec::new();
for (pb_id, accepted) in pkgbases {
let releases = db::published_release_ids(db, pb_id)?;
- // Still in the index? Then it is being served and is not a candidate for
- // eviction no matter how old it is.
+ // Still in the index? Then it is being served, whatever its age.
let serving = db::serving_release_ids(db, pb_id)?;
let mut keep_set: std::collections::BTreeSet<i64> = serving.iter().cloned().collect();
@@ -298,10 +272,8 @@ pub struct EvictPlan {
/// 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.
+/// Files are only removed when no *retained* release still references them: the store
+/// is content-addressed.
pub fn retention(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<RetentionReport> {
let keep = keep.unwrap_or_else(|| db::setting_i64(db, "retention_versions", DEFAULT_KEEP as i64) as usize);
let (kept, evict) = plan_retention(db, keep)?;
@@ -366,13 +338,11 @@ pub fn retention(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<Retention
/// 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.
+/// 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.
+/// Returned as a unit because that is how they must be treated: keeping one and
+/// dropping the others is how a store ends up full of orphans.
pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathBuf>> {
let mut out = Vec::new();
for (path, sig, log) in db::release_artifact_paths(db, release_id)? {
@@ -380,8 +350,8 @@ pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathB
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).
+ // Cached sources, by content digest (§5.1a: these are what make an old
+ // release rebuildable).
let digests = db::release_by_id(db, release_id)?
.map(|r| r.source_digests_json)
.unwrap_or_else(|| "[]".into());
@@ -395,13 +365,10 @@ pub fn release_files(cfg: &Config, db: &Db, release_id: i64) -> Result<Vec<PathB
Ok(out)
}
-/// Remove staging directories whose build is finished or unknown (§8.2: staging
-/// is disposable, and a GC pass sweeps what was abandoned).
+/// Remove staging directories whose build is finished or unknown (§8.2).
///
-/// "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.
+/// "Abandoned" is derived, not guessed: a dir is swept when its build row is terminal
+/// or absent and the dir is older than the grace period.
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)) };
@@ -419,7 +386,7 @@ pub fn sweep_staging(cfg: &Config, db: &Db, grace_secs: i64) -> Result<(usize, u
let state = db::builds::get(db, &build_id)?.map(|b| b.state);
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.
+ // written.
None => true,
Some(s) => matches!(s.as_str(), "succeeded" | "failed" | "cancelled"),
};
@@ -461,11 +428,9 @@ fn record_run(db: &Db, r: &RetentionReport) -> Result<()> {
/// 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.
+/// `VACUUM INTO` runs on the writer connection so the snapshot cannot interleave with
+/// a write, and produces a compacted single file with no WAL. A `cp` of a live WAL
+/// database gives a main file and a sidecar log that may not belong to it.
pub fn backup(db: &Db, dest: &Path) -> Result<PathBuf> {
let dest = dest.to_path_buf();
if dest.exists() {