tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
use std::{error::Error as StdError, fmt};

use http::StatusCode;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Class {
    Request,
    Authentication,
    Connect,
    Timeout,
    Redirect,
    Body,
    BodyTooLarge,
    Decode,
    Upgrade,
    Status(StatusCode),
}

/// An error from building, sending, or consuming an HTTP message.
///
/// The type hides transport implementation errors. Use its stable predicates
/// for application decisions. Its display and debug forms do not echo
/// caller-provided request data.
#[derive(Clone)]
pub struct Error {
    class: Class,
    message: &'static str,
}

/// A specialized [`std::result::Result`] for Tez operations.
pub type Result<T> = std::result::Result<T, Error>;

impl Error {
    /// Creates an error for invalid client or request configuration.
    ///
    /// Provider clients may use this when validating configuration before
    /// constructing a Tez client or request.
    #[must_use]
    pub const fn request(message: &'static str) -> Self {
        Self {
            class: Class::Request,
            message,
        }
    }

    pub(crate) const fn connect() -> Self {
        Self {
            class: Class::Connect,
            message: "could not establish an HTTP connection",
        }
    }

    /// Creates a redacted error for an authentication failure.
    ///
    /// Authentication implementations should use this instead of exposing
    /// credential-provider error details.
    #[must_use]
    pub const fn authentication() -> Self {
        Self {
            class: Class::Authentication,
            message: "request authentication could not be obtained",
        }
    }

    pub(crate) const fn timeout() -> Self {
        Self {
            class: Class::Timeout,
            message: "HTTP request deadline exceeded",
        }
    }

    pub(crate) const fn redirect() -> Self {
        Self {
            class: Class::Redirect,
            message: "HTTP redirect could not be completed",
        }
    }

    pub(crate) const fn body() -> Self {
        Self {
            class: Class::Body,
            message: "HTTP body could not be read or written",
        }
    }

    pub(crate) const fn body_too_large() -> Self {
        Self {
            class: Class::BodyTooLarge,
            message: "HTTP body exceeds its collection limit",
        }
    }

    pub(crate) const fn decode(message: &'static str) -> Self {
        Self {
            class: Class::Decode,
            message,
        }
    }

    pub(crate) const fn upgrade() -> Self {
        Self {
            class: Class::Upgrade,
            message: "HTTP protocol upgrade could not be completed",
        }
    }

    pub(crate) const fn status_error(status: StatusCode) -> Self {
        Self {
            class: Class::Status(status),
            message: "HTTP response status indicates an error",
        }
    }

    /// Returns true when request construction or request preparation failed.
    #[must_use]
    pub fn is_request(&self) -> bool {
        self.class == Class::Request
    }

    /// Returns true when request authentication could not be obtained.
    #[must_use]
    pub fn is_authentication(&self) -> bool {
        self.class == Class::Authentication
    }

    /// Returns true when DNS, TCP, or TLS connection setup failed.
    #[must_use]
    pub fn is_connect(&self) -> bool {
        self.class == Class::Connect
    }

    /// Returns true when the configured request deadline expired.
    #[must_use]
    pub fn is_timeout(&self) -> bool {
        self.class == Class::Timeout
    }

    /// Returns true when redirect processing failed.
    #[must_use]
    pub fn is_redirect(&self) -> bool {
        self.class == Class::Redirect
    }

    /// Returns true when a request or response body failed.
    ///
    /// This is also true when [`Error::is_body_too_large`] is true.
    #[must_use]
    pub fn is_body(&self) -> bool {
        matches!(self.class, Class::Body | Class::BodyTooLarge)
    }

    /// Returns true when a collecting response helper exceeded its configured limit.
    #[must_use]
    pub fn is_body_too_large(&self) -> bool {
        self.class == Class::BodyTooLarge
    }

    /// Returns true when text, JSON, or content decoding failed.
    #[must_use]
    pub fn is_decode(&self) -> bool {
        self.class == Class::Decode
    }

    /// Returns true when an HTTP Upgrade or `CONNECT` transition failed.
    #[must_use]
    pub fn is_upgrade(&self) -> bool {
        self.class == Class::Upgrade
    }

    /// Returns true when a response status was converted into an error.
    #[must_use]
    pub fn is_status(&self) -> bool {
        matches!(self.class, Class::Status(_))
    }

    /// Returns the response status associated with this error.
    #[must_use]
    pub const fn status(&self) -> Option<StatusCode> {
        match self.class {
            Class::Status(status) => Some(status),
            _ => None,
        }
    }
}

impl From<http::Error> for Error {
    fn from(_: http::Error) -> Self {
        Self::request("HTTP request could not be constructed")
    }
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.message)
    }
}

impl fmt::Debug for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Error")
            .field("class", &self.class)
            .field("message", &self.message)
            .finish()
    }
}

impl StdError for Error {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn predicates_expose_only_the_stable_error_categories() {
        assert!(Error::request("invalid").is_request());
        assert!(Error::authentication().is_authentication());
        assert!(Error::connect().is_connect());
        assert!(Error::timeout().is_timeout());
        assert!(Error::redirect().is_redirect());
        assert!(Error::body().is_body());
        assert!(Error::decode("invalid").is_decode());
        assert!(Error::upgrade().is_upgrade());
        let status = Error::status_error(StatusCode::BAD_REQUEST);
        assert!(status.is_status());
        assert_eq!(status.status(), Some(StatusCode::BAD_REQUEST));

        let too_large = Error::body_too_large();
        assert!(too_large.is_body());
        assert!(too_large.is_body_too_large());
    }

    #[test]
    fn formatting_does_not_expose_callers_input() {
        let error = Error::request("request URL is invalid");

        assert!(!error.to_string().contains("secret"));
        assert!(!format!("{error:?}").contains("secret"));
    }
}