grow-graylog 0.2.0

Rust SDK for Graylog Open by Grow Codes
Documentation
// Generated by sdk-kit 0.3.0 — do not edit; change sdk-kit and run "sdk-kit sync"
//! Retry policy with full-jitter exponential backoff and `Retry-After` parsing (SPEC §2.3).

use std::fmt;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use super::error::{Error, Result};

/// Source of uniformly distributed numbers in `[0, 1)`; injectable for tests.
#[derive(Clone)]
pub struct RandomSource(Arc<dyn Fn() -> f64 + Send + Sync>);

impl RandomSource {
    /// Wraps a function returning values in `[0, 1)` (values outside are clamped).
    pub fn new(f: impl Fn() -> f64 + Send + Sync + 'static) -> Self {
        RandomSource(Arc::new(f))
    }

    /// A source that always returns `value`.
    pub fn fixed(value: f64) -> Self {
        RandomSource::new(move || value)
    }

    /// Next value, clamped to `[0, 1]`.
    pub fn next(&self) -> f64 {
        let v = (self.0)();
        if v.is_nan() {
            0.0
        } else {
            v.clamp(0.0, 1.0)
        }
    }
}

impl Default for RandomSource {
    fn default() -> Self {
        RandomSource::new(rand::random::<f64>)
    }
}

impl fmt::Debug for RandomSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("RandomSource")
    }
}

/// Retry settings. Defaults: 3 retries (4 attempts), 100 ms initial backoff, 10 s maximum
/// backoff, multiplier 2, at most 60 s honoured from `Retry-After`.
#[derive(Debug, Clone)]
pub struct RetryPolicy {
    /// Retries after the first attempt (`0` disables retries).
    pub max_retries: u32,
    /// Backoff cap for the first retry.
    pub initial_backoff: Duration,
    /// Upper bound of every backoff.
    pub max_backoff: Duration,
    /// Growth factor per retry.
    pub multiplier: f64,
    /// Longest `Retry-After` the client waits for; longer waits fail immediately.
    pub max_retry_after: Duration,
    /// Jitter source.
    pub random: RandomSource,
}

impl Default for RetryPolicy {
    fn default() -> Self {
        RetryPolicy {
            max_retries: 3,
            initial_backoff: Duration::from_millis(100),
            max_backoff: Duration::from_secs(10),
            multiplier: 2.0,
            max_retry_after: Duration::from_secs(60),
            random: RandomSource::default(),
        }
    }
}

impl RetryPolicy {
    /// A policy that never retries.
    pub fn none() -> Self {
        RetryPolicy {
            max_retries: 0,
            ..RetryPolicy::default()
        }
    }

    /// Sets `max_retries`.
    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = max_retries;
        self
    }

    /// Sets the jitter source.
    pub fn with_random(mut self, random: RandomSource) -> Self {
        self.random = random;
        self
    }

    /// Upper bound of the backoff for retry `n` (0-based): `min(max, initial * multiplier^n)`.
    pub fn backoff_cap(&self, retry: u32) -> Duration {
        let exp = self.multiplier.powi(retry.min(1024) as i32);
        let cap = self.initial_backoff.as_secs_f64() * exp;
        let max = self.max_backoff.as_secs_f64();
        if !cap.is_finite() || cap >= max {
            self.max_backoff
        } else {
            Duration::from_secs_f64(cap)
        }
    }

    /// Full-jitter backoff for retry `n` (0-based): `random(0, backoff_cap(n))`.
    pub fn backoff(&self, retry: u32) -> Duration {
        self.backoff_cap(retry).mul_f64(self.random.next())
    }

    /// Checks the policy values.
    pub fn validate(&self) -> Result<()> {
        if !(self.multiplier.is_finite() && self.multiplier >= 1.0) {
            return Err(Error::config("retry multiplier must be >= 1"));
        }
        if self.max_backoff < self.initial_backoff {
            return Err(Error::config(
                "retry max_backoff must be >= initial_backoff",
            ));
        }
        Ok(())
    }
}

/// Parses a `Retry-After` value: delay seconds (`"120"`) or an HTTP date relative to `now`.
/// Dates in the past yield zero; unparseable values yield `None`.
pub fn parse_retry_after(value: &str, now: SystemTime) -> Option<Duration> {
    let v = value.trim();
    if v.is_empty() {
        return None;
    }
    if let Ok(secs) = v.parse::<u64>() {
        return Some(Duration::from_secs(secs));
    }
    if let Ok(secs) = v.parse::<f64>() {
        return (secs.is_finite() && secs >= 0.0).then(|| Duration::from_secs_f64(secs));
    }
    let date = httpdate::parse_http_date(v).ok()?;
    Some(date.duration_since(now).unwrap_or(Duration::ZERO))
}