Skip to main content

kube_runtime/utils/
backoff_reset_timer.rs

1use std::time::Duration;
2use tokio::time::Instant;
3
4/// A mostly internal trait to allow resetting backoff based on a reset duration
5pub trait Backoff: Iterator<Item = Duration> + Send + Sync + Unpin {
6    /// Resets the internal state to the initial value.
7    fn reset(&mut self);
8}
9
10impl<B: Backoff + ?Sized> Backoff for Box<B> {
11    fn reset(&mut self) {
12        let this: &mut B = self;
13        this.reset()
14    }
15}
16
17/// A [`Backoff`] wrapper that resets after a fixed duration has elapsed.
18pub struct ResetTimerBackoff<B: Backoff> {
19    backoff: B,
20    last_backoff: Option<Instant>,
21    reset_duration: Duration,
22}
23
24impl<B: Backoff> ResetTimerBackoff<B> {
25    /// Create a reset backoff wrapper for a given `Backoff` implementing object and a reset duration.
26    pub fn new(backoff: B, reset_duration: Duration) -> Self {
27        Self {
28            backoff,
29            last_backoff: None,
30            reset_duration,
31        }
32    }
33}
34
35impl<B: Backoff> Iterator for ResetTimerBackoff<B> {
36    type Item = Duration;
37
38    fn next(&mut self) -> Option<Duration> {
39        if let Some(last_backoff) = self.last_backoff
40            && Instant::now() > last_backoff + self.reset_duration
41        {
42            tracing::debug!(
43                ?last_backoff,
44                reset_duration = ?self.reset_duration,
45                "Resetting backoff, since reset duration has expired"
46            );
47            self.backoff.reset();
48        }
49        self.last_backoff = Some(Instant::now());
50        self.backoff.next()
51    }
52}
53
54impl<B: Backoff> Backoff for ResetTimerBackoff<B> {
55    fn reset(&mut self) {
56        self.backoff.reset();
57    }
58}
59
60#[cfg(test)]
61mod tests {
62    use tokio::time::advance;
63
64    use super::ResetTimerBackoff;
65    use crate::utils::stream_backoff::tests::LinearBackoff;
66    use std::time::Duration;
67
68    #[tokio::test]
69    async fn should_reset_when_timer_expires() {
70        tokio::time::pause();
71        let mut backoff = ResetTimerBackoff::new(
72            LinearBackoff::new(Duration::from_secs(2)),
73            Duration::from_secs(60),
74        );
75        assert_eq!(backoff.next(), Some(Duration::from_secs(2)));
76        advance(Duration::from_secs(40)).await;
77        assert_eq!(backoff.next(), Some(Duration::from_secs(4)));
78        advance(Duration::from_secs(40)).await;
79        assert_eq!(backoff.next(), Some(Duration::from_secs(6)));
80        advance(Duration::from_secs(80)).await;
81        assert_eq!(backoff.next(), Some(Duration::from_secs(2)));
82        advance(Duration::from_secs(80)).await;
83        assert_eq!(backoff.next(), Some(Duration::from_secs(2)));
84    }
85}