feedparser-rs 0.8.0

High-performance RSS/Atom/JSON Feed parser
Documentation
//! Typed failures of the HTTP fetch path.

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;

/// A failure status code: always in `400..=999`.
///
/// # Examples
///
/// ```
/// use feedparser_rs::http::HttpStatus;
///
/// assert_eq!(HttpStatus::new(404).map(HttpStatus::as_u16), Some(404));
/// assert!(HttpStatus::new(200).is_none());
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct HttpStatus(u16);

impl HttpStatus {
    /// Returns `Some` exactly when `code` is in `400..=999`.
    #[must_use]
    pub const fn new(code: u16) -> Option<Self> {
        match code {
            400..=999 => Some(Self(code)),
            _ => None,
        }
    }

    /// The numeric status code.
    #[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)
    }
}

/// Request header whose value was rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum HeaderField {
    /// `User-Agent`
    UserAgent,
    /// `If-None-Match`
    IfNoneMatch,
    /// `If-Modified-Since`
    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",
        })
    }
}

/// Formats `error` followed by every error in its `source()` chain, joined by `": "`.
///
/// A fetch error's own message can be generic ("HTTP request failed"); the detail sits
/// further down the chain. The bindings use this to build one complete message.
///
/// # Examples
///
/// ```
/// use feedparser_rs::http::{error_chain, validate_url};
///
/// let err = validate_url("not a url").unwrap_err();
/// assert!(error_chain(&err).starts_with("Invalid URL"));
/// ```
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
}

/// Whether `error` is a timeout, directly or through the error it wraps.
///
/// A body read through `reqwest` surfaces as an `io::Error` of kind `Other` wrapping the
/// `reqwest::Error`, and `io::Error::source` skips that wrapped error.
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)
}

/// Opaque transport-level failure (connect, TLS, timeout, I/O).
#[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),
        }
    }

    /// Whether the failure was a timeout: a `reqwest` timeout or an `io::ErrorKind::TimedOut`
    /// anywhere in the source chain, including one wrapped by a body read.
    ///
    /// # Examples
    ///
    /// ```
    /// use feedparser_rs::http::{FetchError, validate_url};
    ///
    /// // A rejected URL never reaches the network, so it is not a transport timeout.
    /// let err = validate_url("http://127.0.0.1/").unwrap_err();
    /// let timed_out = match err {
    ///     FetchError::Transport(transport) => transport.is_timeout(),
    ///     _ => false,
    /// };
    /// assert!(!timed_out);
    /// ```
    #[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)
    }
}

/// `Display` prints the wrapped error's own message, so `source` continues with that
/// error's source: a chain reporter then prints each message once.
impl Error for TransportError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.source.source()
    }
}

/// Failure while fetching a feed over HTTP.
///
/// Match on the variant to react to a specific failure; the enum is `#[non_exhaustive]`.
///
/// # Examples
///
/// ```
/// use feedparser_rs::http::{FetchError, validate_url};
///
/// let err = validate_url("http://127.0.0.1/feed.xml").unwrap_err();
/// assert!(matches!(err, FetchError::BlockedAddress { .. }));
/// ```
#[derive(Debug, Clone, Error)]
#[non_exhaustive]
pub enum FetchError {
    /// The server answered with a failure status.
    #[error("HTTP {status} for URL: {url}")]
    Status {
        /// The failure status.
        status: HttpStatus,
        /// Final URL after redirects.
        url: String,
    },
    /// The URL, a redirect hop or a resolved address was rejected by SSRF protection.
    #[error("{reason}")]
    BlockedAddress {
        /// Why the target was rejected.
        reason: SsrfRejection,
    },
    /// More redirects than allowed.
    #[error("Too many redirects")]
    TooManyRedirects,
    /// The body exceeded the configured size limit.
    #[error("Response body exceeds the limit of {limit} bytes")]
    BodyTooLarge {
        /// The configured limit in bytes.
        limit: usize,
    },
    /// A request header value was invalid.
    #[error("Invalid {name} header value")]
    InvalidHeader {
        /// The offending header.
        name: HeaderField,
    },
    /// The URL could not be parsed.
    #[error("Invalid URL: {0}")]
    InvalidUrl(UrlParseError),
    /// Any other transport failure.
    #[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 {
    /// Classifies a `reqwest` failure.
    ///
    /// The redirect policy and the DNS resolver attach a typed [`FetchError`] to the
    /// error chain; the first one found is returned. Anything else is a transport
    /// failure.
    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(_)
        ));
    }
}