Skip to main content

pain001_sdk/
retry.rs

1// SPDX-License-Identifier: Apache-2.0 OR MIT
2//! Opt-in retries for idempotent calls.
3
4use std::hash::{BuildHasher, RandomState};
5use std::time::{Duration, SystemTime, UNIX_EPOCH};
6
7use crate::client::Reply;
8use crate::Error;
9
10/// When a [`Client`](crate::Client) tries a `GET` call again.
11///
12/// Retries are off unless a policy is set with
13/// [`Client::retry`](crate::Client::retry). With one, a `GET` call
14/// ([`health`](crate::Client::health), [`faces`](crate::Client::faces),
15/// and [`request`](crate::Client::request) with `"GET"`) is tried again
16/// after a connection failure or timeout ([`Error::Transport`]), or an
17/// HTTP `429` or `503` answer, up to [`max_attempts`](Self::max_attempts)
18/// attempts in all. A `POST` is never retried: repeating `validate`,
19/// `generate`, `check` or `project_face` could submit a payment file
20/// twice.
21///
22/// The wait before retry `n` (from 1) is exponential with jitter: a random
23/// point in the upper half of `min(max_delay, base_delay * 2^(n-1))`. A
24/// `Retry-After` header on a `429` or `503`, in seconds or as an HTTP
25/// date, is waited exactly instead; one asking for longer than
26/// [`max_delay`](Self::max_delay) ends the retries and returns that
27/// answer, so the client never comes back earlier than the server asked.
28/// The client's timeout applies to each attempt.
29///
30/// ```
31/// use pain001_sdk::{Client, RetryPolicy};
32/// use std::time::Duration;
33///
34/// let policy = RetryPolicy::new()
35///     .with_max_attempts(4)
36///     .with_base_delay(Duration::from_millis(100));
37/// let client = Client::new("http://127.0.0.1:8000").retry(policy);
38/// assert_eq!(policy.max_delay(), RetryPolicy::DEFAULT_MAX_DELAY);
39/// # drop(client);
40/// ```
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct RetryPolicy {
43    max_attempts: u32,
44    base_delay: Duration,
45    max_delay: Duration,
46}
47
48impl Default for RetryPolicy {
49    fn default() -> Self {
50        RetryPolicy {
51            max_attempts: Self::DEFAULT_MAX_ATTEMPTS,
52            base_delay: Self::DEFAULT_BASE_DELAY,
53            max_delay: Self::DEFAULT_MAX_DELAY,
54        }
55    }
56}
57
58impl RetryPolicy {
59    /// Attempts in all, the first one included, of [`RetryPolicy::new`].
60    pub const DEFAULT_MAX_ATTEMPTS: u32 = 3;
61    /// The wait before the first retry, before jitter.
62    pub const DEFAULT_BASE_DELAY: Duration = Duration::from_millis(200);
63    /// The longest wait before any retry, and the longest `Retry-After`
64    /// honoured.
65    pub const DEFAULT_MAX_DELAY: Duration = Duration::from_secs(5);
66
67    /// The defaults: 3 attempts, 200 ms base delay, 5 s maximum delay.
68    pub fn new() -> Self {
69        Self::default()
70    }
71
72    /// Sets the number of attempts in all, the first one included. `1`
73    /// (or `0`, read as `1`) makes the policy retry nothing.
74    pub fn with_max_attempts(mut self, attempts: u32) -> Self {
75        self.max_attempts = attempts.max(1);
76        self
77    }
78
79    /// Sets the wait before the first retry, before jitter; each later
80    /// wait doubles it, up to the maximum delay.
81    pub fn with_base_delay(mut self, delay: Duration) -> Self {
82        self.base_delay = delay;
83        self
84    }
85
86    /// Sets the longest wait before any retry, which is also the longest
87    /// `Retry-After` the client waits for.
88    pub fn with_max_delay(mut self, delay: Duration) -> Self {
89        self.max_delay = delay;
90        self
91    }
92
93    /// Attempts in all, the first one included.
94    pub fn max_attempts(&self) -> u32 {
95        self.max_attempts
96    }
97
98    /// The wait before the first retry, before jitter.
99    pub fn base_delay(&self) -> Duration {
100        self.base_delay
101    }
102
103    /// The longest wait before any retry.
104    pub fn max_delay(&self) -> Duration {
105        self.max_delay
106    }
107
108    /// The backoff before retry `retry` (from 1): a point in the upper
109    /// half of `min(max_delay, base_delay * 2^(retry-1))`, picked by
110    /// `random`.
111    pub(crate) fn backoff(&self, retry: u32, random: u64) -> Duration {
112        let shift = retry.saturating_sub(1).min(31);
113        let ceiling = self
114            .base_delay
115            .saturating_mul(1 << shift)
116            .min(self.max_delay);
117        let half = ceiling / 2;
118        let span = (ceiling - half).as_nanos();
119        let extra = u64::try_from(u128::from(random) % (span + 1)).unwrap_or(u64::MAX);
120        half.saturating_add(Duration::from_nanos(extra))
121    }
122
123    /// The wait after attempt `attempt` (from 1) ended in `outcome`, or
124    /// `None` when that outcome is the call's result.
125    pub(crate) fn next_wait(
126        &self,
127        attempt: u32,
128        outcome: &Result<Reply, Error>,
129        now: SystemTime,
130        random: u64,
131    ) -> Option<Duration> {
132        if attempt >= self.max_attempts {
133            return None;
134        }
135        match outcome {
136            Err(Error::Transport(_)) => Some(self.backoff(attempt, random)),
137            Ok(reply) if matches!(reply.status, 429 | 503) => {
138                self.server_wait(reply, attempt, now, random)
139            }
140            _ => None,
141        }
142    }
143
144    /// The wait the server asked for with `Retry-After`, or the backoff
145    /// without a readable one; `None` when it asked for too long.
146    fn server_wait(
147        &self,
148        reply: &Reply,
149        attempt: u32,
150        now: SystemTime,
151        random: u64,
152    ) -> Option<Duration> {
153        match reply
154            .retry_after
155            .as_deref()
156            .and_then(|v| retry_after(v, now))
157        {
158            Some(wait) if wait > self.max_delay => None,
159            Some(wait) => Some(wait),
160            None => Some(self.backoff(attempt, random)),
161        }
162    }
163}
164
165/// Makes attempts until `policy` says to stop, sleeping with `sleep`
166/// between them, and returns the last outcome.
167pub(crate) fn run<A, S>(policy: &RetryPolicy, mut attempt: A, mut sleep: S) -> Result<Reply, Error>
168where
169    A: FnMut() -> Result<Reply, Error>,
170    S: FnMut(Duration),
171{
172    let mut made = 1;
173    loop {
174        let outcome = attempt();
175        match policy.next_wait(made, &outcome, SystemTime::now(), random()) {
176            Some(wait) => sleep(wait),
177            None => return outcome,
178        }
179        made += 1;
180    }
181}
182
183/// A random `u64` for jitter, from the standard library's per-process
184/// random hash keys; no dependency, and good enough to spread retries.
185fn random() -> u64 {
186    RandomState::new().hash_one(SystemTime::now())
187}
188
189/// A `Retry-After` value as a wait from `now`: delta-seconds, or an
190/// IMF-fixdate (RFC 9110, section 10.2.3). A date in the past is no wait.
191pub(crate) fn retry_after(value: &str, now: SystemTime) -> Option<Duration> {
192    let value = value.trim();
193    if !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()) {
194        return Some(Duration::from_secs(value.parse().unwrap_or(u64::MAX)));
195    }
196    let at = http_date(value)?;
197    Some(at.duration_since(now).unwrap_or(Duration::ZERO))
198}
199
200const MONTHS: [&str; 12] = [
201    "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
202];
203
204/// An IMF-fixdate, `Sun, 06 Nov 1994 08:49:37 GMT`, as a time. The
205/// obsolete RFC 850 and asctime forms are not read.
206fn http_date(value: &str) -> Option<SystemTime> {
207    let fields: Vec<&str> = value.split(' ').collect();
208    let [_weekday, day, month, year, time, "GMT"] = fields.as_slice() else {
209        return None;
210    };
211    let month = MONTHS.iter().position(|m| m == month)?;
212    // Four-digit years and two-digit days: u16 and u8 bound the arithmetic.
213    let year = i64::from(year.parse::<u16>().ok()?);
214    let day = i64::from(day.parse::<u8>().ok()?);
215    let seconds = days_from_civil(year, month, day) * 86_400 + seconds_of_day(time)?;
216    u64::try_from(seconds)
217        .ok()
218        .map(|s| UNIX_EPOCH + Duration::from_secs(s))
219}
220
221/// `HH:MM:SS` as seconds since midnight.
222fn seconds_of_day(time: &str) -> Option<i64> {
223    let fields: Vec<&str> = time.split(':').collect();
224    let [hours, minutes, seconds] = fields.as_slice() else {
225        return None;
226    };
227    let [hours, minutes, seconds] =
228        [hours, minutes, seconds].map(|f| f.parse::<u8>().ok().map(i64::from));
229    Some(hours? * 3600 + minutes? * 60 + seconds?)
230}
231
232/// Days from 1970-01-01 to `year`-`month0 + 1`-`day` in the proleptic
233/// Gregorian calendar (Howard Hinnant's `days_from_civil`).
234fn days_from_civil(year: i64, month0: usize, day: i64) -> i64 {
235    // Months counted from March, so the leap day ends the year.
236    let march = i64::try_from((month0 + 10) % 12).unwrap_or(0);
237    let year = if march >= 10 { year - 1 } else { year };
238    let era = year.div_euclid(400);
239    let year_of_era = year - era * 400;
240    let day_of_year = (153 * march + 2) / 5 + day - 1;
241    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
242    era * 146_097 + day_of_era - 719_468
243}
244
245#[cfg(test)]
246mod tests;