Skip to main content

carbium/
retry.rs

1//! The one retry and backoff policy carbium.sh/skill.md states for every plane: wait the larger of the server's hint
2//! (retry-after-ms, else data.retryAfterMs, else Retry-After) and 250 ms × 2^(attempt−1) capped at 4 s, plus 0 to 250 ms of jitter; never cut
3//! a server hint; stop after 4 attempts unless the row says otherwise. sendTransaction is never retried.
4
5use std::time::{SystemTime, UNIX_EPOCH};
6
7use reqwest::header::HeaderMap;
8use serde_json::Value;
9
10/// How a client retries. `None` in place of a policy sends each call once.
11#[derive(Debug, Clone, Copy)]
12pub struct RetryOptions {
13    /// A cap on the total calls including the first. Unset, each row's own count applies (4 for most).
14    pub max_attempts: Option<u32>,
15    /// A server hint above this is not waited for: the error comes back at once with retry_after_ms set.
16    pub max_hint_ms: u64,
17    /// Random source for the jitter, 0 ≤ r < 1.
18    pub random: fn() -> f64,
19}
20
21impl Default for RetryOptions {
22    fn default() -> Self {
23        Self {
24            max_attempts: None,
25            max_hint_ms: 30_000,
26            random: default_random,
27        }
28    }
29}
30
31/// A retry row: the backoff base and cap, and the most attempts including the first.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct RetryPlan {
34    pub base_ms: u64,
35    pub cap_ms: u64,
36    pub max_attempts: u32,
37}
38
39/// The standard row: 250 ms doubling to 4 s, 4 attempts.
40pub const STANDARD: RetryPlan = RetryPlan {
41    base_ms: 250,
42    cap_ms: 4000,
43    max_attempts: 4,
44};
45
46const fn plan(base_ms: u64, cap_ms: u64, max_attempts: u32) -> RetryPlan {
47    RetryPlan {
48        base_ms,
49        cap_ms,
50        max_attempts,
51    }
52}
53
54/// What a failed attempt looked like.
55#[derive(Debug, Clone, Copy)]
56pub struct RetryContext<'a> {
57    pub method: &'a str,
58    /// HTTP status, 0 for no answer.
59    pub http_status: u16,
60    /// JSON-RPC error code, None when the body had none.
61    pub code: Option<i64>,
62    pub message: &'a str,
63    /// error.data as served.
64    pub data: Option<&'a Value>,
65    /// The caller's minContextSlot, for -32016.
66    pub min_context_slot: Option<u64>,
67}
68
69fn field<'a>(data: Option<&'a Value>, key: &str) -> Option<&'a Value> {
70    data.and_then(|d| d.as_object()).and_then(|o| o.get(key))
71}
72
73/// Whether a failed call is retried and with which backoff; None means it is not sent again. Rules in order.
74pub fn decide_retry(ctx: &RetryContext) -> Option<RetryPlan> {
75    let (status, code, msg) = (ctx.http_status, ctx.code, ctx.message);
76    if ctx.method == "sendTransaction" {
77        return None; // a send may have landed: check the signature, never resend blindly
78    }
79    if status == 0 {
80        return Some(STANDARD); // no answer: network error or timeout
81    }
82    if field(ctx.data, "retryable") == Some(&Value::Bool(false)) {
83        return None; // the door says waiting cannot help
84    }
85    match status {
86        429 => Some(if code == Some(-32010) {
87            plan(100, 5000, 6)
88        } else {
89            STANDARD
90        }),
91        425 => Some(plan(0, 0, 2)), // early data refused, nothing was forwarded
92        502 => (!msg.contains("response too large")).then_some(STANDARD),
93        503 if msg.starts_with("upstream RPC unavailable") => Some(plan(2000, 8000, 4)),
94        503 if msg == "compat verbs not initialised" => Some(plan(250, 4000, 3)),
95        503 => Some(STANDARD),
96        504 => (!msg.starts_with("upstream_slow")).then_some(plan(250, 4000, 2)),
97        200 if field(ctx.data, "reason").is_some() => None, // a door policy answer at 200 is final
98        200 => match code? {
99            -32602 => msg
100                .starts_with("the walk read no history")
101                .then_some(STANDARD),
102            -32016 => {
103                let behind = match (
104                    field(ctx.data, "contextSlot").and_then(Value::as_f64),
105                    ctx.min_context_slot,
106                ) {
107                    (Some(slot), Some(min)) if min != 0 => min as f64 - slot,
108                    _ => 1.0,
109                };
110                let wait = (220.0 * behind.max(1.0)).clamp(250.0, 30_000.0) as u64; // about 220 ms per missing slot
111                Some(plan(wait, wait, 4))
112            }
113            -32004 => Some(plan(1000, 2000, 4)), // block not available yet
114            -32014 => Some(plan(1000, 1000, 4)), // block status not yet available
115            -32005 | -32021 | -32024 | -32026 => Some(STANDARD),
116            -32011 => (msg == "das upstream timed out").then_some(STANDARD),
117            -32603 => matches!(
118                msg,
119                "Internal error" | "das upstream refused the request" | "upstream internal error"
120            )
121            .then_some(plan(250, 4000, 2)),
122            -32010 => msg
123                .contains("peer refused the copy")
124                .then_some(plan(20_000, 20_000, 2)),
125            _ => None,
126        },
127        _ => None, // 400, 401, 402, 403, 413, 501 and anything unknown
128    }
129}
130
131fn header<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
132    headers
133        .get(name)
134        .and_then(|v| v.to_str().ok())
135        .map(str::trim)
136        .filter(|v| !v.is_empty())
137}
138
139fn digits(s: &str) -> Option<u64> {
140    s.bytes()
141        .all(|b| b.is_ascii_digit())
142        .then(|| s.parse().ok())
143        .flatten()
144}
145
146/// The server's wait hint in ms: retry-after-ms, else data.retryAfterMs, else Retry-After (seconds or an HTTP date).
147pub fn server_hint_ms(headers: &HeaderMap, data: Option<&Value>) -> Option<u64> {
148    if let Some(ms) = header(headers, "retry-after-ms").and_then(digits) {
149        return Some(ms);
150    }
151    if let Some(ms) = field(data, "retryAfterMs")
152        .and_then(Value::as_f64)
153        .filter(|ms| *ms >= 0.0)
154    {
155        return Some(ms as u64);
156    }
157    retry_after_header_ms(headers)
158}
159
160/// Milliseconds from a Retry-After header: whole seconds or an HTTP date.
161pub(crate) fn retry_after_header_ms(headers: &HeaderMap) -> Option<u64> {
162    let ra = header(headers, "retry-after")?;
163    if let Some(s) = digits(ra) {
164        return Some(s.saturating_mul(1000));
165    }
166    let now = SystemTime::now()
167        .duration_since(UNIX_EPOCH)
168        .ok()?
169        .as_millis() as u64;
170    http_date_ms(ra).map(|at| at.saturating_sub(now))
171}
172
173/// An IMF-fixdate (`Sun, 06 Nov 1994 08:49:37 GMT`) as Unix milliseconds.
174fn http_date_ms(s: &str) -> Option<u64> {
175    let p: Vec<&str> = s.split_whitespace().collect();
176    if p.len() != 6 || p[5] != "GMT" {
177        return None;
178    }
179    const MONTHS: [&str; 12] = [
180        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
181    ];
182    let (d, m, y): (i64, i64, i64) = (
183        p[1].parse().ok()?,
184        MONTHS.iter().position(|x| *x == p[2])? as i64 + 1,
185        p[3].parse().ok()?,
186    );
187    let t: Vec<i64> = p[4]
188        .split(':')
189        .map(|x| x.parse().ok())
190        .collect::<Option<_>>()?;
191    if t.len() != 3
192        || !(1..=31).contains(&d)
193        || !(1970..=9999).contains(&y)
194        || !(0..=23).contains(&t[0])
195        || !(0..=59).contains(&t[1])
196        || !(0..=60).contains(&t[2])
197    {
198        return None; // out of range: no hint, and no arithmetic on it
199    }
200    let y = if m <= 2 { y - 1 } else { y }; // days from 1970-01-01, H. Hinnant's civil-from-days inverse
201    let era = y.div_euclid(400);
202    let yoe = y - era * 400;
203    let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1;
204    let days = era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468;
205    u64::try_from((days * 86_400 + t[0] * 3600 + t[1] * 60 + t[2]) * 1000).ok()
206}
207
208/// The wait before retry number `attempt` (1 for the first retry): max(hint, backoff) plus 0 to 250 ms of jitter.
209pub fn backoff_delay_ms(
210    plan: &RetryPlan,
211    attempt: u32,
212    hint_ms: Option<u64>,
213    random: fn() -> f64,
214) -> u64 {
215    let computed = plan
216        .base_ms
217        .saturating_mul(1u64 << (attempt.saturating_sub(1)).min(30))
218        .min(plan.cap_ms);
219    hint_ms
220        .unwrap_or(0)
221        .max(computed)
222        .saturating_add((random() * 251.0).floor() as u64)
223}
224
225pub(crate) fn default_random() -> f64 {
226    use std::hash::{BuildHasher, Hasher};
227    let mut h = std::collections::hash_map::RandomState::new().build_hasher();
228    h.write_u128(
229        SystemTime::now()
230            .duration_since(UNIX_EPOCH)
231            .map_or(0, |d| d.as_nanos()),
232    );
233    (h.finish() >> 11) as f64 / (1u64 << 53) as f64
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn an_http_date_reads_as_unix_time() {
242        assert_eq!(
243            http_date_ms("Sun, 06 Nov 1994 08:49:37 GMT"),
244            Some(784_111_777_000)
245        );
246        assert_eq!(http_date_ms("Thu, 01 Jan 1970 00:00:00 GMT"), Some(0));
247        assert_eq!(http_date_ms("Sunday, 06-Nov-94 08:49:37 GMT"), None);
248        assert_eq!(http_date_ms("Sun, 06 Nov 9999999999 08:49:37 GMT"), None);
249        assert_eq!(http_date_ms("Sun, 06 Nov 1994 99:49:37 GMT"), None);
250        assert_eq!(http_date_ms("Sun, 06 Nov 1994 08:60:37 GMT"), None);
251        assert_eq!(
252            http_date_ms("Fri, 31 Dec 9999 23:59:60 GMT"),
253            Some(253_402_300_800_000)
254        );
255    }
256
257    #[test]
258    fn a_hint_of_u64_max_neither_overflows_nor_panics() {
259        assert_eq!(
260            backoff_delay_ms(&STANDARD, 1, Some(u64::MAX), || 0.999),
261            u64::MAX
262        );
263        assert_eq!(backoff_delay_ms(&STANDARD, 200, None, || 0.0), 4000);
264    }
265}