use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct RetryPolicy {
pub max_attempts: u32,
pub base_delay: Duration,
pub max_delay: Duration,
pub max_server_delay: Duration,
}
impl RetryPolicy {
pub fn new(max_attempts: u32) -> Self {
Self {
max_attempts: max_attempts.max(1),
base_delay: Duration::from_millis(500),
max_delay: Duration::from_secs(8),
max_server_delay: Duration::from_secs(60),
}
}
pub fn with_base_delay(mut self, delay: Duration) -> Self {
self.base_delay = delay;
self
}
pub fn with_max_delay(mut self, delay: Duration) -> Self {
self.max_delay = delay;
self
}
pub fn with_max_server_delay(mut self, delay: Duration) -> Self {
self.max_server_delay = delay;
self
}
pub(super) fn backoff(&self, attempt: u32) -> Duration {
let doubling = 1u32 << attempt.saturating_sub(1).min(31);
let capped = self.base_delay.saturating_mul(doubling).min(self.max_delay);
jittered(capped, 0.75 + 0.25 * fastrand::f64())
}
}
fn jittered(delay: Duration, factor: f64) -> Duration {
Duration::from_nanos(((delay.as_nanos() as f64) * factor) as u64)
}