tokio_retry2/strategy/
max_interval.rs

1use std::time::Instant;
2use tokio::time::Duration;
3
4/// Wraps a strategy, applying `max_interval``, after which strategy will
5/// stop retrying.
6pub trait MaxInterval: Iterator<Item = Duration> {
7    /// Applies a `max_interval` for a strategy. Same as  `max_duration`, but using millis instead of `Duration`.
8    fn max_interval(self, max_interval: u64) -> MaxIntervalIterator<Self>
9    where
10        Self: Sized,
11    {
12        MaxIntervalIterator {
13            iter: self,
14            start: Instant::now(),
15            max_duration: Duration::from_millis(max_interval),
16        }
17    }
18
19    /// Applies a `max_duration` for a strategy. In `max_duration` from now,
20    /// the strategy will stop retrying. If `max_duration` is passed, the strategy
21    /// will stop retrying after `max_duration` is reached.
22    fn max_duration(self, max_duration: Duration) -> MaxIntervalIterator<Self>
23    where
24        Self: Sized,
25    {
26        MaxIntervalIterator {
27            iter: self,
28            start: Instant::now(),
29            max_duration,
30        }
31    }
32}
33
34impl<I> MaxInterval for I where I: Iterator<Item = Duration> {}
35
36/// A strategy wrapper with applied max_interval,
37/// created by [`MaxInterval::max_interval`] function.
38#[derive(Debug)]
39pub struct MaxIntervalIterator<I> {
40    iter: I,
41    start: Instant,
42    max_duration: Duration,
43}
44
45impl<I: Iterator<Item = Duration>> Iterator for MaxIntervalIterator<I> {
46    type Item = Duration;
47
48    fn next(&mut self) -> Option<Self::Item> {
49        if self.start.elapsed() > self.max_duration {
50            #[cfg(feature = "tracing")]
51            tracing::warn!("`max_duration` reached, cancelling retry");
52
53            None
54        } else {
55            self.iter.next()
56        }
57    }
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    use crate::strategy::FixedInterval;
65
66    #[tokio::test]
67    async fn returns_none_after_max_interval_passes() {
68        let mut s = FixedInterval::from_millis(10).max_interval(50);
69        assert_eq!(s.next(), Some(Duration::from_millis(10)));
70        tokio::time::sleep(Duration::from_millis(15)).await;
71        assert_eq!(s.next(), Some(Duration::from_millis(10)));
72        tokio::time::sleep(Duration::from_millis(100)).await;
73        assert_eq!(s.next(), None);
74    }
75
76    #[tokio::test]
77    async fn returns_none_after_max_duration_passes() {
78        let mut s = FixedInterval::from_millis(10).max_duration(Duration::from_millis(50));
79        assert_eq!(s.next(), Some(Duration::from_millis(10)));
80        tokio::time::sleep(Duration::from_millis(15)).await;
81        assert_eq!(s.next(), Some(Duration::from_millis(10)));
82        tokio::time::sleep(Duration::from_millis(100)).await;
83        assert_eq!(s.next(), None);
84    }
85}