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(clippy::struct_excessive_bools)]
588#[derive(Default)]
589struct TransportEvidence {
590    tls: bool,
591    cancelled: bool,
592    protocol: bool,
593    connect: bool,
594}
595
596impl TransportEvidence {
597    /// Record the typed evidence carried by one wrapped cause.
598    ///
599    /// `body_boundary` proves the failure surfaced while polling a Hyper
600    /// response body (the `Error::Hyper` variant is only constructed there),
601    /// so premature-termination/malformed-framing I/O inside it is proven
602    /// HTTP framing evidence, while the same I/O kinds elsewhere stay
603    /// unknown. No `Display`/`Debug` text is inspected.
604    fn inspect(&mut self, node: &(dyn std::error::Error + 'static), body_boundary: bool) {
605        use std::sync::Arc;
606        if let Some(inner) = node
607            .downcast_ref::<Error>()
608            .or_else(|| node.downcast_ref::<Arc<Error>>().map(Arc::as_ref))
609        {
610            match classify_explicit(inner) {
611                Some(TransportFailureKind::Tls) => self.tls = true,
612                Some(TransportFailureKind::Protocol) => self.protocol = true,
613                Some(TransportFailureKind::Connect) => self.connect = true,
614                // Explicit classification never returns Cancelled today;
615                // retain the arm so a future explicit cancellation fact
616                // cannot silently fall through.
617                Some(TransportFailureKind::Cancelled) => self.cancelled = true,
618                None => {}
619            }
620        }
621        let hyper_error = node
622            .downcast_ref::<hyper::Error>()
623            .or_else(|| node.downcast_ref::<Arc<hyper::Error>>().map(Arc::as_ref));
624        if let Some(hyper_error) = hyper_error {
625            if hyper_error.is_canceled() {
626                self.cancelled = true;
627            }
628            if hyper_error.is_parse() || hyper_error.is_incomplete_message() {
629                self.protocol = true;
630            }
631        }
632        #[cfg(feature = "tls-rustls")]
633        if node.downcast_ref::<rustls::Error>().is_some()
634            || node.downcast_ref::<Arc<rustls::Error>>().is_some()
635        {
636            self.tls = true;
637        }
638        // The legacy client `Error` type only exists when Hyper's HTTP/1 or
639        // HTTP/2 protocol support is compiled in (via `transport-http1/2`).
640        #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
641        {
642            let legacy = node
643                .downcast_ref::<hyper_util::client::legacy::Error>()
644                .or_else(|| {
645                    node.downcast_ref::<Arc<hyper_util::client::legacy::Error>>()
646                        .map(Arc::as_ref)
647                });
648            if legacy.is_some_and(hyper_util::client::legacy::Error::is_connect) {
649                self.connect = true;
650            }
651        }
652        let io_error = node
653            .downcast_ref::<std::io::Error>()
654            .or_else(|| node.downcast_ref::<Arc<std::io::Error>>().map(Arc::as_ref));
655        if let Some(io_error) = io_error {
656            // Only connection refusal is proven establishment failure
657            // anywhere.
658            if io_error.kind() == std::io::ErrorKind::ConnectionRefused {
659                self.connect = true;
660            } else if body_boundary
661                && matches!(
662                    io_error.kind(),
663                    std::io::ErrorKind::UnexpectedEof
664                        | std::io::ErrorKind::InvalidData
665                        | std::io::ErrorKind::InvalidInput
666                )
667            {
668                self.protocol = true;
669            }
670        }
671    }
672
673    /// Resolve the accumulated evidence into the final category.
674    fn category(self) -> Option<TransportFailureKind> {
675        if self.tls {
676            return Some(TransportFailureKind::Tls);
677        }
678        if self.cancelled {
679            return Some(TransportFailureKind::Cancelled);
680        }
681        if self.protocol {
682            return Some(TransportFailureKind::Protocol);
683        }
684        if self.connect {
685            return Some(TransportFailureKind::Connect);
686        }
687        None
688    }
689}
690
691/// Central private classifier authority for [`TransportFailureKind`].
692///
693/// Precedence is typed and explicit: explicit Eggfetch variants first, then
694/// bounded wrapped causes with TLS before generic connect, cancellation
695/// next, protocol next, and proven connection I/O last. Caller-owned dialer
696/// sources are never inspected beyond their
697/// [`crate::transport::dialer::DialErrorKind`]; unknown evidence stays
698/// unknown and no `Display`/`Debug` text is parsed.
699///
700/// Two transport-layer facts shape the walk. First, `std::io::Error` hides
701/// its custom payload from `source()` (it is exposed only through
702/// `get_ref()`), so the walk descends through `get_ref()` edges as well as
703/// `source()` edges; this is how nested `rustls::Error` evidence behind
704/// hyper-rustls `io::Error` wrappers is found without string matching.
705/// Second, the `Error::Hyper` variant is only constructed at the
706/// `IncomingErrorBody` polling boundary (after response headers), so I/O
707/// premature-termination/malformed-framing evidence inside it proves an HTTP
708/// body framing failure, while the same I/O kinds in a bare `Error::Io`
709/// stay unknown.
710fn classify_transport_failure(error: &Error) -> Option<TransportFailureKind> {
711    use std::error::Error as StdError;
712    // Caller-owned dialer failures preserve DialErrorKind authority. Only
713    // Connection maps broadly; richer custom_transport_error() is unchanged
714    // and nested caller sources are never inspected.
715    if let Error::CustomTransport(_) = error {
716        return classify_explicit(error);
717    }
718    if let Some(kind) = classify_explicit(error) {
719        return Some(kind);
720    }
721    // The body-boundary context: `Error::Hyper` proves the failure surfaced
722    // while polling a Hyper response body, so truncated/malformed framing I/O
723    // inside it is proven HTTP framing evidence.
724    let body_boundary = matches!(error, Error::Hyper(_));
725    let mut evidence = TransportEvidence::default();
726    // Bounded worklist DFS over `source()`/`get_ref()` edges. `Error` wraps
727    // transport errors in `Arc`, so each expected type is checked both
728    // directly and behind `Arc`.
729    let mut stack: Vec<&(dyn StdError + 'static)> = vec![error];
730    let mut visited: Vec<*const (dyn StdError + 'static)> = Vec::new();
731    let mut visits = 0usize;
732    // The top-level error itself was already checked explicitly; only wrapped
733    // typed causes are inspected below.
734    let mut skipped_top = false;
735    while let Some(node) = stack.pop() {
736        if visits >= TRANSPORT_FAILURE_WALK_BOUND {
737            break;
738        }
739        visits += 1;
740        let ptr = std::ptr::from_ref(node);
741        if visited.contains(&ptr) {
742            continue;
743        }
744        visited.push(ptr);
745        if skipped_top {
746            evidence.inspect(node, body_boundary);
747        } else {
748            skipped_top = true;
749        }
750        if let Some(source) = node.source() {
751            stack.push(source);
752        }
753        // `io::Error` custom payloads are invisible to `source()`; descend
754        // through `get_ref()` so nested typed evidence (e.g. `rustls::Error`
755        // behind hyper-rustls wrappers) is still found.
756        let payload: Option<&(dyn StdError + 'static)> = node
757            .downcast_ref::<std::io::Error>()
758            .and_then(|io_error| io_error.get_ref())
759            .map(|payload| payload as &(dyn StdError + 'static))
760            .or_else(|| {
761                node.downcast_ref::<std::sync::Arc<std::io::Error>>()
762                    .and_then(|io_error| io_error.get_ref())
763                    .map(|payload| payload as &(dyn StdError + 'static))
764            });
765        if let Some(payload) = payload {
766            stack.push(payload);
767        }
768    }
769    evidence.category()
770}
771
772/// Returns `true` when a hyper-util legacy client error wraps a canceled
773/// hyper connection, using the same centralized classifier evidence as the
774/// public [`Error::transport_failure_kind`].
775///
776/// This preserves the existing retry policy semantics exactly: only the
777/// typed cancellation fact is consulted, never the broader
778/// [`TransportFailureKind`] category.
779#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
780pub(crate) fn hyper_legacy_is_canceled(inner: &hyper_util::client::legacy::Error) -> bool {
781    use std::error::Error as _;
782    use std::sync::Arc;
783    let mut source = inner.source();
784    for _ in 0..TRANSPORT_FAILURE_WALK_BOUND {
785        let Some(err) = source else { break };
786        let canceled = err
787            .downcast_ref::<hyper::Error>()
788            .or_else(|| err.downcast_ref::<Arc<hyper::Error>>().map(Arc::as_ref))
789            .is_some_and(hyper::Error::is_canceled);
790        if canceled {
791            return true;
792        }
793        source = err.source();
794    }
795    false
796}
797
798#[cfg(test)]
799mod tests {
800    use super::*;
801
802    #[test]
803    fn error_display() {
804        let err = Error::InvalidUrl("not a url".into());
805        assert_eq!(err.to_string(), "invalid URL: not a url");
806    }
807
808    #[test]
809    fn error_kind() {
810        let err = Error::Connect("refused".into());
811        assert_eq!(err.kind(), "connect");
812    }
813
814    #[test]
815    fn error_from_io() {
816        let io_err = std::sync::Arc::new(std::io::Error::other("test"));
817        let err: Error = io_err.into();
818        assert_eq!(err.kind(), "io");
819    }
820
821    #[test]
822    fn request_failure_exposes_timeout_without_changing_error() {
823        let error = Error::Timeout {
824            phase: TimeoutPhase::Connect,
825            elapsed: std::time::Duration::from_millis(5),
826        };
827        let failure = RequestFailure::from_error(error);
828        assert!(failure.is_timeout());
829        assert_eq!(failure.timeout_phase(), Some(TimeoutPhase::Connect));
830        assert_eq!(failure.error().kind(), "timeout_connect");
831        assert_eq!(failure.into_error().kind(), "timeout_connect");
832    }
833
834    #[test]
835    fn request_failure_keeps_transport_timeout_distinct() {
836        let failure = RequestFailure::from_error(Error::TransportIoTimeout {
837            direction: crate::transport::lifecycle::TransportIoDirection::Read,
838            elapsed: std::time::Duration::from_secs(1),
839        });
840        assert!(failure.is_timeout());
841        assert_eq!(failure.timeout_phase(), None);
842    }
843
844    #[test]
845    fn request_failure_context_replaces_transient_classification() {
846        let context = RequestFailureContext::new();
847        context.record(NetworkFailureKind::Dns);
848        context.record(NetworkFailureKind::ConnectionRefused);
849        let failure = RequestFailure::from_context(Error::Connect("refused".into()), &context);
850        assert_eq!(
851            failure.network_failure_kind(),
852            Some(NetworkFailureKind::ConnectionRefused)
853        );
854        context.clear();
855        assert_eq!(context.network_failure_kind(), None);
856    }
857
858    #[test]
859    fn error_http2_go_away_display() {
860        let err = Error::Http2GoAway {
861            last_stream_id: 1,
862            debug_data: "no error: connection closed".into(),
863        };
864        assert_eq!(err.kind(), "http2_go_away");
865        let msg = err.to_string();
866        assert!(msg.contains("GOAWAY"));
867        assert!(msg.contains("no error: connection closed"));
868    }
869
870    #[test]
871    fn error_http2_stream_reset_display() {
872        let err = Error::Http2StreamReset {
873            reason: "REFUSED_STREAM: stream refused".into(),
874        };
875        assert_eq!(err.kind(), "http2_stream_reset");
876        assert!(err.to_string().contains("REFUSED_STREAM"));
877    }
878
879    #[test]
880    fn error_http2_flow_control_display() {
881        let err = Error::Http2FlowControl("flow-control violated".into());
882        assert_eq!(err.kind(), "http2_flow_control");
883    }
884
885    #[test]
886    fn error_http2_protocol_display() {
887        let err = Error::Http2Protocol("stream closed after headers".into());
888        assert_eq!(err.kind(), "http2_protocol");
889    }
890
891    #[cfg(feature = "logical-retry")]
892    #[test]
893    fn http2_refused_stream_is_retryable() {
894        let err = Error::Http2StreamReset {
895            reason: "REFUSED_STREAM: stream refused before processing".into(),
896        };
897        assert!(crate::retry::RetryPolicy::is_error_retryable(&err));
898    }
899
900    #[cfg(feature = "logical-retry")]
901    #[test]
902    fn http2_cancel_is_not_retryable() {
903        let err = Error::Http2StreamReset {
904            reason: "CANCEL: stream no longer needed".into(),
905        };
906        assert!(!crate::retry::RetryPolicy::is_error_retryable(&err));
907    }
908
909    #[cfg(feature = "logical-retry")]
910    #[test]
911    fn http2_go_away_is_not_retryable() {
912        let err = Error::Http2GoAway {
913            last_stream_id: 0,
914            debug_data: " shutting down".into(),
915        };
916        assert!(!crate::retry::RetryPolicy::is_error_retryable(&err));
917    }
918
919    #[test]
920    fn transport_failure_explicit_tls_family() {
921        for error in [
922            Error::Tls("handshake failed".into()),
923            Error::TlsConfig("bad config".into()),
924            Error::CaBundle("bad bundle".into()),
925            Error::ClientCert("bad cert".into()),
926            Error::PrivateKey("bad key".into()),
927            Error::CertificateVerification("expired".into()),
928            Error::HostnameVerification("mismatch".into()),
929        ] {
930            assert_eq!(
931                error.transport_failure_kind(),
932                Some(TransportFailureKind::Tls),
933                "kind={}",
934                error.kind()
935            );
936        }
937    }
938
939    #[test]
940    fn transport_failure_explicit_protocol_family() {
941        for error in [
942            Error::Protocol("framing".into()),
943            Error::Http2Protocol("h2 framing".into()),
944            Error::Http2FlowControl("window exhausted".into()),
945            Error::H3Protocol("h3 framing".into()),
946        ] {
947            assert_eq!(
948                error.transport_failure_kind(),
949                Some(TransportFailureKind::Protocol),
950                "kind={}",
951                error.kind()
952            );
953        }
954    }
955
956    #[test]
957    fn transport_failure_explicit_connect_family() {
958        assert_eq!(
959            Error::Connect("refused".into()).transport_failure_kind(),
960            Some(TransportFailureKind::Connect)
961        );
962        assert_eq!(
963            Error::H3Connect("quic refused".into()).transport_failure_kind(),
964            Some(TransportFailureKind::Connect)
965        );
966        let connection = Error::CustomTransport(std::sync::Arc::new(
967            crate::transport::dialer::DialError::new(
968                crate::transport::dialer::DialErrorKind::Connection,
969                "route failed",
970            ),
971        ));
972        assert_eq!(
973            connection.transport_failure_kind(),
974            Some(TransportFailureKind::Connect)
975        );
976    }
977
978    #[test]
979    fn transport_failure_custom_transport_preserves_dial_kind() {
980        for kind in [
981            crate::transport::dialer::DialErrorKind::Timeout,
982            crate::transport::dialer::DialErrorKind::Authentication,
983            crate::transport::dialer::DialErrorKind::Rejected,
984            crate::transport::dialer::DialErrorKind::Other,
985        ] {
986            let error = Error::CustomTransport(std::sync::Arc::new(
987                crate::transport::dialer::DialError::new(kind, "route failed"),
988            ));
989            assert_eq!(error.transport_failure_kind(), None);
990            assert!(error.custom_transport_error().is_some());
991        }
992    }
993
994    #[test]
995    fn transport_failure_timeouts_admission_and_io_timeouts_stay_unknown() {
996        let timeout = Error::Timeout {
997            phase: TimeoutPhase::Connect,
998            elapsed: std::time::Duration::from_millis(5),
999        };
1000        assert_eq!(timeout.transport_failure_kind(), None);
1001        let io_timeout = Error::TransportIoTimeout {
1002            direction: crate::transport::lifecycle::TransportIoDirection::Read,
1003            elapsed: std::time::Duration::from_secs(1),
1004        };
1005        assert_eq!(io_timeout.transport_failure_kind(), None);
1006        assert!(io_timeout.is_transport_io_timeout());
1007        let admission =
1008            Error::Pool(crate::transport::lifecycle::PHYSICAL_ADMISSION_TIMEOUT.to_owned());
1009        assert!(admission.is_physical_connection_admission_timeout());
1010        assert_eq!(admission.transport_failure_kind(), None);
1011    }
1012
1013    #[test]
1014    fn transport_failure_unknown_stays_unknown() {
1015        for error in [
1016            Error::InvalidUrl("bad".into()),
1017            Error::Body("body".into()),
1018            Error::Pool("busy".into()),
1019            Error::ProxyConnect("proxy down".into()),
1020            Error::Http2GoAway {
1021                last_stream_id: 0,
1022                debug_data: "shutdown".into(),
1023            },
1024            Error::Http2StreamReset {
1025                reason: "CANCEL".into(),
1026            },
1027            Error::H3ConnectionClosed("closed".into()),
1028            Error::H3Stream("reset".into()),
1029            Error::TooManyRedirects {
1030                followed: 5,
1031                max: 5,
1032            },
1033        ] {
1034            assert_eq!(
1035                error.transport_failure_kind(),
1036                None,
1037                "kind={}",
1038                error.kind()
1039            );
1040        }
1041    }
1042
1043    #[test]
1044    fn transport_failure_does_not_change_kind_or_display() {
1045        let error = Error::Connect("refused".into());
1046        assert_eq!(error.kind(), "connect");
1047        assert_eq!(error.to_string(), "connect error: refused");
1048        assert_eq!(
1049            error.transport_failure_kind(),
1050            Some(TransportFailureKind::Connect)
1051        );
1052        let tls = Error::Tls("boom".into());
1053        assert_eq!(tls.kind(), "tls");
1054        assert_eq!(tls.to_string(), "TLS error: boom");
1055    }
1056
1057    #[test]
1058    fn transport_failure_wrapped_io_refused_maps_connect_unexpected_eof_stays_unknown() {
1059        let refused = Error::Io(std::sync::Arc::new(std::io::Error::new(
1060            std::io::ErrorKind::ConnectionRefused,
1061            "refused",
1062        )));
1063        assert_eq!(
1064            refused.transport_failure_kind(),
1065            Some(TransportFailureKind::Connect)
1066        );
1067        let eof = Error::Io(std::sync::Arc::new(std::io::Error::new(
1068            std::io::ErrorKind::UnexpectedEof,
1069            "eof",
1070        )));
1071        assert_eq!(eof.transport_failure_kind(), None);
1072    }
1073
1074    #[test]
1075    fn transport_failure_output_is_enum_only_and_redacted() {
1076        use std::fmt::Write as _;
1077        #[derive(Debug)]
1078        struct SecretSource;
1079        impl std::fmt::Display for SecretSource {
1080            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1081                f.write_str("authorization: Bearer hunter2 cookie=secret")
1082            }
1083        }
1084        impl std::error::Error for SecretSource {}
1085        let error = Error::CustomTransport(std::sync::Arc::new(
1086            crate::transport::dialer::DialError::with_source(
1087                crate::transport::dialer::DialErrorKind::Connection,
1088                "safe route description",
1089                SecretSource,
1090            ),
1091        ));
1092        let kind = error.transport_failure_kind();
1093        assert_eq!(kind, Some(TransportFailureKind::Connect));
1094        let mut rendered = String::new();
1095        write!(rendered, "{kind:?}").unwrap();
1096        assert!(!rendered.contains("hunter2"));
1097        assert!(!rendered.contains("authorization"));
1098        let debug = format!("{error:?}");
1099        assert!(!debug.contains("hunter2"));
1100    }
1101}