backoff/
backoff.rs

1use std::time::Duration;
2
3/// `Backoff` is a backoff policy for retrying an operation.
4pub trait Backoff {
5    /// Resets the internal state to the initial value.
6    fn reset(&mut self) {}
7    /// next_backoff() time is elapsed before it is called again.
8    /// If it returns None, it means the operation timed out and no
9    /// further retries are done.
10    fn next_backoff(&mut self) -> Option<Duration>;
11}
12
13impl<B: Backoff + ?Sized> Backoff for Box<B> {
14    fn next_backoff(&mut self) -> Option<Duration> {
15        let this: &mut B = self;
16        this.next_backoff()
17    }
18
19    fn reset(&mut self) {
20        let this: &mut B = self;
21        this.reset()
22    }
23}
24
25/// Immediately retry the operation.
26#[derive(Debug)]
27pub struct Zero {}
28
29impl Backoff for Zero {
30    fn next_backoff(&mut self) -> Option<Duration> {
31        Some(Duration::default())
32    }
33}
34
35/// The operation should never be retried.
36#[derive(Debug)]
37pub struct Stop {}
38
39impl Backoff for Stop {
40    fn next_backoff(&mut self) -> Option<Duration> {
41        None
42    }
43}
44
45/// Contant is a backoff policy which always returns
46/// a constant duration.
47#[derive(Debug)]
48pub struct Constant {
49    interval: Duration,
50}
51
52impl Constant {
53    /// Creates a new Constant backoff with `interval` contant
54    /// backoff.
55    pub fn new(interval: Duration) -> Constant {
56        Constant { interval }
57    }
58}
59
60impl Backoff for Constant {
61    fn next_backoff(&mut self) -> Option<Duration> {
62        Some(self.interval)
63    }
64}