diff options
Diffstat (limited to 'src/error.rs')
| -rw-r--r-- | src/error.rs | 344 |
1 files changed, 325 insertions, 19 deletions
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(_)))); + } } |
