1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
use crate::{Jitter, RetryDecision, RetryPolicy};
use rand::distributions::uniform::{UniformFloat, UniformSampler};
use std::{
    cmp::{self, min},
    time::{Duration, SystemTime},
};

/// Exponential backoff with optional jitter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ExponentialBackoff {
    /// Maximum number of allowed retries attempts.
    pub max_n_retries: Option<u32>,
    /// Minimum waiting time between two retry attempts (it can end up being lower when using full jitter).
    pub min_retry_interval: Duration,
    /// Maximum waiting time between two retry attempts.
    pub max_retry_interval: Duration,
    /// How we apply jitter to the calculated backoff intervals.
    pub jitter: Jitter,
    /// Base of the exponential
    pub base: u32,
}

/// Exponential backoff with a maximum retry duration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExponentialBackoffTimed {
    /// Maximum duration the retries can continue for, after which retries will stop.
    max_total_retry_duration: Duration,

    backoff: ExponentialBackoff,
}

/// Builds an exponential backoff policy.
///
/// # Example
///
/// ```rust
/// use retry_policies::{RetryDecision, RetryPolicy, Jitter};
/// use retry_policies::policies::ExponentialBackoff;
/// use std::time::Duration;
///
/// let backoff = ExponentialBackoff::builder()
///     .retry_bounds(Duration::from_secs(1), Duration::from_secs(60))
///     .jitter(Jitter::Bounded)
///     .base(2)
///     .build_with_total_retry_duration(Duration::from_secs(24 * 60 * 60));
/// ```
pub struct ExponentialBackoffBuilder {
    min_retry_interval: Duration,
    max_retry_interval: Duration,
    jitter: Jitter,
    base: u32,
}

impl ExponentialBackoff {
    /// Returns a builder.
    ///
    /// # Example
    /// ```
    /// use retry_policies::policies::ExponentialBackoff;
    /// use std::time::Duration;
    ///
    /// let backoff = ExponentialBackoff::builder()
    ///     .build_with_max_retries(5);
    ///
    /// assert_eq!(backoff.min_retry_interval, Duration::from_secs(1));
    /// assert_eq!(backoff.max_retry_interval, Duration::from_secs(30 * 60));
    /// assert_eq!(backoff.max_n_retries, Some(5));
    /// assert_eq!(backoff.base, 2);
    /// ```
    pub fn builder() -> ExponentialBackoffBuilder {
        <_>::default()
    }

    fn too_many_attempts(&self, n_past_retries: u32) -> bool {
        self.max_n_retries
            .is_some_and(|max_n| max_n <= n_past_retries)
    }
}

impl RetryPolicy for ExponentialBackoff {
    fn should_retry(&self, _request_start_time: SystemTime, n_past_retries: u32) -> RetryDecision {
        if self.too_many_attempts(n_past_retries) {
            RetryDecision::DoNotRetry
        } else {
            let unjittered_wait_for = min(
                self.max_retry_interval,
                self.min_retry_interval * calculate_exponential(self.base, n_past_retries),
            );

            let jittered_wait_for = match self.jitter {
                Jitter::None => unjittered_wait_for,
                Jitter::Full => {
                    let jitter_factor =
                        UniformFloat::<f64>::sample_single(0.0, 1.0, &mut rand::thread_rng());

                    unjittered_wait_for.mul_f64(jitter_factor)
                }
                Jitter::Bounded => {
                    let jitter_factor =
                        UniformFloat::<f64>::sample_single(0.0, 1.0, &mut rand::thread_rng());

                    let jittered_wait_for =
                        (unjittered_wait_for - self.min_retry_interval).mul_f64(jitter_factor);

                    jittered_wait_for + self.min_retry_interval
                }
            };

            let execute_after =
                SystemTime::now() + clip(jittered_wait_for, self.max_retry_interval);
            RetryDecision::Retry { execute_after }
        }
    }
}

/// Clip to the maximum allowed retry interval.
fn clip(duration: Duration, max_duration: Duration) -> Duration {
    cmp::min(duration, max_duration)
}

/// Calculate exponential using base and number of past retries
fn calculate_exponential(base: u32, n_past_retries: u32) -> u32 {
    base.checked_pow(n_past_retries).unwrap_or(u32::MAX)
}

impl ExponentialBackoffTimed {
    /// Maximum number of allowed retries attempts.
    pub fn max_retries(&self) -> Option<u32> {
        self.backoff.max_n_retries
    }

