relay_server/utils/
retry.rs1use std::time::{Duration, Instant};
2
3use backoff::ExponentialBackoff;
4use backoff::backoff::Backoff;
5
6const DEFAULT_MULTIPLIER: f64 = 1.5;
8const DEFAULT_RANDOMIZATION: f64 = 0.0;
10const INITIAL_INTERVAL: u64 = 1000;
12
13#[derive(Debug)]
15pub struct RetryBackoff {
16 backoff: ExponentialBackoff,
17 attempt: usize,
18}
19
20impl RetryBackoff {
21 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 pub fn reset(&mut self) {
42 self.backoff.reset();
43 self.attempt = 0;
44 }
45
46 pub fn started(&self) -> bool {
48 self.attempt > 0
49 }
50
51 pub fn attempt(&self) -> usize {
53 self.attempt
54 }
55
56 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}