use std::fmt;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use super::error::{Error, Result};
#[derive(Clone)]
pub struct RandomSource(Arc<dyn Fn() -> f64 + Send + Sync>);
impl RandomSource {
pub fn new(f: impl Fn() -> f64 + Send + Sync + 'static) -> Self {
RandomSource(Arc::new(f))
}
pub fn fixed(value: f64) -> Self {
RandomSource::new(move || value)
}
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")
}
}
#[derive(Debug, Clone)]
pub struct RetryPolicy {
pub max_retries: u32,
pub initial_backoff: Duration,
pub max_backoff: Duration,
pub multiplier: f64,
pub max_retry_after: Duration,
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 {
pub fn none() -> Self {
RetryPolicy {
max_retries: 0,
..RetryPolicy::default()
}
}
pub fn with_max_retries(mut self, max_retries: u32) -> Self {
self.max_retries = max_retries;
self
}
pub fn with_random(mut self, random: RandomSource) -> Self {
self.random = random;
self
}
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)
}
}
pub fn backoff(&self, retry: u32) -> Duration {
self.backoff_cap(retry).mul_f64(self.random.next())
}
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(())
}
}
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))
}