tokio_retry2/strategy/
fibonacci_backoff.rs

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
use std::iter::Iterator;
use tokio::time::Duration;

/// A retry strategy driven by the fibonacci series.
///
/// Each retry uses a delay which is the sum of the two previous delays.
///
/// Depending on the problem at hand, a fibonacci retry strategy might
/// perform better and lead to better throughput than the `ExponentialBackoff`
/// strategy.
///
/// See ["A Performance Comparison of Different Backoff Algorithms under Different Rebroadcast Probabilities for MANETs."](https://www.researchgate.net/profile/Saher-Manaseer/publication/255672213_A_Performance_Comparison_of_Different_Backoff_Algorithms_under_Different_Rebroadcast_Probabilities_for_MANET's/links/542d40220cf29bbc126d2378/A-Performance-Comparison-of-Different-Backoff-Algorithms-under-Different-Rebroadcast-Probabilities-for-MANETs.pdf)
/// for more details.
#[derive(Debug, Clone)]
pub struct FibonacciBackoff {
    current: u64,
    next: u64,
    factor: u64,
    max_delay: Option<Duration>,
}

impl FibonacciBackoff {
    /// Constructs a new fibonacci back-off strategy,
    /// given a base duration in milliseconds.
    pub const fn from_millis(millis: u64) -> FibonacciBackoff {
        FibonacciBackoff {
            current: millis,
            next: millis,
            factor: 1u64,
            max_delay: None,
        }
    }

    /// A multiplicative factor that will be applied to the retry delay.
    ///
    /// For example, using a factor of `1000` will make each delay in units of seconds.
    ///
    /// Default factor is `1`.
    pub const fn factor(mut self, factor: u64) -> FibonacciBackoff {
        self.factor = factor;
        self
    }

    /// Apply a maximum delay. No single retry delay will be longer than this `Duration`.
    pub const fn max_delay(mut self, duration: Duration) -> FibonacciBackoff {
        self.max_delay = Some(duration);
        self
    }

    /// Apply a maximum delay. No single retry delay will be longer than this `Duration::from_millis`.
    pub const fn max_delay_millis(mut self, duration: u64) -> FibonacciBackoff {
        self.max_delay = Some(Duration::from_millis(duration));
        self
    }
}

impl Iterator for FibonacciBackoff {
    type Item = Duration;

    fn next(&mut self) -> Option<Duration> {
        // set delay duration by applying factor
        let duration = if let Some(duration) = self.current.checked_mul(self.factor) {
            Duration::from_millis(duration)
        } else {
            Duration::from_millis(u64::MAX)
        };

        // check if we reached max delay
        if let Some(ref max_delay) = self.max_delay {
            if duration > *max_delay {
                #[cfg(feature = "tracing")]
                tracing::warn!("`max_delay` for strategy reached");
                return Some(*max_delay);
            }
        }

        if let Some(next_next) = self.current.checked_add(self.next) {
            self.current = self.next;
            self.next = next_next;
        } else {
            self.current = self.next;
            self.next = u64::MAX;
        }

        Some(duration)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn returns_the_fibonacci_series_starting_at_10() {
        let mut iter = FibonacciBackoff::from_millis(10);
        assert_eq!(iter.next(), Some(Duration::from_millis(10)));
        assert_eq!(iter.next(), Some(Duration::from_millis(10)));
        assert_eq!(iter.next(), Some(Duration::from_millis(20)));
        assert_eq!(iter.next(), Some(Duration::from_millis(30)));
        assert_eq!(iter.next(), Some(Duration::from_millis(50)));
        assert_eq!(iter.next(), Some(Duration::from_millis(80)));
    }

    #[test]
    fn saturates_at_maximum_value() {
        let mut iter = FibonacciBackoff::from_millis(u64::MAX);
        assert_eq!(iter.next(), Some(Duration::from_millis(u64::MAX)));
        assert_eq!(iter.next(), Some(Duration::from_millis(u64::MAX)));
    }

    #[test]
    fn stops_increasing_at_max_delay() {
        let mut iter = FibonacciBackoff::from_millis(10).max_delay(Duration::from_millis(50));
        assert_eq!(iter.next(), Some(Duration::from_millis(10)));
        assert_eq!(iter.next(), Some(Duration::from_millis(10)));
        assert_eq!(iter.next(), Some(Duration::from_millis(20)));
        assert_eq!(iter.next(), Some(Duration::from_millis(30)));
        assert_eq!(iter.next(), Some(Duration::from_millis(50)));
        assert_eq!(iter.next(), Some(Duration::from_millis(50)));
    }

    #[test]
    fn returns_max_when_max_less_than_base() {
        let mut iter = FibonacciBackoff::from_millis(20).max_delay(Duration::from_millis(10));

        assert_eq!(iter.next(), Some(Duration::from_millis(10)));
        assert_eq!(iter.next(), Some(Duration::from_millis(10)));
    }

    #[test]
    fn can_use_factor_to_get_seconds() {
        let factor = 1000;
        let mut s = FibonacciBackoff::from_millis(1).factor(factor);

        assert_eq!(s.next(), Some(Duration::from_secs(1)));
        assert_eq!(s.next(), Some(Duration::from_secs(1)));
        assert_eq!(s.next(), Some(Duration::from_secs(2)));
    }
}