Skip to main content

rmv_core/
retry.rs

1//! Bounded repetitions after transient errors.
2//!
3//! A request is repeated at most `retries` times, and only after a
4//! connection error, a timeout, or a status 500, 502, 503 or 504 without a
5//! HAFAS error code. Never after another status, a HAFAS error code (like
6//! `API_QUOTA` or `API_TOO_MANY_REQUESTS`) or an unexpected answer: those do
7//! not change by asking again, and every request counts against the quota of
8//! the access key.
9//!
10//! The waits double from [`Policy::delay`] with some jitter, or follow
11//! `Retry-After`. All attempts and waits together stay within
12//! [`Policy::timeout`]: what does not fit is not tried.
13
14use std::future::Future;
15use std::time::Duration;
16
17use tokio::time::Instant;
18
19/// The first wait before a repetition.
20pub const DEFAULT_DELAY: Duration = Duration::from_millis(500);
21
22/// How to repeat a request.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct Policy {
25    /// The most repetitions after the first attempt.
26    pub retries: u32,
27    /// The time for all attempts and waits together.
28    pub timeout: Duration,
29    /// The first wait, doubled for each further one.
30    pub delay: Duration,
31}
32
33/// Why the attempts ended without an answer.
34#[derive(Debug)]
35pub(crate) enum Failure {
36    /// The last error of the client.
37    Hafas(hafas::Error),
38    /// The time ran out during an attempt.
39    OutOfTime,
40}
41
42impl From<Failure> for crate::Error {
43    fn from(failure: Failure) -> Self {
44        match failure {
45            Failure::Hafas(error) => error.into(),
46            Failure::OutOfTime => Self::Timeout,
47        }
48    }
49}
50
51/// Whether asking again can help.
52pub(crate) fn is_transient(error: &hafas::Error) -> bool {
53    match error {
54        hafas::Error::Timeout(_) | hafas::Error::Http(_) => true,
55        hafas::Error::Status { status, .. } => matches!(status, 500 | 502 | 503 | 504),
56        _ => false,
57    }
58}
59
60/// The wait before repetition `attempt` (1 for the first): `delay` doubled
61/// for each earlier one, plus up to half of it as jitter, or what the server
62/// asked for.
63fn wait(policy: &Policy, attempt: u32, error: &hafas::Error) -> Duration {
64    if let Some(wait) = error.retry_after() {
65        return wait;
66    }
67    let base = policy
68        .delay
69        .saturating_mul(2u32.saturating_pow(attempt.saturating_sub(1)));
70    // Enough to keep clients from asking at the same moment.
71    let nanos = jiff::Timestamp::now().subsec_nanosecond().unsigned_abs();
72    let jitter = base.mul_f64(f64::from(nanos % 1000) / 2000.0);
73    base + jitter
74}
75
76/// Runs `attempt` until it succeeds, fails for good, the repetitions are
77/// used up or the time runs out.
78pub(crate) async fn run<T, F, Fut>(policy: &Policy, mut attempt: F) -> Result<T, Failure>
79where
80    F: FnMut() -> Fut,
81    Fut: Future<Output = Result<T, hafas::Error>>,
82{
83    let deadline = Instant::now() + policy.timeout;
84    let mut repetition = 0;
85    loop {
86        let remaining = deadline.saturating_duration_since(Instant::now());
87        let error = match tokio::time::timeout(remaining, attempt()).await {
88            Ok(Ok(value)) => return Ok(value),
89            Ok(Err(error)) => error,
90            Err(_) => return Err(Failure::OutOfTime),
91        };
92        if repetition >= policy.retries || !is_transient(&error) {
93            return Err(Failure::Hafas(error));
94        }
95        repetition += 1;
96        let wait = wait(policy, repetition, &error);
97        // Compared as durations: a huge `Retry-After` must not overflow.
98        if wait >= deadline.saturating_duration_since(Instant::now()) {
99            return Err(Failure::Hafas(error));
100        }
101        let wait_ms = u64::try_from(wait.as_millis()).unwrap_or(u64::MAX);
102        tracing::warn!(attempt = repetition, wait_ms, %error, "repeating the request");
103        tokio::time::sleep(wait).await;
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use std::sync::atomic::{AtomicU32, Ordering};
111
112    fn status(status: u16, retry_after: Option<Duration>) -> hafas::Error {
113        hafas::Error::Status {
114            status,
115            message: "text".into(),
116            retry_after,
117        }
118    }
119
120    fn policy(retries: u32) -> Policy {
121        Policy {
122            retries,
123            timeout: Duration::from_secs(5),
124            delay: Duration::from_millis(1),
125        }
126    }
127
128    /// Runs with `errors` as the answers of the first attempts, then
129    /// success. Returns the result and the number of attempts.
130    async fn attempts(policy: &Policy, errors: Vec<hafas::Error>) -> (Result<u8, Failure>, u32) {
131        let count = AtomicU32::new(0);
132        let errors = std::sync::Mutex::new(errors.into_iter());
133        let result = run(policy, || {
134            count.fetch_add(1, Ordering::SeqCst);
135            let next = errors.lock().unwrap().next();
136            async move { next.map_or(Ok(7), Err) }
137        })
138        .await;
139        (result, count.load(Ordering::SeqCst))
140    }
141
142    #[test]
143    fn only_transient_errors_are_repeated() {
144        for code in [500, 502, 503, 504] {
145            assert!(is_transient(&status(code, None)), "{code}");
146        }
147        for code in [400, 401, 403, 404, 429, 501] {
148            assert!(!is_transient(&status(code, None)), "{code}");
149        }
150        let api = hafas::Error::Api {
151            status: Some(503),
152            code: "INT_TIMEOUT".into(),
153            text: String::new(),
154            retry_after: None,
155        };
156        assert!(!is_transient(&api));
157        assert!(!is_transient(&hafas::Error::Decode("x".into())));
158        assert!(!is_transient(&hafas::Error::AccessIdMissing));
159    }
160
161    #[tokio::test]
162    async fn repeats_until_it_works() {
163        let (result, count) =
164            attempts(&policy(2), vec![status(503, None), status(502, None)]).await;
165        assert_eq!(result.unwrap(), 7);
166        assert_eq!(count, 3);
167    }
168
169    #[tokio::test]
170    async fn stops_after_the_last_repetition() {
171        let errors = vec![status(503, None), status(503, None), status(500, None)];
172        let (result, count) = attempts(&policy(2), errors).await;
173        assert!(
174            matches!(
175                result,
176                Err(Failure::Hafas(hafas::Error::Status { status: 500, .. }))
177            ),
178            "{result:?}"
179        );
180        assert_eq!(count, 3);
181        let (result, count) = attempts(&policy(0), vec![status(503, None)]).await;
182        assert!(result.is_err());
183        assert_eq!(count, 1);
184    }
185
186    #[tokio::test]
187    async fn does_not_repeat_a_final_error() {
188        let (result, count) = attempts(&policy(2), vec![status(400, None)]).await;
189        assert!(result.is_err());
190        assert_eq!(count, 1);
191    }
192
193    #[tokio::test]
194    async fn a_wait_beyond_the_time_is_not_taken() {
195        let wait = Some(Duration::from_secs(60));
196        let (result, count) = attempts(&policy(2), vec![status(503, wait)]).await;
197        assert!(result.is_err());
198        assert_eq!(count, 1);
199    }
200
201    #[tokio::test]
202    async fn a_huge_retry_after_does_not_overflow() {
203        let wait = Some(Duration::from_secs(u64::MAX));
204        let (result, count) = attempts(&policy(2), vec![status(503, wait)]).await;
205        assert!(result.is_err());
206        assert_eq!(count, 1);
207    }
208
209    #[tokio::test]
210    async fn follows_retry_after() {
211        let wait = Some(Duration::from_millis(20));
212        let start = Instant::now();
213        let (result, count) = attempts(&policy(1), vec![status(503, wait)]).await;
214        assert_eq!(result.unwrap(), 7);
215        assert_eq!(count, 2);
216        assert!(start.elapsed() >= Duration::from_millis(20));
217    }
218
219    #[tokio::test]
220    async fn an_attempt_beyond_the_time_is_cut() {
221        let policy = Policy {
222            timeout: Duration::from_millis(20),
223            ..policy(2)
224        };
225        let result: Result<u8, Failure> =
226            run(&policy, std::future::pending::<Result<u8, hafas::Error>>).await;
227        assert!(matches!(result, Err(Failure::OutOfTime)), "{result:?}");
228        assert_eq!(crate::Error::from(Failure::OutOfTime).status(), "timeout");
229    }
230
231    #[test]
232    fn the_waits_double() {
233        let policy = Policy {
234            delay: Duration::from_millis(100),
235            ..policy(3)
236        };
237        let error = status(503, None);
238        for (attempt, base) in [(1, 100), (2, 200), (3, 400)] {
239            let wait = wait(&policy, attempt, &error);
240            let base = Duration::from_millis(base);
241            assert!(wait >= base && wait <= base * 3 / 2, "{attempt}: {wait:?}");
242        }
243    }
244}