    fn trying_for_too_long(&self, started_at: SystemTime) -> bool {
        self.max_total_retry_duration <= Self::elapsed(started_at)
    }

    fn elapsed(started_at: SystemTime) -> Duration {
        SystemTime::now()
            .duration_since(started_at)
            // If `started_at` is in the future then return a zero duration.
            .unwrap_or_default()
    }
}

impl Default for ExponentialBackoffBuilder {
    fn default() -> Self {
        Self {
            min_retry_interval: Duration::from_secs(1),
            max_retry_interval: Duration::from_secs(30 * 60),
            jitter: Jitter::Full,
            base: 2,
        }
    }
}

impl RetryPolicy for ExponentialBackoffTimed {
    fn should_retry(&self, request_start_time: SystemTime, n_past_retries: u32) -> RetryDecision {
        if self.trying_for_too_long(request_start_time) {
            return RetryDecision::DoNotRetry;
        }
        self.backoff
            .should_retry(request_start_time, n_past_retries)
    }
}

impl ExponentialBackoffBuilder {
    /// Add min & max retry interval bounds. _Default [1s, 30m]_.
    ///
    /// See [`ExponentialBackoff::min_retry_interval`], [`ExponentialBackoff::max_retry_interval`].
    ///
    /// Panics if `min_retry_interval` > `max_retry_interval`.
    pub fn retry_bounds(
        mut self,
        min_retry_interval: Duration,
        max_retry_interval: Duration,
    ) -> Self {
        assert!(
            min_retry_interval <= max_retry_interval,
            "The maximum interval between retries should be greater or equal than the minimum retry interval."
        );
        self.min_retry_interval = min_retry_interval;
        self.max_retry_interval = max_retry_interval;
        self
    }

    /// Set what type of jitter to apply.
    pub fn jitter(mut self, jitter: Jitter) -> Self {
        self.jitter = jitter;
        self
    }

    /// Set what base to use for the exponential.
    pub fn base(mut self, base: u32) -> Self {
        self.base = base;
        self
    }

    /// Builds an [`ExponentialBackoff`] with the given maximum retries.
    ///
    /// See [`ExponentialBackoff::max_n_retries`].
    pub fn build_with_max_retries(self, n: u32) -> ExponentialBackoff {
        ExponentialBackoff {
            min_retry_interval: self.min_retry_interval,
            max_retry_interval: self.max_retry_interval,
            max_n_retries: Some(n),
            jitter: self.jitter,
            base: self.base,
        }
    }

    /// Builds an [`ExponentialBackoff`] with the given maximum total duration for which retries will
    /// continue to be performed.
    ///
    /// # Example
    ///
    /// ```rust
    /// use retry_policies::{RetryDecision, RetryPolicy};
    /// use retry_policies::policies::ExponentialBackoff;
    /// use std::time::{Duration, SystemTime};
    ///
    /// let backoff = ExponentialBackoff::builder()
    ///     .build_with_total_retry_duration(Duration::from_secs(24 * 60 * 60));
    ///
    /// let started_at = SystemTime::now()
    ///     .checked_sub(Duration::from_secs(25 * 60 * 60))
    ///     .unwrap();
    ///
    /// let should_retry = backoff.should_retry(started_at, 0);
    /// assert!(matches!(RetryDecision::DoNotRetry, should_retry));
    /// ```
    pub fn build_with_total_retry_duration(
        self,
        total_duration: Duration,
    ) -> ExponentialBackoffTimed {
        ExponentialBackoffTimed {
            max_total_retry_duration: total_duration,
            backoff: ExponentialBackoff {
                min_retry_interval: self.min_retry_interval,
                max_retry_interval: self.max_retry_interval,
                max_n_retries: None,
                jitter: self.jitter,
                base: self.base,
            },
        }
    }

