tez 0.0.2

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

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

/// An error from building, sending, or consuming an HTTP message.
///
/// The type hides backend error values. Use its stable predicate methods to
/// handle the cases relevant to an application. 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.
    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.
    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 runtime() -> Self {
        Self {
            class: Class::Runtime,
            message: "an asynchronous I/O and time runtime is required to send HTTP requests",
        }
    }

    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 the 16 MiB collection limit",
        }
    }

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

    /// 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 the required native async runtime was unavailable.
    #[must_use]
    pub fn is_runtime(&self) -> bool {
        self.class == Class::Runtime
    }

    /// 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 16 MiB 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
    }
}

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::runtime().is_runtime());
        assert!(Error::body().is_body());
        assert!(Error::decode("invalid").is_decode());

        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"));
    }

    #[test]
    fn runtime_error_does_not_name_the_private_runtime() {
        assert!(!Error::runtime().to_string().contains("Tokio"));
    }
}