Skip to main content

teloxide/
backoff.rs

1use std::time::Duration;
2
3pub type BackoffStrategy = Box<dyn Send + Fn(u32) -> Duration>;
4
5/// Calculates the backoff time in seconds for exponential strategy with base 2
6///
7/// The maximum duration is limited to a little more than a minute: 64s, so the
8/// successive timings are: 1s, 2s, 4s, .., 64, .., 64
9///
10/// More at: <https://en.wikipedia.org/wiki/Exponential_backoff#Exponential_backoff_algorithm>
11pub fn exponential_backoff_strategy(error_count: u32) -> Duration {
12    // 2^6 = 64s ~ a little more than a minute
13    Duration::from_secs(1_u64 << error_count.min(6))
14}
15
16#[cfg(test)]
17mod tests {
18    use super::*;
19
20    #[test]
21    fn test_exponential_backoff_strategy() {
22        let cases = [
23            (1, Duration::from_secs(2)),
24            (5, Duration::from_secs(32)),
25            (42, Duration::from_secs(64)),
26        ];
27
28        for (error_count, expected) in cases {
29            assert_eq!(exponential_backoff_strategy(error_count), expected);
30        }
31    }
32}