tez 0.0.3

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
//! Resource and time bounds shared by Tez clients.

use std::time::Duration;

use crate::{Error, Result};

const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const DEFAULT_CONNECTIONS_PER_ORIGIN: usize = 16;
const DEFAULT_IDLE_CONNECTIONS_PER_ORIGIN: usize = 8;
const DEFAULT_IDLE_CONNECTION_TIMEOUT: Duration = Duration::from_secs(90);
const DEFAULT_RESPONSE_BODY_LIMIT: usize = 16 * 1024 * 1024;
const DEFAULT_STREAM_ITEM_LIMIT: usize = 32 * 1024 * 1024;
const DEFAULT_TOTAL_TIMEOUT: Duration = Duration::from_secs(30);

/// Resource bounds enforced by a client.
///
/// Limits are independent of transport implementation and apply equally to
/// asynchronous and blocking clients. Defaults favor bounded memory and
/// connection use without constraining streaming response bodies.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Limits {
    response_body: usize,
    stream_item: usize,
    connections_per_origin: usize,
    idle_connections_per_origin: usize,
}

impl Limits {
    /// Sets the largest body accepted by collecting response helpers.
    ///
    /// Streaming through [`crate::Response::body_mut`],
    /// [`crate::Response::into_body`], or [`crate::Response::stream`] is not
    /// constrained by this limit.
    #[must_use]
    pub const fn response_body(mut self, bytes: usize) -> Self {
        self.response_body = bytes;
        self
    }

    /// Sets the largest JSON value or server-sent event encoded or decoded in
    /// a structured stream.
    ///
    /// The raw response body remains unbounded and backpressured. This limit
    /// bounds only the memory retained while one logical stream item is being
    /// serialized or assembled.
    #[must_use]
    pub const fn stream_item(mut self, bytes: usize) -> Self {
        self.stream_item = bytes;
        self
    }

    /// Sets the maximum number of physical connections opened to one origin.
    #[must_use]
    pub const fn connections_per_origin(mut self, connections: usize) -> Self {
        self.connections_per_origin = connections;
        self
    }

    /// Sets the maximum number of idle HTTP/1 connections retained per origin.
    #[must_use]
    pub const fn idle_connections_per_origin(mut self, connections: usize) -> Self {
        self.idle_connections_per_origin = connections;
        self
    }

    pub(crate) const fn response_body_bytes(self) -> usize {
        self.response_body
    }

    pub(crate) const fn stream_item_bytes(self) -> usize {
        self.stream_item
    }

    pub(crate) const fn connections(self) -> usize {
        self.connections_per_origin
    }

    pub(crate) const fn idle_connections(self) -> usize {
        self.idle_connections_per_origin
    }

    pub(crate) fn validate(self) -> Result<()> {
        if self.response_body == 0 {
            return Err(Error::request(
                "client response body limit must be greater than zero",
            ));
        }
        if self.stream_item == 0 {
            return Err(Error::request(
                "client stream item limit must be greater than zero",
            ));
        }
        if self.connections_per_origin == 0 {
            return Err(Error::request(
                "client connection limit must be greater than zero",
            ));
        }
        if self.idle_connections_per_origin > self.connections_per_origin {
            return Err(Error::request(
                "client idle connection limit exceeds its connection limit",
            ));
        }
        Ok(())
    }
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            response_body: DEFAULT_RESPONSE_BODY_LIMIT,
            stream_item: DEFAULT_STREAM_ITEM_LIMIT,
            connections_per_origin: DEFAULT_CONNECTIONS_PER_ORIGIN,
            idle_connections_per_origin: DEFAULT_IDLE_CONNECTIONS_PER_ORIGIN,
        }
    }
}

