Skip to main content

oicp_kit/client/
retry.rs

1//! `RetryPolicy` — retries that cannot start a charging session twice.
2
3use core::time::Duration;
4
5use crate::transport::{OicpError, Operation};
6
7/// When to try again, and how long to wait.
8///
9/// # The rule that matters
10///
11/// Retrying an OICP call is not always safe, and the difference is not the HTTP status:
12///
13/// * A **transport failure** may mean the request never arrived, or that it arrived and the answer
14///   was lost. For an `AuthorizeRemoteStart` the second case means retrying could start a second
15///   charging session. So retries are allowed only where the operation is idempotent, or where
16///   Hubject's own session handling makes a duplicate harmless.
17/// * A **rejection** (`HTTP 200`, `Result: false`) is a decision, and repeating an identical
18///   request gets an identical decision — except for the handful of transient codes that
19///   [`Code::is_retryable`](crate::types::Code::is_retryable) names.
20///
21/// [`RetryPolicy::should_retry`] takes the operation as well as the error, so it can apply both.
22///
23/// ```
24/// # use oicp_kit::client::RetryPolicy;
25/// # use oicp_kit::transport::{OicpError, Operation};
26/// let policy = RetryPolicy::default();
27/// let lost = OicpError::transport("connection reset");
28///
29/// // A push is idempotent: send it again.
30/// assert!(policy.should_retry(Operation::PushEvseData, &lost, 0).is_some());
31///
32/// // A remote start is not: a second one could start a second session.
33/// assert!(policy.should_retry(Operation::AuthorizeRemoteStart, &lost, 0).is_none());
34/// ```
35#[derive(Clone, Debug)]
36pub struct RetryPolicy {
37    /// How many times to try again after the first attempt.
38    pub max_retries: u32,
39    /// The wait before the first retry.
40    pub initial_backoff: Duration,
41    /// The cap on the wait.
42    pub max_backoff: Duration,
43    /// How much of the backoff is random, as a percentage of it — 0 for none.
44    ///
45    /// Without jitter, every client that lost the same Hubject instance retries in lockstep and
46    /// arrives together, which is how a recovering service is knocked over again.
47    pub jitter_percent: u32,
48    /// Retry operations that are not idempotent.
49    ///
50    /// Off by default. Turn it on only if your own system deduplicates on the partner session id.
51    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    /// A policy that never retries.
68    #[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    /// Sets how many retries to allow.
80    #[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    /// Allows retrying operations that are not idempotent. See the field documentation.
87    #[must_use]
88    pub const fn allowing_non_idempotent(mut self) -> Self {
89        self.retry_non_idempotent = true;
90        self
91    }
92
93    /// How long to wait before attempt `attempt + 1`, or `None` to give up.
94    ///
95    /// `attempt` counts from zero for the first failure.
96    #[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    /// The backoff for `attempt`, doubling and capped, before jitter.
108    #[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    /// The backoff for `attempt` with jitter applied, given a position in `0..=1000`.
115    ///
116    /// `500` is the un-jittered backoff, `0` the earliest and `1000` the latest the spread
117    /// allows. Split out so the jitter is testable without a random source — and computed in
118    /// integer milliseconds, so the crate needs neither a floating-point multiply nor a
119    /// random-number dependency to spread its retries.
120    #[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        // `position` walks the whole spread: 0 → base - span, 500 → base, 1000 → base + span.
129        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
136/// A position in `0..=1000` for the next retry's jitter.
137///
138/// `RandomState` seeds itself from the operating system, so this needs no random-number crate:
139/// jitter exists to stop a fleet of clients retrying in lockstep, and any well-spread value does
140/// that. Nothing here is a secret.
141pub(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
146/// Whether sending this operation twice is harmless.
147///
148/// The four that are not: starting or stopping a session, and starting or stopping a reservation.
149/// Each of them changes the state of a physical charging point, and a duplicate can leave a driver
150/// with a session they did not ask for or a reservation they will be billed for.
151///
152/// Everything else is a push of state (idempotent by construction), a pull (a read), or a record
153/// of something that already happened, which Hubject deduplicates on the session id.
154const 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        // Four operations change the state of a charging point.
179        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        // …but a transient code is.
196        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); // 250 ms
227        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        // Off means off.
236        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}