relay_server/utils/
retry.rs

1use std::time::{Duration, Instant};
2
3use backoff::ExponentialBackoff;
4use backoff::backoff::Backoff;
5
6/// Backoff multiplier (1.5 which is 50% increase per backoff).
7const DEFAULT_MULTIPLIER: f64 = 1.5;
8/// Randomization factor (0 which is no randomization).
9const DEFAULT_RANDOMIZATION: f64 = 0.0;
10/// Initial interval in milliseconds (1 second).
11const INITIAL_INTERVAL: u64 = 1000;
12
13/// A retry interval generator that increases timeouts with exponential backoff.
14#[derive(Debug)]
15pub struct RetryBackoff {
16    backoff: ExponentialBackoff,
17    attempt: usize,
18}
19
20impl RetryBackoff {
21    /// Creates a new retry backoff based on configured thresholds.
22    pub fn new(max_interval: Duration) -> Self {
23        let backoff = ExponentialBackoff {
24            current_interval: Duration::from_millis(INITIAL_INTERVAL),
25            initial_interval: Duration::from_millis(INITIAL_INTERVAL),
26            randomization_factor: DEFAULT_RANDOMIZATION,
27            multiplier: DEFAULT_MULTIPLIER,
28            max_interval,
29            max_elapsed_time: None,
30            clock: Default::default(),
31            start_time: Instant::now(),
32        };
33
34        RetryBackoff {
35            backoff,
36            attempt: 0,
37        }
38    }
39
40    /// Resets this backoff to its initial state.
41    pub fn reset(&mut self) {
42        self.backoff.reset();
43        self.attempt = 0;
44    }
45
46    /// Indicates whether a backoff attempt has started.
47    pub fn started(&self) -> bool {
48        self.attempt > 0
49    }
50
51    /// Returns the number of the retry attempt.
52    pub fn attempt(&self) -> usize {
53        self.attempt
54    }
55
56    /// Returns the next backoff duration.
57    pub fn next_backoff(&mut self) -> Duration {
58        let duration = match self.attempt {
59            0 => Duration::new(0, 0),
60            _ => self.backoff.next_backoff().unwrap(),
61        };
62
63        self.attempt += 1;
64        duration
65    }
66}