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 /// The caller supplies the [`Jitter`] so that the schedule stays deterministic under test
48 /// and the engine needs no entropy source of its own.
49 #[must_use]
50 pub const fn delay(&self, attempt: u32, jitter: Jitter) -> Duration {
51 let doublings = if attempt < self.repeat_times {
52 attempt
53 } else {
54 self.repeat_times
55 };
56 let factor = 1u64 << if doublings < 32 { doublings } else { 32 };
57 // The doubling is capped at 32, so `factor` fits a u32 long before the guard below
58 // is reached; the guard is what makes that a fact rather than an assumption.
59 #[allow(clippy::cast_possible_truncation)]
60 let base = self
61 .wait_minimum
62 .saturating_mul(if factor > u32::MAX as u64 {
63 u32::MAX
64 } else {
65 factor as u32
66 });
67 let spread = jitter.of_millis(self.random_range.as_millis());
68 base.saturating_add(Duration::from_millis(spread))
69 }
70}
71
72/// How much of a back-off's random range to add, as a fraction of `u32::MAX`.
73///
74/// Integer rather than floating point, so the schedule a test asserts is the schedule that
75/// runs: `Jitter::from_ratio(1, 2)` is exactly half the range on every platform, which
76/// `0.5f64` multiplied into a duration is not.
77#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
78pub struct Jitter(u32);
79
80impl Jitter {
81 /// No jitter — the shortest wait §5.4 allows.
82 pub const NONE: Self = Self(0);
83 /// The whole random range.
84 pub const FULL: Self = Self(u32::MAX);
85
86 /// A uniformly drawn `u32` — four bytes straight from an entropy source — as a jitter.
87 #[must_use]
88 pub const fn from_random_u32(value: u32) -> Self {
89 Self(value)
90 }
91
92 /// `numerator / denominator` of the range, clamped to `0 ..= 1`.
93 ///
94 /// # Panics
95 ///
96 /// If `denominator` is zero.
97 #[must_use]
98 pub const fn from_ratio(numerator: u32, denominator: u32) -> Self {
99 assert!(denominator != 0, "a jitter ratio needs a denominator");
100 if numerator >= denominator {
101 return Self::FULL;
102 }
103 // Rounded, so `from_ratio(1, 2)` is exactly half a range of any width.
104 let scaled =
105 (numerator as u64 * u32::MAX as u64 + denominator as u64 / 2) / denominator as u64;
106 // `numerator < denominator` by the branch above, so the quotient is below `u32::MAX`.
107 #[allow(clippy::cast_possible_truncation)]
108 Self(scaled as u32)
109 }
110
111 /// This fraction of `millis`, rounded to the nearest millisecond.
112 const fn of_millis(self, millis: u128) -> u64 {
113 let whole = u32::MAX as u128;
114 let scaled = (millis * self.0 as u128 + whole / 2) / whole;
115 #[allow(clippy::cast_possible_truncation)]
116 if scaled > u64::MAX as u128 {
117 u64::MAX
118 } else {
119 scaled as u64
120 }
121 }
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127
128 #[test]
129 fn doubles_then_plateaus_per_part_4_5_4() {
130 let backoff = Backoff::default();
131 let seconds = |attempt| backoff.delay(attempt, Jitter::NONE).as_secs();
132 assert_eq!(seconds(0), 10);
133 assert_eq!(seconds(1), 20);
134 assert_eq!(seconds(2), 40);
135 assert_eq!(seconds(3), 80);
136 // RetryBackOffRepeatTimes = 3: no further doubling.
137 assert_eq!(seconds(4), 80);
138 assert_eq!(seconds(50), 80);
139 }
140
141 #[test]
142 fn jitter_is_added_on_top_of_every_wait() {
143 let backoff = Backoff::default();
144 assert_eq!(backoff.delay(0, Jitter::FULL).as_secs(), 20);
145 assert_eq!(
146 backoff.delay(0, Jitter::from_ratio(1, 2)).as_millis(),
147 15_000
148 );
149 assert_eq!(backoff.delay(3, Jitter::FULL).as_secs(), 90);
150 }
151}