use std::hash::{BuildHasher, RandomState};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::client::Reply;
use crate::Error;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RetryPolicy {
max_attempts: u32,
base_delay: Duration,
max_delay: Duration,
}
impl Default for RetryPolicy {
fn default() -> Self {
RetryPolicy {
max_attempts: Self::DEFAULT_MAX_ATTEMPTS,
base_delay: Self::DEFAULT_BASE_DELAY,
max_delay: Self::DEFAULT_MAX_DELAY,
}
}
}
impl RetryPolicy {
pub const DEFAULT_MAX_ATTEMPTS: u32 = 3;
pub const DEFAULT_BASE_DELAY: Duration = Duration::from_millis(200);
pub const DEFAULT_MAX_DELAY: Duration = Duration::from_secs(5);
pub fn new() -> Self {
Self::default()
}
pub fn with_max_attempts(mut self, attempts: u32) -> Self {
self.max_attempts = attempts.max(1);
self
}
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 max_attempts(&self) -> u32 {
self.max_attempts
}
pub fn base_delay(&self) -> Duration {
self.base_delay
}
pub fn max_delay(&self) -> Duration {
self.max_delay
}
pub(crate) fn backoff(&self, retry: u32, random: u64) -> Duration {
let shift = retry.saturating_sub(1).min(31);
let ceiling = self
.base_delay
.saturating_mul(1 << shift)
.min(self.max_delay);
let half = ceiling / 2;
let span = (ceiling - half).as_nanos();
let extra = u64::try_from(u128::from(random) % (span + 1)).unwrap_or(u64::MAX);
half.saturating_add(Duration::from_nanos(extra))
}
pub(crate) fn next_wait(
&self,
attempt: u32,
outcome: &Result<Reply, Error>,
now: SystemTime,
random: u64,
) -> Option<Duration> {
if attempt >= self.max_attempts {
return None;
}
match outcome {
Err(Error::Transport(_)) => Some(self.backoff(attempt, random)),
Ok(reply) if matches!(reply.status, 429 | 503) => {
self.server_wait(reply, attempt, now, random)
}
_ => None,
}
}
fn server_wait(
&self,
reply: &Reply,
attempt: u32,
now: SystemTime,
random: u64,
) -> Option<Duration> {
match reply
.retry_after
.as_deref()
.and_then(|v| retry_after(v, now))
{
Some(wait) if wait > self.max_delay => None,
Some(wait) => Some(wait),
None => Some(self.backoff(attempt, random)),
}
}
}
pub(crate) fn run<A, S>(policy: &RetryPolicy, mut attempt: A, mut sleep: S) -> Result<Reply, Error>
where
A: FnMut() -> Result<Reply, Error>,
S: FnMut(Duration),
{
let mut made = 1;
loop {
let outcome = attempt();
match policy.next_wait(made, &outcome, SystemTime::now(), random()) {
Some(wait) => sleep(wait),
None => return outcome,
}
made += 1;
}
}
fn random() -> u64 {
RandomState::new().hash_one(SystemTime::now())
}
pub(crate) fn retry_after(value: &str, now: SystemTime) -> Option<Duration> {
let value = value.trim();
if !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()) {
return Some(Duration::from_secs(value.parse().unwrap_or(u64::MAX)));
}
let at = http_date(value)?;
Some(at.duration_since(now).unwrap_or(Duration::ZERO))
}
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
fn http_date(value: &str) -> Option<SystemTime> {
let fields: Vec<&str> = value.split(' ').collect();
let [_weekday, day, month, year, time, "GMT"] = fields.as_slice() else {
return None;
};
let month = MONTHS.iter().position(|m| m == month)?;
let year = i64::from(year.parse::<u16>().ok()?);
let day = i64::from(day.parse::<u8>().ok()?);
let seconds = days_from_civil(year, month, day) * 86_400 + seconds_of_day(time)?;
u64::try_from(seconds)
.ok()
.map(|s| UNIX_EPOCH + Duration::from_secs(s))
}
fn seconds_of_day(time: &str) -> Option<i64> {
let fields: Vec<&str> = time.split(':').collect();
let [hours, minutes, seconds] = fields.as_slice() else {
return None;
};
let [hours, minutes, seconds] =
[hours, minutes, seconds].map(|f| f.parse::<u8>().ok().map(i64::from));
Some(hours? * 3600 + minutes? * 60 + seconds?)
}
fn days_from_civil(year: i64, month0: usize, day: i64) -> i64 {
let march = i64::try_from((month0 + 10) % 12).unwrap_or(0);
let year = if march >= 10 { year - 1 } else { year };
let era = year.div_euclid(400);
let year_of_era = year - era * 400;
let day_of_year = (153 * march + 2) / 5 + day - 1;
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
era * 146_097 + day_of_era - 719_468
}
#[cfg(test)]
mod tests;