use std::fmt;
use rama_core::error::BoxError;
use rama_http_types::{StatusCode, Version};
use rama_net::client::{ConnectionError, ConnectionErrorDomain, ConnectionErrorKind};
#[derive(Debug)]
pub enum HttpProxyError {
AuthRequired,
Unavailable,
Transport(BoxError),
InvalidVersion(Version),
Rejected(StatusCode),
}
impl fmt::Display for HttpProxyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::AuthRequired => {
write!(f, "http proxy error: proxy auth required (http 407)")
}
Self::Unavailable => {
write!(f, "http proxy error: proxy unavailable (http 503)")
}
Self::Transport(error) => {
write!(f, "http proxy error: transport error: I/O [{error}]")
}
Self::InvalidVersion(version) => {
write!(f, "http proxy error: invalid CONNECT version: {version:?}")
}
Self::Rejected(status) => {
write!(f, "http proxy error: CONNECT rejected with status {status}")
}
}
}
}
impl From<HttpProxyError> for ConnectionError {
fn from(error: HttpProxyError) -> Self {
let (domain, kind) = match &error {
HttpProxyError::AuthRequired => (
ConnectionErrorDomain::Transport,
ConnectionErrorKind::Authentication,
),
HttpProxyError::Unavailable | HttpProxyError::Transport(_) => (
ConnectionErrorDomain::Transport,
ConnectionErrorKind::Unavailable,
),
HttpProxyError::Rejected(_) => (
ConnectionErrorDomain::Transport,
ConnectionErrorKind::Rejected,
),
HttpProxyError::InvalidVersion(_) => (
ConnectionErrorDomain::Local,
ConnectionErrorKind::InvalidInput,
),
};
Self::new(error, domain, kind)
}
}
impl From<std::io::Error> for HttpProxyError {
fn from(value: std::io::Error) -> Self {
Self::Transport(value.into())
}
}
impl std::error::Error for HttpProxyError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
let Self::Transport(err) = self else {
return None;
};
let err_ref = err.source().unwrap_or_else(|| err.as_ref());
if err_ref.is::<std::io::Error>() {
Some(self)
} else {
Some(err_ref)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classifies_proxy_responses() {
let error = ConnectionError::from(HttpProxyError::AuthRequired);
assert_eq!(error.domain(), ConnectionErrorDomain::Transport);
assert_eq!(error.kind(), ConnectionErrorKind::Authentication);
let error = ConnectionError::from(HttpProxyError::Unavailable);
assert_eq!(error.domain(), ConnectionErrorDomain::Transport);
assert_eq!(error.kind(), ConnectionErrorKind::Unavailable);
let error = ConnectionError::from(HttpProxyError::Rejected(StatusCode::BAD_GATEWAY));
assert_eq!(error.domain(), ConnectionErrorDomain::Transport);
assert_eq!(error.kind(), ConnectionErrorKind::Rejected);
let error = ConnectionError::from(HttpProxyError::InvalidVersion(Version::HTTP_3));
assert_eq!(error.domain(), ConnectionErrorDomain::Local);
assert_eq!(error.kind(), ConnectionErrorKind::InvalidInput);
}
}