use crate::error::UrlParseError;
use crate::util::ssrf::{SsrfRejection, UrlRejection};
use std::error::Error;
use std::fmt;
use std::io;
use std::sync::Arc;
use thiserror::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HttpStatus(u16);
impl HttpStatus {
#[must_use]
pub const fn new(code: u16) -> Option<Self> {
match code {
400..=999 => Some(Self(code)),
_ => None,
}
}
#[must_use]
pub const fn as_u16(self) -> u16 {
self.0
}
}
impl fmt::Display for HttpStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum HeaderField {
UserAgent,
IfNoneMatch,
IfModifiedSince,
}
impl fmt::Display for HeaderField {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::UserAgent => "User-Agent",
Self::IfNoneMatch => "If-None-Match",
Self::IfModifiedSince => "If-Modified-Since",
})
}
}
pub fn error_chain(error: &(dyn Error + 'static)) -> String {
use std::fmt::Write as _;
let mut message = error.to_string();
let mut source = error.source();
while let Some(err) = source {
let _ = write!(message, ": {err}");
source = err.source();
}
message
}
fn io_error_is_timeout(error: &io::Error) -> bool {
error.kind() == io::ErrorKind::TimedOut
|| error
.get_ref()
.and_then(|inner| inner.downcast_ref::<reqwest::Error>())
.is_some_and(reqwest::Error::is_timeout)
}
#[derive(Debug, Clone)]
pub struct TransportError {
source: Arc<dyn Error + Send + Sync>,
}
impl TransportError {
pub(crate) fn new(source: impl Error + Send + Sync + 'static) -> Self {
Self {
source: Arc::new(source),
}
}
#[must_use]
pub fn is_timeout(&self) -> bool {
let root: &(dyn Error + 'static) = &*self.source;
std::iter::successors(Some(root), |err| (*err).source()).any(|err| {
err.downcast_ref::<reqwest::Error>()
.is_some_and(reqwest::Error::is_timeout)
|| err
.downcast_ref::<io::Error>()
.is_some_and(io_error_is_timeout)
})
}
}
impl fmt::Display for TransportError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.source.fmt(f)
}
}
impl Error for TransportError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
self.source.source()
}
}
#[derive(Debug, Clone, Error)]
#[non_exhaustive]
pub enum FetchError {
#[error("HTTP {status} for URL: {url}")]
Status {
status: HttpStatus,
url: String,
},
#[error("{reason}")]
BlockedAddress {
reason: SsrfRejection,
},
#[error("Too many redirects")]
TooManyRedirects,
#[error("Response body exceeds the limit of {limit} bytes")]
BodyTooLarge {
limit: usize,
},
#[error("Invalid {name} header value")]
InvalidHeader {
name: HeaderField,
},
#[error("Invalid URL: {0}")]
InvalidUrl(UrlParseError),
#[error("HTTP request failed")]
Transport(#[source] TransportError),
}
impl From<UrlRejection> for FetchError {
fn from(rejection: UrlRejection) -> Self {
match rejection {
UrlRejection::Invalid(e) => Self::InvalidUrl(UrlParseError::new(e)),
UrlRejection::Blocked(reason) => Self::BlockedAddress { reason },
}
}
}
impl FetchError {
pub(crate) fn from_request_error(error: reqwest::Error) -> Self {
let root: &(dyn Error + 'static) = &error;
let typed = std::iter::successors(Some(root), |err| (*err).source())
.find_map(|err| err.downcast_ref::<Self>().cloned());
typed.unwrap_or_else(|| Self::Transport(TransportError::new(error)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn http_status_accepts_only_400_to_999() {
assert!(HttpStatus::new(399).is_none());
assert_eq!(HttpStatus::new(400).map(HttpStatus::as_u16), Some(400));
assert_eq!(HttpStatus::new(999).map(HttpStatus::as_u16), Some(999));
assert!(HttpStatus::new(1000).is_none());
}
#[test]
fn transport_timeout_is_detected_through_the_source_chain() {
let timed_out = TransportError::new(io::Error::new(io::ErrorKind::TimedOut, "slow"));
assert!(timed_out.is_timeout());
let refused = TransportError::new(io::Error::new(io::ErrorKind::ConnectionRefused, "no"));
assert!(!refused.is_timeout());
}
#[expect(
clippy::significant_drop_tightening,
reason = "the mockito server must outlive the request under test"
)]
#[test]
fn typed_error_in_the_chain_is_recovered_without_wrapping() {
let client = reqwest::blocking::Client::builder()
.redirect(reqwest::redirect::Policy::custom(|attempt| {
attempt.error(FetchError::TooManyRedirects)
}))
.build()
.expect("client");
let mut server = mockito::Server::new();
let _mock = server
.mock("GET", "/r")
.with_status(302)
.with_header("location", "/r2")
.create();
let err = client
.get(format!("{}/r", server.url()))
.send()
.expect_err("redirect is rejected");
assert!(matches!(
FetchError::from_request_error(err),
FetchError::TooManyRedirects
));
}
#[expect(
clippy::significant_drop_tightening,
reason = "the mockito server must outlive the request under test"
)]
#[test]
fn body_read_timeout_is_detected() {
use std::io::Read as _;
use std::time::Duration;
let mut server = mockito::Server::new();
let _mock = server
.mock("GET", "/slow-body")
.with_chunked_body(|w| {
w.write_all(b"<rss>")?;
w.flush()?;
std::thread::sleep(Duration::from_millis(600));
w.write_all(b"</rss>")
})
.create();
let client = reqwest::blocking::Client::builder()
.timeout(Duration::from_millis(200))
.build()
.expect("client");
let response = client
.get(format!("{}/slow-body", server.url()))
.send()
.expect("headers arrive before the timeout");
let mut bytes = Vec::new();
let err = response
.take(1 << 20)
.read_to_end(&mut bytes)
.expect_err("the body read times out");
assert!(TransportError::new(err).is_timeout());
}
#[test]
fn untyped_request_error_is_a_transport_failure() {
let client = reqwest::blocking::Client::new();
let err = client
.get("http://127.0.0.1:1/")
.send()
.expect_err("nothing listens on port 1");
assert!(matches!(
FetchError::from_request_error(err),
FetchError::Transport(_)
));
}
}