jitter-backoff 11.2.0

Zero-dependency exponential backoff, full/equal/decorrelated jitter, deadline retry budgets, Retry-After header parsing, and synchronous retry execution.
Documentation
use super::*;

/// Default construction for [`RetryPolicy`].
impl Default for RetryPolicy {
    /// Creates a standard retry policy (`3` retries, `100 ms` base, `30 s` max, `2.0x`, full jitter).
    ///
    /// # Returns
    ///
    /// - `Self` - Default retry policy.
    fn default() -> Self {
        Self {
            max_retries: DEFAULT_MAX_RETRIES,
            initial_delay_ms: DEFAULT_INITIAL_DELAY_MS,
            max_delay_ms: DEFAULT_MAX_DELAY_MS,
            multiplier_tenths: 20,
            jitter: JitterMode::Full,
            total_timeout_ms: 0,
        }
    }
}

/// Builder and delay calculation methods for [`RetryPolicy`].
impl RetryPolicy {
    /// Creates a policy with explicit `max_retries`, `initial_delay_ms`, and `max_delay_ms`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Maximum number of retries after the initial attempt.
    /// - `u64` - Initial base delay in milliseconds.
    /// - `u64` - Maximum delay cap in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured retry policy.
    pub const fn new(max_retries: u32, initial_delay_ms: u64, max_delay_ms: u64) -> Self {
        Self {
            max_retries,
            initial_delay_ms,
            max_delay_ms,
            multiplier_tenths: 20,
            jitter: JitterMode::Full,
            total_timeout_ms: 0,
        }
    }

    /// Sets the jitter mode for this policy.
    ///
    /// # Arguments
    ///
    /// - `JitterMode` - Desired jitter strategy.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated policy.
    pub const fn with_jitter(self, jitter: JitterMode) -> Self {
        Self { jitter, ..self }
    }

    /// Sets the exponential backoff factor in tenths (e.g. `15` = `1.5x`, `20` = `2.0x`, clamped `>= 10`).
    ///
    /// # Arguments
    ///
    /// - `u32` - Backoff factor multiplied by 10.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated policy.
    pub const fn with_multiplier_tenths(self, tenths: u32) -> Self {
        let multiplier_tenths: u32 = if tenths < 10 { 10 } else { tenths };
        Self {
            multiplier_tenths,
            ..self
        }
    }

    /// Sets an overall deadline budget across all attempts and sleeps (`0` = no total deadline).
    ///
    /// # Arguments
    ///
    /// - `u64` - Total deadline budget in milliseconds.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated policy.
    pub const fn with_total_timeout_ms(self, total_timeout_ms: u64) -> Self {
        Self {
            total_timeout_ms,
            ..self
        }
    }

    /// Returns the configured maximum retries.
    ///
    /// # Returns
    ///
    /// - `u32` - Maximum retry count.
    #[inline(always)]
    pub const fn get_max_retries(&self) -> u32 {
        let Self { max_retries, .. } = self;
        *max_retries
    }

    /// Returns the initial delay in milliseconds.
    ///
    /// # Returns
    ///
    /// - `u64` - Base delay in milliseconds.
    #[inline(always)]
    pub const fn get_initial_delay_ms(&self) -> u64 {
        let Self {
            initial_delay_ms, ..
        } = self;
        *initial_delay_ms
    }

    /// Returns the maximum delay cap in milliseconds.
    ///
    /// # Returns
    ///
    /// - `u64` - Delay cap in milliseconds.
    #[inline(always)]
    pub const fn get_max_delay_ms(&self) -> u64 {
        let Self { max_delay_ms, .. } = self;
        *max_delay_ms
    }

    /// Returns the deterministic uncapped-jitter exponential delay in milliseconds for `attempt`.
    ///
    /// # Arguments
    ///
    /// - `u32` - Zero-based retry index (`0` = first retry).
    ///
    /// # Returns
    ///
    /// - `u64` - Delay in milliseconds clamped to `max_delay_ms`.
    #[inline]
    pub fn raw_delay_ms(&self, attempt: u32) -> u64 {
        let Self {
            initial_delay_ms,
            max_delay_ms,
            multiplier_tenths,
            ..
        } = self;
        let cap: u64 = (*max_delay_ms).max(*initial_delay_ms);
        let shift: u32 = attempt.min(31);
        if *multiplier_tenths == 20 {
            let shifted: u128 = u128::from(*initial_delay_ms) << shift;
            return shifted.min(u128::from(cap)) as u64;
        }
        if *multiplier_tenths == 10 {
            return *initial_delay_ms;
        }
        let mut delay: u128 = u128::from(*initial_delay_ms);
        let mult: u128 = u128::from(*multiplier_tenths);
        let capped: u128 = u128::from(cap);
        for _ in 0..shift {
            delay = delay.saturating_mul(mult) / 10;
            if delay >= capped {
                return cap;
            }
        }
        (delay as u64).min(cap)
    }

    /// Starts a stateful [`RetrySchedule`] seeded from system time.
    ///
    /// # Returns
    ///
    /// - `RetrySchedule` - Active retry schedule.
    #[inline]
    pub fn start(&self) -> RetrySchedule {
        let seed: u64 = match SystemTime::now().duration_since(UNIX_EPOCH) {
            Ok(d) => d.as_nanos() as u64,
            Err(_) => JITTER_MIX_INC,
        };
        self.start_with_seed(seed)
    }

