use std::hash::{BuildHasher, RandomState};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RetryPolicy {
max_retries: u32,
initial_delay: Duration,
max_delay: Duration,
}
impl Default for RetryPolicy {
fn default() -> Self {
RetryPolicy {
max_retries: 0,
initial_delay: Duration::from_millis(200),
max_delay: Duration::from_secs(2),
}
}
}
impl RetryPolicy {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn max_retries(mut self, retries: u32) -> Self {
self.max_retries = retries;
self
}
#[must_use]
pub fn initial_delay(mut self, delay: Duration) -> Self {
self.initial_delay = delay;
self
}
#[must_use]
pub fn max_delay(mut self, delay: Duration) -> Self {
self.max_delay = delay;
self
}
#[must_use]
pub fn get_max_retries(&self) -> u32 {
self.max_retries
}
#[must_use]
pub fn get_initial_delay(&self) -> Duration {
self.initial_delay
}
#[must_use]
pub fn get_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 cap = self
.initial_delay
.saturating_mul(1 << shift)
.min(self.max_delay);
let nanos = u64::try_from(cap.as_nanos()).unwrap_or(u64::MAX);
let picked = u128::from(random) * u128::from(nanos) / u128::from(u64::MAX);
Duration::from_nanos(u64::try_from(picked).unwrap_or(nanos))
}
pub(crate) fn after_status(
&self,
retry: u32,
status: u16,
retry_after: Option<&str>,
idempotent: bool,
) -> Option<Duration> {
if retry > self.max_retries || !matches!(status, 429 | 503 | 504) {
return None;
}
if !idempotent && status == 504 {
return None;
}
match retry_after.and_then(|v| parse_retry_after(v, SystemTime::now())) {
Some(wait) if wait > self.max_delay => None,
Some(wait) => Some(wait),
None => Some(self.backoff(retry, random())),
}
}
pub(crate) fn after_failure(&self, retry: u32, idempotent: bool) -> Option<Duration> {
(idempotent && retry <= self.max_retries).then(|| self.backoff(retry, random()))
}
}
#[must_use]
pub(crate) fn is_idempotent(method: &http::Method, path: &str) -> bool {
method == http::Method::GET || !is_stateful(path)
}
fn is_stateful(path: &str) -> bool {
path.contains("/keygen")
|| path.contains("/keys/generate")
|| path.contains("/keys/delete")
|| path.contains("/kms/create-key")
|| path.contains("/opaque/register/")
}
pub(crate) fn random() -> u64 {
RandomState::new().hash_one(SystemTime::now())
}
pub(crate) fn parse_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;