tez 0.0.0

A lightweight, ergonomic, and fast high-level HTTP client for Rust
Documentation
use std::time::{Duration, SystemTime};

use http::{HeaderMap, StatusCode, header::RETRY_AFTER};

use crate::{Error, ErrorKind, Result};

/// Opt-in retry policy.
///
/// `max_attempts` includes the first attempt and is always finite.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Retry {
    max_attempts: u8,
}

impl Retry {
    /// Creates a retry policy with between one and five total attempts.
    ///
    /// A value of one disables retries while preserving the same execution
    /// path. Client defaults use one attempt.
    ///
    /// # Errors
    ///
    /// Returns an error when `max_attempts` is outside `1..=5`.
    pub fn new(max_attempts: u8) -> Result<Self> {
        if !(1..=5).contains(&max_attempts) {
            return Err(Error::invalid_request(
                "retry max_attempts must be between 1 and 5",
            ));
        }
        Ok(Self { max_attempts })
    }

    /// Returns the maximum number of attempts, including the first.
    #[must_use]
    pub fn max_attempts(self) -> u8 {
        self.max_attempts
    }

    pub(crate) fn full_jitter(self, retry_number: u8, sample: u64) -> Duration {
        let exponent = u32::from(retry_number.saturating_sub(1)).min(5);
        let ceiling_ms = 100u64.saturating_mul(1u64 << exponent);
        Duration::from_millis(sample % (ceiling_ms + 1))
    }
}

impl Default for Retry {
    fn default() -> Self {
        Self { max_attempts: 1 }
    }
}

pub(crate) fn is_transient_error(error: &Error) -> bool {
    matches!(
        error.kind(),
        ErrorKind::Dns | ErrorKind::Connect | ErrorKind::Timeout | ErrorKind::Transport
    )
}

pub(crate) fn is_retry_status(status: StatusCode) -> bool {
    matches!(
        status,
        StatusCode::REQUEST_TIMEOUT
            | StatusCode::TOO_EARLY
            | StatusCode::TOO_MANY_REQUESTS
            | StatusCode::INTERNAL_SERVER_ERROR
            | StatusCode::BAD_GATEWAY
            | StatusCode::SERVICE_UNAVAILABLE
            | StatusCode::GATEWAY_TIMEOUT
    )
}

pub(crate) fn retry_after(headers: &HeaderMap) -> Option<Duration> {
    retry_after_at(headers, SystemTime::now())
}

pub(crate) fn retry_after_at(headers: &HeaderMap, now: SystemTime) -> Option<Duration> {
    let value = headers.get(RETRY_AFTER)?.to_str().ok()?.trim();
    if let Ok(seconds) = value.parse::<u64>() {
        return Some(Duration::from_secs(seconds));
    }
    let date = httpdate::parse_http_date(value).ok()?;
    Some(date.duration_since(now).unwrap_or(Duration::ZERO))
}

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

    #[test]
    fn it_retry_attempts_are_finite_and_validated() {
        assert!(Retry::new(0).is_err());
        assert_eq!(Retry::new(1).unwrap().max_attempts(), 1);
        assert_eq!(Retry::new(5).unwrap().max_attempts(), 5);
        assert!(Retry::new(6).is_err());
    }

    #[test]
    fn it_full_jitter_is_deterministic_with_an_injected_sample() {
        let retry = Retry::new(3).unwrap();

        assert_eq!(retry.full_jitter(1, 0), Duration::ZERO);
        assert_eq!(retry.full_jitter(1, 100), Duration::from_millis(100));
        assert_eq!(retry.full_jitter(2, 201), Duration::ZERO);
    }
}