Skip to main content

graphrt_provider_api/http/
retry.rs

1//! Jittered exponential backoff for 429 / 5xx / network errors (C9).
2
3use std::future::Future;
4use std::hash::{BuildHasher, Hasher};
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::time::Duration;
7
8use crate::error::ProviderError;
9
10/// A tiny SplitMix64 generator for jitter. Not cryptographic; seeded from the
11/// std `RandomState` by default or from a fixed seed in simulations.
12#[derive(Debug)]
13pub struct JitterRng {
14    state: AtomicU64,
15}
16
17impl JitterRng {
18    /// A generator with a fixed seed (deterministic simulation).
19    pub fn seeded(seed: u64) -> Self {
20        Self { state: AtomicU64::new(seed) }
21    }
22
23    /// A generator seeded from the process's random hasher keys.
24    pub fn from_entropy() -> Self {
25        let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
26        hasher.write_u64(0x9e37_79b9_7f4a_7c15);
27        Self::seeded(hasher.finish())
28    }
29
30    /// Next 64 random bits.
31    pub fn next_u64(&self) -> u64 {
32        let mut value =
33            self.state.fetch_add(0x9e37_79b9_7f4a_7c15, Ordering::Relaxed).wrapping_add(0x9e37_79b9_7f4a_7c15);
34        value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
35        value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
36        value ^ (value >> 31)
37    }
38
39    /// Uniform in `[0, 1)`.
40    pub fn next_unit(&self) -> f64 {
41        (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
42    }
43
44    /// Uniform duration in `[low, high]`.
45    pub fn between(&self, low: Duration, high: Duration) -> Duration {
46        if high <= low {
47            return low;
48        }
49        low + (high - low).mul_f64(self.next_unit())
50    }
51}
52
53/// Retry policy: `max_attempts` tries in total, delay of attempt `n` (from 0)
54/// uniformly in `[d/2, d]` with `d = min(base * 2^n, max_delay)` ("equal
55/// jitter"), or the server's `Retry-After` when longer (capped at `max_delay`).
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub struct RetryPolicy {
58    /// Total attempts including the first one.
59    pub max_attempts: u32,
60    /// Base delay.
61    pub base_delay: Duration,
62    /// Upper bound of one delay.
63    pub max_delay: Duration,
64}
65
66impl Default for RetryPolicy {
67    fn default() -> Self {
68        Self { max_attempts: 5, base_delay: Duration::from_millis(200), max_delay: Duration::from_secs(10) }
69    }
70}
71
72impl RetryPolicy {
73    /// Delay before retry number `attempt` (0 = first retry).
74    pub fn delay(&self, attempt: u32, retry_after: Option<Duration>, rng: &JitterRng) -> Duration {
75        let exponential = self.base_delay.saturating_mul(1u32.checked_shl(attempt.min(20)).unwrap_or(u32::MAX));
76        let ceiling = exponential.min(self.max_delay);
77        let jittered = rng.between(ceiling / 2, ceiling);
78        match retry_after {
79            Some(hint) => hint.min(self.max_delay).max(jittered),
80            None => jittered,
81        }
82    }
83
84    /// Runs `operation` until it succeeds, fails with a non-retryable kind, or
85    /// attempts run out. Returns the last error.
86    pub async fn run<T, F, Fut>(&self, rng: &JitterRng, mut operation: F) -> Result<T, ProviderError>
87    where
88        F: FnMut(u32) -> Fut,
89        Fut: Future<Output = Result<T, ProviderError>>,
90    {
91        let mut attempt = 0;
92        loop {
93            match operation(attempt).await {
94                Ok(value) => return Ok(value),
95                Err(error) if error.kind.is_retryable() && attempt + 1 < self.max_attempts => {
96                    tokio::time::sleep(self.delay(attempt, error.retry_after, rng)).await;
97                    attempt += 1;
98                }
99                Err(error) => return Err(error),
100            }
101        }
102    }
103}
104
105/// Parses a `Retry-After` header given in seconds (the HTTP-date form is not
106/// used by the provider APIs graphrt talks to and is ignored).
107pub fn parse_retry_after(value: &str) -> Option<Duration> {
108    value.trim().parse::<u64>().ok().map(Duration::from_secs)
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114    use crate::error::ProviderErrorKind;
115
116    #[test]
117    fn delays_grow_with_equal_jitter_and_cap() {
118        let policy =
119            RetryPolicy { max_attempts: 10, base_delay: Duration::from_millis(100), max_delay: Duration::from_secs(1) };
120        let rng = JitterRng::seeded(7);
121        for attempt in 0..10 {
122            let ceiling = (Duration::from_millis(100) * 2u32.pow(attempt)).min(Duration::from_secs(1));
123            let delay = policy.delay(attempt, None, &rng);
124            assert!(delay >= ceiling / 2 && delay <= ceiling, "attempt {attempt}: {delay:?}");
125        }
126    }
127
128    #[test]
129    fn retry_after_is_honoured_but_capped() {
130        let policy = RetryPolicy::default();
131        let rng = JitterRng::seeded(1);
132        assert_eq!(policy.delay(0, Some(Duration::from_secs(3)), &rng), Duration::from_secs(3));
133        assert_eq!(policy.delay(0, Some(Duration::from_secs(600)), &rng), Duration::from_secs(10));
134    }
135
136    #[test]
137    fn seeded_rng_is_deterministic() {
138        let first = JitterRng::seeded(42);
139        let second = JitterRng::seeded(42);
140        assert_eq!(
141            (0..5).map(|_| first.next_u64()).collect::<Vec<_>>(),
142            (0..5).map(|_| second.next_u64()).collect::<Vec<_>>()
143        );
144    }
145
146    #[tokio::test(start_paused = true)]
147    async fn retries_only_retryable_kinds() {
148        let policy = RetryPolicy::default();
149        let rng = JitterRng::seeded(3);
150        let mut calls = 0;
151        let result: Result<(), _> = policy
152            .run(&rng, |_| {
153                calls += 1;
154                async { Err(ProviderError::fatal("bad request")) }
155            })
156            .await;
157        assert_eq!(result.unwrap_err().kind, ProviderErrorKind::Fatal);
158        assert_eq!(calls, 1);
159
160        let mut attempts_seen = Vec::new();
161        let result = policy
162            .run(&rng, |attempt| {
163                attempts_seen.push(attempt);
164                async move { if attempt < 2 { Err(ProviderError::rate_limited("slow down")) } else { Ok(attempt) } }
165            })
166            .await;
167        assert_eq!(result.unwrap(), 2);
168        assert_eq!(attempts_seen, vec![0, 1, 2]);
169    }
170
171    #[tokio::test(start_paused = true)]
172    async fn gives_up_after_max_attempts() {
173        let policy = RetryPolicy { max_attempts: 3, ..RetryPolicy::default() };
174        let rng = JitterRng::seeded(3);
175        let mut calls = 0;
176        let result: Result<(), _> = policy
177            .run(&rng, |_| {
178                calls += 1;
179                async { Err(ProviderError::transient("503")) }
180            })
181            .await;
182        assert!(result.is_err());
183        assert_eq!(calls, 3);
184    }
185
186    #[test]
187    fn parses_retry_after_seconds() {
188        assert_eq!(parse_retry_after(" 7 "), Some(Duration::from_secs(7)));
189        assert_eq!(parse_retry_after("Wed, 21 Oct 2015 07:28:00 GMT"), None);
190    }
191}