Skip to main content

eggfetch_core/
error.rs

1//! Error type and result alias for the eggfetch engine.
2
3use crate::timeout::TimeoutPhase;
4
5/// Result alias using [`Error`].
6pub type Result<T> = std::result::Result<T, Error>;
7
8/// Error taxonomy for the eggfetch engine.
9///
10/// This is the single error entry point for callers. Source errors are
11/// preserved via [`std::error::Error::source`].
12#[derive(Debug, Clone, thiserror::Error)]
13pub enum Error {
14    /// The provided URL could not be parsed.
15    #[error("invalid URL: {0}")]
16    InvalidUrl(String),
17
18    /// The provided HTTP method could not be parsed.
19    #[error("invalid method: {0}")]
20    InvalidMethod(String),
21
22    /// The provided header name is not valid.
23    #[error("invalid header name: {0}")]
24    InvalidHeaderName(String),
25
26    /// The provided header value is not valid.
27    #[error("invalid header value: {0}")]
28    InvalidHeaderValue(String),
29
30    /// The request could not be built.
31    #[error("request build error: {0}")]
32    RequestBuild(String),
33
34    /// A connection could not be established.
35    #[error("connect error: {0}")]
36    Connect(String),
37
38    /// A TLS handshake or configuration error occurred.
39    #[error("TLS error: {0}")]
40    Tls(String),
41
42    /// An HTTP protocol error occurred.
43    #[error("protocol error: {0}")]
44    Protocol(String),
45
46    /// An error occurred while processing a request or response body.
47    #[error("body error: {0}")]
48    Body(String),
49
50    /// An error from the underlying hyper HTTP engine.
51    #[error("hyper error: {0}")]
52    Hyper(#[from] std::sync::Arc<hyper::Error>),
53
54    /// An error from the hyper-util legacy client.
55    #[error("hyper client error: {0}")]
56    HyperClient(#[source] std::sync::Arc<hyper_util::client::legacy::Error>),
57
58    /// An I/O error occurred.
59    #[error("I/O error: {0}")]
60    Io(#[from] std::sync::Arc<std::io::Error>),
61
62    /// The requested feature is not yet supported.
63    #[error("unsupported: {0}")]
64    Unsupported(String),
65
66    /// Connection pool acquisition failed or was cancelled.
67    #[error("pool error: {0}")]
68    Pool(String),
69
70    /// The redirect location is missing or invalid.
71    #[error("invalid redirect location: {0}")]
72    InvalidRedirectLocation(String),
73
74    /// An authentication header value is invalid.
75    #[error("invalid auth header: {0}")]
76    InvalidAuthHeader(String),
77
78    /// Conflicting authentication sources (e.g., explicit header + auth config).
79    #[error("conflicting auth: {0}")]
80    ConflictingAuth(String),
81
82    /// A streaming body cannot be replayed for a redirect.
83    #[error("body not replayable for redirect: streaming request bodies cannot be resent")]
84    BodyNotReplayableForRedirect,
85
86    /// Too many redirects were followed.
87    #[error("too many redirects ({followed} followed, max {max})")]
88    TooManyRedirects {
89        /// Number of redirects actually followed.
90        followed: usize,
91        /// Maximum allowed.
92        max: usize,
93    },
94
95    /// A response decompression error occurred.
96    #[error("decompression error: {0}")]
97    Decompression(String),
98
99    /// The server used a content encoding that is not supported.
100    #[error("unsupported content encoding: {0}")]
101    UnsupportedContentEncoding(String),
102
103    /// A timeout elapsed during the specified phase.
104    #[error("{phase} timeout after {elapsed:?}")]
105    Timeout {
106        /// Which phase of the request timed out.
107        phase: TimeoutPhase,
108        /// The duration that was exceeded.
109        elapsed: std::time::Duration,
110    },
111
112    /// The proxy URL is invalid or malformed.
113    #[error("invalid proxy URL: {0}")]
114    InvalidProxyUrl(String),
115
116    /// The proxy server rejected the connection or tunnel.
117    #[error("proxy error: {0}")]
118    ProxyConnect(String),
119
120    /// The proxy server requires authentication.
121    #[error("proxy authentication required")]
122    ProxyAuthRequired,
123
124    /// The CONNECT tunnel was rejected by the proxy.
125    #[error("CONNECT rejected: {status} {body}")]
126    ProxyConnectRejected {
127        /// HTTP status code from the proxy.
128        status: u16,
129        /// Response body or description.
130        body: String,
131    },
132
133    /// The proxy response could not be parsed.
134    #[error("malformed proxy response: {0}")]
135    MalformedProxyResponse(String),
136
137    /// The decoded body exceeded the configured size limit.
138    #[error("decoded body exceeded max decoded body size")]
139    DecodedBodyTooLarge,
140
141    /// The decompression ratio exceeded the configured limit.
142    #[error("decompression ratio exceeded max ratio")]
143    DecompressionRatioExceeded,
144
145    /// A TLS configuration error occurred.
146    #[error("TLS configuration error: {0}")]
147    TlsConfig(String),
148
149    /// A CA certificate bundle could not be parsed.
150    #[error("CA bundle error: {0}")]
151    CaBundle(String),
152
153    /// A client certificate or private key could not be loaded.
154    #[error("client certificate error: {0}")]
155    ClientCert(String),
156
157    /// A private key could not be parsed or decrypted.
158    #[error("private key error: {0}")]
159    PrivateKey(String),
160
161    /// Certificate verification failed.
162    #[error("certificate verification failed: {0}")]
163    CertificateVerification(String),
164
165    /// Hostname verification failed.
166    #[error("hostname verification failed: {0}")]
167    HostnameVerification(String),
168
169    /// The request body is not replayable and cannot be retried.
170    #[error("body not replayable for retry")]
171    BodyNotReplayableForRetry,
172
173    /// The retry budget was exhausted.
174    #[error("retry budget exhausted after {attempts} attempts")]
175    RetryBudgetExhausted {
176        /// Number of attempts made.
177        attempts: usize,
178    },
179
180    /// Retry is not enabled for this request or client.
181    #[error("retry not configured")]
182    RetryNotConfigured,
183
184    /// The HTTP/2 connection received a GOAWAY frame from the server.
185    ///
186    /// `last_stream_id` is currently always `0`: `h2` 0.4 does not expose
187    /// the GOAWAY last-stream-id through its public error API, so the raw
188    /// error text is preserved in `debug_data` instead.
189    #[error("HTTP/2 GOAWAY: last_stream_id={last_stream_id}, debug={debug_data}")]
190    Http2GoAway {
191        /// The last stream ID the server will process (currently always `0`, see above).
192        last_stream_id: u32,
193        /// Debug data from the GOAWAY frame.
194        debug_data: String,
195    },
196
197    /// An HTTP/2 stream was reset by the server with the given reason code.
198    #[error("HTTP/2 stream reset: {reason}")]
199    Http2StreamReset {
200        /// The HTTP/2 reason code (e.g., `REFUSED_STREAM`, `CANCEL`).
201        reason: String,
202    },
203
204    /// An HTTP/2 flow-control error occurred.
205    #[error("HTTP/2 flow control error: {0}")]
206    Http2FlowControl(String),
207
208    /// An HTTP/2 protocol error occurred.
209    #[error("HTTP/2 protocol error: {0}")]
210    Http2Protocol(String),
211
212    /// An HTTP/3 connection error occurred.
213    #[error("HTTP/3 connect error: {0}")]
214    H3Connect(String),
215
216    /// An HTTP/3 connection was closed by the peer.
217    #[error("HTTP/3 connection closed: {0}")]
218    H3ConnectionClosed(String),
219
220    /// An HTTP/3 stream error occurred.
221    #[error("HTTP/3 stream error: {0}")]
222    H3Stream(String),
223
224    /// An HTTP/3 protocol error occurred.
225    #[error("HTTP/3 protocol error: {0}")]
226    H3Protocol(String),
227
228    /// A trace callback signaled the transport to abort.
229    #[error("trace callback aborted the request")]
230    TraceCallbackAborted,
231}
232
233impl Error {
234    /// Returns the category of this error as a static string.
235    #[must_use]
236    pub fn kind(&self) -> &'static str {
237        match self {
238            Self::InvalidUrl(_) => "invalid_url",
239            Self::InvalidMethod(_) => "invalid_method",
240            Self::InvalidHeaderName(_) => "invalid_header_name",
241            Self::InvalidHeaderValue(_) => "invalid_header_value",
242            Self::RequestBuild(_) => "request_build",
243            Self::Connect(_) => "connect",
244            Self::Tls(_) => "tls",
245            Self::Protocol(_) => "protocol",
246            Self::Body(_) => "body",
247            Self::Hyper(_) => "hyper",
248            Self::HyperClient(_) => "hyper_client",
249            Self::Io(_) => "io",
250            Self::Unsupported(_) => "unsupported",
251            Self::InvalidRedirectLocation(_) => "invalid_redirect_location",
252            Self::InvalidAuthHeader(_) => "invalid_auth_header",
253            Self::ConflictingAuth(_) => "conflicting_auth",
254            Self::BodyNotReplayableForRedirect => "body_not_replayable_for_redirect",
255            Self::TooManyRedirects { .. } => "too_many_redirects",
256            Self::Pool(_) => "pool",
257            Self::Decompression(_) => "decompression",
258            Self::UnsupportedContentEncoding(_) => "unsupported_content_encoding",
259            Self::Timeout { phase, .. } => match phase {
260                crate::timeout::TimeoutPhase::Pool => "timeout_pool",
261                crate::timeout::TimeoutPhase::Connect => "timeout_connect",
262                crate::timeout::TimeoutPhase::ProxyConnect => "timeout_proxy_connect",
263                crate::timeout::TimeoutPhase::ProxyTls => "timeout_proxy_tls",
264                crate::timeout::TimeoutPhase::Write => "timeout_write",
265                crate::timeout::TimeoutPhase::Read => "timeout_read",
266                crate::timeout::TimeoutPhase::Total => "timeout_total",
267            },
268            Self::InvalidProxyUrl(_) => "invalid_proxy_url",
269            Self::ProxyConnect(_) => "proxy_connect",
270            Self::ProxyAuthRequired => "proxy_auth_required",
271            Self::ProxyConnectRejected { .. } => "proxy_connect_rejected",
272            Self::MalformedProxyResponse(_) => "malformed_proxy_response",
273            Self::DecodedBodyTooLarge => "decoded_body_too_large",
274            Self::DecompressionRatioExceeded => "decompression_ratio_exceeded",
275            Self::TlsConfig(_) => "tls_config",
276            Self::CaBundle(_) => "ca_bundle",
277            Self::ClientCert(_) => "client_cert",
278            Self::PrivateKey(_) => "private_key",
279            Self::CertificateVerification(_) => "certificate_verification",
280            Self::HostnameVerification(_) => "hostname_verification",
281            Self::BodyNotReplayableForRetry => "body_not_replayable_for_retry",
282            Self::RetryBudgetExhausted { .. } => "retry_budget_exhausted",
283            Self::RetryNotConfigured => "retry_not_configured",
284            Self::Http2GoAway { .. } => "http2_go_away",
285            Self::Http2StreamReset { .. } => "http2_stream_reset",
286            Self::Http2FlowControl(_) => "http2_flow_control",
287            Self::Http2Protocol(_) => "http2_protocol",
288            Self::H3Connect(_) => "h3_connect",
289            Self::H3ConnectionClosed(_) => "h3_connection_closed",
290            Self::H3Stream(_) => "h3_stream",
291            Self::H3Protocol(_) => "h3_protocol",
292            Self::TraceCallbackAborted => "trace_callback_aborted",
293        }
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    #[test]
302    fn error_display() {
303        let err = Error::InvalidUrl("not a url".into());
304        assert_eq!(err.to_string(), "invalid URL: not a url");
305    }
306
307    #[test]
308    fn error_kind() {
309        let err = Error::Connect("refused".into());
310        assert_eq!(err.kind(), "connect");
311    }
312
313    #[test]
314    fn error_from_io() {
315        let io_err = std::sync::Arc::new(std::io::Error::other("test"));
316        let err: Error = io_err.into();
317        assert_eq!(err.kind(), "io");
318    }
319
320    #[test]
321    fn error_http2_go_away_display() {
322        let err = Error::Http2GoAway {
323            last_stream_id: 1,
324            debug_data: "no error: connection closed".into(),
325        };
326        assert_eq!(err.kind(), "http2_go_away");
327        let msg = err.to_string();
328        assert!(msg.contains("GOAWAY"));
329        assert!(msg.contains("no error: connection closed"));
330    }
331
332    #[test]
333    fn error_http2_stream_reset_display() {
334        let err = Error::Http2StreamReset {
335            reason: "REFUSED_STREAM: stream refused".into(),
336        };
337        assert_eq!(err.kind(), "http2_stream_reset");
338        assert!(err.to_string().contains("REFUSED_STREAM"));
339    }
340
341    #[test]
342    fn error_http2_flow_control_display() {
343        let err = Error::Http2FlowControl("flow-control violated".into());
344        assert_eq!(err.kind(), "http2_flow_control");
345    }
346
347    #[test]
348    fn error_http2_protocol_display() {
349        let err = Error::Http2Protocol("stream closed after headers".into());
350        assert_eq!(err.kind(), "http2_protocol");
351    }
352
353    #[test]
354    fn http2_refused_stream_is_retryable() {
355        let err = Error::Http2StreamReset {
356            reason: "REFUSED_STREAM: stream refused before processing".into(),
357        };
358        assert!(crate::retry::RetryPolicy::is_error_retryable(&err));
359    }
360
361    #[test]
362    fn http2_cancel_is_not_retryable() {
363        let err = Error::Http2StreamReset {
364            reason: "CANCEL: stream no longer needed".into(),
365        };
366        assert!(!crate::retry::RetryPolicy::is_error_retryable(&err));
367    }
368
369    #[test]
370    fn http2_go_away_is_not_retryable() {
371        let err = Error::Http2GoAway {
372            last_stream_id: 0,
373            debug_data: " shutting down".into(),
374        };
375        assert!(!crate::retry::RetryPolicy::is_error_retryable(&err));
376    }
377}