delopay 0.20.0

Official Rust SDK for the DeloPay payments API
Documentation
//! Retry policy. Backend-independent: it sees only `TransportErrorKind` and
//! HTTP status codes.

use std::time::Duration;

pub(crate) const MAX_RETRY_BACKOFF: Duration = Duration::from_secs(30);

/// Exponential backoff: 200ms, 400ms, 800ms, … capped at 30s.
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)
}

/// Parse a `Retry-After` header expressed in seconds.
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));
        // The shift saturates at `2^6`, so growth plateaus at 12.8s and the
        // 30s ceiling is only ever reached via `Retry-After`. This matches the
        // pre-refactor client exactly; do not "fix" it without a decision.
        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);
    }
}