/// Time bounds applied to one logical request and its connections.
///
/// `total` is an absolute deadline for the entire logical request, including
/// retries, redirects, and body consumption. `connect` bounds each DNS, TCP,
/// proxy, TLS, and HTTP handshake attempt. `read` bounds each pending response
/// body read without counting time spent by the caller between reads. `idle_connection`
/// controls how long an unused HTTP/1 connection remains pooled.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Timeouts {
    total: Option<Duration>,
    connect: Option<Duration>,
    read: Option<Duration>,
    idle_connection: Option<Duration>,
}

impl Timeouts {
    /// Sets the total logical-request deadline.
    #[must_use]
    pub fn total(mut self, timeout: impl Into<Option<Duration>>) -> Self {
        self.total = timeout.into();
        self
    }

    /// Sets the deadline for each connection attempt.
    #[must_use]
    pub fn connect(mut self, timeout: impl Into<Option<Duration>>) -> Self {
        self.connect = timeout.into();
        self
    }

    /// Sets the maximum duration of one pending response body read.
    #[must_use]
    pub fn read(mut self, timeout: impl Into<Option<Duration>>) -> Self {
        self.read = timeout.into();
        self
    }

    /// Sets how long an unused HTTP/1 connection remains in the pool.
    #[must_use]
    pub fn idle_connection(mut self, timeout: impl Into<Option<Duration>>) -> Self {
        self.idle_connection = timeout.into();
        self
    }

    pub(crate) const fn total_timeout(self) -> Option<Duration> {
        self.total
    }

    pub(crate) const fn connect_timeout(self) -> Option<Duration> {
        self.connect
    }

    pub(crate) const fn read_timeout(self) -> Option<Duration> {
        self.read
    }

    pub(crate) const fn idle_connection_timeout(self) -> Option<Duration> {
        self.idle_connection
    }

    pub(crate) fn validate(self) -> Result<()> {
        for (value, message) in [
            (self.total, "client total timeout must be greater than zero"),
            (
                self.connect,
                "client connect timeout must be greater than zero",
            ),
            (self.read, "client read timeout must be greater than zero"),
            (
                self.idle_connection,
                "client idle connection timeout must be greater than zero",
            ),
        ] {
            if value.is_some_and(|duration| duration.is_zero()) {
                return Err(Error::request(message));
            }
        }
        Ok(())
    }
}

impl Default for Timeouts {
    fn default() -> Self {
        Self {
            total: Some(DEFAULT_TOTAL_TIMEOUT),
            connect: Some(DEFAULT_CONNECT_TIMEOUT),
            read: None,
            idle_connection: Some(DEFAULT_IDLE_CONNECTION_TIMEOUT),
        }
    }
}

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

    #[test]
    fn defaults_bound_collection_connections_and_connection_setup() {
        let limits = Limits::default();
        assert_eq!(limits.response_body_bytes(), 16 * 1024 * 1024);
        assert_eq!(limits.stream_item_bytes(), 32 * 1024 * 1024);
        assert_eq!(limits.connections(), 16);
        assert_eq!(limits.idle_connections(), 8);

        let timeouts = Timeouts::default();
        assert_eq!(timeouts.total_timeout(), Some(Duration::from_secs(30)));
        assert_eq!(timeouts.connect_timeout(), Some(Duration::from_secs(10)));
        assert_eq!(
            timeouts.idle_connection_timeout(),
            Some(Duration::from_secs(90))
        );
        assert_eq!(timeouts.read_timeout(), None);
    }

    #[test]
    fn invalid_limits_and_zero_timeouts_are_rejected() {
        assert!(
            Limits::default()
                .response_body(0)
                .validate()
                .unwrap_err()
                .is_request()
        );
        assert!(
            Limits::default()
                .stream_item(0)
                .validate()
                .unwrap_err()
                .is_request()
        );
        assert!(
            Limits::default()
                .connections_per_origin(1)
                .idle_connections_per_origin(2)
                .validate()
                .unwrap_err()
                .is_request()
        );
        assert!(
            Timeouts::default()
                .read(Duration::ZERO)
                .validate()
                .unwrap_err()
                .is_request()
        );
    }
}