wellfriend-document-sdk 1.0.0

Official async Rust SDK for the Wellfriend document API: typed document tools, pipelines, streaming uploads and downloads, retries and webhook verification.
Documentation
//! Retry policy: which failures are retried and how long to wait between attempts.

use std::time::Duration;

use reqwest::header::{HeaderMap, RETRY_AFTER};
use reqwest::{Method, StatusCode};

/// The first backoff step.
pub(crate) const BASE_DELAY: Duration = Duration::from_millis(500);
/// The longest computed backoff step.
pub(crate) const MAX_DELAY: Duration = Duration::from_secs(8);
/// The longest `Retry-After` the SDK honours before giving up on a retry.
pub(crate) const MAX_RETRY_AFTER: Duration = Duration::from_secs(120);

/// Statuses worth retrying: request timeout, rate limit, transient server errors and the
/// 520 to 524 answers a CDN gives when the origin is briefly unreachable.
pub(crate) fn retryable_status(status: StatusCode) -> bool {
    matches!(
        status.as_u16(),
        408 | 429 | 500 | 502 | 503 | 504 | 520..=524
    )
}

/// Requests that are safe to send twice: reads, deletes, and writes carrying an idempotency key.
pub(crate) fn retryable_request(method: &Method, idempotent: bool) -> bool {
    idempotent
        || matches!(
            *method,
            Method::GET | Method::HEAD | Method::DELETE | Method::OPTIONS
        )
}

/// Exponential backoff with full jitter: a random delay between zero and
/// `min(MAX_DELAY, BASE_DELAY * 2^attempt)`.
pub(crate) fn backoff(attempt: u32) -> Duration {
    let ceiling = BASE_DELAY
        .saturating_mul(1u32 << attempt.min(16))
        .min(MAX_DELAY);
    let fraction = jitter();
    ceiling.mul_f64(fraction)
}

/// The delay before the next attempt: the server's `Retry-After` when it sent one (capped),
/// otherwise the jittered backoff.
pub(crate) fn delay(attempt: u32, retry_after: Option<Duration>) -> Duration {
    match retry_after {
        Some(wait) => wait.min(MAX_RETRY_AFTER),
        None => backoff(attempt),
    }
}

/// Parses `Retry-After` given in seconds (the form the API sends).
pub(crate) fn parse_retry_after(headers: &HeaderMap) -> Option<Duration> {
    let value = headers.get(RETRY_AFTER)?.to_str().ok()?.trim();
    if let Ok(seconds) = value.parse::<u64>() {
        return Some(Duration::from_secs(seconds));
    }
    value
        .parse::<f64>()
        .ok()
        .filter(|seconds| seconds.is_finite() && *seconds >= 0.0)
        .map(Duration::from_secs_f64)
}

/// Whether an error body says, in the API's envelope, that retrying cannot help
/// (`{"error": {"retryable": false}}`). A body without the flag says nothing.
pub(crate) fn explicitly_final(body: &[u8]) -> bool {
    serde_json::from_slice::<serde_json::Value>(body)
        .ok()
        .and_then(|value| value.get("error")?.get("retryable")?.as_bool())
        .is_some_and(|retryable| !retryable)
}

/// A uniform value in `[0, 1)` from the per-process random state, without an extra dependency.
fn jitter() -> f64 {
    use std::collections::hash_map::RandomState;
    use std::hash::{BuildHasher, Hasher};
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let mut hasher = RandomState::new().build_hasher();
    hasher.write_u64(COUNTER.fetch_add(1, Ordering::Relaxed));
    hasher.write_u128(
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0),
    );
    (hasher.finish() >> 11) as f64 / (1u64 << 53) as f64
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn backoff_stays_within_the_cap() {
        for attempt in 0..20 {
            let wait = backoff(attempt);
            assert!(wait <= MAX_DELAY, "attempt {attempt}: {wait:?}");
            assert!(wait <= BASE_DELAY.saturating_mul(1 << attempt.min(16)));
        }
    }

    #[test]
    fn retry_after_wins_and_is_capped() {
        assert_eq!(
            delay(0, Some(Duration::from_secs(3))),
            Duration::from_secs(3)
        );
        assert_eq!(delay(0, Some(Duration::from_secs(4000))), MAX_RETRY_AFTER);
    }

    #[test]
    fn parses_retry_after_seconds() {
        let mut headers = HeaderMap::new();
        headers.insert(RETRY_AFTER, "49".parse().unwrap());
        assert_eq!(parse_retry_after(&headers), Some(Duration::from_secs(49)));
        headers.insert(RETRY_AFTER, "soon".parse().unwrap());
        assert_eq!(parse_retry_after(&headers), None);
    }

    #[test]
    fn retries_only_safe_requests() {
        assert!(retryable_request(&Method::GET, false));
        assert!(retryable_request(&Method::DELETE, false));
        assert!(!retryable_request(&Method::POST, false));
        assert!(retryable_request(&Method::POST, true));
        assert!(retryable_status(StatusCode::TOO_MANY_REQUESTS));
        assert!(retryable_status(StatusCode::BAD_GATEWAY));
        assert!(retryable_status(StatusCode::from_u16(522).unwrap()));
        assert!(!retryable_status(StatusCode::NOT_IMPLEMENTED));
        assert!(!retryable_status(StatusCode::BAD_REQUEST));
    }
}