1use std::time::{SystemTime, UNIX_EPOCH};
6
7use reqwest::header::HeaderMap;
8use serde_json::Value;
9
10#[derive(Debug, Clone, Copy)]
12pub struct RetryOptions {
13 pub max_attempts: Option<u32>,
15 pub max_hint_ms: u64,
17 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#[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
39pub 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#[derive(Debug, Clone, Copy)]
56pub struct RetryContext<'a> {
57 pub method: &'a str,
58 pub http_status: u16,
60 pub code: Option<i64>,
62 pub message: &'a str,
63 pub data: Option<&'a Value>,
65 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
73pub 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; }
79 if status == 0 {
80 return Some(STANDARD); }
82 if field(ctx.data, "retryable") == Some(&Value::Bool(false)) {
83 return None; }
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)), 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, 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; Some(plan(wait, wait, 4))
112 }
113 -32004 => Some(plan(1000, 2000, 4)), -32014 => Some(plan(1000, 1000, 4)), -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, }
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
146pub 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
160pub(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
173fn 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; }
200 let y = if m <= 2 { y - 1 } else { y }; 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
208pub 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}