1use std::collections::hash_map::DefaultHasher;
32use std::hash::{Hash, Hasher};
33use std::time::{Duration, Instant};
34
35use reqwest::StatusCode;
36use reqwest::header::HeaderMap;
37
38use crate::config::Config;
39
40pub const DEFAULT_MAX_RETRIES: u32 = 3;
42pub const DEFAULT_RETRY_BASE_MS: u64 = 200;
44pub const DEFAULT_RETRY_MAX_DELAY_MS: u64 = 30_000;
46pub const HARD_MAX_RETRIES: u32 = 10;
48pub const HARD_MAX_DELAY_MS: u64 = 60_000;
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct RetryConfig {
57 pub max_retries: u32,
59 pub base_ms: u64,
61 pub max_delay_ms: u64,
63 pub enabled: bool,
65}
66
67impl RetryConfig {
68 pub fn from_config(cfg: &Config) -> Self {
70 let max_retries = cfg.max_retries.min(HARD_MAX_RETRIES);
71 let base_ms = if cfg.retry_base_ms == 0 {
72 DEFAULT_RETRY_BASE_MS
73 } else {
74 cfg.retry_base_ms
75 };
76 let max_delay_ms = cfg.retry_max_delay_ms.min(HARD_MAX_DELAY_MS).max(base_ms);
77 let enabled = !cfg.disable_retry && max_retries > 0;
78 Self {
79 max_retries,
80 base_ms,
81 max_delay_ms,
82 enabled,
83 }
84 }
85
86 pub fn max_attempts(self) -> u32 {
88 if !self.enabled {
89 1
90 } else {
91 self.max_retries.saturating_add(1)
92 }
93 }
94
95 pub fn may_retry(self, attempt: u32) -> bool {
97 self.enabled && attempt < self.max_attempts()
98 }
99
100 pub fn delay_for_attempt(self, attempt: u32) -> Duration {
102 backoff_full_jitter(self.base_ms, attempt, self.max_delay_ms)
103 }
104}
105
106impl Default for RetryConfig {
107 fn default() -> Self {
108 Self {
109 max_retries: DEFAULT_MAX_RETRIES,
110 base_ms: DEFAULT_RETRY_BASE_MS,
111 max_delay_ms: DEFAULT_RETRY_MAX_DELAY_MS,
112 enabled: true,
113 }
114 }
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
119pub enum RetryClass {
120 Permanent,
122 Transient,
124 RateLimited {
126 retry_after: Option<Duration>,
128 },
129}
130
131pub fn classify_http_status(status: StatusCode, retry_after: Option<Duration>) -> RetryClass {
133 match status.as_u16() {
134 429 => RetryClass::RateLimited { retry_after },
135 500 | 502 | 504 => RetryClass::Transient,
136 503 => {
138 if retry_after.is_some() {
139 RetryClass::RateLimited { retry_after }
140 } else {
141 RetryClass::Transient
142 }
143 }
144 _ => RetryClass::Permanent,
146 }
147}
148
149pub fn parse_retry_after(headers: &HeaderMap) -> Option<Duration> {
154 let raw = headers
155 .get(reqwest::header::RETRY_AFTER)
156 .and_then(|v| v.to_str().ok())?
157 .trim();
158 if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) {
160 return None;
161 }
162 let secs: u64 = raw.parse().ok()?;
163 Some(Duration::from_secs(secs.min(HARD_MAX_DELAY_MS / 1000)))
165}
166
167pub fn backoff_full_jitter(base_ms: u64, attempt: u32, max_delay_ms: u64) -> Duration {
172 let base = base_ms.max(1);
173 let max_delay = max_delay_ms.max(base);
174 let exp = base.saturating_mul(1u64 << attempt.min(16));
176 let cap = exp.min(max_delay);
177 let pick = mix_u64(attempt) % (cap.saturating_add(1));
178 Duration::from_millis(pick)
179}
180
181pub fn politeness_delay(base: Duration) -> Duration {
191 let base_ms = base.as_millis() as u64;
192 if base_ms == 0 {
193 return Duration::ZERO;
194 }
195 let span = (base_ms / 5).max(1);
196 let extra = mix_u64(base_ms as u32) % (span.saturating_add(1));
197 Duration::from_millis(base_ms.saturating_add(extra))
198}
199
200pub fn wait_for_retry(
202 policy: RetryConfig,
203 attempt: u32,
204 retry_after: Option<Duration>,
205) -> Duration {
206 if let Some(d) = retry_after {
207 return d.min(Duration::from_millis(policy.max_delay_ms));
209 }
210 policy.delay_for_attempt(attempt)
211}
212
213fn mix_u64(attempt: u32) -> u64 {
214 let mut h = DefaultHasher::new();
215 Instant::now().hash(&mut h);
216 attempt.hash(&mut h);
217 std::thread::current().id().hash(&mut h);
218 let marker = &h as *const DefaultHasher as usize;
220 marker.hash(&mut h);
221 h.finish()
222}
223
224#[cfg(test)]
225mod tests {
226 use super::*;
227 use reqwest::header::{HeaderValue, RETRY_AFTER};
228
229 #[test]
230 fn max_attempts_respects_kill_switch() {
231 let mut p = RetryConfig::default();
232 assert_eq!(p.max_attempts(), 4);
233 p.enabled = false;
234 assert_eq!(p.max_attempts(), 1);
235 assert!(!p.may_retry(1));
236 }
237
238 #[test]
239 fn from_config_disable_and_clamp() {
240 let cfg = Config {
241 disable_retry: true,
242 max_retries: 99,
243 retry_max_delay_ms: 999_999,
244 ..Config::default()
245 };
246 let p = RetryConfig::from_config(&cfg);
247 assert!(!p.enabled);
248 assert_eq!(p.max_retries, HARD_MAX_RETRIES);
249 assert_eq!(p.max_delay_ms, HARD_MAX_DELAY_MS);
250 assert_eq!(p.max_attempts(), 1);
251 }
252
253 #[test]
254 fn backoff_respects_cap() {
255 let d = backoff_full_jitter(200, 20, 1_000);
256 assert!(d.as_millis() <= 1_000);
257 }
258
259 #[test]
260 fn politeness_delay_zero_stays_zero() {
261 assert_eq!(politeness_delay(Duration::ZERO), Duration::ZERO);
262 }
263
264 #[test]
265 fn politeness_delay_never_below_floor() {
266 let base = Duration::from_millis(1000);
267 for _ in 0..32 {
268 let d = politeness_delay(base);
269 assert!(d >= base, "delay {d:?} below floor {base:?}");
270 assert!(
272 d <= base + Duration::from_millis(200),
273 "delay {d:?} above floor+20%"
274 );
275 }
276 }
277
278 #[test]
279 fn classify_matrix() {
280 assert_eq!(
281 classify_http_status(StatusCode::OK, None),
282 RetryClass::Permanent
283 );
284 assert_eq!(
285 classify_http_status(StatusCode::NOT_FOUND, None),
286 RetryClass::Permanent
287 );
288 assert_eq!(
289 classify_http_status(StatusCode::BAD_REQUEST, None),
290 RetryClass::Permanent
291 );
292 assert_eq!(
293 classify_http_status(StatusCode::INTERNAL_SERVER_ERROR, None),
294 RetryClass::Transient
295 );
296 assert_eq!(
297 classify_http_status(StatusCode::TOO_MANY_REQUESTS, Some(Duration::from_secs(2))),
298 RetryClass::RateLimited {
299 retry_after: Some(Duration::from_secs(2))
300 }
301 );
302 assert_eq!(
303 classify_http_status(
304 StatusCode::SERVICE_UNAVAILABLE,
305 Some(Duration::from_secs(1))
306 ),
307 RetryClass::RateLimited {
308 retry_after: Some(Duration::from_secs(1))
309 }
310 );
311 assert_eq!(
312 classify_http_status(StatusCode::SERVICE_UNAVAILABLE, None),
313 RetryClass::Transient
314 );
315 }
316
317 #[test]
318 fn parse_retry_after_seconds_only() {
319 let mut h = HeaderMap::new();
320 h.insert(RETRY_AFTER, HeaderValue::from_static("7"));
321 assert_eq!(parse_retry_after(&h), Some(Duration::from_secs(7)));
322
323 h.insert(
324 RETRY_AFTER,
325 HeaderValue::from_static("Wed, 21 Oct 2015 07:28:00 GMT"),
326 );
327 assert_eq!(parse_retry_after(&h), None);
328
329 h.insert(RETRY_AFTER, HeaderValue::from_static(""));
330 assert_eq!(parse_retry_after(&h), None);
331 }
332
333 #[test]
334 fn wait_prefers_retry_after() {
335 let p = RetryConfig::default();
336 let w = wait_for_retry(p, 1, Some(Duration::from_secs(3)));
337 assert_eq!(w, Duration::from_secs(3));
338 }
339}