Skip to main content

wardline_core/
error.rs

1//! Failures that stop a guard from reaching a decision.
2
3use core::fmt;
4
5/// Something went wrong while evaluating a guard.
6///
7/// A `GuardError` means the guard did *not* decide — it is not a decision to
8/// block. Conflating "the check failed" with "the check says no" is how a
9/// broken dependency becomes a silent hole. Blocking is [`Verdict::Block`];
10/// failing is this, resolved by the guard's own [`FailPolicy`].
11///
12/// `#[non_exhaustive]`: match with a wildcard arm, since new failure modes
13/// may arrive in a minor release.
14///
15/// [`Verdict::Block`]: crate::Verdict::Block
16/// [`FailPolicy`]: crate::FailPolicy
17#[derive(Debug, Clone, PartialEq, Eq, Hash)]
18#[non_exhaustive]
19pub enum GuardError {
20    /// The guard did not finish within its declared [`Guard::timeout`].
21    ///
22    /// For a non-strict guard this is best-effort: the pipeline stops
23    /// *waiting*, but the work may still be running. See
24    /// `docs/RELIABILITY.md`.
25    ///
26    /// [`Guard::timeout`]: crate::Guard::timeout
27    Timeout,
28
29    /// A strict guard blew through its deadline.
30    ///
31    /// Unlike [`GuardError::Timeout`], this reports a contract violation: a
32    /// [`Guard::strict`] guard promised to consult the deadline and return on
33    /// its own. Produced by the pipeline, not by guard authors.
34    ///
35    /// [`Guard::strict`]: crate::Guard::strict
36    DeadlineViolated,
37
38    /// The guard panicked and the pipeline caught it. Carries the panic
39    /// message where one could be recovered.
40    ///
41    /// Produced by the pipeline, not by guard authors — deliberate failures
42    /// should be [`GuardError::Internal`].
43    Panicked(String),
44
45    /// The guard's own logic failed: a malformed rule, an impossible state, a
46    /// config error found at check time.
47    Internal(String),
48
49    /// Something the guard relies on failed: a datastore, a model endpoint.
50    ///
51    /// Separate from [`GuardError::Internal`] because the operational
52    /// response differs — a bug in the guard versus an outage elsewhere — and
53    /// because this is the variant worth retrying.
54    Dependency(String),
55}
56
57impl GuardError {
58    /// Builds a [`GuardError::Panicked`] from anything string-like.
59    ///
60    /// Prefer letting the pipeline produce this. Guard authors should return
61    /// [`GuardError::Internal`] for deliberate failures.
62    pub fn panicked(message: impl Into<String>) -> Self {
63        GuardError::Panicked(message.into())
64    }
65
66    /// Builds a [`GuardError::Internal`] from anything string-like.
67    pub fn internal(message: impl Into<String>) -> Self {
68        GuardError::Internal(message.into())
69    }
70
71    /// Builds a [`GuardError::Dependency`] from anything string-like.
72    pub fn dependency(message: impl Into<String>) -> Self {
73        GuardError::Dependency(message.into())
74    }
75
76    /// Returns `true` for both the soft ([`GuardError::Timeout`]) and hard
77    /// ([`GuardError::DeadlineViolated`]) time failures.
78    pub fn is_timeout(&self) -> bool {
79        matches!(self, GuardError::Timeout | GuardError::DeadlineViolated)
80    }
81
82    /// Returns `true` if this failure came from a caught panic.
83    pub fn is_panic(&self) -> bool {
84        matches!(self, GuardError::Panicked(_))
85    }
86
87    /// A short, stable label for metrics and log fields.
88    ///
89    /// Unlike `Display`, it never includes the message payload, so it is safe
90    /// as a bounded-cardinality key.
91    pub fn kind(&self) -> &'static str {
92        match self {
93            GuardError::Timeout => "timeout",
94            GuardError::DeadlineViolated => "deadline_violated",
95            GuardError::Panicked(_) => "panicked",
96            GuardError::Internal(_) => "internal",
97            GuardError::Dependency(_) => "dependency",
98        }
99    }
100
101    /// The message carried by this error, if it has one.
102    pub fn message(&self) -> Option<&str> {
103        match self {
104            GuardError::Panicked(message)
105            | GuardError::Internal(message)
106            | GuardError::Dependency(message) => Some(message),
107            GuardError::Timeout | GuardError::DeadlineViolated => None,
108        }
109    }
110}
111
112impl fmt::Display for GuardError {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        match self {
115            GuardError::Timeout => f.write_str("guard timed out"),
116            GuardError::DeadlineViolated => {
117                f.write_str("strict guard exceeded its deadline without yielding")
118            }
119            GuardError::Panicked(message) => write!(f, "guard panicked: {message}"),
120            GuardError::Internal(message) => write!(f, "guard failed internally: {message}"),
121            GuardError::Dependency(message) => write!(f, "guard dependency failed: {message}"),
122        }
123    }
124}
125
126impl std::error::Error for GuardError {}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    fn all() -> Vec<GuardError> {
133        vec![
134            GuardError::Timeout,
135            GuardError::DeadlineViolated,
136            GuardError::Panicked("boom".to_owned()),
137            GuardError::Internal("bad rule".to_owned()),
138            GuardError::Dependency("classifier unreachable".to_owned()),
139        ]
140    }
141
142    #[test]
143    fn kinds_are_unique_and_payload_free() {
144        let mut kinds: Vec<_> = all().iter().map(GuardError::kind).collect();
145        let count = kinds.len();
146        kinds.sort_unstable();
147        kinds.dedup();
148        assert_eq!(kinds.len(), count, "two variants share a kind label");
149        for error in all() {
150            assert!(
151                !error.kind().contains(' '),
152                "kind labels must be usable as metric dimensions"
153            );
154        }
155    }
156
157    #[test]
158    fn timeout_predicates_cover_both_time_variants() {
159        assert!(GuardError::Timeout.is_timeout());
160        assert!(GuardError::DeadlineViolated.is_timeout());
161        assert!(!GuardError::internal("x").is_timeout());
162        assert!(!GuardError::dependency("x").is_timeout());
163    }
164
165    #[test]
166    fn only_panicked_is_a_panic() {
167        assert!(GuardError::Panicked("boom".to_owned()).is_panic());
168        assert!(!GuardError::internal("boom").is_panic());
169    }
170
171    #[test]
172    fn messages_are_carried_by_the_variants_that_have_them() {
173        assert_eq!(GuardError::internal("bad rule").message(), Some("bad rule"));
174        assert_eq!(GuardError::dependency("down").message(), Some("down"));
175        assert_eq!(
176            GuardError::Panicked("boom".to_owned()).message(),
177            Some("boom")
178        );
179        assert_eq!(GuardError::Timeout.message(), None);
180        assert_eq!(GuardError::DeadlineViolated.message(), None);
181    }
182
183    #[test]
184    fn display_includes_the_message_for_diagnostics() {
185        assert_eq!(
186            GuardError::Panicked("index out of bounds".to_owned()).to_string(),
187            "guard panicked: index out of bounds"
188        );
189        assert_eq!(GuardError::Timeout.to_string(), "guard timed out");
190    }
191
192    #[test]
193    fn is_a_std_error() {
194        fn assert_error<E: std::error::Error>(_: &E) {}
195        for error in all() {
196            assert_error(&error);
197        }
198    }
199}