    /// Builds an [`ExponentialBackoff`] with the given maximum total duration and calculates max
    /// retries that should happen applying no jitter.
    ///
    /// For example if we set total duration 24 hours, with retry bounds [1s, 24h] and 2 as base of the exponential,
    /// we would calculate 17 max retries, as 1s * pow(2, 16) = 65536s = ~18 hours and 18th attempt would be way
    /// after the 24 hours total duration.
    ///
    /// If the 17th retry ends up being scheduled after 10 hours due to jitter, [`ExponentialBackoff::should_retry`]
    /// will return false anyway: no retry will be allowed after total duration.
    ///
    /// If one of the 17 allowed retries for some reason (e.g. previous attempts taking a long time) ends up
    /// being scheduled after total duration, [`ExponentialBackoff::should_retry`] will return false.
    ///
    /// Basically we will enforce whatever comes first, max retries or total duration.
    ///
    /// # Example
    ///
    /// ```rust
    /// use retry_policies::{RetryDecision, RetryPolicy};
    /// use retry_policies::policies::ExponentialBackoff;
    /// use std::time::{Duration, SystemTime};
    ///
    /// let exponential_backoff_timed = ExponentialBackoff::builder()
    ///     .retry_bounds(Duration::from_secs(1), Duration::from_secs(6 * 60 * 60))
    ///     .build_with_total_retry_duration_and_max_retries(Duration::from_secs(24 * 60 * 60));
    ///
    /// assert_eq!(exponential_backoff_timed.max_retries(), Some(17));
    ///
    /// let started_at = SystemTime::now()
    ///     .checked_sub(Duration::from_secs(25 * 60 * 60))
    ///     .unwrap();
    ///
    /// let should_retry = exponential_backoff_timed.should_retry(started_at, 0);
    /// assert!(matches!(RetryDecision::DoNotRetry, should_retry));
    ///
    /// let started_at = SystemTime::now()
    ///     .checked_sub(Duration::from_secs(1 * 60 * 60))
    ///     .unwrap();
    ///
    /// let should_retry = exponential_backoff_timed.should_retry(started_at, 18);
    /// assert!(matches!(RetryDecision::DoNotRetry, should_retry));
    ///
    /// ```
    pub fn build_with_total_retry_duration_and_max_retries(
        self,
        total_duration: Duration,
    ) -> ExponentialBackoffTimed {
        let mut max_n_retries = None;

        let delays = (0u32..).map(|n| {
            min(
                self.max_retry_interval,
                self.min_retry_interval * calculate_exponential(self.base, n),
            )
        });

        let mut total = Duration::from_secs(0);
        for (n, delay) in delays.enumerate() {
            total += delay;
            if total >= total_duration {
                max_n_retries = Some(n as _);
                break;
            }
        }

        ExponentialBackoffTimed {
            max_total_retry_duration: total_duration,
            backoff: ExponentialBackoff {
                min_retry_interval: self.min_retry_interval,
                max_retry_interval: self.max_retry_interval,
                max_n_retries,
                jitter: self.jitter,
                base: self.base,
            },
        }
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    use rand::distributions::{Distribution, Uniform};

    fn get_retry_policy() -> ExponentialBackoff {
        ExponentialBackoff {
            max_n_retries: Some(6),
            min_retry_interval: Duration::from_secs(1),
            max_retry_interval: Duration::from_secs(5 * 60),
            jitter: Jitter::Full,
            base: 2,
        }
    }

    #[test]
    fn if_n_past_retries_is_below_maximum_it_decides_to_retry() {
        // Arrange
        let policy = get_retry_policy();
        let n_past_retries =
            Uniform::from(0..policy.max_n_retries.unwrap()).sample(&mut rand::thread_rng());
        assert!(n_past_retries < policy.max_n_retries.unwrap());

        // Act
        let decision = policy.should_retry(SystemTime::now(), n_past_retries);

        // Assert
        matches!(decision, RetryDecision::Retry { .. });
    }

    #[test]
    fn if_n_past_retries_is_above_maximum_it_decides_to_mark_as_failed() {
        // Arrange
        let policy = get_retry_policy();
        let n_past_retries =
            Uniform::from(policy.max_n_retries.unwrap()..=u32::MAX).sample(&mut rand::thread_rng());
        assert!(n_past_retries >= policy.max_n_retries.unwrap());

        // Act
        let decision = policy.should_retry(SystemTime::now(), n_past_retries);

        // Assert
        matches!(decision, RetryDecision::DoNotRetry);
    }

    #[test]
    fn maximum_retry_interval_is_never_exceeded() {
        // Arrange
        let policy = get_retry_policy();
        let max_interval = policy.max_retry_interval;

        // Act
        let decision = policy.should_retry(SystemTime::now(), policy.max_n_retries.unwrap() - 1);

        // Assert
        match decision {
            RetryDecision::Retry { execute_after } => {
                assert!(execute_after.duration_since(SystemTime::now()).unwrap() <= max_interval)
            }
            RetryDecision::DoNotRetry => panic!("Expected Retry decision."),
        }
    }

    #[test]
    fn overflow_backoff_exponent_does_not_cause_a_panic() {
        let policy = ExponentialBackoff {
            max_n_retries: Some(u32::MAX),
            ..get_retry_policy()
        };
        let max_interval = policy.max_retry_interval;
        let n_failed_attempts = u32::MAX - 1;

        // Act
        let decision = policy.should_retry(SystemTime::now(), n_failed_attempts);

        // Assert
        match decision {
            RetryDecision::Retry { execute_after } => {
                assert!(execute_after.duration_since(SystemTime::now()).unwrap() <= max_interval)
            }
            RetryDecision::DoNotRetry => panic!("Expected Retry decision."),
        }
    }

    #[test]
    #[should_panic]
    fn builder_invalid_retry_bounds() {
        // bounds are the wrong way round or invalid
        ExponentialBackoff::builder().retry_bounds(Duration::from_secs(3), Duration::from_secs(2));
    }

    #[test]
    fn does_not_retry_after_total_retry_duration() {
        let backoff = ExponentialBackoff::builder()
            .build_with_total_retry_duration(Duration::from_secs(24 * 60 * 60));

        {
            let started_at = SystemTime::now()
                .checked_sub(Duration::from_secs(23 * 60 * 60))
                .unwrap();

            let decision = backoff.should_retry(started_at, 0);

            match decision {
                RetryDecision::Retry { .. } => {}
                _ => panic!("should retry"),
            }
        }
        {
            let started_at = SystemTime::now()
                .checked_sub(Duration::from_secs(25 * 60 * 60))
                .unwrap();

            let decision = backoff.should_retry(started_at, 0);

            match decision {
                RetryDecision::DoNotRetry => {}
                _ => panic!("should not retry"),
            }
        }
    }

    #[test]
    fn does_not_retry_before_total_retry_duration_if_max_retries_exceeded() {
        let backoff = ExponentialBackoff::builder()
            // This configuration should allow 17 max retries inside a 24h total duration
            .retry_bounds(Duration::from_secs(1), Duration::from_secs(6 * 60 * 60))
            .build_with_total_retry_duration_and_max_retries(Duration::from_secs(24 * 60 * 60));

        {
            let started_at = SystemTime::now()
                .checked_sub(Duration::from_secs(23 * 60 * 60))
                .unwrap();

            let decision = backoff.should_retry(started_at, 0);

            match decision {
                RetryDecision::Retry { .. } => {}
                _ => panic!("should retry"),
            }
        }
        {
            let started_at = SystemTime::now()
                .checked_sub(Duration::from_secs(23 * 60 * 60))
                .unwrap();

            // Zero based, so this is the 18th retry
            let decision = backoff.should_retry(started_at, 17);

            match decision {
                RetryDecision::DoNotRetry => {}
                _ => panic!("should not retry"),
            }
        }
        {
            let started_at = SystemTime::now()
                .checked_sub(Duration::from_secs(25 * 60 * 60))
                .unwrap();

            let decision = backoff.should_retry(started_at, 0);

            match decision {
                RetryDecision::DoNotRetry => {}
                _ => panic!("should not retry"),
            }
        }
    }

    #[test]
    fn different_exponential_base_produce_different_max_retries_for_the_same_duration() {
        let backoff_base_2 = ExponentialBackoff::builder()
            .retry_bounds(Duration::from_secs(1), Duration::from_secs(60 * 60))
            .base(2)
            .build_with_total_retry_duration_and_max_retries(Duration::from_secs(60 * 60));

        let backoff_base_3 = ExponentialBackoff::builder()
            .retry_bounds(Duration::from_secs(1), Duration::from_secs(60 * 60))
            .base(3)
            .build_with_total_retry_duration_and_max_retries(Duration::from_secs(60 * 60));

        let backoff_base_4 = ExponentialBackoff::builder()
            .retry_bounds(Duration::from_secs(1), Duration::from_secs(60 * 60))
            .base(4)
            .build_with_total_retry_duration_and_max_retries(Duration::from_secs(60 * 60));

        assert_eq!(backoff_base_2.max_retries().unwrap(), 11);
        assert_eq!(backoff_base_3.max_retries().unwrap(), 8);
        assert_eq!(backoff_base_4.max_retries().unwrap(), 6);
    }
}