    /// Starts a deterministic [`RetrySchedule`] with an explicit PRNG `seed`.
    ///
    /// # Arguments
    ///
    /// - `u64` - Explicit PRNG seed for reproducible jitter.
    ///
    /// # Returns
    ///
    /// - `RetrySchedule` - Active retry schedule.
    #[inline]
    pub fn start_with_seed(&self, seed: u64) -> RetrySchedule {
        let Self {
            initial_delay_ms,
            total_timeout_ms,
            ..
        } = self;
        let started_at: Option<Instant> = if *total_timeout_ms > 0 {
            Some(Instant::now())
        } else {
            None
        };
        RetrySchedule {
            policy: *self,
            attempts_used: 0,
            prev_delay_ms: *initial_delay_ms,
            rng_state: splitmix_rand(seed),
            started_at,
        }
    }

    /// Executes a synchronous fallible operation with backoff sleeps until success or retry exhaustion.
    ///
    /// # Arguments
    ///
    /// - `F` - Fallible operation invoked for each attempt.
    /// - `P` - Predicate returning `true` when an error is retryable.
    ///
    /// # Returns
    ///
    /// - `Result<T, E>` - First `Ok(value)` or the final error when exhausted or non-retryable.
    pub fn execute_sync<T, E, F, P>(&self, mut operation: F, mut is_retryable: P) -> Result<T, E>
    where
        F: FnMut() -> Result<T, E>,
        P: FnMut(&E) -> bool,
    {
        let mut schedule: RetrySchedule = self.start();
        loop {
            match operation() {
                Ok(value) => return Ok(value),
                Err(error) => {
                    if !is_retryable(&error) {
                        return Err(error);
                    }
                    let Some(delay) = schedule.next_delay() else {
                        return Err(error);
                    };
                    if !delay.is_zero() {
                        thread::sleep(delay);
                    }
                }
            }
        }
    }
}

/// Step-by-step delay computation for [`RetrySchedule`].
impl RetrySchedule {
    /// Returns the delay before the next retry, or `None` if retries or total timeout are exhausted.
    ///
    /// # Returns
    ///
    /// - `Option<Duration>` - Backoff duration to sleep before retrying, or `None` to stop.
    #[inline(always)]
    pub fn next_delay(&mut self) -> Option<Duration> {
        self.next_delay_with_hint(None)
    }

    /// Returns the delay before the next retry, honoring an optional server `Retry-After` hint.
    ///
    /// # Arguments
    ///
    /// - `Option<Duration>` - Optional minimum delay requested by the remote server.
    ///
    /// # Returns
    ///
    /// - `Option<Duration>` - Effective delay within budget, or `None` if exhausted or past deadline.
    #[inline]
    pub fn next_delay_with_hint(&mut self, retry_after: Option<Duration>) -> Option<Duration> {
        let Self {
            policy,
            attempts_used,
            prev_delay_ms,
            rng_state,
            started_at,
        } = self;
        if *attempts_used >= policy.max_retries {
            return None;
        }
        let attempt: u32 = *attempts_used;
        *attempts_used += 1;
        let jittered_ms: u64 = match policy.jitter {
            JitterMode::None => policy.raw_delay_ms(attempt),
            JitterMode::Full => {
                let base_ms: u64 = policy.raw_delay_ms(attempt);
                let entropy: u64 = splitmix_rand(*rng_state);
                *rng_state = entropy;
                rand_inclusive(entropy, base_ms)
            }
            JitterMode::Equal => {
                let base_ms: u64 = policy.raw_delay_ms(attempt);
                let entropy: u64 = splitmix_rand(*rng_state);
                *rng_state = entropy;
                let half: u64 = base_ms >> 1;
                half + rand_inclusive(entropy, base_ms - half)
            }
            JitterMode::Decorrelated => {
                let entropy: u64 = splitmix_rand(*rng_state);
                *rng_state = entropy;
                let lo: u64 = policy.initial_delay_ms;
                let hi: u64 = (*prev_delay_ms).saturating_mul(3).max(lo);
                let span: u64 = hi.saturating_sub(lo);
                let sampled: u64 = lo.saturating_add(rand_inclusive(entropy, span));
                let cap: u64 = policy.max_delay_ms.max(lo);
                let val: u64 = sampled.min(cap);
                *prev_delay_ms = val.max(lo);
                val
            }
        };
        let chosen_ms: u64 = match retry_after {
            Some(dur) => {
                let hint_ms: u64 = u64::try_from(dur.as_millis())
                    .unwrap_or(policy.max_delay_ms)
                    .min(policy.max_delay_ms.max(policy.initial_delay_ms));
                jittered_ms.max(hint_ms)
            }
            None => jittered_ms,
        };
        if policy.total_timeout_ms > 0
            && let Some(start) = started_at
        {
            let elapsed_ms: u64 = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
            if elapsed_ms.saturating_add(chosen_ms) >= policy.total_timeout_ms {
                return None;
            }
        }
        Some(Duration::from_millis(chosen_ms))
    }

    /// Returns the number of retries consumed so far.
    ///
    /// # Returns
    ///
    /// - `u32` - Consumed retry count.
    #[inline(always)]
    pub fn attempts_used(&self) -> u32 {
        let Self { attempts_used, .. } = self;
        *attempts_used
    }
}