Skip to main content

ocpp_kit/engine/
backoff.rs

1//! Reconnect back-off, exactly as OCPP 2.x Part 4 §5.4 defines it.
2//!
3//! The algorithm is *not* plain exponential back-off: the wait is
4//! `RetryBackOffWaitMinimum + random(0 … RetryBackOffRandomRange)`, doubled after each
5//! failed attempt, and the doubling stops after `RetryBackOffRepeatTimes` attempts — from
6//! which point the (still randomised) maximum wait is reused. 1.6J leaves the schedule
7//! implementation-defined, so the same defaults are used there.
8
9use core::time::Duration;
10
11/// The three `OCPPCommCtrlr` variables that drive reconnect timing (Part 4 §5.4).
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub struct Backoff {
14    /// `RetryBackOffWaitMinimum` — the wait before the first retry.
15    pub wait_minimum: Duration,
16    /// `RetryBackOffRandomRange` — the width of the uniform jitter added to every wait.
17    pub random_range: Duration,
18    /// `RetryBackOffRepeatTimes` — how many times the wait is doubled before it stops
19    /// growing.
20    pub repeat_times: u32,
21}
22
23impl Default for Backoff {
24    /// The values OCPP 2.x suggests: 10 s minimum, 10 s of jitter, doubling 3 times.
25    fn default() -> Self {
26        Self {
27            wait_minimum: Duration::from_secs(10),
28            random_range: Duration::from_secs(10),
29            repeat_times: 3,
30        }
31    }
32}
33
34impl Backoff {
35    /// Never waits — for tests and for local development.
36    #[must_use]
37    pub const fn immediate() -> Self {
38        Self {
39            wait_minimum: Duration::ZERO,
40            random_range: Duration::ZERO,
41            repeat_times: 0,
42        }
43    }
44
45    /// The wait before retry number `attempt` (`0` is the first retry).
46    ///
47    /// `jitter` must be a uniformly distributed value in `0.0 ..= 1.0`; the caller supplies
48    /// it so that the schedule stays deterministic under test and the engine needs no
49    /// entropy source of its own.
50    #[must_use]
51    pub fn delay(&self, attempt: u32, jitter: f64) -> Duration {
52        let doublings = attempt.min(self.repeat_times);
53        let factor = 1u64 << doublings.min(32);
54        let base = self
55            .wait_minimum
56            .saturating_mul(u32::try_from(factor).unwrap_or(u32::MAX));
57        let jitter = jitter.clamp(0.0, 1.0);
58        #[allow(
59            clippy::cast_precision_loss,
60            clippy::cast_sign_loss,
61            clippy::cast_possible_truncation
62        )]
63        let spread = Duration::from_millis((self.random_range.as_millis() as f64 * jitter) as u64);
64        base.saturating_add(spread)
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71
72    #[test]
73    fn doubles_then_plateaus_per_part_4_5_4() {
74        let backoff = Backoff::default();
75        let seconds = |attempt| backoff.delay(attempt, 0.0).as_secs();
76        assert_eq!(seconds(0), 10);
77        assert_eq!(seconds(1), 20);
78        assert_eq!(seconds(2), 40);
79        assert_eq!(seconds(3), 80);
80        // RetryBackOffRepeatTimes = 3: no further doubling.
81        assert_eq!(seconds(4), 80);
82        assert_eq!(seconds(50), 80);
83    }
84
85    #[test]
86    fn jitter_is_added_on_top_of_every_wait() {
87        let backoff = Backoff::default();
88        assert_eq!(backoff.delay(0, 1.0).as_secs(), 20);
89        assert_eq!(backoff.delay(0, 0.5).as_millis(), 15_000);
90        assert_eq!(backoff.delay(3, 1.0).as_secs(), 90);
91    }
92}