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/// Generic transport-failure classification for native embedders.
12///
13/// This is a diagnostic-only fact surface. It does not imply retryability and
14/// does not replace [`Error::kind`], [`Error::is_physical_connection_admission_timeout`],
15/// [`Error::is_transport_io_timeout`], [`Error::custom_transport_error`], or
16/// [`RequestFailure::network_failure_kind`]. Unknown or ambiguous evidence
17/// maps to `None`; classification never parses `Display`/`Debug` text and
18/// never exposes URLs, credentials, bodies, or nested error strings.
19#[non_exhaustive]
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum TransportFailureKind {
22    /// Typed evidence proves connection establishment failed and no more
23    /// specific TLS/cancellation/protocol category applies.
24    Connect,
25    /// TLS configuration, handshake, verification, or nested rustls
26    /// processing failed.
27    Tls,
28    /// Typed HTTP framing/protocol failure, including Hyper
29    /// parse/incomplete-message termination where proven.
30    Protocol,
31    /// Typed evidence says the transport/request was cancelled before
32    /// normal completion.
33    Cancelled,
34}
35
36/// Evidence-backed detail for a request that failed while establishing a
37/// network connection.
38///
39/// This is an additive, opt-in classification. It deliberately does not
40/// replace [`Error::kind`] and is only reported when the transport exposes
41/// typed evidence for the category.
42#[non_exhaustive]
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub enum NetworkFailureKind {
45    /// Name resolution failed before a destination address was attempted.
46    Dns,
47    /// Every attempted destination failed with connection refusal.
48    ConnectionRefused,
49    /// A connection-establishment failure that is not more specifically
50    /// classified.
51    Connect,
52}
53
54/// A request error with optional structured connection-failure detail.
55///
56/// The ordinary [`Error`] remains the compatibility surface. Use
57/// [`Client::send_detailed`](crate::Client::send_detailed) or
58/// [`RequestBuilder::send_detailed`](crate::RequestBuilder::send_detailed)
59/// when native Rust code needs the additional, evidence-backed network
60/// classification.
61pub struct RequestFailure {
62    error: Error,
63    network_failure: Option<NetworkFailureKind>,
64}
65
66impl RequestFailure {
67    /// Return the original public error by reference.
68    #[must_use]
69    pub fn error(&self) -> &Error {
70        &self.error
71    }
72
73    /// Consume the detailed wrapper and return the original public error.
74    #[must_use]
75    pub fn into_error(self) -> Error {
76        self.error
77    }
78
79    /// Return evidence-backed connection-failure detail, when available.
80    #[must_use]
81    pub fn network_failure_kind(&self) -> Option<NetworkFailureKind> {
82        self.network_failure
83    }
84
85    /// Return whether the error represents a timeout.
86    ///
87    /// This includes both ordinary request-phase [`Error::Timeout`] values
88    /// and established-transport inactivity [`Error::TransportIoTimeout`]
89    /// values. Caller-dialer timeout categories remain available through
90    /// [`Error::custom_transport_error`] and are not reclassified here.
91    #[must_use]
92    pub fn is_timeout(&self) -> bool {
93        matches!(
94            self.error,
95            Error::Timeout { .. } | Error::TransportIoTimeout { .. }
96        )
97    }
98
99    /// Return the request timeout phase, when the error carries one.
100    ///
101    /// Established-transport inactivity timeouts intentionally return
102    /// `None`; they are not ordinary request-phase timeouts.
103    #[must_use]
104    pub fn timeout_phase(&self) -> Option<TimeoutPhase> {
105        match self.error {
106            Error::Timeout { phase, .. } => Some(phase),
107            _ => None,
108        }
109    }
110
111    pub(crate) fn from_error(error: Error) -> Self {
112        Self {
113            error,
114            network_failure: None,
115        }
116    }
117
118    pub(crate) fn from_context(error: Error, context: &RequestFailureContext) -> Self {
119        Self {
120            error,
121            network_failure: context.network_failure_kind(),
122        }
123    }
124}
125
126impl std::fmt::Debug for RequestFailure {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        f.debug_struct("RequestFailure")
129            .field("error", &self.error)
130            .field("network_failure", &self.network_failure)
131            .finish()
132    }
133}
134
135impl std::fmt::Display for RequestFailure {
136    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
137        self.error.fmt(f)
138    }
139}
140
141impl std::error::Error for RequestFailure {
142    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
143        self.error.source()
144    }
145}
146
147/// Request-local storage for the one terminal network classification.
148///
149/// This is only allocated by detailed sends. An atomic is sufficient because
150/// the context stores one small value and later terminal attempts replace
151/// earlier transient classifications.
152pub(crate) struct RequestFailureContext {
153    network_failure: AtomicU8,
154}
155
156impl RequestFailureContext {
157    pub(crate) fn new() -> Arc<Self> {
158        Arc::new(Self {
159            network_failure: AtomicU8::new(0),
160        })
161    }
162
163    pub(crate) fn clear(&self) {
164        self.network_failure.store(0, Ordering::Relaxed);
165    }
166
167    pub(crate) fn record(&self, kind: NetworkFailureKind) {
168        self.network_failure
169            .store(kind as u8 + 1, Ordering::Relaxed);
170    }
171
172    fn network_failure_kind(&self) -> Option<NetworkFailureKind> {
173        match self.network_failure.load(Ordering::Relaxed) {
174            1 => Some(NetworkFailureKind::Dns),
175            2 => Some(NetworkFailureKind::ConnectionRefused),
176            3 => Some(NetworkFailureKind::Connect),
177            _ => None,
178        }
179    }
180}
181
182/// Error taxonomy for the eggfetch engine.
183///
184/// This is the single error entry point for callers. Source errors are
185/// preserved via [`std::error::Error::source`].
186#[derive(Debug, Clone, thiserror::Error)]
187pub enum Error {
188    /// The provided URL could not be parsed.
189    #[error("invalid URL: {0}")]
190    InvalidUrl(String),
191
192    /// The provided HTTP method could not be parsed.
193    #[error("invalid method: {0}")]
194    InvalidMethod(String),
195
196    /// The provided header name is not valid.
197    #[error("invalid header name: {0}")]
198    InvalidHeaderName(String),
199
200    /// The provided header value is not valid.
201    #[error("invalid header value: {0}")]
202    InvalidHeaderValue(String),
203
204    /// The request could not be built.
205    #[error("request build error: {0}")]
206    RequestBuild(String),
207
208    /// A caller-supplied resolved destination is invalid for the request.
209    #[error("invalid resolved destination: {0}")]
210    InvalidResolvedTarget(String),
211
212    /// A pinned request attempted to follow a redirect that changes origin.
213    #[error("resolved destination cannot be reused across a cross-origin redirect")]
214    ResolvedTargetRedirect,
215
216    /// Request JSON serialization failed.
217    #[error("JSON serialization error: {0}")]
218    JsonSerialize(String),
219
220    /// Response JSON deserialization failed.
221    #[error("JSON deserialization error: {0}")]
222    JsonDeserialize(String),
223
224    /// A connection could not be established.
225    #[error("connect error: {0}")]
226    Connect(String),
227
228    /// A caller-supplied native dialer failed.
229    #[error("custom transport error: {0}")]
230    CustomTransport(#[source] std::sync::Arc<crate::transport::dialer::DialError>),
231
232    /// A TLS handshake or configuration error occurred.
233    #[error("TLS error: {0}")]
234    Tls(String),
235
236    /// An HTTP protocol error occurred.
237    #[error("protocol error: {0}")]
238    Protocol(String),
239
240    /// An error occurred while processing a request or response body.
241    #[error("body error: {0}")]
242    Body(String),
243
244    /// An error from the underlying hyper HTTP engine.
245    #[error("hyper error: {0}")]
246    Hyper(#[from] std::sync::Arc<hyper::Error>),
247
248    /// An error from the hyper-util legacy client.
249    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
250    #[error("hyper client error: {0}")]
251    HyperClient(#[source] std::sync::Arc<hyper_util::client::legacy::Error>),
252
253    /// An I/O error occurred.
254    #[error("I/O error: {0}")]
255    Io(#[from] std::sync::Arc<std::io::Error>),
256
257    /// The requested feature is not yet supported.
258    #[error("unsupported: {0}")]
259    Unsupported(String),
260
261    /// Connection pool acquisition failed or was cancelled.
262    #[error("pool error: {0}")]
263    Pool(String),
264
265    /// The redirect location is missing or invalid.
266    #[error("invalid redirect location: {0}")]
267    InvalidRedirectLocation(String),
268
269    /// An authentication header value is invalid.
270    #[error("invalid auth header: {0}")]
271    InvalidAuthHeader(String),
272
273    /// Conflicting authentication sources (e.g., explicit header + auth config).
274    #[error("conflicting auth: {0}")]
275    ConflictingAuth(String),
276
277    /// A streaming body cannot be replayed for a redirect.
278    #[error("body not replayable for redirect: streaming request bodies cannot be resent")]
279    BodyNotReplayableForRedirect,
280
281    /// Too many redirects were followed.
282    #[error("too many redirects ({followed} followed, max {max})")]
283    TooManyRedirects {
284        /// Number of redirects actually followed.
285        followed: usize,
286        /// Maximum allowed.
287        max: usize,
288    },
289
290    /// A response decompression error occurred.
291    #[error("decompression error: {0}")]
292    Decompression(String),
293
294    /// The server used a content encoding that is not supported.
295    #[error("unsupported content encoding: {0}")]
296    UnsupportedContentEncoding(String),
297
298    /// A timeout elapsed during the specified phase.
299    #[error("{phase} timeout after {elapsed:?}")]
300    Timeout {
301        /// Which phase of the request timed out.
302        phase: TimeoutPhase,
303        /// The duration that was exceeded.
304        elapsed: std::time::Duration,
305    },
306
307    /// An established transport made no read or write progress before its
308    /// dedicated inactivity deadline.
309    #[error("transport {direction:?} inactivity timeout after {elapsed:?}")]
310    TransportIoTimeout {
311        /// Which established I/O direction stalled.
312        direction: crate::transport::lifecycle::TransportIoDirection,
313        /// Duration for which no progress was observed.
314        elapsed: std::time::Duration,
315    },
316
317    /// The proxy URL is invalid or malformed.
318    #[error("invalid proxy URL: {0}")]
319    InvalidProxyUrl(String),
320
321    /// The proxy server rejected the connection or tunnel.
322    #[error("proxy error: {0}")]
323    ProxyConnect(String),
324
325    /// The proxy server requires authentication.
326    #[error("proxy authentication required")]
327    ProxyAuthRequired,
328
329    /// The CONNECT tunnel was rejected by the proxy.
330    #[error("CONNECT rejected: {status} {body}")]
331    ProxyConnectRejected {
332        /// HTTP status code from the proxy.
333        status: u16,
334        /// Response body or description.
335        body: String,
336    },
337
338    /// The proxy response could not be parsed.
339    #[error("malformed proxy response: {0}")]
340    MalformedProxyResponse(String),
341
342    /// The decoded body exceeded the configured size limit.
343    #[error("decoded body exceeded max decoded body size")]
344    DecodedBodyTooLarge,
345
346    /// The decompression ratio exceeded the configured limit.
347    #[error("decompression ratio exceeded max ratio")]
348    DecompressionRatioExceeded,
349
350    /// A TLS configuration error occurred.
351    #[error("TLS configuration error: {0}")]
352    TlsConfig(String),
353
354    /// A CA certificate bundle could not be parsed.
355    #[error("CA bundle error: {0}")]
356    CaBundle(String),
357
358    /// A client certificate or private key could not be loaded.
359    #[error("client certificate error: {0}")]
360    ClientCert(String),
361
362    /// A private key could not be parsed or decrypted.
363    #[error("private key error: {0}")]
364    PrivateKey(String),
365
366    /// Certificate verification failed.
367    #[error("certificate verification failed: {0}")]
368    CertificateVerification(String),
369
370    /// Hostname verification failed.
371    #[error("hostname verification failed: {0}")]
372    HostnameVerification(String),
373
374    /// The request body is not replayable and cannot be retried.
375    #[error("body not replayable for retry")]
376    BodyNotReplayableForRetry,
377
378    /// The retry budget was exhausted.
379    #[error("retry budget exhausted after {attempts} attempts")]
380    RetryBudgetExhausted {
381        /// Number of attempts made.
382        attempts: usize,
383    },
384
385    /// Retry is not enabled for this request or client.
386    #[error("retry not configured")]
387    RetryNotConfigured,
388
389    /// The HTTP/2 connection received a GOAWAY frame from the server.
390    ///
391    /// `last_stream_id` is currently always `0`: `h2` 0.4 does not expose
392    /// the GOAWAY last-stream-id through its public error API, so the raw
393    /// error text is preserved in `debug_data` instead.
394    #[error("HTTP/2 GOAWAY: last_stream_id={last_stream_id}, debug={debug_data}")]
395    Http2GoAway {
396        /// The last stream ID the server will process (currently always `0`, see above).
397        last_stream_id: u32,
398        /// Debug data from the GOAWAY frame.
399        debug_data: String,
400    },
401
402    /// An HTTP/2 stream was reset by the server with the given reason code.
403    #[error("HTTP/2 stream reset: {reason}")]
404    Http2StreamReset {
405        /// The HTTP/2 reason code (e.g., `REFUSED_STREAM`, `CANCEL`).
406        reason: String,
407    },
408
409    /// An HTTP/2 flow-control error occurred.
410    #[error("HTTP/2 flow control error: {0}")]
411    Http2FlowControl(String),
412
413    /// An HTTP/2 protocol error occurred.
414    #[error("HTTP/2 protocol error: {0}")]
415    Http2Protocol(String),
416
417    /// An HTTP/3 connection error occurred.
418    #[error("HTTP/3 connect error: {0}")]
419    H3Connect(String),
420
421    /// An HTTP/3 connection was closed by the peer.
422    #[error("HTTP/3 connection closed: {0}")]
423    H3ConnectionClosed(String),
424
425    /// An HTTP/3 stream error occurred.
426    #[error("HTTP/3 stream error: {0}")]
427    H3Stream(String),
428
429    /// An HTTP/3 protocol error occurred.
430    #[error("HTTP/3 protocol error: {0}")]
431    H3Protocol(String),
432
433    /// A trace callback signaled the transport to abort.
434    #[error("trace callback aborted the request")]
435    TraceCallbackAborted,
436}
437
438impl Error {
439    /// Returns the category of this error as a static string.
440    #[must_use]
441    pub fn kind(&self) -> &'static str {
442        match self {
443            Self::InvalidUrl(_) => "invalid_url",
444            Self::InvalidMethod(_) => "invalid_method",
445            Self::InvalidHeaderName(_) => "invalid_header_name",
446            Self::InvalidHeaderValue(_) => "invalid_header_value",
447            Self::RequestBuild(_) => "request_build",
448            Self::InvalidResolvedTarget(_) => "invalid_resolved_target",
449            Self::ResolvedTargetRedirect => "resolved_target_redirect",
450            Self::JsonSerialize(_) => "json_serialize",
451            Self::JsonDeserialize(_) => "json_deserialize",
452            Self::Connect(_) => "connect",
453            Self::CustomTransport(_) => "custom_transport",
454            Self::Tls(_) => "tls",
455            Self::Protocol(_) => "protocol",
456            Self::Body(_) => "body",
457            Self::Hyper(_) => "hyper",
458            #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
459            Self::HyperClient(_) => "hyper_client",
460            Self::Io(_) => "io",
461            Self::Unsupported(_) => "unsupported",
462            Self::InvalidRedirectLocation(_) => "invalid_redirect_location",
463            Self::InvalidAuthHeader(_) => "invalid_auth_header",
464            Self::ConflictingAuth(_) => "conflicting_auth",
465            Self::BodyNotReplayableForRedirect => "body_not_replayable_for_redirect",
466            Self::TooManyRedirects { .. } => "too_many_redirects",
467            Self::Pool(_) => "pool",
468            Self::Decompression(_) => "decompression",
469            Self::UnsupportedContentEncoding(_) => "unsupported_content_encoding",
470            Self::Timeout { phase, .. } => match phase {
471                crate::timeout::TimeoutPhase::Pool => "timeout_pool",
472                crate::timeout::TimeoutPhase::Connect => "timeout_connect",
473                crate::timeout::TimeoutPhase::ProxyConnect => "timeout_proxy_connect",
474                crate::timeout::TimeoutPhase::ProxyTls => "timeout_proxy_tls",
475                crate::timeout::TimeoutPhase::Write => "timeout_write",
476                crate::timeout::TimeoutPhase::Read => "timeout_read",
477                crate::timeout::TimeoutPhase::Total => "timeout_total",
478            },
479            Self::TransportIoTimeout { direction, .. } => match direction {
480                crate::transport::lifecycle::TransportIoDirection::Read => "transport_read_timeout",
481                crate::transport::lifecycle::TransportIoDirection::Write => {
482                    "transport_write_timeout"
483                }
484            },
485            Self::InvalidProxyUrl(_) => "invalid_proxy_url",
486            Self::ProxyConnect(_) => "proxy_connect",
487            Self::ProxyAuthRequired => "proxy_auth_required",
488            Self::ProxyConnectRejected { .. } => "proxy_connect_rejected",
489            Self::MalformedProxyResponse(_) => "malformed_proxy_response",
490            Self::DecodedBodyTooLarge => "decoded_body_too_large",
491            Self::DecompressionRatioExceeded => "decompression_ratio_exceeded",
492            Self::TlsConfig(_) => "tls_config",
493            Self::CaBundle(_) => "ca_bundle",
494            Self::ClientCert(_) => "client_cert",
495            Self::PrivateKey(_) => "private_key",
496            Self::CertificateVerification(_) => "certificate_verification",
497            Self::HostnameVerification(_) => "hostname_verification",
498            Self::BodyNotReplayableForRetry => "body_not_replayable_for_retry",
499            Self::RetryBudgetExhausted { .. } => "retry_budget_exhausted",
500            Self::RetryNotConfigured => "retry_not_configured",
501            Self::Http2GoAway { .. } => "http2_go_away",
502            Self::Http2StreamReset { .. } => "http2_stream_reset",
503            Self::Http2FlowControl(_) => "http2_flow_control",
504            Self::Http2Protocol(_) => "http2_protocol",
505            Self::H3Connect(_) => "h3_connect",
506            Self::H3ConnectionClosed(_) => "h3_connection_closed",
507            Self::H3Stream(_) => "h3_stream",
508            Self::H3Protocol(_) => "h3_protocol",
509            Self::TraceCallbackAborted => "trace_callback_aborted",
510        }
511    }
512
513    /// Returns the nested caller error when this is a custom-dialer failure.
514    #[must_use]
515    pub fn custom_transport_error(&self) -> Option<&crate::transport::dialer::DialError> {
516        match self {
517            Self::CustomTransport(error) => Some(error.as_ref()),
518            _ => None,
519        }
520    }
521
522    /// Returns whether this is a physical-connection admission timeout.
523    #[must_use]
524    pub fn is_physical_connection_admission_timeout(&self) -> bool {
525        matches!(self, Self::Pool(message) if message == crate::transport::lifecycle::PHYSICAL_ADMISSION_TIMEOUT)
526    }
527
528    /// Returns whether this is an established-transport inactivity timeout.
529    #[must_use]
530    pub fn is_transport_io_timeout(&self) -> bool {
531        matches!(self, Self::TransportIoTimeout { .. })
532    }
533
534    /// Classify this error into a generic native transport-failure category.
535    ///
536    /// The classifier is diagnostic only and does not imply retryability.
537    /// `None` means the available typed evidence does not prove one of the
538    /// [`TransportFailureKind`] categories. Timeout, physical-admission,
539    /// and transport-I/O-inactivity facts remain authoritative through
540    /// their existing accessors and never map here.
541    #[must_use]
542    pub fn transport_failure_kind(&self) -> Option<TransportFailureKind> {
543        classify_transport_failure(self)
544    }
545}
546
547/// Bound for every transport-classifier source-chain walk.
548const TRANSPORT_FAILURE_WALK_BOUND: usize = 32;
549
550/// Direct-variant classification without source inspection.
551///
552/// Returns `Some` only for explicit Eggfetch variants with unambiguous
553/// category evidence. All other variants (including timeouts, admission,
554/// proxy, retry, H2 peer-action, and H3 lifecycle variants) return `None`.
555fn classify_explicit(error: &Error) -> Option<TransportFailureKind> {
556    match error {
557        Error::Tls(_)
558        | Error::TlsConfig(_)
559        | Error::CaBundle(_)
560        | Error::ClientCert(_)
561        | Error::PrivateKey(_)
562        | Error::CertificateVerification(_)
563        | Error::HostnameVerification(_) => Some(TransportFailureKind::Tls),
564        Error::Protocol(_)
565        | Error::Http2Protocol(_)
566        | Error::Http2FlowControl(_)
567        | Error::H3Protocol(_) => Some(TransportFailureKind::Protocol),
568        Error::Connect(_) | Error::H3Connect(_) => Some(TransportFailureKind::Connect),
569        Error::CustomTransport(error) => match error.kind() {
570            crate::transport::dialer::DialErrorKind::Connection => {
571                Some(TransportFailureKind::Connect)
572            }
573            _ => None,
574        },
575        _ => None,
576    }
577}
578
579/// Accumulated typed evidence for [`TransportFailureKind`].
580///
581/// The public precedence applies when converting into the final category:
582/// TLS before generic connect, cancellation next, protocol next, and proven
583/// connection I/O last. The four flags are independent by construction (one
584/// per category), which is clearer than a bitmask for this fixed set.
585// Clippy's struct-bool lint prefers a bitmask past three flags; the four
586// named fields are kept because each maps to exactly one public category.
587#[allow(
588    clippy::struct_excessive_bools,
589    reason = "the four flags map one-to-one onto the public failure categories, so a bitmask would hide which category each flag records"
590)]
591#[derive(Default)]
592struct TransportEvidence {
593    tls: bool,
594    cancelled: bool,
595    protocol: bool,
596    connect: bool,
597}
598
599impl TransportEvidence {
600    /// Record the typed evidence carried by one wrapped cause.
601    ///
602    /// `body_boundary` proves the failure surfaced while polling a Hyper
603    /// response body (the `Error::Hyper` variant is only constructed there),
604    /// so premature-termination/malformed-framing I/O inside it is proven
605    /// HTTP framing evidence, while the same I/O kinds elsewhere stay
606    /// unknown. No `Display`/`Debug` text is inspected.
607    fn inspect(&mut self, node: &(dyn std::error::Error + 'static), body_boundary: bool) {
608        use std::sync::Arc;
609        if let Some(inner) = node
610            .downcast_ref::<Error>()
611            .or_else(|| node.downcast_ref::<Arc<Error>>().map(Arc::as_ref))
612        {
613            match classify_explicit(inner) {
614                Some(TransportFailureKind::Tls) => self.tls = true,
615                Some(TransportFailureKind::Protocol) => self.protocol = true,
616                Some(TransportFailureKind::Connect) => self.connect = true,
617                // Explicit classification never returns Cancelled today;
618                // retain the arm so a future explicit cancellation fact
619                // cannot silently fall through.
620                Some(TransportFailureKind::Cancelled) => self.cancelled = true,
621                None => {}
622            }
623        }
624        let hyper_error = node
625            .downcast_ref::<hyper::Error>()
626            .or_else(|| node.downcast_ref::<Arc<hyper::Error>>().map(Arc::as_ref));
627        if let Some(hyper_error) = hyper_error {
628            if hyper_error.is_canceled() {
629                self.cancelled = true;
630            }
631            if hyper_error.is_parse() || hyper_error.is_incomplete_message() {
632                self.protocol = true;
633            }
634        }
635        #[cfg(feature = "tls-rustls")]
636        if node.downcast_ref::<rustls::Error>().is_some()
637            || node.downcast_ref::<Arc<rustls::Error>>().is_some()
638        {
639            self.tls = true;
640        }
641        // The legacy client `Error` type only exists when Hyper's HTTP/1 or
642        // HTTP/2 protocol support is compiled in (via `transport-http1/2`).
643        #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
644        {
645            let legacy = node
646                .downcast_ref::<hyper_util::client::legacy::Error>()
647                .or_else(|| {
648                    node.downcast_ref::<Arc<hyper_util::client::legacy::Error>>()
649                        .map(Arc::as_ref)
650                });
651            if legacy.is_some_and(hyper_util::client::legacy::Error::is_connect) {
652                self.connect = true;
653            }
654        }
655        let io_error = node
656            .downcast_ref::<std::io::Error>()
657            .or_else(|| node.downcast_ref::<Arc<std::io::Error>>().map(Arc::as_ref));
658        if let Some(io_error) = io_error {
659            // Only connection refusal is proven establishment failure
660            // anywhere.
661            if io_error.kind() == std::io::ErrorKind::ConnectionRefused {
662                self.connect = true;
663            } else if body_boundary
664                && matches!(
665                    io_error.kind(),
666                    std::io::ErrorKind::UnexpectedEof
667                        | std::io::ErrorKind::InvalidData
668                        | std::io::ErrorKind::InvalidInput
669                )
670            {
671                self.protocol = true;
672            }
673        }
674    }
675
676    /// Resolve the accumulated evidence into the final category.
677    fn category(self) -> Option<TransportFailureKind> {
678        if self.tls {
679            return Some(TransportFailureKind::Tls);
680        }
681        if self.cancelled {
682            return Some(TransportFailureKind::Cancelled);
683        }
684        if self.protocol {
685            return Some(TransportFailureKind::Protocol);
686        }
687        if self.connect {
688            return Some(TransportFailureKind::Connect);
689        }
690        None
691    }
692}
693
694/// Central private classifier authority for [`TransportFailureKind`].
695///
696/// Precedence is typed and explicit: explicit Eggfetch variants first, then
697/// bounded wrapped causes with TLS before generic connect, cancellation
698/// next, protocol next, and proven connection I/O last. Caller-owned dialer
699/// sources are never inspected beyond their
700/// [`crate::transport::dialer::DialErrorKind`]; unknown evidence stays
701/// unknown and no `Display`/`Debug` text is parsed.
702///
703/// Two transport-layer facts shape the walk. First, `std::io::Error` hides
704/// its custom payload from `source()` (it is exposed only through
705/// `get_ref()`), so the walk descends through `get_ref()` edges as well as
706/// `source()` edges; this is how nested `rustls::Error` evidence behind
707/// hyper-rustls `io::Error` wrappers is found without string matching.
708/// Second, the `Error::Hyper` variant is only constructed at the
709/// `IncomingErrorBody` polling boundary (after response headers), so I/O
710/// premature-termination/malformed-framing evidence inside it proves an HTTP
711/// body framing failure, while the same I/O kinds in a bare `Error::Io`
712/// stay unknown.
713fn classify_transport_failure(error: &Error) -> Option<TransportFailureKind> {
714    use std::error::Error as StdError;
715    // Caller-owned dialer failures preserve DialErrorKind authority. Only
716    // Connection maps broadly; richer custom_transport_error() is unchanged
717    // and nested caller sources are never inspected.
718    if let Error::CustomTransport(_) = error {
719        return classify_explicit(error);
720    }
721    if let Some(kind) = classify_explicit(error) {
722        return Some(kind);
723    }
724    // The body-boundary context: `Error::Hyper` proves the failure surfaced
725    // while polling a Hyper response body, so truncated/malformed framing I/O
726    // inside it is proven HTTP framing evidence.
727    let body_boundary = matches!(error, Error::Hyper(_));
728    let mut evidence = TransportEvidence::default();
729    // Bounded worklist DFS over `source()`/`get_ref()` edges. `Error` wraps
730    // transport errors in `Arc`, so each expected type is checked both
731    // directly and behind `Arc`.
732    let mut stack: Vec<&(dyn StdError + 'static)> = vec![error];
733    let mut visited: Vec<*const (dyn StdError + 'static)> = Vec::new();
734    let mut visits = 0usize;
735    // The top-level error itself was already checked explicitly; only wrapped
736    // typed causes are inspected below.
737    let mut skipped_top = false;
738    while let Some(node) = stack.pop() {
739        if visits >= TRANSPORT_FAILURE_WALK_BOUND {
740            break;
741        }
742        visits += 1;
743        let ptr = std::ptr::from_ref(node);
744        if visited.contains(&ptr) {
745            continue;
746        }
747        visited.push(ptr);
748        if skipped_top {
749            evidence.inspect(node, body_boundary);
750        } else {
751            skipped_top = true;
752        }
753        if let Some(source) = node.source() {
754            stack.push(source);
755        }
756        // `io::Error` custom payloads are invisible to `source()`; descend
757        // through `get_ref()` so nested typed evidence (e.g. `rustls::Error`
758        // behind hyper-rustls wrappers) is still found.
759        let payload: Option<&(dyn StdError + 'static)> = node
760            .downcast_ref::<std::io::Error>()
761            .and_then(|io_error| io_error.get_ref())
762            .map(|payload| payload as &(dyn StdError + 'static))
763            .or_else(|| {
764                node.downcast_ref::<std::sync::Arc<std::io::Error>>()
765                    .and_then(|io_error| io_error.get_ref())
766                    .map(|payload| payload as &(dyn StdError + 'static))
767            });
768        if let Some(payload) = payload {
769            stack.push(payload);
770        }
771    }
772    evidence.category()
773}
774
775/// Returns `true` when a hyper-util legacy client error wraps a canceled
776/// hyper connection, using the same centralized classifier evidence as the
777/// public [`Error::transport_failure_kind`].
778///
779/// This preserves the existing retry policy semantics exactly: only the
780/// typed cancellation fact is consulted, never the broader
781/// [`TransportFailureKind`] category.
782#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
783pub(crate) fn hyper_legacy_is_canceled(inner: &hyper_util::client::legacy::Error) -> bool {
784    use std::error::Error as _;
785    use std::sync::Arc;
786    let mut source = inner.source();
787    for _ in 0..TRANSPORT_FAILURE_WALK_BOUND {
788        let Some(err) = source else { break };
789        let canceled = err
790            .downcast_ref::<hyper::Error>()
791            .or_else(|| err.downcast_ref::<Arc<hyper::Error>>().map(Arc::as_ref))
792            .is_some_and(hyper::Error::is_canceled);
793        if canceled {
794            return true;
795        }
796        source = err.source();
797    }
798    false
799}
800
801#[cfg(test)]
802mod tests {
803    use super::*;
804
805    #[test]
806    fn error_display() {
807        let err = Error::InvalidUrl("not a url".into());
808        assert_eq!(err.to_string(), "invalid URL: not a url");
809    }
810
811    #[test]
812    fn error_kind() {
813        let err = Error::Connect("refused".into());
814        assert_eq!(err.kind(), "connect");
815    }
816
817    #[test]
818    fn error_from_io() {
819        let io_err = std::sync::Arc::new(std::io::Error::other("test"));
820        let err: Error = io_err.into();
821        assert_eq!(err.kind(), "io");
822    }
823
824    #[test]
825    fn request_failure_exposes_timeout_without_changing_error() {
826        let error = Error::Timeout {
827            phase: TimeoutPhase::Connect,
828            elapsed: std::time::Duration::from_millis(5),
829        };
830        let failure = RequestFailure::from_error(error);
831        assert!(failure.is_timeout());
832        assert_eq!(failure.timeout_phase(), Some(TimeoutPhase::Connect));
833        assert_eq!(failure.error().kind(), "timeout_connect");
834        assert_eq!(failure.into_error().kind(), "timeout_connect");
835    }
836
837    #[test]
838    fn request_failure_keeps_transport_timeout_distinct() {
839        let failure = RequestFailure::from_error(Error::TransportIoTimeout {
840            direction: crate::transport::lifecycle::TransportIoDirection::Read,
841            elapsed: std::time::Duration::from_secs(1),
842        });
843        assert!(failure.is_timeout());
844        assert_eq!(failure.timeout_phase(), None);
845    }
846
847    #[test]
848    fn request_failure_context_replaces_transient_classification() {
849        let context = RequestFailureContext::new();
850        context.record(NetworkFailureKind::Dns);
851        context.record(NetworkFailureKind::ConnectionRefused);
852        let failure = RequestFailure::from_context(Error::Connect("refused".into()), &context);
853        assert_eq!(
854            failure.network_failure_kind(),
855            Some(NetworkFailureKind::ConnectionRefused)
856        );
857        context.clear();
858        assert_eq!(context.network_failure_kind(), None);
859    }
860
861    #[test]
862    fn error_http2_go_away_display() {
863        let err = Error::Http2GoAway {
864            last_stream_id: 1,
865            debug_data: "no error: connection closed".into(),
866        };
867        assert_eq!(err.kind(), "http2_go_away");
868        let msg = err.to_string();
869        assert!(msg.contains("GOAWAY"));
870        assert!(msg.contains("no error: connection closed"));
871    }
872
873    #[test]
874    fn error_http2_stream_reset_display() {
875        let err = Error::Http2StreamReset {
876            reason: "REFUSED_STREAM: stream refused".into(),
877        };
878        assert_eq!(err.kind(), "http2_stream_reset");
879        assert!(err.to_string().contains("REFUSED_STREAM"));
880    }
881
882    #[test]
883    fn error_http2_flow_control_display() {
884        let err = Error::Http2FlowControl("flow-control violated".into());
885        assert_eq!(err.kind(), "http2_flow_control");
886    }
887
888    #[test]
889    fn error_http2_protocol_display() {
890        let err = Error::Http2Protocol("stream closed after headers".into());
891        assert_eq!(err.kind(), "http2_protocol");
892    }
893
894    #[cfg(feature = "logical-retry")]
895    #[test]
896    fn http2_refused_stream_is_retryable() {
897        let err = Error::Http2StreamReset {
898            reason: "REFUSED_STREAM: stream refused before processing".into(),
899        };
900        assert!(crate::retry::RetryPolicy::is_error_retryable(&err));
901    }
902
903    #[cfg(feature = "logical-retry")]
904    #[test]
905    fn http2_cancel_is_not_retryable() {
906        let err = Error::Http2StreamReset {
907            reason: "CANCEL: stream no longer needed".into(),
908        };
909        assert!(!crate::retry::RetryPolicy::is_error_retryable(&err));
910    }
911
912    #[cfg(feature = "logical-retry")]
913    #[test]
914    fn http2_go_away_is_not_retryable() {
915        let err = Error::Http2GoAway {
916            last_stream_id: 0,
917            debug_data: " shutting down".into(),
918        };
919        assert!(!crate::retry::RetryPolicy::is_error_retryable(&err));
920    }
921
922    #[test]
923    fn transport_failure_explicit_tls_family() {
924        for error in [
925            Error::Tls("handshake failed".into()),
926            Error::TlsConfig("bad config".into()),
927            Error::CaBundle("bad bundle".into()),
928            Error::ClientCert("bad cert".into()),
929            Error::PrivateKey("bad key".into()),
930            Error::CertificateVerification("expired".into()),
931            Error::HostnameVerification("mismatch".into()),
932        ] {
933            assert_eq!(
934                error.transport_failure_kind(),
935                Some(TransportFailureKind::Tls),
936                "kind={}",
937                error.kind()
938            );
939        }
940    }
941
942    #[test]
943    fn transport_failure_explicit_protocol_family() {
944        for error in [
945            Error::Protocol("framing".into()),
946            Error::Http2Protocol("h2 framing".into()),
947            Error::Http2FlowControl("window exhausted".into()),
948            Error::H3Protocol("h3 framing".into()),
949        ] {
950            assert_eq!(
951                error.transport_failure_kind(),
952                Some(TransportFailureKind::Protocol),
953                "kind={}",
954                error.kind()
955            );
956        }
957    }
958
959    #[test]
960    fn transport_failure_explicit_connect_family() {
961        assert_eq!(
962            Error::Connect("refused".into()).transport_failure_kind(),
963            Some(TransportFailureKind::Connect)
964        );
965        assert_eq!(
966            Error::H3Connect("quic refused".into()).transport_failure_kind(),
967            Some(TransportFailureKind::Connect)
968        );
969        let connection = Error::CustomTransport(std::sync::Arc::new(
970            crate::transport::dialer::DialError::new(
971                crate::transport::dialer::DialErrorKind::Connection,
972                "route failed",
973            ),
974        ));
975        assert_eq!(
976            connection.transport_failure_kind(),
977            Some(TransportFailureKind::Connect)
978        );
979    }
980
981    #[test]
982    fn transport_failure_custom_transport_preserves_dial_kind() {
983        for kind in [
984            crate::transport::dialer::DialErrorKind::Timeout,
985            crate::transport::dialer::DialErrorKind::Authentication,
986            crate::transport::dialer::DialErrorKind::Rejected,
987            crate::transport::dialer::DialErrorKind::Other,
988        ] {
989            let error = Error::CustomTransport(std::sync::Arc::new(
990                crate::transport::dialer::DialError::new(kind, "route failed"),
991            ));
992            assert_eq!(error.transport_failure_kind(), None);
993            assert!(error.custom_transport_error().is_some());
994        }
995    }
996
997    #[test]
998    fn transport_failure_timeouts_admission_and_io_timeouts_stay_unknown() {
999        let timeout = Error::Timeout {
1000            phase: TimeoutPhase::Connect,
1001            elapsed: std::time::Duration::from_millis(5),
1002        };
1003        assert_eq!(timeout.transport_failure_kind(), None);
1004        let io_timeout = Error::TransportIoTimeout {
1005            direction: crate::transport::lifecycle::TransportIoDirection::Read,
1006            elapsed: std::time::Duration::from_secs(1),
1007        };
1008        assert_eq!(io_timeout.transport_failure_kind(), None);
1009        assert!(io_timeout.is_transport_io_timeout());
1010        let admission =
1011            Error::Pool(crate::transport::lifecycle::PHYSICAL_ADMISSION_TIMEOUT.to_owned());
1012        assert!(admission.is_physical_connection_admission_timeout());
1013        assert_eq!(admission.transport_failure_kind(), None);
1014    }
1015
1016    #[test]
1017    fn transport_failure_unknown_stays_unknown() {
1018        for error in [
1019            Error::InvalidUrl("bad".into()),
1020            Error::Body("body".into()),
1021            Error::Pool("busy".into()),
1022            Error::ProxyConnect("proxy down".into()),
1023            Error::Http2GoAway {
1024                last_stream_id: 0,
1025                debug_data: "shutdown".into(),
1026            },
1027            Error::Http2StreamReset {
1028                reason: "CANCEL".into(),
1029            },
1030            Error::H3ConnectionClosed("closed".into()),
1031            Error::H3Stream("reset".into()),
1032            Error::TooManyRedirects {
1033                followed: 5,
1034                max: 5,
1035            },
1036        ] {
1037            assert_eq!(
1038                error.transport_failure_kind(),
1039                None,
1040                "kind={}",
1041                error.kind()
1042            );
1043        }
1044    }
1045
1046    #[test]
1047    fn transport_failure_does_not_change_kind_or_display() {
1048        let error = Error::Connect("refused".into());
1049        assert_eq!(error.kind(), "connect");
1050        assert_eq!(error.to_string(), "connect error: refused");
1051        assert_eq!(
1052            error.transport_failure_kind(),
1053            Some(TransportFailureKind::Connect)
1054        );
1055        let tls = Error::Tls("boom".into());
1056        assert_eq!(tls.kind(), "tls");
1057        assert_eq!(tls.to_string(), "TLS error: boom");
1058    }
1059
1060    #[test]
1061    fn transport_failure_wrapped_io_refused_maps_connect_unexpected_eof_stays_unknown() {
1062        let refused = Error::Io(std::sync::Arc::new(std::io::Error::new(
1063            std::io::ErrorKind::ConnectionRefused,
1064            "refused",
1065        )));
1066        assert_eq!(
1067            refused.transport_failure_kind(),
1068            Some(TransportFailureKind::Connect)
1069        );
1070        let eof = Error::Io(std::sync::Arc::new(std::io::Error::new(
1071            std::io::ErrorKind::UnexpectedEof,
1072            "eof",
1073        )));
1074        assert_eq!(eof.transport_failure_kind(), None);
1075    }
1076
1077    #[test]
1078    fn transport_failure_output_is_enum_only_and_redacted() {
1079        use std::fmt::Write as _;
1080        #[derive(Debug)]
1081        struct SecretSource;
1082        impl std::fmt::Display for SecretSource {
1083            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1084                f.write_str("authorization: Bearer hunter2 cookie=secret")
1085            }
1086        }
1087        impl std::error::Error for SecretSource {}
1088        let error = Error::CustomTransport(std::sync::Arc::new(
1089            crate::transport::dialer::DialError::with_source(
1090                crate::transport::dialer::DialErrorKind::Connection,
1091                "safe route description",
1092                SecretSource,
1093            ),
1094        ));
1095        let kind = error.transport_failure_kind();
1096        assert_eq!(kind, Some(TransportFailureKind::Connect));
1097        let mut rendered = String::new();
1098        write!(rendered, "{kind:?}").unwrap();
1099        assert!(!rendered.contains("hunter2"));
1100        assert!(!rendered.contains("authorization"));
1101        let debug = format!("{error:?}");
1102        assert!(!debug.contains("hunter2"));
1103    }
1104}