1use core::time::Duration;
4
5use crate::transport::{OicpError, Operation};
6
7#[derive(Clone, Debug)]
36pub struct RetryPolicy {
37 pub max_retries: u32,
39 pub initial_backoff: Duration,
41 pub max_backoff: Duration,
43 pub jitter_percent: u32,
48 pub retry_non_idempotent: bool,
52}
53
54impl Default for RetryPolicy {
55 fn default() -> Self {
56 Self {
57 max_retries: 3,
58 initial_backoff: Duration::from_millis(250),
59 max_backoff: Duration::from_secs(10),
60 jitter_percent: 25,
61 retry_non_idempotent: false,
62 }
63 }
64}
65
66impl RetryPolicy {
67 #[must_use]
69 pub const fn none() -> Self {
70 Self {
71 max_retries: 0,
72 initial_backoff: Duration::ZERO,
73 max_backoff: Duration::ZERO,
74 jitter_percent: 0,
75 retry_non_idempotent: false,
76 }
77 }
78
79 #[must_use]
81 pub const fn with_max_retries(mut self, max_retries: u32) -> Self {
82 self.max_retries = max_retries;
83 self
84 }
85
86 #[must_use]
88 pub const fn allowing_non_idempotent(mut self) -> Self {
89 self.retry_non_idempotent = true;
90 self
91 }
92
93 #[must_use]
97 pub fn should_retry(&self, operation: Operation, error: &OicpError, attempt: u32) -> Option<Duration> {
98 if attempt >= self.max_retries || !error.is_retryable() {
99 return None;
100 }
101 if !self.retry_non_idempotent && !is_idempotent(operation) {
102 return None;
103 }
104 Some(self.backoff(attempt))
105 }
106
107 #[must_use]
109 pub fn backoff(&self, attempt: u32) -> Duration {
110 let doubled = self.initial_backoff.saturating_mul(1u32 << attempt.min(16));
111 doubled.min(self.max_backoff)
112 }
113
114 #[must_use]
121 pub fn jittered_backoff(&self, attempt: u32, position_permille: u32) -> Duration {
122 let base = self.backoff(attempt);
123 if self.jitter_percent == 0 {
124 return base;
125 }
126 let base_ms = base.as_millis();
127 let span = base_ms * u128::from(self.jitter_percent.min(100)) / 100;
128 let offset = span * u128::from(position_permille.min(1000)) / 500;
130 let millis = (base_ms + offset).saturating_sub(span);
131 let jittered = u64::try_from(millis).map_or(self.max_backoff, Duration::from_millis);
132 jittered.min(self.max_backoff)
133 }
134}
135
136pub(crate) fn random_permille() -> u32 {
142 use std::hash::{BuildHasher as _, RandomState};
143 u32::try_from(RandomState::new().hash_one(0_u8) % 1001).unwrap_or(500)
144}
145
146const fn is_idempotent(operation: Operation) -> bool {
155 !matches!(
156 operation,
157 Operation::AuthorizeRemoteStart
158 | Operation::AuthorizeRemoteStop
159 | Operation::AuthorizeRemoteReservationStart
160 | Operation::AuthorizeRemoteReservationStop
161 )
162}
163
164#[cfg(test)]
165mod tests {
166 use super::*;
167 use crate::types::{Acknowledgement, Code};
168
169 #[test]
170 fn a_lost_push_is_retried_and_a_lost_remote_start_is_not() {
171 let policy = RetryPolicy::default();
172 let lost = OicpError::transport("connection reset");
173
174 assert!(policy.should_retry(Operation::PushEvseData, &lost, 0).is_some());
175 assert!(policy.should_retry(Operation::ChargeDetailRecord, &lost, 0).is_some());
176 assert!(policy.should_retry(Operation::PullEvseData, &lost, 0).is_some());
177
178 for op in [
180 Operation::AuthorizeRemoteStart,
181 Operation::AuthorizeRemoteStop,
182 Operation::AuthorizeRemoteReservationStart,
183 Operation::AuthorizeRemoteReservationStop,
184 ] {
185 assert!(policy.should_retry(op, &lost, 0).is_none(), "{op:?} must not be retried by default");
186 }
187 }
188
189 #[test]
190 fn a_decision_is_never_retried_however_the_transport_went() {
191 let policy = RetryPolicy::default();
192 let refused = OicpError::rejected(Acknowledgement::failure(Code::NoValidContract));
193 assert!(policy.should_retry(Operation::AuthorizeStart, &refused, 0).is_none());
194
195 let unavailable = OicpError::rejected(Acknowledgement::failure(Code::ServiceNotAvailable));
197 assert!(policy.should_retry(Operation::AuthorizeStart, &unavailable, 0).is_some());
198 }
199
200 #[test]
201 fn retries_stop_at_the_limit() {
202 let policy = RetryPolicy::default().with_max_retries(2);
203 let lost = OicpError::transport("reset");
204 assert!(policy.should_retry(Operation::PushEvseData, &lost, 0).is_some());
205 assert!(policy.should_retry(Operation::PushEvseData, &lost, 1).is_some());
206 assert!(policy.should_retry(Operation::PushEvseData, &lost, 2).is_none());
207 }
208
209 #[test]
210 fn backoff_doubles_and_is_capped() {
211 let policy = RetryPolicy {
212 initial_backoff: Duration::from_millis(100),
213 max_backoff: Duration::from_millis(500),
214 ..RetryPolicy::default()
215 };
216 assert_eq!(policy.backoff(0), Duration::from_millis(100));
217 assert_eq!(policy.backoff(1), Duration::from_millis(200));
218 assert_eq!(policy.backoff(2), Duration::from_millis(400));
219 assert_eq!(policy.backoff(3), Duration::from_millis(500), "capped");
220 assert_eq!(policy.backoff(30), Duration::from_millis(500), "no overflow");
221 }
222
223 #[test]
224 fn jitter_spreads_the_retries_around_the_backoff() {
225 let policy = RetryPolicy { jitter_percent: 50, ..RetryPolicy::default() };
226 let base = policy.backoff(0); let early = policy.jittered_backoff(0, 0);
228 let late = policy.jittered_backoff(0, 1000);
229
230 assert!(early < base && late > base, "jitter must move the wait in both directions");
231 assert_eq!(policy.jittered_backoff(0, 500), base, "the midpoint is the base");
232 assert_eq!(early, Duration::from_millis(125), "half of 250 ms early");
233 assert_eq!(late, Duration::from_millis(375), "half of 250 ms late");
234
235 let none = RetryPolicy { jitter_percent: 0, ..RetryPolicy::default() };
237 assert_eq!(none.jittered_backoff(0, 0), none.backoff(0));
238 }
239
240 #[test]
241 fn jitter_never_leaves_the_spread_or_the_cap() {
242 let policy = RetryPolicy { jitter_percent: 100, ..RetryPolicy::default() };
243 let base = policy.backoff(0);
244 for position in 0..=1000 {
245 let wait = policy.jittered_backoff(0, position);
246 assert!(wait <= base * 2, "{position} produced {wait:?}");
247 assert!(wait <= policy.max_backoff, "{position} exceeded the cap");
248 }
249 }
250
251 #[test]
252 fn the_random_position_stays_in_range() {
253 for _ in 0..1000 {
254 assert!(random_permille() <= 1000);
255 }
256 }
257
258 #[test]
259 fn non_idempotent_retries_can_be_opted_into() {
260 let policy = RetryPolicy::default().allowing_non_idempotent();
261 let lost = OicpError::transport("reset");
262 assert!(policy.should_retry(Operation::AuthorizeRemoteStart, &lost, 0).is_some());
263 }
264
265 #[test]
266 fn the_none_policy_never_retries() {
267 let policy = RetryPolicy::none();
268 assert!(policy.should_retry(Operation::PushEvseData, &OicpError::transport("x"), 0).is_none());
269 }
270}