1use crate::timeout::TimeoutPhase;
4
5use std::sync::atomic::{AtomicU8, Ordering};
6use std::sync::Arc;
7
8pub type Result<T> = std::result::Result<T, Error>;
10
11#[non_exhaustive]
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum TransportFailureKind {
22 Connect,
25 Tls,
28 Protocol,
31 Cancelled,
34}
35
36#[non_exhaustive]
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
44pub enum NetworkFailureKind {
45 Dns,
47 ConnectionRefused,
49 Connect,
52}
53
54pub struct RequestFailure {
62 error: Error,
63 network_failure: Option<NetworkFailureKind>,
64}
65
66impl RequestFailure {
67 #[must_use]
69 pub fn error(&self) -> &Error {
70 &self.error
71 }
72
73 #[must_use]
75 pub fn into_error(self) -> Error {
76 self.error
77 }
78
79 #[must_use]
81 pub fn network_failure_kind(&self) -> Option<NetworkFailureKind> {
82 self.network_failure
83 }
84
85 #[must_use]
92 pub fn is_timeout(&self) -> bool {
93 matches!(
94 self.error,
95 Error::Timeout { .. } | Error::TransportIoTimeout { .. }
96 )
97 }
98
99 #[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
147pub(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#[derive(Debug, Clone, thiserror::Error)]
187pub enum Error {
188 #[error("invalid URL: {0}")]
190 InvalidUrl(String),
191
192 #[error("invalid method: {0}")]
194 InvalidMethod(String),
195
196 #[error("invalid header name: {0}")]
198 InvalidHeaderName(String),
199
200 #[error("invalid header value: {0}")]
202 InvalidHeaderValue(String),
203
204 #[error("request build error: {0}")]
206 RequestBuild(String),
207
208 #[error("invalid resolved destination: {0}")]
210 InvalidResolvedTarget(String),
211
212 #[error("resolved destination cannot be reused across a cross-origin redirect")]
214 ResolvedTargetRedirect,
215
216 #[error("JSON serialization error: {0}")]
218 JsonSerialize(String),
219
220 #[error("JSON deserialization error: {0}")]
222 JsonDeserialize(String),
223
224 #[error("connect error: {0}")]
226 Connect(String),
227
228 #[error("custom transport error: {0}")]
230 CustomTransport(#[source] std::sync::Arc<crate::transport::dialer::DialError>),
231
232 #[error("TLS error: {0}")]
234 Tls(String),
235
236 #[error("protocol error: {0}")]
238 Protocol(String),
239
240 #[error("body error: {0}")]
242 Body(String),
243
244 #[error("hyper error: {0}")]
246 Hyper(#[from] std::sync::Arc<hyper::Error>),
247
248 #[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 #[error("I/O error: {0}")]
255 Io(#[from] std::sync::Arc<std::io::Error>),
256
257 #[error("unsupported: {0}")]
259 Unsupported(String),
260
261 #[error("pool error: {0}")]
263 Pool(String),
264
265 #[error("invalid redirect location: {0}")]
267 InvalidRedirectLocation(String),
268
269 #[error("invalid auth header: {0}")]
271 InvalidAuthHeader(String),
272
273 #[error("conflicting auth: {0}")]
275 ConflictingAuth(String),
276
277 #[error("body not replayable for redirect: streaming request bodies cannot be resent")]
279 BodyNotReplayableForRedirect,
280
281 #[error("too many redirects ({followed} followed, max {max})")]
283 TooManyRedirects {
284 followed: usize,
286 max: usize,
288 },
289
290 #[error("decompression error: {0}")]
292 Decompression(String),
293
294 #[error("unsupported content encoding: {0}")]
296 UnsupportedContentEncoding(String),
297
298 #[error("{phase} timeout after {elapsed:?}")]
300 Timeout {
301 phase: TimeoutPhase,
303 elapsed: std::time::Duration,
305 },
306
307 #[error("transport {direction:?} inactivity timeout after {elapsed:?}")]
310 TransportIoTimeout {
311 direction: crate::transport::lifecycle::TransportIoDirection,
313 elapsed: std::time::Duration,
315 },
316
317 #[error("invalid proxy URL: {0}")]
319 InvalidProxyUrl(String),
320
321 #[error("proxy error: {0}")]
323 ProxyConnect(String),
324
325 #[error("proxy authentication required")]
327 ProxyAuthRequired,
328
329 #[error("CONNECT rejected: {status} {body}")]
331 ProxyConnectRejected {
332 status: u16,
334 body: String,
336 },
337
338 #[error("malformed proxy response: {0}")]
340 MalformedProxyResponse(String),
341
342 #[error("decoded body exceeded max decoded body size")]
344 DecodedBodyTooLarge,
345
346 #[error("decompression ratio exceeded max ratio")]
348 DecompressionRatioExceeded,
349
350 #[error("TLS configuration error: {0}")]
352 TlsConfig(String),
353
354 #[error("CA bundle error: {0}")]
356 CaBundle(String),
357
358 #[error("client certificate error: {0}")]
360 ClientCert(String),
361
362 #[error("private key error: {0}")]
364 PrivateKey(String),
365
366 #[error("certificate verification failed: {0}")]
368 CertificateVerification(String),
369
370 #[error("hostname verification failed: {0}")]
372 HostnameVerification(String),
373
374 #[error("body not replayable for retry")]
376 BodyNotReplayableForRetry,
377
378 #[error("retry budget exhausted after {attempts} attempts")]
380 RetryBudgetExhausted {
381 attempts: usize,
383 },
384
385 #[error("retry not configured")]
387 RetryNotConfigured,
388
389 #[error("HTTP/2 GOAWAY: last_stream_id={last_stream_id}, debug={debug_data}")]
395 Http2GoAway {
396 last_stream_id: u32,
398 debug_data: String,
400 },
401
402 #[error("HTTP/2 stream reset: {reason}")]
404 Http2StreamReset {
405 reason: String,
407 },
408
409 #[error("HTTP/2 flow control error: {0}")]
411 Http2FlowControl(String),
412
413 #[error("HTTP/2 protocol error: {0}")]
415 Http2Protocol(String),
416
417 #[error("HTTP/3 connect error: {0}")]
419 H3Connect(String),
420
421 #[error("HTTP/3 connection closed: {0}")]
423 H3ConnectionClosed(String),
424
425 #[error("HTTP/3 stream error: {0}")]
427 H3Stream(String),
428
429 #[error("HTTP/3 protocol error: {0}")]
431 H3Protocol(String),
432
433 #[error("trace callback aborted the request")]
435 TraceCallbackAborted,
436}
437
438impl Error {
439 #[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 #[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 #[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 #[must_use]
530 pub fn is_transport_io_timeout(&self) -> bool {
531 matches!(self, Self::TransportIoTimeout { .. })
532 }
533
534 #[must_use]
542 pub fn transport_failure_kind(&self) -> Option<TransportFailureKind> {
543 classify_transport_failure(self)
544 }
545}
546
547const TRANSPORT_FAILURE_WALK_BOUND: usize = 32;
549
550fn 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#[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 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 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 #[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 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 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
694fn classify_transport_failure(error: &Error) -> Option<TransportFailureKind> {
714 use std::error::Error as StdError;
715 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 let body_boundary = matches!(error, Error::Hyper(_));
728 let mut evidence = TransportEvidence::default();
729 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 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 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#[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}