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]
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19pub enum NetworkFailureKind {
20 Dns,
22 ConnectionRefused,
24 Connect,
27}
28
29pub struct RequestFailure {
37 error: Error,
38 network_failure: Option<NetworkFailureKind>,
39}
40
41impl RequestFailure {
42 #[must_use]
44 pub fn error(&self) -> &Error {
45 &self.error
46 }
47
48 #[must_use]
50 pub fn into_error(self) -> Error {
51 self.error
52 }
53
54 #[must_use]
56 pub fn network_failure_kind(&self) -> Option<NetworkFailureKind> {
57 self.network_failure
58 }
59
60 #[must_use]
67 pub fn is_timeout(&self) -> bool {
68 matches!(
69 self.error,
70 Error::Timeout { .. } | Error::TransportIoTimeout { .. }
71 )
72 }
73
74 #[must_use]
79 pub fn timeout_phase(&self) -> Option<TimeoutPhase> {
80 match self.error {
81 Error::Timeout { phase, .. } => Some(phase),
82 _ => None,
83 }
84 }
85
86 pub(crate) fn from_error(error: Error) -> Self {
87 Self {
88 error,
89 network_failure: None,
90 }
91 }
92
93 pub(crate) fn from_context(error: Error, context: &RequestFailureContext) -> Self {
94 Self {
95 error,
96 network_failure: context.network_failure_kind(),
97 }
98 }
99}
100
101impl std::fmt::Debug for RequestFailure {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 f.debug_struct("RequestFailure")
104 .field("error", &self.error)
105 .field("network_failure", &self.network_failure)
106 .finish()
107 }
108}
109
110impl std::fmt::Display for RequestFailure {
111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112 self.error.fmt(f)
113 }
114}
115
116impl std::error::Error for RequestFailure {
117 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
118 self.error.source()
119 }
120}
121
122pub(crate) struct RequestFailureContext {
128 network_failure: AtomicU8,
129}
130
131impl RequestFailureContext {
132 pub(crate) fn new() -> Arc<Self> {
133 Arc::new(Self {
134 network_failure: AtomicU8::new(0),
135 })
136 }
137
138 pub(crate) fn clear(&self) {
139 self.network_failure.store(0, Ordering::Relaxed);
140 }
141
142 pub(crate) fn record(&self, kind: NetworkFailureKind) {
143 self.network_failure
144 .store(kind as u8 + 1, Ordering::Relaxed);
145 }
146
147 fn network_failure_kind(&self) -> Option<NetworkFailureKind> {
148 match self.network_failure.load(Ordering::Relaxed) {
149 1 => Some(NetworkFailureKind::Dns),
150 2 => Some(NetworkFailureKind::ConnectionRefused),
151 3 => Some(NetworkFailureKind::Connect),
152 _ => None,
153 }
154 }
155}
156
157#[derive(Debug, Clone, thiserror::Error)]
162pub enum Error {
163 #[error("invalid URL: {0}")]
165 InvalidUrl(String),
166
167 #[error("invalid method: {0}")]
169 InvalidMethod(String),
170
171 #[error("invalid header name: {0}")]
173 InvalidHeaderName(String),
174
175 #[error("invalid header value: {0}")]
177 InvalidHeaderValue(String),
178
179 #[error("request build error: {0}")]
181 RequestBuild(String),
182
183 #[error("invalid resolved destination: {0}")]
185 InvalidResolvedTarget(String),
186
187 #[error("resolved destination cannot be reused across a cross-origin redirect")]
189 ResolvedTargetRedirect,
190
191 #[error("JSON serialization error: {0}")]
193 JsonSerialize(String),
194
195 #[error("JSON deserialization error: {0}")]
197 JsonDeserialize(String),
198
199 #[error("connect error: {0}")]
201 Connect(String),
202
203 #[error("custom transport error: {0}")]
205 CustomTransport(#[source] std::sync::Arc<crate::transport::dialer::DialError>),
206
207 #[error("TLS error: {0}")]
209 Tls(String),
210
211 #[error("protocol error: {0}")]
213 Protocol(String),
214
215 #[error("body error: {0}")]
217 Body(String),
218
219 #[error("hyper error: {0}")]
221 Hyper(#[from] std::sync::Arc<hyper::Error>),
222
223 #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
225 #[error("hyper client error: {0}")]
226 HyperClient(#[source] std::sync::Arc<hyper_util::client::legacy::Error>),
227
228 #[error("I/O error: {0}")]
230 Io(#[from] std::sync::Arc<std::io::Error>),
231
232 #[error("unsupported: {0}")]
234 Unsupported(String),
235
236 #[error("pool error: {0}")]
238 Pool(String),
239
240 #[error("invalid redirect location: {0}")]
242 InvalidRedirectLocation(String),
243
244 #[error("invalid auth header: {0}")]
246 InvalidAuthHeader(String),
247
248 #[error("conflicting auth: {0}")]
250 ConflictingAuth(String),
251
252 #[error("body not replayable for redirect: streaming request bodies cannot be resent")]
254 BodyNotReplayableForRedirect,
255
256 #[error("too many redirects ({followed} followed, max {max})")]
258 TooManyRedirects {
259 followed: usize,
261 max: usize,
263 },
264
265 #[error("decompression error: {0}")]
267 Decompression(String),
268
269 #[error("unsupported content encoding: {0}")]
271 UnsupportedContentEncoding(String),
272
273 #[error("{phase} timeout after {elapsed:?}")]
275 Timeout {
276 phase: TimeoutPhase,
278 elapsed: std::time::Duration,
280 },
281
282 #[error("transport {direction:?} inactivity timeout after {elapsed:?}")]
285 TransportIoTimeout {
286 direction: crate::transport::lifecycle::TransportIoDirection,
288 elapsed: std::time::Duration,
290 },
291
292 #[error("invalid proxy URL: {0}")]
294 InvalidProxyUrl(String),
295
296 #[error("proxy error: {0}")]
298 ProxyConnect(String),
299
300 #[error("proxy authentication required")]
302 ProxyAuthRequired,
303
304 #[error("CONNECT rejected: {status} {body}")]
306 ProxyConnectRejected {
307 status: u16,
309 body: String,
311 },
312
313 #[error("malformed proxy response: {0}")]
315 MalformedProxyResponse(String),
316
317 #[error("decoded body exceeded max decoded body size")]
319 DecodedBodyTooLarge,
320
321 #[error("decompression ratio exceeded max ratio")]
323 DecompressionRatioExceeded,
324
325 #[error("TLS configuration error: {0}")]
327 TlsConfig(String),
328
329 #[error("CA bundle error: {0}")]
331 CaBundle(String),
332
333 #[error("client certificate error: {0}")]
335 ClientCert(String),
336
337 #[error("private key error: {0}")]
339 PrivateKey(String),
340
341 #[error("certificate verification failed: {0}")]
343 CertificateVerification(String),
344
345 #[error("hostname verification failed: {0}")]
347 HostnameVerification(String),
348
349 #[error("body not replayable for retry")]
351 BodyNotReplayableForRetry,
352
353 #[error("retry budget exhausted after {attempts} attempts")]
355 RetryBudgetExhausted {
356 attempts: usize,
358 },
359
360 #[error("retry not configured")]
362 RetryNotConfigured,
363
364 #[error("HTTP/2 GOAWAY: last_stream_id={last_stream_id}, debug={debug_data}")]
370 Http2GoAway {
371 last_stream_id: u32,
373 debug_data: String,
375 },
376
377 #[error("HTTP/2 stream reset: {reason}")]
379 Http2StreamReset {
380 reason: String,
382 },
383
384 #[error("HTTP/2 flow control error: {0}")]
386 Http2FlowControl(String),
387
388 #[error("HTTP/2 protocol error: {0}")]
390 Http2Protocol(String),
391
392 #[error("HTTP/3 connect error: {0}")]
394 H3Connect(String),
395
396 #[error("HTTP/3 connection closed: {0}")]
398 H3ConnectionClosed(String),
399
400 #[error("HTTP/3 stream error: {0}")]
402 H3Stream(String),
403
404 #[error("HTTP/3 protocol error: {0}")]
406 H3Protocol(String),
407
408 #[error("trace callback aborted the request")]
410 TraceCallbackAborted,
411}
412
413impl Error {
414 #[must_use]
416 pub fn kind(&self) -> &'static str {
417 match self {
418 Self::InvalidUrl(_) => "invalid_url",
419 Self::InvalidMethod(_) => "invalid_method",
420 Self::InvalidHeaderName(_) => "invalid_header_name",
421 Self::InvalidHeaderValue(_) => "invalid_header_value",
422 Self::RequestBuild(_) => "request_build",
423 Self::InvalidResolvedTarget(_) => "invalid_resolved_target",
424 Self::ResolvedTargetRedirect => "resolved_target_redirect",
425 Self::JsonSerialize(_) => "json_serialize",
426 Self::JsonDeserialize(_) => "json_deserialize",
427 Self::Connect(_) => "connect",
428 Self::CustomTransport(_) => "custom_transport",
429 Self::Tls(_) => "tls",
430 Self::Protocol(_) => "protocol",
431 Self::Body(_) => "body",
432 Self::Hyper(_) => "hyper",
433 #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
434 Self::HyperClient(_) => "hyper_client",
435 Self::Io(_) => "io",
436 Self::Unsupported(_) => "unsupported",
437 Self::InvalidRedirectLocation(_) => "invalid_redirect_location",
438 Self::InvalidAuthHeader(_) => "invalid_auth_header",
439 Self::ConflictingAuth(_) => "conflicting_auth",
440 Self::BodyNotReplayableForRedirect => "body_not_replayable_for_redirect",
441 Self::TooManyRedirects { .. } => "too_many_redirects",
442 Self::Pool(_) => "pool",
443 Self::Decompression(_) => "decompression",
444 Self::UnsupportedContentEncoding(_) => "unsupported_content_encoding",
445 Self::Timeout { phase, .. } => match phase {
446 crate::timeout::TimeoutPhase::Pool => "timeout_pool",
447 crate::timeout::TimeoutPhase::Connect => "timeout_connect",
448 crate::timeout::TimeoutPhase::ProxyConnect => "timeout_proxy_connect",
449 crate::timeout::TimeoutPhase::ProxyTls => "timeout_proxy_tls",
450 crate::timeout::TimeoutPhase::Write => "timeout_write",
451 crate::timeout::TimeoutPhase::Read => "timeout_read",
452 crate::timeout::TimeoutPhase::Total => "timeout_total",
453 },
454 Self::TransportIoTimeout { direction, .. } => match direction {
455 crate::transport::lifecycle::TransportIoDirection::Read => "transport_read_timeout",
456 crate::transport::lifecycle::TransportIoDirection::Write => {
457 "transport_write_timeout"
458 }
459 },
460 Self::InvalidProxyUrl(_) => "invalid_proxy_url",
461 Self::ProxyConnect(_) => "proxy_connect",
462 Self::ProxyAuthRequired => "proxy_auth_required",
463 Self::ProxyConnectRejected { .. } => "proxy_connect_rejected",
464 Self::MalformedProxyResponse(_) => "malformed_proxy_response",
465 Self::DecodedBodyTooLarge => "decoded_body_too_large",
466 Self::DecompressionRatioExceeded => "decompression_ratio_exceeded",
467 Self::TlsConfig(_) => "tls_config",
468 Self::CaBundle(_) => "ca_bundle",
469 Self::ClientCert(_) => "client_cert",
470 Self::PrivateKey(_) => "private_key",
471 Self::CertificateVerification(_) => "certificate_verification",
472 Self::HostnameVerification(_) => "hostname_verification",
473 Self::BodyNotReplayableForRetry => "body_not_replayable_for_retry",
474 Self::RetryBudgetExhausted { .. } => "retry_budget_exhausted",
475 Self::RetryNotConfigured => "retry_not_configured",
476 Self::Http2GoAway { .. } => "http2_go_away",
477 Self::Http2StreamReset { .. } => "http2_stream_reset",
478 Self::Http2FlowControl(_) => "http2_flow_control",
479 Self::Http2Protocol(_) => "http2_protocol",
480 Self::H3Connect(_) => "h3_connect",
481 Self::H3ConnectionClosed(_) => "h3_connection_closed",
482 Self::H3Stream(_) => "h3_stream",
483 Self::H3Protocol(_) => "h3_protocol",
484 Self::TraceCallbackAborted => "trace_callback_aborted",
485 }
486 }
487
488 #[must_use]
490 pub fn custom_transport_error(&self) -> Option<&crate::transport::dialer::DialError> {
491 match self {
492 Self::CustomTransport(error) => Some(error.as_ref()),
493 _ => None,
494 }
495 }
496
497 #[must_use]
499 pub fn is_physical_connection_admission_timeout(&self) -> bool {
500 matches!(self, Self::Pool(message) if message == crate::transport::lifecycle::PHYSICAL_ADMISSION_TIMEOUT)
501 }
502
503 #[must_use]
505 pub fn is_transport_io_timeout(&self) -> bool {
506 matches!(self, Self::TransportIoTimeout { .. })
507 }
508}
509
510#[cfg(test)]
511mod tests {
512 use super::*;
513
514 #[test]
515 fn error_display() {
516 let err = Error::InvalidUrl("not a url".into());
517 assert_eq!(err.to_string(), "invalid URL: not a url");
518 }
519
520 #[test]
521 fn error_kind() {
522 let err = Error::Connect("refused".into());
523 assert_eq!(err.kind(), "connect");
524 }
525
526 #[test]
527 fn error_from_io() {
528 let io_err = std::sync::Arc::new(std::io::Error::other("test"));
529 let err: Error = io_err.into();
530 assert_eq!(err.kind(), "io");
531 }
532
533 #[test]
534 fn request_failure_exposes_timeout_without_changing_error() {
535 let error = Error::Timeout {
536 phase: TimeoutPhase::Connect,
537 elapsed: std::time::Duration::from_millis(5),
538 };
539 let failure = RequestFailure::from_error(error);
540 assert!(failure.is_timeout());
541 assert_eq!(failure.timeout_phase(), Some(TimeoutPhase::Connect));
542 assert_eq!(failure.error().kind(), "timeout_connect");
543 assert_eq!(failure.into_error().kind(), "timeout_connect");
544 }
545
546 #[test]
547 fn request_failure_keeps_transport_timeout_distinct() {
548 let failure = RequestFailure::from_error(Error::TransportIoTimeout {
549 direction: crate::transport::lifecycle::TransportIoDirection::Read,
550 elapsed: std::time::Duration::from_secs(1),
551 });
552 assert!(failure.is_timeout());
553 assert_eq!(failure.timeout_phase(), None);
554 }
555
556 #[test]
557 fn request_failure_context_replaces_transient_classification() {
558 let context = RequestFailureContext::new();
559 context.record(NetworkFailureKind::Dns);
560 context.record(NetworkFailureKind::ConnectionRefused);
561 let failure = RequestFailure::from_context(Error::Connect("refused".into()), &context);
562 assert_eq!(
563 failure.network_failure_kind(),
564 Some(NetworkFailureKind::ConnectionRefused)
565 );
566 context.clear();
567 assert_eq!(context.network_failure_kind(), None);
568 }
569
570 #[test]
571 fn error_http2_go_away_display() {
572 let err = Error::Http2GoAway {
573 last_stream_id: 1,
574 debug_data: "no error: connection closed".into(),
575 };
576 assert_eq!(err.kind(), "http2_go_away");
577 let msg = err.to_string();
578 assert!(msg.contains("GOAWAY"));
579 assert!(msg.contains("no error: connection closed"));
580 }
581
582 #[test]
583 fn error_http2_stream_reset_display() {
584 let err = Error::Http2StreamReset {
585 reason: "REFUSED_STREAM: stream refused".into(),
586 };
587 assert_eq!(err.kind(), "http2_stream_reset");
588 assert!(err.to_string().contains("REFUSED_STREAM"));
589 }
590
591 #[test]
592 fn error_http2_flow_control_display() {
593 let err = Error::Http2FlowControl("flow-control violated".into());
594 assert_eq!(err.kind(), "http2_flow_control");
595 }
596
597 #[test]
598 fn error_http2_protocol_display() {
599 let err = Error::Http2Protocol("stream closed after headers".into());
600 assert_eq!(err.kind(), "http2_protocol");
601 }
602
603 #[cfg(feature = "logical-retry")]
604 #[test]
605 fn http2_refused_stream_is_retryable() {
606 let err = Error::Http2StreamReset {
607 reason: "REFUSED_STREAM: stream refused before processing".into(),
608 };
609 assert!(crate::retry::RetryPolicy::is_error_retryable(&err));
610 }
611
612 #[cfg(feature = "logical-retry")]
613 #[test]
614 fn http2_cancel_is_not_retryable() {
615 let err = Error::Http2StreamReset {
616 reason: "CANCEL: stream no longer needed".into(),
617 };
618 assert!(!crate::retry::RetryPolicy::is_error_retryable(&err));
619 }
620
621 #[cfg(feature = "logical-retry")]
622 #[test]
623 fn http2_go_away_is_not_retryable() {
624 let err = Error::Http2GoAway {
625 last_stream_id: 0,
626 debug_data: " shutting down".into(),
627 };
628 assert!(!crate::retry::RetryPolicy::is_error_retryable(&err));
629 }
630}