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(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 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 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 #[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 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 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
691fn classify_transport_failure(error: &Error) -> Option<TransportFailureKind> {
711 use std::error::Error as StdError;
712 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 let body_boundary = matches!(error, Error::Hyper(_));
725 let mut evidence = TransportEvidence::default();
726 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 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 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#[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}