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