Skip to main content

engenho_controllers/
curve.rs

1//! `Curve` — the one shape every retry delay in the controllers takes: a
2//! floor that doubles per step up to a ceiling.
3//!
4//! ★ WHY ONE TYPE. Before this, each loop grew its own delay by hand: the
5//! watch driver's re-subscribe had a private `grow`, a Transient reconcile
6//! error retried at a FLAT 1 s forever, and the kubelet's crash backoff is
7//! a third hand-written doubling. A flat retry is the defect the flat one
8//! shipped: a controller whose store was down retried every second for as
9//! long as the outage lasted, each attempt a log line and a store round-trip.
10//! Upstream's workqueue rate limiter grows the delay on every consecutive
11//! failure and forgets on success; [`Streak`] is that, and [`Curve`] is the
12//! shape it reads.
13//!
14//! ★ A BACKWARDS CURVE DOES NOT COMPILE. A curve whose cap does not exceed
15//! its base is either flat (cap == base, the defect above) or a curve that
16//! never reaches its base. A zero base never grows at all: `0 × 2ⁿ` is a
17//! hot loop at every step. [`Curve::from_millis`] takes both bounds as const
18//! generics and asserts `0 < base < cap` in an inline `const` block, so the
19//! check runs when the constructor is instantiated — in a `const` item or
20//! in ordinary runtime code alike — and a bad pair is a build error, never
21//! a runtime panic. The fields are private, so there is no other way in.
22//!
23//! Tier-honest: the assertion is a post-monomorphization error. `cargo
24//! build` and `cargo test` (doctests included) reject a bad pair; `cargo
25//! check` alone does not instantiate the constructor and may not. The
26//! `compile_fail` doctests below name E0080, which only nightly rustdoc
27//! checks; each differs from the passing example only in its bounds, and
28//! deleting the assertion turns all three red.
29
30use std::time::Duration;
31
32/// A delay that starts at `base`, doubles on each step, and stops at `cap`.
33///
34/// Built only through [`Curve::from_millis`], which rejects `cap <= base`
35/// (and a zero base) at compile time:
36///
37/// ```
38/// use std::time::Duration;
39/// use engenho_controllers::curve::Curve;
40///
41/// const RETRY: Curve = Curve::from_millis::<1_000, 60_000>();
42/// assert_eq!(RETRY.delay(0), Duration::from_secs(1));
43/// assert_eq!(RETRY.delay(1), Duration::from_secs(2));
44/// assert_eq!(RETRY.delay(40), Duration::from_secs(60));
45/// ```
46///
47/// A cap below the base does not compile:
48///
49/// ```compile_fail,E0080
50/// use engenho_controllers::curve::Curve;
51///
52/// const BACKWARDS: Curve = Curve::from_millis::<60_000, 1_000>();
53/// ```
54///
55/// Nor does a flat curve (`cap == base`), even built at runtime rather than
56/// in a `const` item:
57///
58/// ```compile_fail,E0080
59/// use engenho_controllers::curve::Curve;
60///
61/// let flat = Curve::from_millis::<1_000, 1_000>();
62/// let _ = flat.delay(3);
63/// ```
64///
65/// Nor a zero base, which would never grow:
66///
67/// ```compile_fail,E0080
68/// use engenho_controllers::curve::Curve;
69///
70/// const STUCK: Curve = Curve::from_millis::<0, 30_000>();
71/// ```
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub struct Curve {
74    base_ms: u64,
75    cap_ms: u64,
76}
77
78impl Curve {
79    /// A curve from `BASE_MS` doubling to `CAP_MS`, both in milliseconds.
80    ///
81    /// Fails to compile unless `0 < BASE_MS < CAP_MS`.
82    #[must_use]
83    pub const fn from_millis<const BASE_MS: u64, const CAP_MS: u64>() -> Self {
84        const {
85            assert!(
86                BASE_MS > 0 && CAP_MS > BASE_MS,
87                "a Curve must grow: it needs 0 < base < cap"
88            );
89        }
90        Self {
91            base_ms: BASE_MS,
92            cap_ms: CAP_MS,
93        }
94    }
95
96    /// The first delay on the curve.
97    #[must_use]
98    pub const fn base(&self) -> Duration {
99        Duration::from_millis(self.base_ms)
100    }
101
102    /// The delay the curve never exceeds.
103    #[must_use]
104    pub const fn cap(&self) -> Duration {
105        Duration::from_millis(self.cap_ms)
106    }
107
108    /// The delay at step `n`: `base × 2ⁿ`, capped.
109    ///
110    /// `n` counts from zero, so `delay(0)` is `base`. A step too large to
111    /// represent saturates at the cap — never wraps to a small delay, which
112    /// would be a hot loop that appears only after a long run of failures,
113    /// exactly when it matters.
114    #[must_use]
115    pub const fn delay(&self, n: u32) -> Duration {
116        let ms = match 1u64.checked_shl(n) {
117            Some(factor) => match self.base_ms.checked_mul(factor) {
118                Some(ms) if ms < self.cap_ms => ms,
119                _ => self.cap_ms,
120            },
121            None => self.cap_ms,
122        };
123        Duration::from_millis(ms)
124    }
125}
126
127/// A run of consecutive misses, read against a [`Curve`].
128///
129/// Each [`miss`](Self::miss) owes the next delay on the curve — `base` for
130/// the first miss in a row, doubling to `cap` — and [`reset`](Self::reset),
131/// on progress, starts the next run from `base` again. The count and the
132/// curve it indexes live together, so no caller can grow one without the
133/// other.
134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
135pub struct Streak {
136    curve: Curve,
137    misses: u32,
138}
139
140impl Streak {
141    /// An empty streak on `curve`: the next miss owes `curve.base()`.
142    #[must_use]
143    pub const fn new(curve: Curve) -> Self {
144        Self { curve, misses: 0 }
145    }
146
147    /// Count one miss and return the delay it owes.
148    pub fn miss(&mut self) -> Duration {
149        let owed = self.curve.delay(self.misses);
150        self.misses = self.misses.saturating_add(1);
151        owed
152    }
153
154    /// Progress was made: the next miss starts from the base again.
155    pub fn reset(&mut self) {
156        self.misses = 0;
157    }
158
159    /// How many misses in a row so far.
160    #[must_use]
161    pub const fn misses(&self) -> u32 {
162        self.misses
163    }
164
165    /// The curve this streak is read against.
166    #[must_use]
167    pub const fn curve(&self) -> Curve {
168        self.curve
169    }
170}
171
172#[cfg(test)]
173mod tests {
174    use super::*;
175
176    const C: Curve = Curve::from_millis::<100, 30_000>();
177
178    #[test]
179    fn each_step_doubles_until_the_cap_then_holds() {
180        let steps: Vec<Duration> = (0..20).map(|n| C.delay(n)).collect();
181        assert_eq!(steps[0], C.base());
182        for pair in steps.windows(2) {
183            let (a, b) = (pair[0], pair[1]);
184            if a < C.cap() {
185                assert!(
186                    b.as_millis() * 10 >= a.as_millis() * 18 || b == C.cap(),
187                    "{a:?} -> {b:?}: below the cap a step must grow at least 1.8x"
188                );
189            } else {
190                assert_eq!(b, C.cap(), "past the cap the delay holds");
191            }
192        }
193        assert_eq!(*steps.last().unwrap(), C.cap());
194    }
195
196    #[test]
197    fn a_huge_step_saturates_at_the_cap_rather_than_wrapping() {
198        for n in [31, 32, 63, 64, 65, u32::MAX] {
199            assert_eq!(C.delay(n), C.cap(), "step {n}");
200        }
201    }
202
203    #[test]
204    fn a_streak_grows_per_miss_and_restarts_from_the_base_on_reset() {
205        let mut s = Streak::new(C);
206        assert_eq!(s.miss(), C.delay(0));
207        assert_eq!(s.miss(), C.delay(1));
208        assert_eq!(s.miss(), C.delay(2));
209        assert_eq!(s.misses(), 3);
210        s.reset();
211        assert_eq!(s.misses(), 0);
212        assert_eq!(s.miss(), C.base(), "a reset streak owes the base again");
213    }
214
215    #[test]
216    fn a_streak_count_saturates_instead_of_wrapping_to_the_base() {
217        let mut s = Streak {
218            curve: C,
219            misses: u32::MAX,
220        };
221        assert_eq!(s.miss(), C.cap());
222        assert_eq!(s.misses(), u32::MAX);
223        assert_eq!(s.miss(), C.cap());
224    }
225}