use std::time::{Duration, SystemTime};
use http::{HeaderMap, Method, StatusCode, Uri, Version, header::RETRY_AFTER};
use crate::{Error, Request, Response, body::Replayable};
const MAX_ATTEMPTS: usize = 3;
const FIRST_RETRY_DELAY: Duration = Duration::from_millis(100);
const SECOND_RETRY_DELAY: Duration = Duration::from_millis(500);
const MAX_RETRY_AFTER: Duration = Duration::from_mins(1);
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[non_exhaustive]
pub enum Policy {
#[default]
Never,
Idempotent,
}
pub(crate) enum Plan {
Once(Request),
Repeat(RepeatableRequest),
}
pub(crate) struct RepeatableRequest {
method: Method,
uri: Uri,
version: Version,
headers: HeaderMap,
extensions: http::Extensions,
body: Replayable,
}
impl Plan {
pub(crate) fn new(policy: Policy, request: Request) -> Self {
if policy != Policy::Idempotent {
return Self::Once(request);
}
let (parts, body) = request.into_parts();
if !is_idempotent(&parts.method) {
return Self::Once(http::Request::from_parts(parts, body));
}
let body = match body.into_replayable() {
Ok(body) => body,
Err(body) => return Self::Once(http::Request::from_parts(parts, body)),
};
Self::Repeat(RepeatableRequest {
method: parts.method,
uri: parts.uri,
version: parts.version,
headers: parts.headers,
extensions: parts.extensions,
body,
})
}
}
impl RepeatableRequest {
pub(crate) fn request(&self) -> Request {
let mut request = http::Request::new(self.body.body());
*request.method_mut() = self.method.clone();
*request.uri_mut() = self.uri.clone();
*request.version_mut() = self.version;
*request.headers_mut() = self.headers.clone();
*request.extensions_mut() = self.extensions.clone();
request
}
}
pub(crate) fn retry_after_response(response: &Response, attempts: usize) -> Option<Duration> {
if attempts >= MAX_ATTEMPTS || !retryable_status(response.status()) {
return None;
}
let delay = match response.status() {
StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE => {
retry_after(response.headers()).unwrap_or_else(|| backoff(attempts))
}
_ => backoff(attempts),
};
Some(delay)
}
pub(crate) fn retry_after_error(error: &Error, attempts: usize) -> Option<Duration> {
(attempts < MAX_ATTEMPTS && error.is_connect()).then(|| backoff(attempts))
}
fn is_idempotent(method: &Method) -> bool {
matches!(
*method,
Method::GET | Method::HEAD | Method::OPTIONS | Method::TRACE | Method::PUT | Method::DELETE
)
}
fn retryable_status(status: StatusCode) -> bool {
matches!(
status,
StatusCode::REQUEST_TIMEOUT
| StatusCode::TOO_EARLY
| StatusCode::TOO_MANY_REQUESTS
| StatusCode::BAD_GATEWAY
| StatusCode::SERVICE_UNAVAILABLE
| StatusCode::GATEWAY_TIMEOUT
)
}
fn retry_after(headers: &HeaderMap) -> Option<Duration> {
let value = headers.get(RETRY_AFTER)?.to_str().ok()?;
let delay = value
.parse::<u64>()
.ok()
.map(Duration::from_secs)
.or_else(|| {
httpdate::parse_http_date(value)
.ok()
.map(|date| date.duration_since(SystemTime::now()).unwrap_or_default())
})?;
Some(delay.min(MAX_RETRY_AFTER))
}
fn backoff(attempts: usize) -> Duration {
let ceiling = match attempts {
1 => FIRST_RETRY_DELAY,
_ => SECOND_RETRY_DELAY,
};
let ceiling_nanos = u64::try_from(ceiling.as_nanos()).unwrap_or(u64::MAX);
Duration::from_nanos(fastrand::u64(..=ceiling_nanos))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn standard_idempotent_methods_are_eligible() {
for method in [
Method::GET,
Method::HEAD,
Method::OPTIONS,
Method::TRACE,
Method::PUT,
Method::DELETE,
] {
assert!(is_idempotent(&method));
}
assert!(!is_idempotent(&Method::POST));
assert!(!is_idempotent(&Method::PATCH));
}
#[test]
fn only_transient_statuses_are_retried() {
for status in [408, 425, 429, 502, 503, 504] {
assert!(retryable_status(StatusCode::from_u16(status).unwrap()));
}
for status in [200, 400, 500, 501] {
assert!(!retryable_status(StatusCode::from_u16(status).unwrap()));
}
}
#[test]
fn retry_after_is_parsed_and_capped() {
let mut headers = HeaderMap::new();
headers.insert(RETRY_AFTER, "2".parse().unwrap());
assert_eq!(retry_after(&headers), Some(Duration::from_secs(2)));
headers.insert(RETRY_AFTER, "999".parse().unwrap());
assert_eq!(retry_after(&headers), Some(MAX_RETRY_AFTER));
let expired = httpdate::fmt_http_date(SystemTime::now() - Duration::from_secs(1));
headers.insert(RETRY_AFTER, expired.parse().unwrap());
assert_eq!(retry_after(&headers), Some(Duration::ZERO));
}
#[test]
fn backoff_never_exceeds_its_attempt_ceiling() {
for _ in 0..16 {
assert!(backoff(1) <= FIRST_RETRY_DELAY);
assert!(backoff(2) <= SECOND_RETRY_DELAY);
}
}
#[test]
fn only_connection_errors_are_retried() {
assert!(retry_after_error(&Error::connect(), 1).is_some());
assert!(retry_after_error(&Error::body(), 1).is_none());
assert!(retry_after_error(&Error::connect(), MAX_ATTEMPTS).is_none());
}
}