use crate::timeout::TimeoutPhase;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::Arc;
pub type Result<T> = std::result::Result<T, Error>;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NetworkFailureKind {
Dns,
ConnectionRefused,
Connect,
}
pub struct RequestFailure {
error: Error,
network_failure: Option<NetworkFailureKind>,
}
impl RequestFailure {
#[must_use]
pub fn error(&self) -> &Error {
&self.error
}
#[must_use]
pub fn into_error(self) -> Error {
self.error
}
#[must_use]
pub fn network_failure_kind(&self) -> Option<NetworkFailureKind> {
self.network_failure
}
#[must_use]
pub fn is_timeout(&self) -> bool {
matches!(
self.error,
Error::Timeout { .. } | Error::TransportIoTimeout { .. }
)
}
#[must_use]
pub fn timeout_phase(&self) -> Option<TimeoutPhase> {
match self.error {
Error::Timeout { phase, .. } => Some(phase),
_ => None,
}
}
pub(crate) fn from_error(error: Error) -> Self {
Self {
error,
network_failure: None,
}
}
pub(crate) fn from_context(error: Error, context: &RequestFailureContext) -> Self {
Self {
error,
network_failure: context.network_failure_kind(),
}
}
}
impl std::fmt::Debug for RequestFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RequestFailure")
.field("error", &self.error)
.field("network_failure", &self.network_failure)
.finish()
}
}
impl std::fmt::Display for RequestFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.error.fmt(f)
}
}
impl std::error::Error for RequestFailure {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.error.source()
}
}
pub(crate) struct RequestFailureContext {
network_failure: AtomicU8,
}
impl RequestFailureContext {
pub(crate) fn new() -> Arc<Self> {
Arc::new(Self {
network_failure: AtomicU8::new(0),
})
}
pub(crate) fn clear(&self) {
self.network_failure.store(0, Ordering::Relaxed);
}
pub(crate) fn record(&self, kind: NetworkFailureKind) {
self.network_failure
.store(kind as u8 + 1, Ordering::Relaxed);
}
fn network_failure_kind(&self) -> Option<NetworkFailureKind> {
match self.network_failure.load(Ordering::Relaxed) {
1 => Some(NetworkFailureKind::Dns),
2 => Some(NetworkFailureKind::ConnectionRefused),
3 => Some(NetworkFailureKind::Connect),
_ => None,
}
}
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum Error {
#[error("invalid URL: {0}")]
InvalidUrl(String),
#[error("invalid method: {0}")]
InvalidMethod(String),
#[error("invalid header name: {0}")]
InvalidHeaderName(String),
#[error("invalid header value: {0}")]
InvalidHeaderValue(String),
#[error("request build error: {0}")]
RequestBuild(String),
#[error("invalid resolved destination: {0}")]
InvalidResolvedTarget(String),
#[error("resolved destination cannot be reused across a cross-origin redirect")]
ResolvedTargetRedirect,
#[error("JSON serialization error: {0}")]
JsonSerialize(String),
#[error("JSON deserialization error: {0}")]
JsonDeserialize(String),
#[error("connect error: {0}")]
Connect(String),
#[error("custom transport error: {0}")]
CustomTransport(#[source] std::sync::Arc<crate::transport::dialer::DialError>),
#[error("TLS error: {0}")]
Tls(String),
#[error("protocol error: {0}")]
Protocol(String),
#[error("body error: {0}")]
Body(String),
#[error("hyper error: {0}")]
Hyper(#[from] std::sync::Arc<hyper::Error>),
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
#[error("hyper client error: {0}")]
HyperClient(#[source] std::sync::Arc<hyper_util::client::legacy::Error>),
#[error("I/O error: {0}")]
Io(#[from] std::sync::Arc<std::io::Error>),
#[error("unsupported: {0}")]
Unsupported(String),
#[error("pool error: {0}")]
Pool(String),
#[error("invalid redirect location: {0}")]
InvalidRedirectLocation(String),
#[error("invalid auth header: {0}")]
InvalidAuthHeader(String),
#[error("conflicting auth: {0}")]
ConflictingAuth(String),
#[error("body not replayable for redirect: streaming request bodies cannot be resent")]
BodyNotReplayableForRedirect,
#[error("too many redirects ({followed} followed, max {max})")]
TooManyRedirects {
followed: usize,
max: usize,
},
#[error("decompression error: {0}")]
Decompression(String),
#[error("unsupported content encoding: {0}")]
UnsupportedContentEncoding(String),
#[error("{phase} timeout after {elapsed:?}")]
Timeout {
phase: TimeoutPhase,
elapsed: std::time::Duration,
},
#[error("transport {direction:?} inactivity timeout after {elapsed:?}")]
TransportIoTimeout {
direction: crate::transport::lifecycle::TransportIoDirection,
elapsed: std::time::Duration,
},
#[error("invalid proxy URL: {0}")]
InvalidProxyUrl(String),
#[error("proxy error: {0}")]
ProxyConnect(String),
#[error("proxy authentication required")]
ProxyAuthRequired,
#[error("CONNECT rejected: {status} {body}")]
ProxyConnectRejected {
status: u16,
body: String,
},
#[error("malformed proxy response: {0}")]
MalformedProxyResponse(String),
#[error("decoded body exceeded max decoded body size")]
DecodedBodyTooLarge,
#[error("decompression ratio exceeded max ratio")]
DecompressionRatioExceeded,
#[error("TLS configuration error: {0}")]
TlsConfig(String),
#[error("CA bundle error: {0}")]
CaBundle(String),
#[error("client certificate error: {0}")]
ClientCert(String),
#[error("private key error: {0}")]
PrivateKey(String),
#[error("certificate verification failed: {0}")]
CertificateVerification(String),
#[error("hostname verification failed: {0}")]
HostnameVerification(String),
#[error("body not replayable for retry")]
BodyNotReplayableForRetry,
#[error("retry budget exhausted after {attempts} attempts")]
RetryBudgetExhausted {
attempts: usize,
},
#[error("retry not configured")]
RetryNotConfigured,
#[error("HTTP/2 GOAWAY: last_stream_id={last_stream_id}, debug={debug_data}")]
Http2GoAway {
last_stream_id: u32,
debug_data: String,
},
#[error("HTTP/2 stream reset: {reason}")]
Http2StreamReset {
reason: String,
},
#[error("HTTP/2 flow control error: {0}")]
Http2FlowControl(String),
#[error("HTTP/2 protocol error: {0}")]
Http2Protocol(String),
#[error("HTTP/3 connect error: {0}")]
H3Connect(String),
#[error("HTTP/3 connection closed: {0}")]
H3ConnectionClosed(String),
#[error("HTTP/3 stream error: {0}")]
H3Stream(String),
#[error("HTTP/3 protocol error: {0}")]
H3Protocol(String),
#[error("trace callback aborted the request")]
TraceCallbackAborted,
}
impl Error {
#[must_use]
pub fn kind(&self) -> &'static str {
match self {
Self::InvalidUrl(_) => "invalid_url",
Self::InvalidMethod(_) => "invalid_method",
Self::InvalidHeaderName(_) => "invalid_header_name",
Self::InvalidHeaderValue(_) => "invalid_header_value",
Self::RequestBuild(_) => "request_build",
Self::InvalidResolvedTarget(_) => "invalid_resolved_target",
Self::ResolvedTargetRedirect => "resolved_target_redirect",
Self::JsonSerialize(_) => "json_serialize",
Self::JsonDeserialize(_) => "json_deserialize",
Self::Connect(_) => "connect",
Self::CustomTransport(_) => "custom_transport",
Self::Tls(_) => "tls",
Self::Protocol(_) => "protocol",
Self::Body(_) => "body",
Self::Hyper(_) => "hyper",
#[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
Self::HyperClient(_) => "hyper_client",
Self::Io(_) => "io",
Self::Unsupported(_) => "unsupported",
Self::InvalidRedirectLocation(_) => "invalid_redirect_location",
Self::InvalidAuthHeader(_) => "invalid_auth_header",
Self::ConflictingAuth(_) => "conflicting_auth",
Self::BodyNotReplayableForRedirect => "body_not_replayable_for_redirect",
Self::TooManyRedirects { .. } => "too_many_redirects",
Self::Pool(_) => "pool",
Self::Decompression(_) => "decompression",
Self::UnsupportedContentEncoding(_) => "unsupported_content_encoding",
Self::Timeout { phase, .. } => match phase {
crate::timeout::TimeoutPhase::Pool => "timeout_pool",
crate::timeout::TimeoutPhase::Connect => "timeout_connect",
crate::timeout::TimeoutPhase::ProxyConnect => "timeout_proxy_connect",
crate::timeout::TimeoutPhase::ProxyTls => "timeout_proxy_tls",
crate::timeout::TimeoutPhase::Write => "timeout_write",
crate::timeout::TimeoutPhase::Read => "timeout_read",
crate::timeout::TimeoutPhase::Total => "timeout_total",
},
Self::TransportIoTimeout { direction, .. } => match direction {
crate::transport::lifecycle::TransportIoDirection::Read => "transport_read_timeout",
crate::transport::lifecycle::TransportIoDirection::Write => {
"transport_write_timeout"
}
},
Self::InvalidProxyUrl(_) => "invalid_proxy_url",
Self::ProxyConnect(_) => "proxy_connect",
Self::ProxyAuthRequired => "proxy_auth_required",
Self::ProxyConnectRejected { .. } => "proxy_connect_rejected",
Self::MalformedProxyResponse(_) => "malformed_proxy_response",
Self::DecodedBodyTooLarge => "decoded_body_too_large",
Self::DecompressionRatioExceeded => "decompression_ratio_exceeded",
Self::TlsConfig(_) => "tls_config",
Self::CaBundle(_) => "ca_bundle",
Self::ClientCert(_) => "client_cert",
Self::PrivateKey(_) => "private_key",
Self::CertificateVerification(_) => "certificate_verification",
Self::HostnameVerification(_) => "hostname_verification",
Self::BodyNotReplayableForRetry => "body_not_replayable_for_retry",
Self::RetryBudgetExhausted { .. } => "retry_budget_exhausted",
Self::RetryNotConfigured => "retry_not_configured",
Self::Http2GoAway { .. } => "http2_go_away",
Self::Http2StreamReset { .. } => "http2_stream_reset",
Self::Http2FlowControl(_) => "http2_flow_control",
Self::Http2Protocol(_) => "http2_protocol",
Self::H3Connect(_) => "h3_connect",
Self::H3ConnectionClosed(_) => "h3_connection_closed",
Self::H3Stream(_) => "h3_stream",
Self::H3Protocol(_) => "h3_protocol",
Self::TraceCallbackAborted => "trace_callback_aborted",
}
}
#[must_use]
pub fn custom_transport_error(&self) -> Option<&crate::transport::dialer::DialError> {
match self {
Self::CustomTransport(error) => Some(error.as_ref()),
_ => None,
}
}
#[must_use]
pub fn is_physical_connection_admission_timeout(&self) -> bool {
matches!(self, Self::Pool(message) if message == crate::transport::lifecycle::PHYSICAL_ADMISSION_TIMEOUT)
}
#[must_use]
pub fn is_transport_io_timeout(&self) -> bool {
matches!(self, Self::TransportIoTimeout { .. })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn error_display() {
let err = Error::InvalidUrl("not a url".into());
assert_eq!(err.to_string(), "invalid URL: not a url");
}
#[test]
fn error_kind() {
let err = Error::Connect("refused".into());
assert_eq!(err.kind(), "connect");
}
#[test]
fn error_from_io() {
let io_err = std::sync::Arc::new(std::io::Error::other("test"));
let err: Error = io_err.into();
assert_eq!(err.kind(), "io");
}
#[test]
fn request_failure_exposes_timeout_without_changing_error() {
let error = Error::Timeout {
phase: TimeoutPhase::Connect,
elapsed: std::time::Duration::from_millis(5),
};
let failure = RequestFailure::from_error(error);
assert!(failure.is_timeout());
assert_eq!(failure.timeout_phase(), Some(TimeoutPhase::Connect));
assert_eq!(failure.error().kind(), "timeout_connect");
assert_eq!(failure.into_error().kind(), "timeout_connect");
}
#[test]
fn request_failure_keeps_transport_timeout_distinct() {
let failure = RequestFailure::from_error(Error::TransportIoTimeout {
direction: crate::transport::lifecycle::TransportIoDirection::Read,
elapsed: std::time::Duration::from_secs(1),
});
assert!(failure.is_timeout());
assert_eq!(failure.timeout_phase(), None);
}
#[test]
fn request_failure_context_replaces_transient_classification() {
let context = RequestFailureContext::new();
context.record(NetworkFailureKind::Dns);
context.record(NetworkFailureKind::ConnectionRefused);
let failure = RequestFailure::from_context(Error::Connect("refused".into()), &context);
assert_eq!(
failure.network_failure_kind(),
Some(NetworkFailureKind::ConnectionRefused)
);
context.clear();
assert_eq!(context.network_failure_kind(), None);
}
#[test]
fn error_http2_go_away_display() {
let err = Error::Http2GoAway {
last_stream_id: 1,
debug_data: "no error: connection closed".into(),
};
assert_eq!(err.kind(), "http2_go_away");
let msg = err.to_string();
assert!(msg.contains("GOAWAY"));
assert!(msg.contains("no error: connection closed"));
}
#[test]
fn error_http2_stream_reset_display() {
let err = Error::Http2StreamReset {
reason: "REFUSED_STREAM: stream refused".into(),
};
assert_eq!(err.kind(), "http2_stream_reset");
assert!(err.to_string().contains("REFUSED_STREAM"));
}
#[test]
fn error_http2_flow_control_display() {
let err = Error::Http2FlowControl("flow-control violated".into());
assert_eq!(err.kind(), "http2_flow_control");
}
#[test]
fn error_http2_protocol_display() {
let err = Error::Http2Protocol("stream closed after headers".into());
assert_eq!(err.kind(), "http2_protocol");
}
#[cfg(feature = "logical-retry")]
#[test]
fn http2_refused_stream_is_retryable() {
let err = Error::Http2StreamReset {
reason: "REFUSED_STREAM: stream refused before processing".into(),
};
assert!(crate::retry::RetryPolicy::is_error_retryable(&err));
}
#[cfg(feature = "logical-retry")]
#[test]
fn http2_cancel_is_not_retryable() {
let err = Error::Http2StreamReset {
reason: "CANCEL: stream no longer needed".into(),
};
assert!(!crate::retry::RetryPolicy::is_error_retryable(&err));
}
#[cfg(feature = "logical-retry")]
#[test]
fn http2_go_away_is_not_retryable() {
let err = Error::Http2GoAway {
last_stream_id: 0,
debug_data: " shutting down".into(),
};
assert!(!crate::retry::RetryPolicy::is_error_retryable(&err));
}
}