use std::time::Duration;
pub(crate) const MAX_RETRY_BACKOFF: Duration = Duration::from_secs(30);
pub(crate) fn backoff(attempt: u32) -> Duration {
let millis = 200u64.saturating_mul(1u64 << attempt.saturating_sub(1).min(6));
Duration::from_millis(millis).min(MAX_RETRY_BACKOFF)
}
pub(crate) fn parse_retry_after(raw: Option<&str>) -> Option<Duration> {
let secs: f64 = raw?.trim().parse().ok()?;
if secs.is_finite() && secs >= 0.0 {
Some(Duration::from_secs_f64(secs).min(MAX_RETRY_BACKOFF))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn backoff_doubles_then_caps() {
assert_eq!(backoff(1), Duration::from_millis(200));
assert_eq!(backoff(2), Duration::from_millis(400));
assert_eq!(backoff(3), Duration::from_millis(800));
assert_eq!(backoff(50), Duration::from_millis(12_800));
assert!(backoff(50) <= MAX_RETRY_BACKOFF);
}
#[test]
fn retry_after_parses_seconds() {
assert_eq!(parse_retry_after(Some("5")), Some(Duration::from_secs(5)));
assert_eq!(
parse_retry_after(Some(" 2.5 ")),
Some(Duration::from_secs_f64(2.5))
);
}
#[test]
fn retry_after_caps_at_max() {
assert_eq!(parse_retry_after(Some("9999")), Some(MAX_RETRY_BACKOFF));
}
#[test]
fn retry_after_rejects_garbage() {
assert_eq!(parse_retry_after(None), None);
assert_eq!(parse_retry_after(Some("later")), None);
assert_eq!(parse_retry_after(Some("-1")), None);
assert_eq!(parse_retry_after(Some("NaN")), None);
}
}