Skip to main content

eggfetch_core/
error.rs

1//! Error type and result alias for the eggfetch engine.
2
3use crate::timeout::TimeoutPhase;
4
5use std::sync::atomic::{AtomicU8, Ordering};
6use std::sync::Arc;
7
8/// Result alias using [`Error`].
9pub type Result<T> = std::result::Result<T, Error>;
10
11/// Evidence-backed detail for a request that failed while establishing a
12/// network connection.
13///
14/// This is an additive, opt-in classification. It deliberately does not
15/// replace [`Error::kind`] and is only reported when the transport exposes
16/// typed evidence for the category.
17#[non_exhaustive]
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum NetworkFailureKind {
20    /// Name resolution failed before a destination address was attempted.
21    Dns,
22    /// Every attempted destination failed with connection refusal.
23    ConnectionRefused,
24    /// A connection-establishment failure that is not more specifically
25    /// classified.
26    Connect,
27}
28
29/// A request error with optional structured connection-failure detail.
30///
31/// The ordinary [`Error`] remains the compatibility surface. Use
32/// [`Client::send_detailed`](crate::Client::send_detailed) or
33/// [`RequestBuilder::send_detailed`](crate::RequestBuilder::send_detailed)
34/// when native Rust code needs the additional, evidence-backed network
35/// classification.
36pub struct RequestFailure {
37    error: Error,
38    network_failure: Option<NetworkFailureKind>,
39}
40
41impl RequestFailure {
42    /// Return the original public error by reference.
43    #[must_use]
44    pub fn error(&self) -> &Error {
45        &self.error
46    }
47
48    /// Consume the detailed wrapper and return the original public error.
49    #[must_use]
50    pub fn into_error(self) -> Error {
51        self.error
52    }
53
54    /// Return evidence-backed connection-failure detail, when available.
55    #[must_use]
56    pub fn network_failure_kind(&self) -> Option<NetworkFailureKind> {
57        self.network_failure
58    }
59
60    /// Return whether the error represents a timeout.
61    ///
62    /// This includes both ordinary request-phase [`Error::Timeout`] values
63    /// and established-transport inactivity [`Error::TransportIoTimeout`]
64    /// values. Caller-dialer timeout categories remain available through
65    /// [`Error::custom_transport_error`] and are not reclassified here.
66    #[must_use]
67    pub fn is_timeout(&self) -> bool {
68        matches!(
69            self.error,
70            Error::Timeout { .. } | Error::TransportIoTimeout { .. }
71        )
72    }
73
74    /// Return the request timeout phase, when the error carries one.
75    ///
76    /// Established-transport inactivity timeouts intentionally return
77    /// `None`; they are not ordinary request-phase timeouts.
78    #[must_use]
79    pub fn timeout_phase(&self) -> Option<TimeoutPhase> {
80        match self.error {
81            Error::Timeout { phase, .. } => Some(phase),
82            _ => None,
83        }
84    }
85
86    pub(crate) fn from_error(error: Error) -> Self {
87        Self {
88            error,
89            network_failure: None,
90        }
91    }
92
93    pub(crate) fn from_context(error: Error, context: &RequestFailureContext) -> Self {
94        Self {
95            error,
96            network_failure: context.network_failure_kind(),
97        }
98    }
99}
100
101impl std::fmt::Debug for RequestFailure {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        f.debug_struct("RequestFailure")
104            .field("error", &self.error)
105            .field("network_failure", &self.network_failure)
106            .finish()
107    }
108}
109
110impl std::fmt::Display for RequestFailure {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        self.error.fmt(f)
113    }
114}
115
116impl std::error::Error for RequestFailure {
117    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
118        self.error.source()
119    }
120}
121
122/// Request-local storage for the one terminal network classification.
123///
124/// This is only allocated by detailed sends. An atomic is sufficient because
125/// the context stores one small value and later terminal attempts replace
126/// earlier transient classifications.
127pub(crate) struct RequestFailureContext {
128    network_failure: AtomicU8,
129}
130
131impl RequestFailureContext {
132    pub(crate) fn new() -> Arc<Self> {
133        Arc::new(Self {
134            network_failure: AtomicU8::new(0),
135        })
136    }
137
138    pub(crate) fn clear(&self) {
139        self.network_failure.store(0, Ordering::Relaxed);
140    }
141
142    pub(crate) fn record(&self, kind: NetworkFailureKind) {
143        self.network_failure
144            .store(kind as u8 + 1, Ordering::Relaxed);
145    }
146
147    fn network_failure_kind(&self) -> Option<NetworkFailureKind> {
148        match self.network_failure.load(Ordering::Relaxed) {
149            1 => Some(NetworkFailureKind::Dns),
150            2 => Some(NetworkFailureKind::ConnectionRefused),
151            3 => Some(NetworkFailureKind::Connect),
152            _ => None,
153        }
154    }
155}
156
157/// Error taxonomy for the eggfetch engine.
158///
159/// This is the single error entry point for callers. Source errors are
160/// preserved via [`std::error::Error::source`].
161#[derive(Debug, Clone, thiserror::Error)]
162pub enum Error {
163    /// The provided URL could not be parsed.
164    #[error("invalid URL: {0}")]
165    InvalidUrl(String),
166
167    /// The provided HTTP method could not be parsed.
168    #[error("invalid method: {0}")]
169    InvalidMethod(String),
170
171    /// The provided header name is not valid.
172    #[error("invalid header name: {0}")]
173    InvalidHeaderName(String),
174
175    /// The provided header value is not valid.
176    #[error("invalid header value: {0}")]
177    InvalidHeaderValue(String),
178
179    /// The request could not be built.
180    #[error("request build error: {0}")]
181    RequestBuild(String),
182
183    /// A caller-supplied resolved destination is invalid for the request.
184    #[error("invalid resolved destination: {0}")]
185    InvalidResolvedTarget(String),
186
187    /// A pinned request attempted to follow a redirect that changes origin.
188    #[error("resolved destination cannot be reused across a cross-origin redirect")]
189    ResolvedTargetRedirect,
190
191    /// Request JSON serialization failed.
192    #[error("JSON serialization error: {0}")]
193    JsonSerialize(String),
194
195    /// Response JSON deserialization failed.
196    #[error("JSON deserialization error: {0}")]
197    JsonDeserialize(String),
198
199    /// A connection could not be established.
200    #[error("connect error: {0}")]
201    Connect(String),
202
203    /// A caller-supplied native dialer failed.
204    #[error("custom transport error: {0}")]
205    CustomTransport(#[source] std::sync::Arc<crate::transport::dialer::DialError>),
206
207    /// A TLS handshake or configuration error occurred.
208    #[error("TLS error: {0}")]
209    Tls(String),
210
211    /// An HTTP protocol error occurred.
212    #[error("protocol error: {0}")]
213    Protocol(String),
214
215    /// An error occurred while processing a request or response body.
216    #[error("body error: {0}")]
217    Body(String),
218
219    /// An error from the underlying hyper HTTP engine.
220    #[error("hyper error: {0}")]
221    Hyper(#[from] std::sync::Arc<hyper::Error>),
222
223    /// An error from the hyper-util legacy client.
224    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
225    #[error("hyper client error: {0}")]
226    HyperClient(#[source] std::sync::Arc<hyper_util::client::legacy::Error>),
227
228    /// An I/O error occurred.
229    #[error("I/O error: {0}")]
230    Io(#[from] std::sync::Arc<std::io::Error>),
231
232    /// The requested feature is not yet supported.
233    #[error("unsupported: {0}")]
234    Unsupported(String),
235
236    /// Connection pool acquisition failed or was cancelled.
237    #[error("pool error: {0}")]
238    Pool(String),
239
240    /// The redirect location is missing or invalid.
241    #[error("invalid redirect location: {0}")]
242    InvalidRedirectLocation(String),
243
244    /// An authentication header value is invalid.
245    #[error("invalid auth header: {0}")]
246    InvalidAuthHeader(String),
247
248    /// Conflicting authentication sources (e.g., explicit header + auth config).
249    #[error("conflicting auth: {0}")]
250    ConflictingAuth(String),
251
252    /// A streaming body cannot be replayed for a redirect.
253    #[error("body not replayable for redirect: streaming request bodies cannot be resent")]
254    BodyNotReplayableForRedirect,
255
256    /// Too many redirects were followed.
257    #[error("too many redirects ({followed} followed, max {max})")]
258    TooManyRedirects {
259        /// Number of redirects actually followed.
260        followed: usize,
261        /// Maximum allowed.
262        max: usize,
263    },
264
265    /// A response decompression error occurred.
266    #[error("decompression error: {0}")]
267    Decompression(String),
268
269    /// The server used a content encoding that is not supported.
270    #[error("unsupported content encoding: {0}")]
271    UnsupportedContentEncoding(String),
272
273    /// A timeout elapsed during the specified phase.
274    #[error("{phase} timeout after {elapsed:?}")]
275    Timeout {
276        /// Which phase of the request timed out.
277        phase: TimeoutPhase,
278        /// The duration that was exceeded.
279        elapsed: std::time::Duration,
280    },
281
282    /// An established transport made no read or write progress before its
283    /// dedicated inactivity deadline.
284    #[error("transport {direction:?} inactivity timeout after {elapsed:?}")]
285    TransportIoTimeout {
286        /// Which established I/O direction stalled.
287        direction: crate::transport::lifecycle::TransportIoDirection,
288        /// Duration for which no progress was observed.
289        elapsed: std::time::Duration,
290    },
291
292    /// The proxy URL is invalid or malformed.
293    #[error("invalid proxy URL: {0}")]
294    InvalidProxyUrl(String),
295
296    /// The proxy server rejected the connection or tunnel.
297    #[error("proxy error: {0}")]
298    ProxyConnect(String),
299
300    /// The proxy server requires authentication.
301    #[error("proxy authentication required")]
302    ProxyAuthRequired,
303
304    /// The CONNECT tunnel was rejected by the proxy.
305    #[error("CONNECT rejected: {status} {body}")]
306    ProxyConnectRejected {
307        /// HTTP status code from the proxy.
308        status: u16,
309        /// Response body or description.
310        body: String,
311    },
312
313    /// The proxy response could not be parsed.
314    #[error("malformed proxy response: {0}")]
315    MalformedProxyResponse(String),
316
317    /// The decoded body exceeded the configured size limit.
318    #[error("decoded body exceeded max decoded body size")]
319    DecodedBodyTooLarge,
320
321    /// The decompression ratio exceeded the configured limit.
322    #[error("decompression ratio exceeded max ratio")]
323    DecompressionRatioExceeded,
324
325    /// A TLS configuration error occurred.
326    #[error("TLS configuration error: {0}")]
327    TlsConfig(String),
328
329    /// A CA certificate bundle could not be parsed.
330    #[error("CA bundle error: {0}")]
331    CaBundle(String),
332
333    /// A client certificate or private key could not be loaded.
334    #[error("client certificate error: {0}")]
335    ClientCert(String),
336
337    /// A private key could not be parsed or decrypted.
338    #[error("private key error: {0}")]
339    PrivateKey(String),
340
341    /// Certificate verification failed.
342    #[error("certificate verification failed: {0}")]
343    CertificateVerification(String),
344
345    /// Hostname verification failed.
346    #[error("hostname verification failed: {0}")]
347    HostnameVerification(String),
348
349    /// The request body is not replayable and cannot be retried.
350    #[error("body not replayable for retry")]
351    BodyNotReplayableForRetry,
352
353    /// The retry budget was exhausted.
354    #[error("retry budget exhausted after {attempts} attempts")]
355    RetryBudgetExhausted {
356        /// Number of attempts made.
357        attempts: usize,
358    },
359
360    /// Retry is not enabled for this request or client.
361    #[error("retry not configured")]
362    RetryNotConfigured,
363
364    /// The HTTP/2 connection received a GOAWAY frame from the server.
365    ///
366    /// `last_stream_id` is currently always `0`: `h2` 0.4 does not expose
367    /// the GOAWAY last-stream-id through its public error API, so the raw
368    /// error text is preserved in `debug_data` instead.
369    #[error("HTTP/2 GOAWAY: last_stream_id={last_stream_id}, debug={debug_data}")]
370    Http2GoAway {
371        /// The last stream ID the server will process (currently always `0`, see above).
372        last_stream_id: u32,
373        /// Debug data from the GOAWAY frame.
374        debug_data: String,
375    },
376
377    /// An HTTP/2 stream was reset by the server with the given reason code.
378    #[error("HTTP/2 stream reset: {reason}")]
379    Http2StreamReset {
380        /// The HTTP/2 reason code (e.g., `REFUSED_STREAM`, `CANCEL`).
381        reason: String,
382    },
383
384    /// An HTTP/2 flow-control error occurred.
385    #[error("HTTP/2 flow control error: {0}")]
386    Http2FlowControl(String),
387
388    /// An HTTP/2 protocol error occurred.
389    #[error("HTTP/2 protocol error: {0}")]
390    Http2Protocol(String),
391
392    /// An HTTP/3 connection error occurred.
393    #[error("HTTP/3 connect error: {0}")]
394    H3Connect(String),
395
396    /// An HTTP/3 connection was closed by the peer.
397    #[error("HTTP/3 connection closed: {0}")]
398    H3ConnectionClosed(String),
399
400    /// An HTTP/3 stream error occurred.
401    #[error("HTTP/3 stream error: {0}")]
402    H3Stream(String),
403
404    /// An HTTP/3 protocol error occurred.
405    #[error("HTTP/3 protocol error: {0}")]
406    H3Protocol(String),
407
408    /// A trace callback signaled the transport to abort.
409    #[error("trace callback aborted the request")]
410    TraceCallbackAborted,
411}
412
413impl Error {
414    /// Returns the category of this error as a static string.
415    #[must_use]
416    pub fn kind(&self) -> &'static str {
417        match self {
418            Self::InvalidUrl(_) => "invalid_url",
419            Self::InvalidMethod(_) => "invalid_method",
420            Self::InvalidHeaderName(_) => "invalid_header_name",
421            Self::InvalidHeaderValue(_) => "invalid_header_value",
422            Self::RequestBuild(_) => "request_build",
423            Self::InvalidResolvedTarget(_) => "invalid_resolved_target",
424            Self::ResolvedTargetRedirect => "resolved_target_redirect",
425            Self::JsonSerialize(_) => "json_serialize",
426            Self::JsonDeserialize(_) => "json_deserialize",
427            Self::Connect(_) => "connect",
428            Self::CustomTransport(_) => "custom_transport",
429            Self::Tls(_) => "tls",
430            Self::Protocol(_) => "protocol",
431            Self::Body(_) => "body",
432            Self::Hyper(_) => "hyper",
433            #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
434            Self::HyperClient(_) => "hyper_client",
435            Self::Io(_) => "io",
436            Self::Unsupported(_) => "unsupported",
437            Self::InvalidRedirectLocation(_) => "invalid_redirect_location",
438            Self::InvalidAuthHeader(_) => "invalid_auth_header",
439            Self::ConflictingAuth(_) => "conflicting_auth",
440            Self::BodyNotReplayableForRedirect => "body_not_replayable_for_redirect",
441            Self::TooManyRedirects { .. } => "too_many_redirects",
442            Self::Pool(_) => "pool",
443            Self::Decompression(_) => "decompression",
444            Self::UnsupportedContentEncoding(_) => "unsupported_content_encoding",
445            Self::Timeout { phase, .. } => match phase {
446                crate::timeout::TimeoutPhase::Pool => "timeout_pool",
447                crate::timeout::TimeoutPhase::Connect => "timeout_connect",
448                crate::timeout::TimeoutPhase::ProxyConnect => "timeout_proxy_connect",
449                crate::timeout::TimeoutPhase::ProxyTls => "timeout_proxy_tls",
450                crate::timeout::TimeoutPhase::Write => "timeout_write",
451                crate::timeout::TimeoutPhase::Read => "timeout_read",
452                crate::timeout::TimeoutPhase::Total => "timeout_total",
453            },
454            Self::TransportIoTimeout { direction, .. } => match direction {
455                crate::transport::lifecycle::TransportIoDirection::Read => "transport_read_timeout",
456                crate::transport::lifecycle::TransportIoDirection::Write => {
457                    "transport_write_timeout"
458                }
459            },
460            Self::InvalidProxyUrl(_) => "invalid_proxy_url",
461            Self::ProxyConnect(_) => "proxy_connect",
462            Self::ProxyAuthRequired => "proxy_auth_required",
463            Self::ProxyConnectRejected { .. } => "proxy_connect_rejected",
464            Self::MalformedProxyResponse(_) => "malformed_proxy_response",
465            Self::DecodedBodyTooLarge => "decoded_body_too_large",
466            Self::DecompressionRatioExceeded => "decompression_ratio_exceeded",
467            Self::TlsConfig(_) => "tls_config",
468            Self::CaBundle(_) => "ca_bundle",
469            Self::ClientCert(_) => "client_cert",
470            Self::PrivateKey(_) => "private_key",
471            Self::CertificateVerification(_) => "certificate_verification",
472            Self::HostnameVerification(_) => "hostname_verification",
473            Self::BodyNotReplayableForRetry => "body_not_replayable_for_retry",
474            Self::RetryBudgetExhausted { .. } => "retry_budget_exhausted",
475            Self::RetryNotConfigured => "retry_not_configured",
476            Self::Http2GoAway { .. } => "http2_go_away",
477            Self::Http2StreamReset { .. } => "http2_stream_reset",
478            Self::Http2FlowControl(_) => "http2_flow_control",
479            Self::Http2Protocol(_) => "http2_protocol",
480            Self::H3Connect(_) => "h3_connect",
481            Self::H3ConnectionClosed(_) => "h3_connection_closed",
482            Self::H3Stream(_) => "h3_stream",
483            Self::H3Protocol(_) => "h3_protocol",
484            Self::TraceCallbackAborted => "trace_callback_aborted",
485        }
486    }
487
488    /// Returns the nested caller error when this is a custom-dialer failure.
489    #[must_use]
490    pub fn custom_transport_error(&self) -> Option<&crate::transport::dialer::DialError> {
491        match self {
492            Self::CustomTransport(error) => Some(error.as_ref()),
493            _ => None,
494        }
495    }
496
497    /// Returns whether this is a physical-connection admission timeout.
498    #[must_use]
499    pub fn is_physical_connection_admission_timeout(&self) -> bool {
500        matches!(self, Self::Pool(message) if message == crate::transport::lifecycle::PHYSICAL_ADMISSION_TIMEOUT)
501    }
502
503    /// Returns whether this is an established-transport inactivity timeout.
504    #[must_use]
505    pub fn is_transport_io_timeout(&self) -> bool {
506        matches!(self, Self::TransportIoTimeout { .. })
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    use super::*;
513
514    #[test]
515    fn error_display() {
516        let err = Error::InvalidUrl("not a url".into());
517        assert_eq!(err.to_string(), "invalid URL: not a url");
518    }
519
520    #[test]
521    fn error_kind() {
522        let err = Error::Connect("refused".into());
523        assert_eq!(err.kind(), "connect");
524    }
525
526    #[test]
527    fn error_from_io() {
528        let io_err = std::sync::Arc::new(std::io::Error::other("test"));
529        let err: Error = io_err.into();
530        assert_eq!(err.kind(), "io");
531    }
532
533    #[test]
534    fn request_failure_exposes_timeout_without_changing_error() {
535        let error = Error::Timeout {
536            phase: TimeoutPhase::Connect,
537            elapsed: std::time::Duration::from_millis(5),
538        };
539        let failure = RequestFailure::from_error(error);
540        assert!(failure.is_timeout());
541        assert_eq!(failure.timeout_phase(), Some(TimeoutPhase::Connect));
542        assert_eq!(failure.error().kind(), "timeout_connect");
543        assert_eq!(failure.into_error().kind(), "timeout_connect");
544    }
545
546    #[test]
547    fn request_failure_keeps_transport_timeout_distinct() {
548        let failure = RequestFailure::from_error(Error::TransportIoTimeout {
549            direction: crate::transport::lifecycle::TransportIoDirection::Read,
550            elapsed: std::time::Duration::from_secs(1),
551        });
552        assert!(failure.is_timeout());
553        assert_eq!(failure.timeout_phase(), None);
554    }
555
556    #[test]
557    fn request_failure_context_replaces_transient_classification() {
558        let context = RequestFailureContext::new();
559        context.record(NetworkFailureKind::Dns);
560        context.record(NetworkFailureKind::ConnectionRefused);
561        let failure = RequestFailure::from_context(Error::Connect("refused".into()), &context);
562        assert_eq!(
563            failure.network_failure_kind(),
564            Some(NetworkFailureKind::ConnectionRefused)
565        );
566        context.clear();
567        assert_eq!(context.network_failure_kind(), None);
568    }
569
570    #[test]
571    fn error_http2_go_away_display() {
572        let err = Error::Http2GoAway {
573            last_stream_id: 1,
574            debug_data: "no error: connection closed".into(),
575        };
576        assert_eq!(err.kind(), "http2_go_away");
577        let msg = err.to_string();
578        assert!(msg.contains("GOAWAY"));
579        assert!(msg.contains("no error: connection closed"));
580    }
581
582    #[test]
583    fn error_http2_stream_reset_display() {
584        let err = Error::Http2StreamReset {
585            reason: "REFUSED_STREAM: stream refused".into(),
586        };
587        assert_eq!(err.kind(), "http2_stream_reset");
588        assert!(err.to_string().contains("REFUSED_STREAM"));
589    }
590
591    #[test]
592    fn error_http2_flow_control_display() {
593        let err = Error::Http2FlowControl("flow-control violated".into());
594        assert_eq!(err.kind(), "http2_flow_control");
595    }
596
597    #[test]
598    fn error_http2_protocol_display() {
599        let err = Error::Http2Protocol("stream closed after headers".into());
600        assert_eq!(err.kind(), "http2_protocol");
601    }
602
603    #[cfg(feature = "logical-retry")]
604    #[test]
605    fn http2_refused_stream_is_retryable() {
606        let err = Error::Http2StreamReset {
607            reason: "REFUSED_STREAM: stream refused before processing".into(),
608        };
609        assert!(crate::retry::RetryPolicy::is_error_retryable(&err));
610    }
611
612    #[cfg(feature = "logical-retry")]
613    #[test]
614    fn http2_cancel_is_not_retryable() {
615        let err = Error::Http2StreamReset {
616            reason: "CANCEL: stream no longer needed".into(),
617        };
618        assert!(!crate::retry::RetryPolicy::is_error_retryable(&err));
619    }
620
621    #[cfg(feature = "logical-retry")]
622    #[test]
623    fn http2_go_away_is_not_retryable() {
624        let err = Error::Http2GoAway {
625            last_stream_id: 0,
626            debug_data: " shutting down".into(),
627        };
628        assert!(!crate::retry::RetryPolicy::is_error_retryable(&err));
629    }
630}