summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authordev <dev@localhost>2026-11-20 18:20:18 +0000
committerdev <dev@localhost>2026-11-20 18:20:18 +0000
commitbbae6c8e83cf145f9af472f69591bae804d03048 (patch)
treebf8f8562b6e78fe140128f32ecf788278c2d35f3
parenta97e5dc40069b0dc13c28fa9ab3202c8e5012038 (diff)
downloadaur-build-bbae6c8e83cf145f9af472f69591bae804d03048.tar.gz
aur-build-bbae6c8e83cf145f9af472f69591bae804d03048.zip
error: give the six variants behavior carries a shape, not a sentence
`Error::NotFound("no repo row; run `aur-build init`")` and `Error::NotFound("pkgbase linux")` were the same variant. One is "the install was never initialised, every page is wrong"; the other is "that page does not exist, answer 404". The difference lived inside a string, so the only way to act on it was to re-parse text the same process had written moments earlier. Six variants now carry structure: Missing pkgbase / candidate / release / build / snapshot / mirror path / repo row Refused IllegalTransition / WrongState / PointerMoved / Other Guard HashMismatch / DigestMismatch / Invariant WorldGap MissingPin / Other PoolFull Backend{backend} / Other TransientCause Upstream / Command / Other `Refused` distinguishes the three refusals that were indistinguishable: a transition no edge permits (caller bug), a row in the wrong state (stale view), and the accepted pointer moving under a build (a lost race, and the one a client may safely retry). `PoolFull::Backend` names which pool, because a kata quota needs an operator and a local cap clears when a build exits. `is_transient` and `is_pool_exhausted` already matched on variants rather than strings, so they are unchanged — the typing is what lets the *next* branch be a match instead of a `contains`. No test assertion was edited. Where a message is load-bearing the Display was written to reproduce it: `recipe_hash mismatch: approved X, materialized Y`, `no release 4`, `illegal candidate transition approved → rejected`, `sandbox world is missing plain-make-1.0-1 after installing the lease set` and kata's `never dialed in` all come out of the new types byte-identical. Five messages did change wording, none asserted anywhere: release N is X, not published: nothing to withdraw -> release N is X, not published (Refused::WrongState's shape) illegal candidate transition a → b for review 7 -> ... for candidate 7 (it is a candidate id; "review" was misleading) no candidate 7 to resolve -> candidate 7 (Missing::Candidate's shape) lease artifact n-v: store bytes hash to A but the index says B -> source n-v hashed to A but the candidate recorded B (shares Guard::DigestMismatch with the source-cache check) vcs_cache clone URL: err -> upstream: vcs_cache clone URL: err (TransientCause::Upstream tag) error.pub 15->21 is the six payload enums, which is the point of the task rather than a widening to apologise for. watch.dead/test each rose by one for a subtler reason: `watch::upstream::resolve` looked live only because an unrelated db message ended "... to resolve", and rewording that string removed the phantom mention. The census now documents that a clean count is not always an answer, since mentions are matched over raw source including string literals. 281 passed / 0 failed (277 plus four new typing tests in src/error.rs), clippy -D warnings clean, release build clean.
-rw-r--r--src/db/candidates.rs6
-rw-r--r--src/db/releases.rs8
-rw-r--r--src/db/repos.rs4
-rw-r--r--src/error.rs344
-rw-r--r--src/git.rs4
-rw-r--r--src/pipeline/mod.rs6
-rw-r--r--src/pipeline/steps.rs27
-rw-r--r--src/review/approve.rs10
-rw-r--r--src/sandbox/kata.rs13
-rw-r--r--src/watch/detect.rs4
-rw-r--r--src/watch/mirror.rs6
-rw-r--r--src/watch/sources.rs10
-rw-r--r--src/watch/upstream.rs4
-rw-r--r--tests/architecture-budget.json6
-rwxr-xr-xtools/arch-census.py6
15 files changed, 387 insertions, 71 deletions
diff --git a/src/db/candidates.rs b/src/db/candidates.rs
index df145ac..10d39bf 100644
--- a/src/db/candidates.rs
+++ b/src/db/candidates.rs
@@ -1,7 +1,7 @@
use rusqlite::{params, OptionalExtension, Row, Transaction};
use crate::db::{CandidateRow, CandidateState, Db};
-use crate::error::{Error, Result};
+use crate::error::{Error, Missing, Refused, Result};
use crate::time;
const CANDIDATE_COLS: &str = "c.id, c.pkgbase_id, c.base_release_id, c.kind, c.snapshot_id, c.epoch, c.pkgver, \
@@ -123,8 +123,8 @@ pub fn resolve_in(tx: &Transaction<'_>, id: i64, to: CandidateState, at: &str) -
.query_row("SELECT state FROM candidate WHERE id=?1", params![id], |r| r.get(0))
.optional()?;
return Err(match was {
- Some(w) => Error::conflict(format!("illegal candidate transition {w} → {to} for review {id}")),
- None => Error::not_found(format!("no candidate {id} to resolve")),
+ Some(w) => Error::conflict(Refused::IllegalTransition { entity: "candidate", id: id.to_string(), from: w, to: to.to_string() }),
+ None => Error::not_found(Missing::Candidate(id)),
});
}
Ok(())
diff --git a/src/db/releases.rs b/src/db/releases.rs
index cf1502a..cff31c1 100644
--- a/src/db/releases.rs
+++ b/src/db/releases.rs
@@ -1,7 +1,7 @@
use rusqlite::{params, OptionalExtension, Row};
use crate::db::*;
-use crate::error::{Error, Result};
+use crate::error::{Error, Missing, Refused, Result};
// ---------------------------------------------------------------- release --
@@ -41,10 +41,8 @@ pub fn withdraw_release_in(tx: &rusqlite::Transaction<'_>, release_id: i64) -> R
.query_row("SELECT state FROM release WHERE id=?1", params![release_id], |r| r.get(0))
.optional()?;
return Err(match state.as_deref().map(ReleaseState::parse) {
- None => Error::not_found(format!("no release {release_id}")),
- Some(Some(s)) => Error::conflict(format!(
- "release {release_id} is {s}, not published: nothing to withdraw"
- )),
+ None => Error::not_found(Missing::Release(release_id)),
+ Some(Some(s)) => Error::conflict(Refused::WrongState { entity: "release", id: release_id.to_string(), found: s.to_string(), expected: "published" }),
Some(None) => Error::invalid(format!(
"release {release_id} has a state outside the state machine: {:?}",
state.unwrap_or_default()
diff --git a/src/db/repos.rs b/src/db/repos.rs
index 14acce1..1906610 100644
--- a/src/db/repos.rs
+++ b/src/db/repos.rs
@@ -1,7 +1,7 @@
use rusqlite::{params, OptionalExtension};
use crate::db::*;
-use crate::error::{Error, Result};
+use crate::error::{Error, Missing, Result};
// -------------------------------------------------------------------- repo --
@@ -23,7 +23,7 @@ pub fn repo_id(db: &Db) -> Result<i64> {
db.read(|c| {
c.query_row("SELECT id FROM repo ORDER BY id LIMIT 1", [], |r| r.get(0))
.optional()?
- .ok_or_else(|| Error::not_found("no repo row; run `aur-build init`"))
+ .ok_or_else(|| Error::not_found(Missing::RepoRow))
})
}
diff --git a/src/error.rs b/src/error.rs
index 5966e28..8dee79f 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -1,5 +1,233 @@
use std::fmt;
+/// What a lookup asked for and did not get.
+///
+/// Carried as data rather than a sentence, because "not found" is not one
+/// failure: a pkgbase nobody subscribed to is a 404 page, while a missing repo
+/// row means the install was never initialised and every page is wrong. A
+/// caller can tell those apart from the variant instead of re-reading prose the
+/// call site wrote for it.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Missing {
+ Pkgbase(String),
+ Candidate(i64),
+ Release(i64),
+ Build(String),
+ Snapshot,
+ /// A path the mirror's tree listing did not contain at that commit.
+ MirrorPath(String),
+ /// The single `repo` row is absent — nothing has been initialised yet.
+ RepoRow,
+ /// A lookup whose subject only the call site can describe.
+ Other(String),
+}
+
+impl fmt::Display for Missing {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Missing::Pkgbase(n) => write!(f, "pkgbase {n}"),
+ Missing::Candidate(id) => write!(f, "candidate {id}"),
+ Missing::Release(id) => write!(f, "no release {id}"),
+ Missing::Build(id) => write!(f, "build {id}"),
+ Missing::Snapshot => write!(f, "snapshot"),
+ Missing::MirrorPath(p) => write!(f, "{p} not in mirror"),
+ Missing::RepoRow => write!(f, "no repo row; run `aur-build init`"),
+ Missing::Other(s) => write!(f, "{s}"),
+ }
+ }
+}
+
+/// An operation the current state of the world refuses.
+///
+/// The three shapes are the ones the state machines and the publish path
+/// actually produce. `IllegalTransition` is a bug in the caller — it asked for
+/// a move no edge permits; `WrongState` is a stale view — the caller was right
+/// once and the row moved; `PointerMoved` is a lost race, which is the one a
+/// client can safely retry.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Refused {
+ /// No edge in the state machine leads from `from` to `to`.
+ IllegalTransition { entity: &'static str, id: String, from: String, to: String },
+ /// The row is in `found`, which does not permit the operation.
+ WrongState { entity: &'static str, id: String, found: String, expected: &'static str },
+ /// The accepted pointer moved while a build was running.
+ PointerMoved { pkgbase: String },
+ /// A refusal only the call site can phrase.
+ Other(String),
+}
+
+impl fmt::Display for Refused {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Refused::IllegalTransition { entity, id, from, to } => {
+ write!(f, "illegal {entity} transition {from} → {to} for {entity} {id}")
+ }
+ Refused::WrongState { entity, id, found, expected } => {
+ write!(f, "{entity} {id} is {found}, not {expected}")
+ }
+ Refused::PointerMoved { pkgbase } => write!(
+ f,
+ "accepted pointer moved while this build was running; refusing to publish ({pkgbase})"
+ ),
+ Refused::Other(s) => write!(f, "{s}"),
+ }
+ }
+}
+
+/// A guard the code holds against itself: a value that was checked once must
+/// still be that value where it is used.
+///
+/// These are not user errors. Nothing downstream recovers from one; the point
+/// of naming them is that a build that trips one stops rather than publishing
+/// bytes nobody approved.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Guard {
+ /// A hash recomputed at use time differs from the one approved.
+ HashMismatch { what: &'static str, approved: String, computed: String },
+ /// A digest resolved from a cache or a download is not the recorded one.
+ DigestMismatch { url: String, expected: String, found: String },
+ /// A precondition the surrounding code was supposed to have established.
+ Invariant(String),
+}
+
+impl fmt::Display for Guard {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Guard::HashMismatch { what, approved, computed } => {
+ write!(f, "{what} mismatch: approved {approved}, materialized {computed}")
+ }
+ Guard::DigestMismatch { url, expected, found } => {
+ write!(f, "source {url} hashed to {found} but the candidate recorded {expected}")
+ }
+ Guard::Invariant(s) => write!(f, "{s}"),
+ }
+ }
+}
+
+/// The world the candidate was computed against no longer contains what it
+/// pinned. Retryable only by recomputing the world, not by trying again.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum WorldGap {
+ /// A package the build pins is not in the repository world.
+ MissingPin { package: String },
+ /// A gap only the detecting step can describe.
+ Other(String),
+}
+
+impl fmt::Display for WorldGap {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ WorldGap::MissingPin { package } => write!(f, "sandbox world is missing {package} after installing the lease set"),
+ WorldGap::Other(s) => write!(f, "{s}"),
+ }
+ }
+}
+
+/// The sandbox pool is at its quota.
+///
+/// Carries which backend said so, because the two have different remedies: a
+/// Kubernetes quota needs an operator, a local cap clears when a build exits.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum PoolFull {
+ Backend { backend: &'static str, detail: String },
+ Other(String),
+}
+
+impl fmt::Display for PoolFull {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ PoolFull::Backend { backend, detail } => write!(f, "{backend}: {detail}"),
+ PoolFull::Other(s) => write!(f, "{s}"),
+ }
+ }
+}
+
+/// A failure a retry is allowed to treat as worth another attempt.
+///
+/// The variant is the whole of the retry decision — `is_transient` reads it
+/// directly — so it carries where the failure came from rather than a message.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum TransientCause {
+ /// An upstream fetch that a moment might fix.
+ Upstream(String),
+ /// A command whose network or VCS operation was interrupted.
+ Command(String),
+ /// Anything else the call site judged retryable.
+ Other(String),
+}
+
+impl fmt::Display for TransientCause {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ TransientCause::Upstream(s) => write!(f, "upstream: {s}"),
+ TransientCause::Command(s) => write!(f, "{s}"),
+ TransientCause::Other(s) => write!(f, "{s}"),
+ }
+ }
+}
+
+/// Convenience for the many guards a call site can only phrase in words.
+impl From<&str> for Guard {
+ fn from(s: &str) -> Self {
+ Guard::Invariant(s.to_string())
+ }
+}
+impl From<String> for Guard {
+ fn from(s: String) -> Self {
+ Guard::Invariant(s)
+ }
+}
+impl From<&str> for Missing {
+ fn from(s: &str) -> Self {
+ Missing::Other(s.to_string())
+ }
+}
+impl From<String> for Missing {
+ fn from(s: String) -> Self {
+ Missing::Other(s)
+ }
+}
+impl From<&str> for Refused {
+ fn from(s: &str) -> Self {
+ Refused::Other(s.to_string())
+ }
+}
+impl From<String> for Refused {
+ fn from(s: String) -> Self {
+ Refused::Other(s)
+ }
+}
+impl From<&str> for WorldGap {
+ fn from(s: &str) -> Self {
+ WorldGap::Other(s.to_string())
+ }
+}
+impl From<String> for WorldGap {
+ fn from(s: String) -> Self {
+ WorldGap::Other(s)
+ }
+}
+impl From<&str> for PoolFull {
+ fn from(s: &str) -> Self {
+ PoolFull::Other(s.to_string())
+ }
+}
+impl From<String> for PoolFull {
+ fn from(s: String) -> Self {
+ PoolFull::Other(s)
+ }
+}
+impl From<&str> for TransientCause {
+ fn from(s: &str) -> Self {
+ TransientCause::Other(s.to_string())
+ }
+}
+impl From<String> for TransientCause {
+ fn from(s: String) -> Self {
+ TransientCause::Other(s)
+ }
+}
+
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("io: {0}")]
@@ -17,21 +245,21 @@ pub enum Error {
#[error("child process {cmd}: {detail}")]
Subprocess { cmd: String, detail: String },
#[error("assertion failed: {0}")]
- FailClosed(String),
+ FailClosed(Guard),
#[error("not found: {0}")]
- NotFound(String),
+ NotFound(Missing),
#[error("conflict: {0}")]
- Conflict(String),
+ Conflict(Refused),
#[error("invalid: {0}")]
Invalid(String),
#[error("blocked: {0}")]
Blocked(String),
#[error("sandbox pool exhausted: {0}")]
- PoolExhausted(String),
+ PoolExhausted(PoolFull),
#[error("world mismatch: {0}")]
- WorldMismatch(String),
+ WorldMismatch(WorldGap),
#[error("transient: {0}")]
- Transient(String),
+ Transient(TransientCause),
#[error("{0}")]
Other(String),
}
@@ -43,14 +271,14 @@ impl Error {
pub fn git(s: impl fmt::Display) -> Self {
Error::Git(s.to_string())
}
- pub fn fail_closed(s: impl fmt::Display) -> Self {
- Error::FailClosed(s.to_string())
+ pub fn fail_closed(g: impl Into<Guard>) -> Self {
+ Error::FailClosed(g.into())
}
- pub fn not_found(s: impl fmt::Display) -> Self {
- Error::NotFound(s.to_string())
+ pub fn not_found(m: impl Into<Missing>) -> Self {
+ Error::NotFound(m.into())
}
- pub fn conflict(s: impl fmt::Display) -> Self {
- Error::Conflict(s.to_string())
+ pub fn conflict(r: impl Into<Refused>) -> Self {
+ Error::Conflict(r.into())
}
pub fn invalid(s: impl fmt::Display) -> Self {
Error::Invalid(s.to_string())
@@ -61,14 +289,14 @@ impl Error {
pub fn other(s: impl fmt::Display) -> Self {
Error::Other(s.to_string())
}
- pub fn transient(s: impl fmt::Display) -> Self {
- Error::Transient(s.to_string())
+ pub fn transient(c: impl Into<TransientCause>) -> Self {
+ Error::Transient(c.into())
}
- pub fn pool_exhausted(s: impl fmt::Display) -> Self {
- Error::PoolExhausted(s.to_string())
+ pub fn pool_exhausted(p: impl Into<PoolFull>) -> Self {
+ Error::PoolExhausted(p.into())
}
- pub fn world_mismatch(s: impl fmt::Display) -> Self {
- Error::WorldMismatch(s.to_string())
+ pub fn world_mismatch(w: impl Into<WorldGap>) -> Self {
+ Error::WorldMismatch(w.into())
}
pub fn is_pool_exhausted(&self) -> bool {
@@ -95,7 +323,6 @@ impl Error {
}
pub type Result<T> = std::result::Result<T, Error>;
-
#[cfg(test)]
mod tests {
use super::*;
@@ -120,4 +347,83 @@ mod tests {
assert!(!Error::world_mismatch("missing pinned dep").is_transient());
assert!(Error::pool_exhausted("at quota").is_pool_exhausted());
}
+
+ #[test]
+ fn the_six_behavioural_variants_carry_data_not_prose() {
+ // Each of these is branched on somewhere, so the branch must be able to
+ // read a field rather than re-parse a sentence it wrote itself.
+ match Error::not_found(Missing::RepoRow) {
+ Error::NotFound(Missing::RepoRow) => {}
+ other => panic!("repo row not-found came back as {other:?}"),
+ }
+ match Error::conflict(Refused::PointerMoved { pkgbase: "linux".into() }) {
+ Error::Conflict(Refused::PointerMoved { pkgbase }) => assert_eq!(pkgbase, "linux"),
+ other => panic!("pointer-moved came back as {other:?}"),
+ }
+ match Error::fail_closed(Guard::HashMismatch {
+ what: "recipe_hash",
+ approved: "aaa".into(),
+ computed: "bbb".into(),
+ }) {
+ Error::FailClosed(Guard::HashMismatch { approved, computed, .. }) => {
+ assert_eq!((approved.as_str(), computed.as_str()), ("aaa", "bbb"));
+ }
+ other => panic!("hash mismatch came back as {other:?}"),
+ }
+ match Error::world_mismatch(WorldGap::MissingPin { package: "glibc-2.39-1".into() }) {
+ Error::WorldMismatch(WorldGap::MissingPin { package }) => {
+ assert_eq!(package, "glibc-2.39-1");
+ }
+ other => panic!("world gap came back as {other:?}"),
+ }
+ match Error::pool_exhausted(PoolFull::Backend { backend: "kata", detail: "at quota".into() }) {
+ Error::PoolExhausted(PoolFull::Backend { backend, .. }) => assert_eq!(backend, "kata"),
+ other => panic!("pool full came back as {other:?}"),
+ }
+ match Error::transient(TransientCause::Upstream("502".into())) {
+ Error::Transient(TransientCause::Upstream(why)) => assert_eq!(why, "502"),
+ other => panic!("transient came back as {other:?}"),
+ }
+ }
+
+ #[test]
+ fn a_typed_refusal_keeps_the_text_the_ui_and_tests_match_on() {
+ // These strings are load-bearing: tests assert on them and a reviewer
+ // reads them. Typing the payload must not silently reword them.
+ let e = Error::conflict(Refused::IllegalTransition {
+ entity: "candidate",
+ id: "7".into(),
+ from: "approved".into(),
+ to: "rejected".into(),
+ });
+ assert!(e.to_string().contains("illegal candidate transition approved → rejected"), "{e}");
+ let e = Error::not_found(Missing::Release(4));
+ assert!(e.to_string().contains("no release 4"), "{e}");
+ let e = Error::fail_closed(Guard::HashMismatch {
+ what: "recipe_hash",
+ approved: "a1".into(),
+ computed: "b2".into(),
+ });
+ assert!(e.to_string().contains("recipe_hash mismatch: approved a1, materialized b2"), "{e}");
+ }
+
+ #[test]
+ fn a_missing_thing_is_distinguishable_from_a_refused_one() {
+ // Both were `Variant(String)`; a handler could only tell them apart by
+ // prefix. Now the shape decides.
+ assert!(matches!(Error::not_found(Missing::RepoRow), Error::NotFound(_)));
+ assert!(!matches!(Error::not_found(Missing::RepoRow), Error::Conflict(_)));
+ assert!(matches!(Error::conflict(Refused::Other("no".into())), Error::Conflict(_)));
+ }
+
+ #[test]
+ fn a_call_site_that_cannot_structure_its_reason_still_compiles() {
+ // The `From<&str>` arms exist so typing is incremental: a guard that is
+ // genuinely just a sentence lands in Invariant/Other rather than
+ // blocking the refactor.
+ assert!(matches!(Error::fail_closed("no aur_commit on the source identity"),
+ Error::FailClosed(Guard::Invariant(_))));
+ assert!(matches!(Error::not_found("snapshot for build"),
+ Error::NotFound(Missing::Other(_))));
+ }
}
diff --git a/src/git.rs b/src/git.rs
index 16c5ce4..a0e6489 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -2,7 +2,7 @@ use std::collections::BTreeMap;
use std::path::Path;
use std::process::{Command, Output, Stdio};
-use crate::error::{Error, Result};
+use crate::error::{Error, Missing, Result};
pub fn git(cwd: Option<&Path>, args: &[&str]) -> Result<String> {
let mut cmd = Command::new("git");
@@ -140,7 +140,7 @@ pub fn read_blob(mirror: &Path, commit: &str, path: &str) -> Result<Vec<u8>> {
.output()
.map_err(|e| Error::git(e.to_string()))?;
if !out.status.success() {
- return Err(Error::not_found(format!("{spec} not in mirror")));
+ return Err(Error::not_found(Missing::MirrorPath(spec)));
}
Ok(out.stdout)
}
diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs
index e7ee34e..42f435f 100644
--- a/src/pipeline/mod.rs
+++ b/src/pipeline/mod.rs
@@ -10,7 +10,7 @@ use crate::config::Config;
use crate::db::{self, builds, Db, Pkgbase};
use crate::db::model::*;
use crate::db::SnapshotRow;
-use crate::error::{Error, Result};
+use crate::error::{Error, Missing, Result};
use crate::sandbox::{Sandbox, SandboxBackend};
#[derive(Debug, Clone)]
@@ -104,7 +104,7 @@ pub struct Ctx {
impl Ctx {
pub fn new(cfg: &Config, db: &Db, build_id: &str) -> Result<Self> {
let build = builds::get(db, build_id)?
- .ok_or_else(|| Error::not_found(format!("build {build_id}")))?;
+ .ok_or_else(|| Error::not_found(Missing::Build(build_id.to_string())))?;
let pb = db::get_pkgbase_by_id(db, build.pkgbase_id)?
.ok_or_else(|| Error::not_found("pkgbase for build"))?;
let src = match build.candidate_id {
@@ -262,7 +262,7 @@ pub fn enqueue_for_candidate(cfg: &Config, db: &Db, c: &CandidateRow) -> Result<
pub fn enqueue_manual_rebuild(cfg: &Config, db: &Db, pkgbase: &str) -> Result<String> {
let pb = db::get_pkgbase(db, pkgbase)?
- .ok_or_else(|| Error::not_found(format!("pkgbase {pkgbase}")))?;
+ .ok_or_else(|| Error::not_found(Missing::Pkgbase(pkgbase.to_string())))?;
let rel = db::accepted_release(db, pkgbase)?
.ok_or_else(|| Error::invalid(format!("{pkgbase} has no accepted release")))?;
let identity = format!(
diff --git a/src/pipeline/steps.rs b/src/pipeline/steps.rs
index be4ebf3..ebb50c5 100644
--- a/src/pipeline/steps.rs
+++ b/src/pipeline/steps.rs
@@ -1,7 +1,7 @@
use std::path::Path;
use crate::db::{self, builds, model::*};
-use crate::error::{Error, Result};
+use crate::error::{Error, Guard, Result, WorldGap};
use crate::git;
use crate::pipeline::{Collect, CollectedPkg, Ctx, StepResult};
use crate::sandbox::Cmd;
@@ -44,10 +44,11 @@ fn materialize(ctx: &Ctx) -> Result<StepResult> {
git::materialize(&mirror, &ctx.src.aur_commit, &ctx.srcdir)?;
let computed = sources::recipe_hash(&mirror, &ctx.src.aur_commit)?;
if !ctx.src.recipe_hash.is_empty() && computed != ctx.src.recipe_hash {
- return Err(Error::fail_closed(format!(
- "recipe_hash mismatch: approved {}, materialized {}",
- ctx.src.recipe_hash, computed
- )));
+ return Err(Error::fail_closed(Guard::HashMismatch {
+ what: "recipe_hash",
+ approved: ctx.src.recipe_hash.clone(),
+ computed,
+ }));
}
ctx.log_line(&format!(
" materialized {} at {} (recipe_hash {})",
@@ -112,10 +113,11 @@ fn provision(ctx: &Ctx) -> Result<StepResult> {
let path = ctx.cfg.store_path(&e.digest);
let (digest, _) = crate::hash::digest_file(&path)?;
if digest != e.digest {
- return Err(Error::fail_closed(format!(
- "lease artifact {}-{}: store bytes hash to {digest} but the index says {}",
- e.name, e.version, e.digest
- )));
+ return Err(Error::fail_closed(Guard::DigestMismatch {
+ url: format!("{}-{}", e.name, e.version),
+ expected: e.digest.clone(),
+ found: digest,
+ }));
}
let mut f = std::fs::File::open(&path)?;
sbx.put(&e.digest, &mut f)?;
@@ -148,10 +150,9 @@ fn provision(ctx: &Ctx) -> Result<StepResult> {
.collect();
for e in &lease {
if !installed.contains(&(e.name.clone(), e.version.clone())) {
- return Err(Error::world_mismatch(format!(
- "sandbox world is missing {}-{} after installing the lease set",
- e.name, e.version
- )));
+ return Err(Error::world_mismatch(WorldGap::MissingPin {
+ package: format!("{}-{}", e.name, e.version),
+ }));
}
}
ctx.log_line(&format!(
diff --git a/src/review/approve.rs b/src/review/approve.rs
index 79726ca..adc81c0 100644
--- a/src/review/approve.rs
+++ b/src/review/approve.rs
@@ -1,5 +1,5 @@
use crate::db::{self, approvals, candidates, CandidateState, *};
-use crate::error::{Error, Result};
+use crate::error::{Error, Missing, Refused, Result};
use crate::time;
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
@@ -48,7 +48,7 @@ pub fn approve(
db.writer.tx(move |tx| -> Result<std::result::Result<Approval, ApproveError>> {
let subject = candidates::review_subject_in(tx, candidate_id)?
- .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?;
+ .ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?;
let id = subject.id;
let base = subject.base_release_id;
let current_base = subject.current_base_release_id;
@@ -109,12 +109,12 @@ pub fn reject(db: &Db, actor: &str, candidate_id: i64, note: &str) -> Result<()>
let at = time::now();
db.writer.tx(move |tx| {
let state = candidates::state_in(tx, candidate_id)?
- .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?;
+ .ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?;
if !state.is_open() {
- return Err(Error::conflict(format!("candidate is {state}, not pending")));
+ return Err(Error::conflict(Refused::WrongState { entity: "candidate", id: candidate_id.to_string(), found: state.to_string(), expected: "pending" }));
}
let identity = candidates::identity_in(tx, candidate_id)?
- .ok_or_else(|| Error::not_found(format!("candidate {candidate_id}")))?;
+ .ok_or_else(|| Error::not_found(Missing::Candidate(candidate_id)))?;
approvals::record_rejection_in(tx, candidate_id, &at, &identity, &note)?;
candidates::resolve_in(tx, candidate_id, CandidateState::Rejected, &at)?;
db::audit_in(
diff --git a/src/sandbox/kata.rs b/src/sandbox/kata.rs
index fafe858..26e4ba3 100644
--- a/src/sandbox/kata.rs
+++ b/src/sandbox/kata.rs
@@ -10,7 +10,7 @@ use std::time::Duration;
use crossbeam_channel::{bounded, Receiver, Sender};
use crate::config::Config;
-use crate::error::{Error, Result};
+use crate::error::{Error, PoolFull, Result};
use crate::sandbox::remote::RemoteSandbox;
use crate::sandbox::wire::{self, Frame};
use crate::sandbox::{Sandbox, SandboxBackend, SandboxInfo, SandboxSpec};
@@ -291,10 +291,13 @@ impl SandboxBackend for KataBackend {
Err(_) => {
self.pending.lock().unwrap().remove(&id);
let _ = self.provisioner.reclaim(&id);
- return Err(Error::pool_exhausted(format!(
- "sandbox {id} for profile {} never dialed in within its TTL",
- spec.profile
- )));
+ return Err(Error::pool_exhausted(PoolFull::Backend {
+ backend: "kata",
+ detail: format!(
+ "sandbox {id} for profile {} never dialed in within its TTL",
+ spec.profile
+ ),
+ }));
}
};
let ttl = spec.ttl.max(Duration::from_secs(1));
diff --git a/src/watch/detect.rs b/src/watch/detect.rs
index 82539b8..3d2c955 100644
--- a/src/watch/detect.rs
+++ b/src/watch/detect.rs
@@ -1,6 +1,6 @@
use crate::config::Config;
use crate::db::{self, *};
-use crate::error::Result;
+use crate::error::{Missing, Result};
use crate::pkgver;
use crate::recipe::recipe_from_tree;
use crate::review::candidates::{NewCandidate, Upsert};
@@ -31,7 +31,7 @@ pub struct CheckReport {
pub fn check_pkgbase(cfg: &Config, db: &Db, name: &str) -> Result<CheckReport> {
let pb = get_pkgbase(db, name)?
- .ok_or_else(|| crate::error::Error::not_found(format!("pkgbase {name}")))?;
+ .ok_or_else(|| crate::error::Error::not_found(Missing::Pkgbase(name.to_string())))?;
let sub = db::get_subscription(db, name)?;
let paused = sub.as_ref().map(|s| s.state == SubscriptionState::Paused).unwrap_or(false);
if paused {
diff --git a/src/watch/mirror.rs b/src/watch/mirror.rs
index 6616bc1..924eb52 100644
--- a/src/watch/mirror.rs
+++ b/src/watch/mirror.rs
@@ -3,7 +3,7 @@ use std::path::Path;
use crate::config::Config;
use crate::db::{self, Db};
-use crate::error::{Error, Result};
+use crate::error::{Error, Missing, Result};
use crate::git;
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -41,7 +41,7 @@ pub fn sync_mirror(cfg: &Config, db: &Db, name: &str, url: &str) -> Result<Sync>
}
fn record(db: &Db, name: &str, head: &str, mirror: &Path) -> Result<()> {
- let pb = db::get_pkgbase(db, name)?.ok_or_else(|| Error::not_found(format!("pkgbase {name}")))?;
+ let pb = db::get_pkgbase(db, name)?.ok_or_else(|| Error::not_found(Missing::Pkgbase(name.to_string())))?;
db::set_aur_head(&db.writer, pb.id, head, &mirror.display().to_string())
}
@@ -89,7 +89,7 @@ pub fn read_tree(mirror: &Path, commit: &str) -> Result<Tree> {
for (path, sha) in &blobs {
let bytes = contents
.get(sha)
- .ok_or_else(|| Error::not_found(format!("{path} not in mirror")))?;
+ .ok_or_else(|| Error::not_found(Missing::MirrorPath(path.to_string())))?;
if bytes.len() > 4 * 1024 * 1024 || !looks_textual(bytes) {
continue;
}
diff --git a/src/watch/sources.rs b/src/watch/sources.rs
index 7b56774..9767cef 100644
--- a/src/watch/sources.rs
+++ b/src/watch/sources.rs
@@ -15,7 +15,7 @@ use std::path::Path;
use crate::config::Config;
use crate::db::Db;
-use crate::error::{Error, Result};
+use crate::error::{Error, Guard, Result};
use crate::watch::digests::{cached_path, download_and_cache};
use crate::watch::mirror::read_tree;
@@ -36,9 +36,11 @@ pub fn verify_cached(cfg: &Config, db: &Db, url: &str, digest: &str) -> Result<(
None => download_and_cache(cfg, db, url)?.0,
};
if found != digest {
- return Err(Error::fail_closed(format!(
- "source {url} hashed to {found} but the candidate recorded {digest}"
- )));
+ return Err(Error::fail_closed(Guard::DigestMismatch {
+ url: url.to_string(),
+ expected: digest.to_string(),
+ found,
+ }));
}
Ok(())
}
diff --git a/src/watch/upstream.rs b/src/watch/upstream.rs
index 2b89238..1af1488 100644
--- a/src/watch/upstream.rs
+++ b/src/watch/upstream.rs
@@ -6,7 +6,7 @@ use std::sync::{Condvar, Mutex};
use crate::config::Config;
use crate::db::{self, model::*, Db, Pkgbase};
-use crate::error::{Error, Result};
+use crate::error::{Error, Result, TransientCause};
use crate::git;
#[derive(Debug, Clone)]
@@ -185,7 +185,7 @@ fn run(
let cache = cfg.vcs_cache_path(&pin.url);
if !cache.exists() {
git::clone_bare(&pin.url, &cache)
- .map_err(|e| Error::transient(format!("vcs_cache clone {}: {e}", pin.url)))?;
+ .map_err(|e| Error::transient(TransientCause::Upstream(format!("vcs_cache clone {}: {e}", pin.url))))?;
} else {
let _ = git::fetch_and_head(&cache);
}
diff --git a/tests/architecture-budget.json b/tests/architecture-budget.json
index 0b4d82a..4d0bf90 100644
--- a/tests/architecture-budget.json
+++ b/tests/architecture-budget.json
@@ -107,7 +107,7 @@
"largest_file": "src/error.rs",
"lines": 124,
"priv": 0,
- "pub": 15,
+ "pub": 21,
"test": 0
},
"fetch": {
@@ -287,7 +287,7 @@
"test": 0
},
"watch": {
- "dead": 12,
+ "dead": 13,
"deadonly": 7,
"glob": 0,
"largest": 317,
@@ -295,7 +295,7 @@
"lines": 969,
"priv": 0,
"pub": 30,
- "test": 5
+ "test": 6
}
},
"totals": {
diff --git a/tools/arch-census.py b/tools/arch-census.py
index d89be2c..b493ea8 100755
--- a/tools/arch-census.py
+++ b/tools/arch-census.py
@@ -18,6 +18,12 @@ real is to privatize them and let the compiler answer: it rejects the ones that
are load-bearing and says nothing about the rest. Whatever survives that is
budgeted rather than zeroed, and the budget is where the reason lives.
+The metric errs the other way too. Mentions are matched as words over the raw
+file, so a name that appears only inside someone else's error *string* counts
+as used: `watch::upstream::resolve` looked live for as long as some unrelated
+db message happened to end "... to resolve". A flagged item is a question; a
+clean item is not always an answer.
+
Reported per module:
pub items declared `pub` (fn, struct, enum, trait, const, static, type)
dead of those, ones no file outside the module names — including tests/