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), /// 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::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 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 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 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 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 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 for TransientCause { fn from(s: String) -> Self { TransientCause::Other(s) } } #[derive(Debug, thiserror::Error)] pub enum Error { #[error("io: {0}")] Io(#[from] std::io::Error), #[error("json: {0}")] Json(#[from] serde_json::Error), #[error("sqlite: {0}")] Db(String), #[error("sqlite: {0}")] Sqlite(#[from] rusqlite::Error), #[error("git: {0}")] Git(String), #[error("http fetch: {0}")] Http(String), #[error("child process {cmd}: {detail}")] Subprocess { cmd: String, detail: String }, #[error("assertion failed: {0}")] FailClosed(Guard), #[error("not found: {0}")] NotFound(Missing), #[error("conflict: {0}")] Conflict(Refused), #[error("invalid: {0}")] Invalid(String), #[error("blocked: {0}")] Blocked(String), #[error("sandbox pool exhausted: {0}")] PoolExhausted(PoolFull), #[error("world mismatch: {0}")] WorldMismatch(WorldGap), #[error("transient: {0}")] Transient(TransientCause), #[error("{0}")] Other(String), } impl Error { pub fn db(s: impl fmt::Display) -> Self { Error::Db(s.to_string()) } pub fn git(s: impl fmt::Display) -> Self { Error::Git(s.to_string()) } pub fn fail_closed(g: impl Into) -> Self { Error::FailClosed(g.into()) } pub fn not_found(m: impl Into) -> Self { Error::NotFound(m.into()) } pub fn conflict(r: impl Into) -> Self { Error::Conflict(r.into()) } pub fn invalid(s: impl fmt::Display) -> Self { Error::Invalid(s.to_string()) } pub fn blocked(s: impl fmt::Display) -> Self { Error::Blocked(s.to_string()) } pub fn other(s: impl fmt::Display) -> Self { Error::Other(s.to_string()) } pub fn transient(c: impl Into) -> Self { Error::Transient(c.into()) } pub fn pool_exhausted(p: impl Into) -> Self { Error::PoolExhausted(p.into()) } pub fn world_mismatch(w: impl Into) -> Self { Error::WorldMismatch(w.into()) } pub fn is_pool_exhausted(&self) -> bool { matches!(self, Error::PoolExhausted(_)) } pub fn is_transient(&self) -> bool { match self { Error::Http(_) | Error::Transient(_) => true, Error::PoolExhausted(_) | Error::WorldMismatch(_) => false, Error::Io(e) => matches!( e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut | std::io::ErrorKind::Interrupted | std::io::ErrorKind::BrokenPipe | std::io::ErrorKind::ConnectionReset | std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::ConnectionAborted ), _ => false, } } } pub type Result = std::result::Result; #[cfg(test)] mod tests { use super::*; #[test] fn a_full_disk_is_not_a_retryable_failure() { let enospc = Error::Io(std::io::Error::from_raw_os_error(28)); let eacces = Error::Io(std::io::Error::from_raw_os_error(13)); assert!(!enospc.is_transient(), "a full disk does not clear itself between retries"); assert!(!eacces.is_transient(), "a permissions problem does not clear itself either"); } #[test] fn what_a_moment_might_fix_is_retried() { let refused = Error::Io(std::io::Error::from_raw_os_error(111)); assert!(refused.is_transient()); assert!(Error::transient("mirror returned 502").is_transient()); assert!(Error::Http("connection reset".into()).is_transient()); assert!(!Error::invalid("recipe has no pkgbase").is_transient()); assert!(!Error::fail_closed("identity hash moved").is_transient()); assert!(!Error::pool_exhausted("at quota").is_transient()); 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(_)))); } }