ocpp_kit/engine/
backoff.rs1use core::time::Duration;
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub struct Backoff {
14 pub wait_minimum: Duration,
16 pub random_range: Duration,
18 pub repeat_times: u32,
21}
22
23impl Default for Backoff {
24 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 #[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 #[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 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}