Skip to main content

matier_core/
error.rs

1//! The single error type, with a recovery classification.
2
3use std::error::Error as StdError;
4use std::fmt;
5use std::time::Duration;
6
7type BoxError = Box<dyn StdError + Send + Sync>;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
10pub enum ErrorKind {
11    Connect,
12    Tls,
13    Dns,
14    Timeout,
15    Protocol,
16    Io,
17    Canceled,
18    BodyWrite,
19    BodyRead,
20    PoolTimeout,
21    InvalidRequest,
22    Closed,
23}
24
25impl ErrorKind {
26    /// Stable lowercase snake_case label (OTel `error.type`).
27    #[must_use]
28    pub const fn label(self) -> &'static str {
29        match self {
30            Self::Connect => "connect",
31            Self::Tls => "tls",
32            Self::Dns => "dns",
33            Self::Timeout => "timeout",
34            Self::Protocol => "protocol",
35            Self::Io => "io",
36            Self::Canceled => "canceled",
37            Self::BodyWrite => "body_write",
38            Self::BodyRead => "body_read",
39            Self::PoolTimeout => "pool_timeout",
40            Self::InvalidRequest => "invalid_request",
41            Self::Closed => "closed",
42        }
43    }
44
45    const fn describe(self) -> &'static str {
46        match self {
47            Self::Connect => "connection failed",
48            Self::Tls => "TLS error",
49            Self::Dns => "DNS resolution failed",
50            Self::Timeout => "operation timed out",
51            Self::Protocol => "protocol error",
52            Self::Io => "I/O error",
53            Self::Canceled => "request canceled",
54            Self::BodyWrite => "failed to write body",
55            Self::BodyRead => "failed to read body",
56            Self::PoolTimeout => "timed out waiting for a pooled connection",
57            Self::InvalidRequest => "invalid request",
58            Self::Closed => "connection closed",
59        }
60    }
61}
62
63/// Whether and how a failed request may be retried (fetch/seatbelt `RecoveryInfo` idea).
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub enum Recovery {
66    Never,
67    /// May have been processed; retry only idempotent requests.
68    Retryable,
69    /// Guaranteed not processed (GOAWAY above last_stream_id, REFUSED_STREAM, connect failure): always safe.
70    Unprocessed,
71    /// Server asked us to back off, optionally for this long.
72    Unavailable(Option<Duration>),
73}
74
75/// One error type for the whole client. Constructing one without a source does not allocate.
76pub struct Error {
77    kind: ErrorKind,
78    recovery: Recovery,
79    source: Option<BoxError>,
80}
81
82pub type Result<T> = std::result::Result<T, Error>;
83
84impl Error {
85    /// No source, no allocation.
86    #[must_use]
87    pub const fn new(kind: ErrorKind, recovery: Recovery) -> Self {
88        Self {
89            kind,
90            recovery,
91            source: None,
92        }
93    }
94
95    pub fn with_source(kind: ErrorKind, recovery: Recovery, source: impl Into<BoxError>) -> Self {
96        Self {
97            kind,
98            recovery,
99            source: Some(source.into()),
100        }
101    }
102
103    /// Connect failure: the request was never sent.
104    pub fn connect(source: impl Into<BoxError>) -> Self {
105        Self::with_source(ErrorKind::Connect, Recovery::Unprocessed, source)
106    }
107
108    pub fn dns(source: impl Into<BoxError>) -> Self {
109        Self::with_source(ErrorKind::Dns, Recovery::Unprocessed, source)
110    }
111
112    /// TLS failure that will not fix itself on retry (bad certificate, config).
113    pub fn tls(source: impl Into<BoxError>) -> Self {
114        Self::with_source(ErrorKind::Tls, Recovery::Never, source)
115    }
116
117    pub fn io(source: impl Into<BoxError>) -> Self {
118        Self::with_source(ErrorKind::Io, Recovery::Retryable, source)
119    }
120
121    pub fn protocol(source: impl Into<BoxError>) -> Self {
122        Self::with_source(ErrorKind::Protocol, Recovery::Never, source)
123    }
124
125    pub fn invalid_request(source: impl Into<BoxError>) -> Self {
126        Self::with_source(ErrorKind::InvalidRequest, Recovery::Never, source)
127    }
128
129    #[must_use]
130    pub const fn timeout() -> Self {
131        Self::new(ErrorKind::Timeout, Recovery::Retryable)
132    }
133
134    #[must_use]
135    pub const fn canceled() -> Self {
136        Self::new(ErrorKind::Canceled, Recovery::Never)
137    }
138
139    #[must_use]
140    pub const fn closed() -> Self {
141        Self::new(ErrorKind::Closed, Recovery::Retryable)
142    }
143
144    #[must_use]
145    pub const fn pool_timeout() -> Self {
146        Self::new(ErrorKind::PoolTimeout, Recovery::Unprocessed)
147    }
148
149    /// Guaranteed-unprocessed failure of the given kind.
150    pub fn unprocessed(kind: ErrorKind, source: impl Into<BoxError>) -> Self {
151        Self::with_source(kind, Recovery::Unprocessed, source)
152    }
153
154    /// Possibly-processed failure of the given kind.
155    pub fn retryable(kind: ErrorKind, source: impl Into<BoxError>) -> Self {
156        Self::with_source(kind, Recovery::Retryable, source)
157    }
158
159    #[must_use]
160    pub const fn unavailable(kind: ErrorKind, retry_after: Option<Duration>) -> Self {
161        Self::new(kind, Recovery::Unavailable(retry_after))
162    }
163
164    /// Overrides the recovery classification.
165    #[must_use]
166    pub fn with_recovery(mut self, recovery: Recovery) -> Self {
167        self.recovery = recovery;
168        self
169    }
170
171    #[must_use]
172    pub const fn kind(&self) -> ErrorKind {
173        self.kind
174    }
175
176    #[must_use]
177    pub const fn recovery(&self) -> Recovery {
178        self.recovery
179    }
180
181    /// Stable lowercase snake_case label for OTel `error.type`.
182    #[must_use]
183    pub const fn label(&self) -> &'static str {
184        self.kind.label()
185    }
186}
187
188impl fmt::Debug for Error {
189    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190        let mut d = f.debug_struct("Error");
191        d.field("kind", &self.kind)
192            .field("recovery", &self.recovery);
193        if let Some(s) = &self.source {
194            d.field("source", s);
195        }
196        d.finish()
197    }
198}
199
200impl fmt::Display for Error {
201    /// Prints only this level; walk `source()` for the chain.
202    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
203        f.write_str(self.kind.describe())?;
204        if let Some(s) = &self.source {
205            write!(f, ": {s}")?;
206        }
207        Ok(())
208    }
209}
210
211impl StdError for Error {
212    fn source(&self) -> Option<&(dyn StdError + 'static)> {
213        self.source
214            .as_deref()
215            .map(|e| e as &(dyn StdError + 'static))
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn labels_are_snake_case_and_unique() {
225        use ErrorKind::*;
226        let all = [
227            Connect,
228            Tls,
229            Dns,
230            Timeout,
231            Protocol,
232            Io,
233            Canceled,
234            BodyWrite,
235            BodyRead,
236            PoolTimeout,
237            InvalidRequest,
238            Closed,
239        ];
240        let mut seen = std::collections::HashSet::new();
241        for k in all {
242            let l = k.label();
243            assert!(
244                l.bytes().all(|b| b.is_ascii_lowercase() || b == b'_'),
245                "{l}"
246            );
247            assert!(seen.insert(l));
248        }
249        assert_eq!(Error::new(BodyRead, Recovery::Never).label(), "body_read");
250    }
251
252    #[test]
253    fn recovery_and_source_chain() {
254        let e = Error::connect(std::io::Error::other("refused"));
255        assert_eq!(e.kind(), ErrorKind::Connect);
256        assert_eq!(e.recovery(), Recovery::Unprocessed);
257        assert_eq!(e.source().unwrap().to_string(), "refused");
258        assert_eq!(e.to_string(), "connection failed: refused");
259        assert_eq!(Error::dns("x").recovery(), Recovery::Unprocessed);
260        assert_eq!(Error::tls("x").recovery(), Recovery::Never);
261        assert_eq!(Error::timeout().recovery(), Recovery::Retryable);
262        assert!(Error::closed().source().is_none());
263        let u = Error::unprocessed(ErrorKind::Protocol, "refused stream");
264        assert_eq!(
265            (u.kind(), u.recovery()),
266            (ErrorKind::Protocol, Recovery::Unprocessed)
267        );
268        let d = Duration::from_secs(1);
269        assert_eq!(
270            Error::unavailable(ErrorKind::Protocol, Some(d)).recovery(),
271            Recovery::Unavailable(Some(d))
272        );
273        assert_eq!(
274            Error::canceled()
275                .with_recovery(Recovery::Retryable)
276                .recovery(),
277            Recovery::Retryable
278        );
279    }
280
281    #[test]
282    fn is_send_sync() {
283        fn check<T: Send + Sync + 'static>() {}
284        check::<Error>();
285    }
286}