Skip to main content

pb_mapper_core/
timeout.rs

1use std::time::Duration;
2
3/// A retry ladder: a delay that doubles from a minimum up to a maximum with
4/// each failure, until [`Self::reset`].
5///
6/// Plain, it waits exactly that delay, for ladders whose sequence is a
7/// contract. [`Self::with_jitter`] spreads it, for retries against a shared
8/// server.
9#[derive(Debug, Clone, Copy)]
10pub struct RetryBackoff {
11    failures: u32,
12    min_delay: Duration,
13    max_delay: Duration,
14    jitter: bool,
15}
16
17const _: () = assert!(
18    RetryBackoff::MAX_DOUBLINGS < u32::BITS,
19    "the multiplier is a u32 shifted left by at most MAX_DOUBLINGS"
20);
21
22impl Default for RetryBackoff {
23    fn default() -> Self {
24        Self::new(Duration::from_millis(100), Duration::from_secs(1))
25    }
26}
27
28impl RetryBackoff {
29    /// How many times the delay doubles before it stops growing: past that it
30    /// stays at the minimum times `2^MAX_DOUBLINGS` (1024), or the maximum if
31    /// that is lower.
32    pub const MAX_DOUBLINGS: u32 = 10;
33
34    pub fn new(min_delay: Duration, max_delay: Duration) -> Self {
35        assert!(
36            !min_delay.is_zero(),
37            "RetryBackoff needs a positive minimum delay"
38        );
39        assert!(
40            max_delay >= min_delay,
41            "RetryBackoff's maximum delay must not be below its minimum"
42        );
43        Self {
44            failures: 0,
45            min_delay,
46            max_delay,
47            jitter: false,
48        }
49    }
50
51    /// This ladder, each delay drawn at random from its last quarter: from
52    /// three quarters of the plain delay up to the plain delay itself.
53    ///
54    /// For retries that many processes make against one server, such as
55    /// clients of a relay that restarted: they failed together and would
56    /// otherwise come back together, at every step. A delay is never longer
57    /// than the plain one, so the cap holds and no retry comes later.
58    pub fn with_jitter(self) -> Self {
59        Self {
60            jitter: true,
61            ..self
62        }
63    }
64
65    pub fn failures(&self) -> u32 {
66        self.failures
67    }
68
69    pub fn reset(&mut self) {
70        self.failures = 0;
71    }
72
73    pub fn next_delay(&mut self) -> Duration {
74        let multiplier = 1_u32 << self.failures.min(Self::MAX_DOUBLINGS);
75        self.failures = self.failures.saturating_add(1);
76        let delay = self
77            .min_delay
78            .saturating_mul(multiplier)
79            .min(self.max_delay);
80        if !self.jitter {
81            return delay;
82        }
83        // In whole nanoseconds, so the draw stays within the quarter exactly.
84        let quarter = u64::try_from((delay / 4).as_nanos()).unwrap_or(u64::MAX);
85        delay.saturating_sub(Duration::from_nanos(rand::random_range(0..=quarter)))
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92
93    #[test]
94    fn retry_backoff_caps_and_resets_without_exhausting() {
95        let mut backoff = RetryBackoff::new(Duration::from_millis(100), Duration::from_secs(1));
96
97        assert_eq!(backoff.next_delay(), Duration::from_millis(100));
98        assert_eq!(backoff.next_delay(), Duration::from_millis(200));
99        assert_eq!(backoff.next_delay(), Duration::from_millis(400));
100        assert_eq!(backoff.next_delay(), Duration::from_millis(800));
101        assert_eq!(backoff.next_delay(), Duration::from_secs(1));
102        for _ in 0..32 {
103            assert_eq!(backoff.next_delay(), Duration::from_secs(1));
104        }
105
106        assert!(backoff.failures() > 0);
107        backoff.reset();
108        assert_eq!(backoff.failures(), 0);
109        assert_eq!(backoff.next_delay(), Duration::from_millis(100));
110    }
111
112    /// Below a distant maximum, the delay stops growing at 1024 times the
113    /// minimum ([`RetryBackoff::MAX_DOUBLINGS`]), however many failures follow.
114    #[test]
115    fn retry_backoff_stops_doubling_at_1024_times_the_minimum() {
116        let mut backoff = RetryBackoff::new(Duration::from_millis(1), Duration::from_secs(3600));
117        let delays: Vec<_> = (0..64).map(|_| backoff.next_delay()).collect();
118        assert_eq!(delays[10], Duration::from_millis(1024));
119        assert!(delays[10..].iter().all(|delay| *delay == delays[10]));
120        assert!(delays[..10].windows(2).all(|pair| pair[1] == pair[0] * 2));
121    }
122
123    /// A jittered ladder waits at most the plain ladder's delay, so its cap
124    /// holds and its first retry comes no later, and at least three quarters
125    /// of it, so it still doubles. Its draws differ, which is what spreads
126    /// the retries of clients that failed together.
127    #[test]
128    fn a_jittered_backoff_draws_from_the_last_quarter_of_the_plain_ladder() {
129        let (min, max) = (Duration::from_millis(100), Duration::from_secs(2));
130        let mut plain = RetryBackoff::new(min, max);
131        let mut jittered = RetryBackoff::new(min, max).with_jitter();
132        let draws: Vec<_> = (0..64)
133            .map(|_| (plain.next_delay(), jittered.next_delay()))
134            .collect();
135        for (plain, jittered) in &draws {
136            assert!(
137                *jittered <= *plain && *jittered >= *plain - *plain / 4,
138                "{jittered:?} against {plain:?}"
139            );
140        }
141        assert!(draws.iter().any(|(plain, jittered)| plain != jittered));
142        jittered.reset();
143        assert!(jittered.next_delay() <= min);
144    }
145}