Skip to main content

timvw_rust_runtime/
retry.rs

1//! Retries for HTTP APIs: [`RetryPolicy`], a tower retry policy, and [`RetryLayer`], which adds to it a look at the
2//! body of a `429` to tell a rate limit (retried) from an exhausted quota (not retried).
3//!
4//! `Client::default()` already retries with `RetryLayer::new(RetryPolicy::default())`. For another policy, start from
5//! the bare service:
6//!
7//! ```no_run
8//! # #[cfg(feature = "reqwest")]
9//! # fn demo() {
10//! use timvw_rust_runtime::retry::{self, RetryLayer, RetryPolicy};
11//! use timvw_rust_runtime::{Client, ReqwestService};
12//!
13//! let client = Client::from_service(ReqwestService::default())
14//!     .layer(RetryLayer::new(RetryPolicy::new(5)).permanent_429(retry::openai_insufficient_quota));
15//! # }
16//! ```
17
18use std::fmt;
19use std::sync::Arc;
20use std::task::{Context, Poll};
21use std::time::Duration;
22
23use bytes::{Bytes, BytesMut};
24use http::header::RETRY_AFTER;
25use http::{HeaderMap, StatusCode};
26use http_body_util::{BodyDataStream, BodyExt};
27use tower::retry::Policy;
28use tower::{Layer, Service};
29
30use crate::maybe::BoxFuture;
31use crate::timer::{since_epoch, Instant, Sleep};
32use crate::{Body, BoxError, MaybeSend, MaybeSync};
33
34/// The header OpenAI (and others) send next to `Retry-After`, in milliseconds.
35const RETRY_AFTER_MS: &str = "retry-after-ms";
36
37/// How much of a `429` body [`RetryLayer`] reads by default to classify it: 64 KiB.
38pub const DEFAULT_BODY_LIMIT: usize = 64 * 1024;
39
40/// Retries `429 Too Many Requests`, `408 Request Timeout` and `5xx` responses, and failures to connect.
41///
42/// - It waits as long as the server asks, with `retry-after-ms` (milliseconds) or `Retry-After` (seconds or an HTTP
43///   date), up to [`RetryPolicy::max_retry_after`] (60 s by default). The wait is read once into a deadline, counted
44///   from when the response arrived, and the policy sleeps until it: time spent in between (reading a `429` body for
45///   [`RetryLayer::permanent_429`]) is not added. A server that asks for longer than `max_retry_after` gets its
46///   response returned at once: waiting less than it asked would likely fail again, and waiting an hour is rarely
47///   what a caller wants. A date in the past means retry now.
48/// - With [`RetryPolicy::server_directed_429`], a `429` is retried only when the server says when.
49/// - Without those headers it backs off exponentially from [`RetryPolicy::base_delay`] (200 ms), doubling on each retry
50///   up to [`RetryPolicy::max_delay`] (8 s), with jitter: each delay is picked at random between half and all of it, so
51///   that clients that failed together do not retry together. [`RetryPolicy::jitter`] turns that off.
52/// - A request that timed out (a [`TimeoutLayer`](crate::timeout::TimeoutLayer) inside the retries, or a reqwest
53///   timeout) is retried only with [`RetryPolicy::retry_timeouts`]: it may have reached the server.
54/// - It never retries a response marked [`Permanent`] (see [`RetryLayer::permanent_429`]), nor a request whose body is
55///   a stream (a streamed file upload), which cannot be sent again.
56#[derive(Clone, Debug)]
57pub struct RetryPolicy {
58    max_retries: usize,
59    attempts: usize,
60    base_delay: Duration,
61    max_delay: Duration,
62    max_retry_after: Duration,
63    jitter: bool,
64    server_directed_429: bool,
65    retry_timeouts: bool,
66}
67
68impl RetryPolicy {
69    /// A policy that retries at most `max_retries` times (after the first attempt).
70    pub fn new(max_retries: usize) -> Self {
71        Self {
72            max_retries,
73            attempts: 0,
74            base_delay: Duration::from_millis(200),
75            max_delay: Duration::from_secs(8),
76            max_retry_after: Duration::from_secs(60),
77            jitter: true,
78            server_directed_429: false,
79            retry_timeouts: false,
80        }
81    }
82
83    /// The first backoff delay, doubled on each retry (default 200 ms).
84    pub fn base_delay(mut self, delay: Duration) -> Self {
85        self.base_delay = delay;
86        self
87    }
88
89    /// The longest backoff delay (default 8 s). It does not limit how long a server can ask to wait with
90    /// `Retry-After`: that is [`RetryPolicy::max_retry_after`].
91    pub fn max_delay(mut self, delay: Duration) -> Self {
92        self.max_delay = delay;
93        self
94    }
95
96    /// The longest wait a server can ask for with `Retry-After` or `retry-after-ms` (default 60 s). A response that
97    /// asks for longer is not retried but returned.
98    pub fn max_retry_after(mut self, delay: Duration) -> Self {
99        self.max_retry_after = delay;
100        self
101    }
102
103    /// Whether each backoff delay is picked at random between half and all of it (default `true`). The waits a
104    /// server asks for are never jittered.
105    pub fn jitter(mut self, jitter: bool) -> Self {
106        self.jitter = jitter;
107        self
108    }
109
110    /// Whether a `429` is retried only when the server says when, with `Retry-After` or `retry-after-ms` (default
111    /// `false`: every `429` is retried, with backoff when the server does not say when).
112    ///
113    /// Some APIs answer a `429` without advice when waiting will not help (a quota, a request too large for a rate
114    /// limit), and with it when it will. `408`, `5xx` and connect failures are retried either way.
115    pub fn server_directed_429(mut self, server_directed: bool) -> Self {
116        self.server_directed_429 = server_directed;
117        self
118    }
119
120    /// Whether a request that timed out is retried (default `false`), like a failure to connect: with a
121    /// [`TimeoutLayer`](crate::timeout::TimeoutLayer) inside the retries, an attempt that takes too long is given up
122    /// and tried again. A request that timed out may have reached the server, so turn this on for requests that are
123    /// safe to repeat (or that the API deduplicates, with an idempotency key).
124    pub fn retry_timeouts(mut self, retry: bool) -> Self {
125        self.retry_timeouts = retry;
126        self
127    }
128
129    /// The number of retries allowed.
130    pub fn max_retries(&self) -> usize {
131        self.max_retries
132    }
133
134    /// When to retry: the server's deadline, or `now` plus the backoff; `None` when the server asks to wait longer than
135    /// `max_retry_after`.
136    fn deadline(&self, retry_after: Option<Instant>, now: Instant) -> Option<Instant> {
137        if let Some(deadline) = retry_after {
138            return (deadline.saturating_duration_since(now) <= self.max_retry_after)
139                .then_some(deadline);
140        }
141        Some(now + self.backoff())
142    }
143
144    /// The backoff before the next retry, jittered unless turned off.
145    fn backoff(&self) -> Duration {
146        let backoff = self
147            .base_delay
148            .saturating_mul(1u32 << self.attempts.min(16))
149            .min(self.max_delay);
150        if self.jitter {
151            jittered(backoff, random_unit())
152        } else {
153            backoff
154        }
155    }
156}
157
158/// Three retries.
159impl Default for RetryPolicy {
160    fn default() -> Self {
161        Self::new(3)
162    }
163}
164
165/// `backoff` scaled to between half and all of it, by `unit` in `[0, 1)`.
166fn jittered(backoff: Duration, unit: f64) -> Duration {
167    backoff.mul_f64(0.5 + 0.5 * unit)
168}
169
170/// A random number in `[0, 1)`, from the standard library's randomly keyed hasher: good enough to spread retries.
171fn random_unit() -> f64 {
172    use std::hash::{BuildHasher, Hasher};
173    let hash = std::collections::hash_map::RandomState::new()
174        .build_hasher()
175        .finish();
176    (hash >> 11) as f64 / (1u64 << 53) as f64
177}
178
179/// When a response arrived, set by [`RetryLayer`] on a `429` before it reads the body, so that the time spent reading
180/// is not added to the server's `Retry-After`.
181#[derive(Clone, Copy, Debug)]
182struct ReceivedAt(Instant);
183
184/// The clocks a `Retry-After` is read against: `Retry-After` in seconds counts from when the response arrived, an HTTP
185/// date against the wall clock (the time since the Unix epoch), read together with the monotonic one.
186#[derive(Clone, Copy, Debug)]
187struct Clocks {
188    received_at: Instant,
189    now: Instant,
190    wall: Duration,
191}
192
193impl Clocks {
194    fn now<B>(response: &http::Response<B>) -> Self {
195        // The wall clock first, so that a pause between the two reads cannot shorten an HTTP date's deadline.
196        let wall = since_epoch();
197        let now = Instant::now();
198        let received_at = response
199            .extensions()
200            .get::<ReceivedAt>()
201            .map_or(now, |received| received.0);
202        Self {
203            received_at,
204            now,
205            wall,
206        }
207    }
208}
209
210/// Whether a response or error is worth retrying, and the deadline the server set, if any.
211fn retryable<B>(
212    result: &Result<http::Response<B>, BoxError>,
213    server_directed_429: bool,
214    retry_timeouts: bool,
215) -> Option<Option<Instant>> {
216    match result {
217        Ok(response) => {
218            let status = response.status();
219            let transient = status == StatusCode::TOO_MANY_REQUESTS
220                || status == StatusCode::REQUEST_TIMEOUT
221                || status.is_server_error();
222            let permanent = response.extensions().get::<Permanent>().is_some();
223            if !transient || permanent {
224                return None;
225            }
226            let deadline = retry_after(response.headers(), Clocks::now(response));
227            if server_directed_429 && status == StatusCode::TOO_MANY_REQUESTS && deadline.is_none()
228            {
229                #[cfg(feature = "tracing")]
230                tracing::debug!(
231                    target: "timvw_rust_runtime::trace",
232                    status = status.as_u16(),
233                    "not retrying: a 429 without Retry-After (server_directed_429)"
234                );
235                return None;
236            }
237            Some(deadline)
238        }
239        Err(error) => (is_connect(error.as_ref())
240            || (retry_timeouts && crate::error::is_timeout(error.as_ref())))
241        .then_some(None),
242    }
243}
244
245/// The deadline a server sets: `retry-after-ms` in milliseconds, else `Retry-After` in seconds (both may have a
246/// fraction) or as an HTTP date. A date in the past is now.
247fn retry_after(headers: &HeaderMap, clocks: Clocks) -> Option<Instant> {
248    let value = |name| Some(headers.get(name)?.to_str().ok()?.trim());
249    let delay = |value: &str, scale: f64| {
250        let delay = Duration::try_from_secs_f64(value.parse::<f64>().ok()? * scale).ok()?;
251        clocks.received_at.checked_add(delay)
252    };
253    if let Some(deadline) = value(RETRY_AFTER_MS).and_then(|value| delay(value, 0.001)) {
254        return Some(deadline);
255    }
256    let value = value(RETRY_AFTER.as_str())?;
257    delay(value, 1.0).or_else(|| {
258        let date = httpdate::parse_http_date(value).ok()?;
259        let date = date
260            .duration_since(std::time::UNIX_EPOCH)
261            .unwrap_or_default();
262        let delay = date.saturating_sub(clocks.wall);
263        clocks.now.checked_add(delay)
264    })
265}
266
267/// Whether the request failed to connect, so it was not sent and can be sent again. Never on WebAssembly: `fetch`
268/// fails the same way whether or not the request reached the server (and for CORS), so a failure there is not retried.
269#[allow(unused_variables)]
270fn is_connect(error: &(dyn std::error::Error + 'static)) -> bool {
271    #[cfg(all(feature = "reqwest", not(target_family = "wasm")))]
272    {
273        let mut source = Some(error);
274        while let Some(error) = source {
275            if error
276                .downcast_ref::<reqwest::Error>()
277                .is_some_and(reqwest::Error::is_connect)
278            {
279                return true;
280            }
281            source = error.source();
282        }
283    }
284    false
285}
286
287impl<B> Policy<http::Request<Body>, http::Response<B>, BoxError> for RetryPolicy {
288    type Future = BoxFuture<'static, ()>;
289
290    fn retry(
291        &mut self,
292        _request: &mut http::Request<Body>,
293        result: &mut Result<http::Response<B>, BoxError>,
294    ) -> Option<Self::Future> {
295        if self.attempts >= self.max_retries {
296            return None;
297        }
298        let retry_after = retryable(result, self.server_directed_429, self.retry_timeouts)?;
299        let now = Instant::now();
300        let Some(deadline) = self.deadline(retry_after, now) else {
301            #[cfg(feature = "tracing")]
302            tracing::debug!(
303                target: "timvw_rust_runtime::trace",
304                retry_after_ms = retry_after
305                    .map_or(0, |deadline| deadline.saturating_duration_since(now).as_millis() as u64),
306                max_retry_after_ms = self.max_retry_after.as_millis() as u64,
307                status = result.as_ref().ok().map(|response| response.status().as_u16()),
308                "not retrying: the server asks to wait longer than max_retry_after"
309            );
310            return None;
311        };
312        self.attempts += 1;
313        #[cfg(feature = "tracing")]
314        tracing::debug!(
315            target: "timvw_rust_runtime::trace",
316            attempt = self.attempts,
317            max_retries = self.max_retries,
318            delay_ms = deadline.saturating_duration_since(now).as_millis() as u64,
319            status = result.as_ref().ok().map(|response| response.status().as_u16()),
320            "retrying"
321        );
322        Some(Box::pin(Sleep::until(deadline)))
323    }
324
325    fn clone_request(&mut self, request: &http::Request<Body>) -> Option<http::Request<Body>> {
326        let body = request.body().try_clone()?;
327        let mut clone = http::Request::new(body);
328        *clone.method_mut() = request.method().clone();
329        *clone.uri_mut() = request.uri().clone();
330        *clone.version_mut() = request.version();
331        *clone.headers_mut() = request.headers().clone();
332        Some(clone)
333    }
334}
335
336/// A response extension that tells [`RetryPolicy`] not to retry a response it would otherwise retry.
337///
338/// [`RetryLayer::permanent_429`] sets it on a `429` whose body says the error is permanent. A layer of your own, inside
339/// the retries, can set it too: `response.extensions_mut().insert(Permanent)`.
340#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
341pub struct Permanent;
342
343/// Whether the body of a `429` says the error is permanent, such as [`openai_insufficient_quota`].
344type Classifier = Arc<dyn Fn(&[u8]) -> bool + Send + Sync>;
345
346/// OpenAI's "quota exhausted": a JSON body whose `error.code` or `error.type` is `insufficient_quota`.
347///
348/// OpenAI answers `429` both when requests come too fast, which passes, and when the account's quota or credit is
349/// used up, which does not pass by waiting. Use it with [`RetryLayer::permanent_429`].
350pub fn openai_insufficient_quota(body: &[u8]) -> bool {
351    const INSUFFICIENT_QUOTA: &str = "insufficient_quota";
352    let Ok(value) = serde_json::from_slice::<serde_json::Value>(body) else {
353        return false;
354    };
355    ["code", "type"].iter().any(|field| {
356        value
357            .pointer(&format!("/error/{field}"))
358            .and_then(serde_json::Value::as_str)
359            == Some(INSUFFICIENT_QUOTA)
360    })
361}
362
363/// Retries with a [`RetryPolicy`], and optionally reads the body of a `429` to tell a permanent error from a rate
364/// limit first.
365///
366/// `RetryLayer::new(policy)` retries exactly like `tower::retry::RetryLayer::new(policy)`. With
367/// [`RetryLayer::permanent_429`], the body of each `429` is read (up to [`RetryLayer::body_limit`]) and given to a
368/// function; when it returns `true`, the response is marked [`Permanent`] and returned at once. The body is put back,
369/// so the caller (and a generated client's error) still sees all of it.
370///
371/// ```no_run
372/// # #[cfg(feature = "reqwest")]
373/// # fn demo() {
374/// use timvw_rust_runtime::retry::{openai_insufficient_quota, RetryLayer, RetryPolicy};
375/// use timvw_rust_runtime::{Client, ReqwestService};
376///
377/// let client = Client::from_service(ReqwestService::default())
378///     .layer(RetryLayer::new(RetryPolicy::default()).permanent_429(openai_insufficient_quota));
379/// # }
380/// ```
381#[derive(Clone)]
382pub struct RetryLayer {
383    policy: RetryPolicy,
384    classify: Option<Classifier>,
385    body_limit: usize,
386}
387
388impl RetryLayer {
389    /// Retries with `policy`, without reading any body.
390    pub fn new(policy: RetryPolicy) -> Self {
391        Self {
392            policy,
393            classify: None,
394            body_limit: DEFAULT_BODY_LIMIT,
395        }
396    }
397
398    /// Reads the body of each `429` and does not retry it when `is_permanent` returns `true` for the body's bytes.
399    ///
400    /// A body longer than [`RetryLayer::body_limit`], or one that fails to read, is not given to `is_permanent`: the
401    /// response is retried as a rate limit, and the caller still reads the whole body (or its error).
402    pub fn permanent_429<F>(mut self, is_permanent: F) -> Self
403    where
404        F: Fn(&[u8]) -> bool + Send + Sync + 'static,
405    {
406        self.classify = Some(Arc::new(is_permanent));
407        self
408    }
409
410    /// How many bytes of a `429` body are read to classify it (default [`DEFAULT_BODY_LIMIT`], 64 KiB).
411    pub fn body_limit(mut self, limit: usize) -> Self {
412        self.body_limit = limit;
413        self
414    }
415
416    /// The retry policy.
417    pub fn policy(&self) -> &RetryPolicy {
418        &self.policy
419    }
420}
421
422/// Retries with [`RetryPolicy::default`].
423impl Default for RetryLayer {
424    fn default() -> Self {
425        Self::new(RetryPolicy::default())
426    }
427}
428
429impl fmt::Debug for RetryLayer {
430    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
431        f.debug_struct("RetryLayer")
432            .field("policy", &self.policy)
433            .field("permanent_429", &self.classify.is_some())
434            .field("body_limit", &self.body_limit)
435            .finish()
436    }
437}
438
439impl<S> Layer<S> for RetryLayer {
440    type Service = tower::retry::Retry<RetryPolicy, Classify429<S>>;
441
442    fn layer(&self, inner: S) -> Self::Service {
443        tower::retry::Retry::new(
444            self.policy.clone(),
445            Classify429 {
446                inner,
447                classify: self.classify.clone(),
448                body_limit: self.body_limit,
449            },
450        )
451    }
452}
453
454/// The service inside the retries of a [`RetryLayer`]: marks a `429` [`Permanent`] when its body says so.
455#[derive(Clone)]
456pub struct Classify429<S> {
457    inner: S,
458    classify: Option<Classifier>,
459    body_limit: usize,
460}
461
462impl<S: fmt::Debug> fmt::Debug for Classify429<S> {
463    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
464        f.debug_struct("Classify429")
465            .field("inner", &self.inner)
466            .field("permanent_429", &self.classify.is_some())
467            .field("body_limit", &self.body_limit)
468            .finish()
469    }
470}
471
472impl<S, R, B> Service<R> for Classify429<S>
473where
474    S: Service<R, Response = http::Response<B>>,
475    S::Future: MaybeSend + 'static,
476    B: http_body::Body + MaybeSend + MaybeSync + 'static,
477    B::Data: Into<Bytes>,
478    B::Error: Into<BoxError>,
479{
480    type Response = http::Response<Body>;
481    type Error = S::Error;
482    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
483
484    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
485        self.inner.poll_ready(cx)
486    }
487
488    fn call(&mut self, request: R) -> Self::Future {
489        let response = self.inner.call(request);
490        let classify = self.classify.clone();
491        let body_limit = self.body_limit;
492        Box::pin(async move {
493            let mut response = response.await?.map(Body::wrap);
494            Ok(match classify {
495                Some(classify) if response.status() == StatusCode::TOO_MANY_REQUESTS => {
496                    response.extensions_mut().insert(ReceivedAt(Instant::now()));
497                    classify_429(response, &*classify, body_limit).await
498                }
499                _ => response,
500            })
501        })
502    }
503}
504
505/// Reads a `429` body, up to `limit` bytes, marks the response [`Permanent`] if `classify` says so, and puts the body
506/// back.
507async fn classify_429(
508    response: http::Response<Body>,
509    classify: &(dyn Fn(&[u8]) -> bool + Send + Sync),
510    limit: usize,
511) -> http::Response<Body> {
512    let (mut parts, mut body) = response.into_parts();
513    let mut read = BytesMut::new();
514    let body = loop {
515        match body.frame().await {
516            None => {
517                let read = read.freeze();
518                if classify(&read) {
519                    parts.extensions.insert(Permanent);
520                    #[cfg(feature = "tracing")]
521                    tracing::debug!(
522                        target: "timvw_rust_runtime::trace",
523                        status = parts.status.as_u16(),
524                        "not retrying: the body says the error is permanent"
525                    );
526                }
527                break Body::from(read);
528            }
529            // Trailers on a 429 are dropped.
530            Some(Ok(frame)) => {
531                let Ok(data) = frame.into_data() else {
532                    continue;
533                };
534                read.extend_from_slice(&data);
535                if read.len() > limit {
536                    let read = futures_util::stream::once(async move { Ok(read.freeze()) });
537                    break Body::wrap_stream(futures_util::StreamExt::chain(
538                        read,
539                        BodyDataStream::new(body),
540                    ));
541                }
542            }
543            Some(Err(error)) => {
544                break Body::wrap_stream(futures_util::stream::iter([
545                    Ok(read.freeze()),
546                    Err::<Bytes, BoxError>(error),
547                ]));
548            }
549        }
550    };
551    http::Response::from_parts(parts, body)
552}
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557
558    fn response(status: u16, headers: &[(&str, &str)]) -> Result<http::Response<()>, BoxError> {
559        let mut builder = http::Response::builder().status(status);
560        for (name, value) in headers {
561            builder = builder.header(*name, *value);
562        }
563        Ok(builder.body(()).unwrap())
564    }
565
566    /// Whether `result` is retried, and after how long, measured from now.
567    fn wait(
568        result: &Result<http::Response<()>, BoxError>,
569        server_directed_429: bool,
570    ) -> Option<Option<Duration>> {
571        let now = Instant::now();
572        retryable(result, server_directed_429, false)
573            .map(|deadline| deadline.map(|deadline| deadline.saturating_duration_since(now)))
574    }
575
576    #[tokio::test(start_paused = true)]
577    async fn retries_transient_statuses_only() {
578        assert_eq!(wait(&response(429, &[]), false), Some(None));
579        assert_eq!(
580            wait(&response(503, &[("retry-after", "2")]), false),
581            Some(Some(Duration::from_secs(2)))
582        );
583        assert_eq!(wait(&response(408, &[]), false), Some(None));
584        assert_eq!(wait(&response(400, &[]), false), None);
585        assert_eq!(wait(&response(200, &[]), false), None);
586        assert_eq!(wait(&Err("boom".into()), false), None);
587    }
588
589    #[tokio::test(start_paused = true)]
590    async fn server_directed_429_needs_advice() {
591        assert_eq!(wait(&response(429, &[]), true), None);
592        assert_eq!(wait(&response(429, &[("retry-after", "soon")]), true), None);
593        assert_eq!(
594            wait(&response(429, &[("retry-after", "0")]), true),
595            Some(Some(Duration::ZERO))
596        );
597        assert_eq!(
598            wait(&response(429, &[("retry-after-ms", "300")]), true),
599            Some(Some(Duration::from_millis(300)))
600        );
601        let past = httpdate::fmt_http_date(std::time::SystemTime::now() - Duration::from_secs(60));
602        assert_eq!(
603            wait(&response(429, &[("retry-after", &past)]), true),
604            Some(Some(Duration::ZERO))
605        );
606        // Only 429s: other transient statuses back off without advice.
607        assert_eq!(wait(&response(503, &[]), true), Some(None));
608        assert_eq!(wait(&response(408, &[]), true), Some(None));
609    }
610
611    #[tokio::test(start_paused = true)]
612    async fn permanent_responses_are_not_retried() {
613        let mut result = response(429, &[("retry-after", "1")]);
614        result.as_mut().unwrap().extensions_mut().insert(Permanent);
615        assert_eq!(wait(&result, false), None);
616    }
617
618    fn clocks() -> Clocks {
619        let now = Instant::now();
620        Clocks {
621            received_at: now,
622            now,
623            wall: httpdate::parse_http_date("Wed, 21 Oct 2015 07:28:00 GMT")
624                .unwrap()
625                .duration_since(std::time::UNIX_EPOCH)
626                .unwrap(),
627        }
628    }
629
630    fn parse(headers: &[(&str, &str)], clocks: Clocks) -> Option<Duration> {
631        let mut map = HeaderMap::new();
632        for (name, value) in headers {
633            map.append(
634                http::HeaderName::from_bytes(name.as_bytes()).unwrap(),
635                value.parse().unwrap(),
636            );
637        }
638        retry_after(&map, clocks).map(|deadline| deadline.saturating_duration_since(clocks.now))
639    }
640
641    #[tokio::test(start_paused = true)]
642    async fn parses_retry_after_and_retry_after_ms() {
643        let wait = |headers: &[(&str, &str)]| parse(headers, clocks());
644        assert_eq!(
645            wait(&[("retry-after", " 20 ")]),
646            Some(Duration::from_secs(20))
647        );
648        assert_eq!(
649            wait(&[("retry-after", "1.5")]),
650            Some(Duration::from_millis(1500))
651        );
652        assert_eq!(
653            wait(&[("retry-after-ms", "250"), ("retry-after", "1")]),
654            Some(Duration::from_millis(250))
655        );
656        assert_eq!(
657            wait(&[("retry-after-ms", "12.5")]),
658            Some(Duration::from_micros(12_500))
659        );
660        assert_eq!(wait(&[("retry-after", "-1")]), None);
661        assert_eq!(wait(&[("retry-after", "")]), None);
662        assert_eq!(wait(&[("retry-after", "later")]), None);
663        assert_eq!(
664            wait(&[("retry-after-ms", "nan"), ("retry-after", "3")]),
665            Some(Duration::from_secs(3))
666        );
667        assert_eq!(wait(&[]), None);
668    }
669
670    #[tokio::test(start_paused = true)]
671    async fn parses_http_dates_against_the_wall_clock() {
672        let wait = |value: &str| parse(&[("retry-after", value)], clocks());
673        // The wall clock of `clocks()` is 07:28:00.
674        assert_eq!(
675            wait("Wed, 21 Oct 2015 07:28:30 GMT"),
676            Some(Duration::from_secs(30))
677        );
678        assert_eq!(wait("Wed, 21 Oct 2015 07:28:00 GMT"), Some(Duration::ZERO));
679        assert_eq!(wait("Wed, 21 Oct 2015 07:00:00 GMT"), Some(Duration::ZERO));
680        // The obsolete formats HTTP still accepts.
681        assert_eq!(
682            wait("Wednesday, 21-Oct-15 07:29:00 GMT"),
683            Some(Duration::from_secs(60))
684        );
685        assert_eq!(
686            wait("Wed Oct 21 07:28:05 2015"),
687            Some(Duration::from_secs(5))
688        );
689    }
690
691    #[tokio::test(start_paused = true)]
692    async fn seconds_count_from_receipt_and_dates_from_now() {
693        let mut clocks = clocks();
694        clocks.now = clocks.received_at + Duration::from_secs(2); // two seconds reading the body
695        assert_eq!(
696            parse(&[("retry-after", "5")], clocks),
697            Some(Duration::from_secs(3))
698        );
699        assert_eq!(
700            parse(&[("retry-after-ms", "1000")], clocks),
701            Some(Duration::ZERO)
702        );
703        assert_eq!(
704            parse(&[("retry-after", "Wed, 21 Oct 2015 07:28:05 GMT")], clocks),
705            Some(Duration::from_secs(5))
706        );
707    }
708
709    #[tokio::test(start_paused = true)]
710    async fn backs_off_and_caps() {
711        let mut policy = RetryPolicy::new(10)
712            .base_delay(Duration::from_millis(100))
713            .max_delay(Duration::from_secs(1))
714            .jitter(false);
715        let now = Instant::now();
716        assert_eq!(
717            policy.deadline(None, now),
718            Some(now + Duration::from_millis(100))
719        );
720        policy.attempts = 2;
721        assert_eq!(
722            policy.deadline(None, now),
723            Some(now + Duration::from_millis(400))
724        );
725        policy.attempts = 8;
726        assert_eq!(
727            policy.deadline(None, now),
728            Some(now + Duration::from_secs(1))
729        );
730    }
731
732    #[tokio::test(start_paused = true)]
733    async fn honours_retry_after_beyond_max_delay_up_to_max_retry_after() {
734        let policy = RetryPolicy::new(3).max_delay(Duration::from_secs(1));
735        let now = Instant::now();
736        let after = |secs| Some(now + Duration::from_secs(secs));
737        assert_eq!(policy.deadline(after(30), now), after(30));
738        assert_eq!(policy.deadline(after(60), now), after(60));
739        assert_eq!(policy.deadline(after(61), now), None);
740        // A deadline already passed is kept: retry now.
741        assert_eq!(
742            policy.deadline(Some(now), now + Duration::from_secs(1)),
743            Some(now)
744        );
745        let policy = policy.max_retry_after(Duration::from_secs(5));
746        assert_eq!(policy.deadline(after(6), now), None);
747    }
748
749    #[tokio::test(start_paused = true)]
750    async fn jitter_stays_between_half_and_all_of_the_backoff() {
751        let backoff = Duration::from_millis(800);
752        assert_eq!(jittered(backoff, 0.0), Duration::from_millis(400));
753        assert_eq!(jittered(backoff, 0.5), Duration::from_millis(600));
754        assert!(jittered(backoff, 0.999_999) <= backoff);
755
756        let mut policy = RetryPolicy::new(10)
757            .base_delay(Duration::from_millis(100))
758            .max_delay(Duration::from_secs(1));
759        policy.attempts = 3; // 800 ms before jitter
760        let delays: Vec<_> = (0..200).map(|_| policy.backoff()).collect();
761        for delay in &delays {
762            assert!(
763                (Duration::from_millis(400)..=backoff).contains(delay),
764                "{delay:?}"
765            );
766        }
767        assert!(delays.iter().any(|delay| *delay != delays[0]), "random");
768        // The waits a server asks for are not jittered.
769        let now = Instant::now();
770        let deadline = Some(now + Duration::from_secs(2));
771        assert_eq!(policy.deadline(deadline, now), deadline);
772    }
773
774    #[test]
775    fn random_unit_is_in_range() {
776        for _ in 0..1000 {
777            assert!((0.0..1.0).contains(&random_unit()));
778        }
779    }
780
781    #[test]
782    fn recognises_openai_insufficient_quota() {
783        assert!(openai_insufficient_quota(
784            br#"{"error":{"message":"You exceeded your current quota","type":"insufficient_quota","param":null,"code":"insufficient_quota"}}"#
785        ));
786        assert!(openai_insufficient_quota(
787            br#"{"error":{"type":"insufficient_quota"}}"#
788        ));
789        assert!(openai_insufficient_quota(
790            br#"{"error":{"type":"requests","code":"insufficient_quota"}}"#
791        ));
792        assert!(!openai_insufficient_quota(
793            br#"{"error":{"message":"Rate limit reached","type":"requests","code":"rate_limit_exceeded"}}"#
794        ));
795        assert!(!openai_insufficient_quota(b"insufficient_quota"));
796        assert!(!openai_insufficient_quota(b""));
797    }
798
799    #[test]
800    fn only_bodies_in_memory_are_cloned() {
801        let mut policy = RetryPolicy::default();
802        let mut clone_request = |request: &http::Request<Body>| {
803            Policy::<_, http::Response<()>, BoxError>::clone_request(&mut policy, request)
804        };
805        let request = http::Request::post("https://example.com")
806            .header("x", "1")
807            .body(Body::from("a"))
808            .unwrap();
809        let clone = clone_request(&request).unwrap();
810        assert_eq!(clone.uri(), request.uri());
811        assert_eq!(clone.headers()["x"], "1");
812        let chunks =
813            futures_util::stream::iter(vec![Ok::<_, std::io::Error>(bytes::Bytes::from("a"))]);
814        let streamed = http::Request::post("https://example.com")
815            .body(Body::wrap_stream(chunks))
816            .unwrap();
817        assert!(clone_request(&streamed).is_none());
818    }
819
820    fn body_429(chunks: Vec<Result<&'static str, &'static str>>) -> http::Response<Body> {
821        let stream = futures_util::stream::iter(
822            chunks
823                .into_iter()
824                .map(|chunk| chunk.map(Bytes::from).map_err(BoxError::from)),
825        );
826        http::Response::builder()
827            .status(429)
828            .body(Body::wrap_stream(stream))
829            .unwrap()
830    }
831
832    #[tokio::test]
833    async fn classifies_the_whole_body_and_puts_it_back() {
834        let response = body_429(vec![
835            Ok(r#"{"error":{"type":"#),
836            Ok(r#""insufficient_quota"}}"#),
837        ]);
838        let response = classify_429(response, &openai_insufficient_quota, 1024).await;
839        assert!(response.extensions().get::<Permanent>().is_some());
840        let body = response.into_body().collect_bytes().await.unwrap();
841        assert_eq!(body, r#"{"error":{"type":"insufficient_quota"}}"#);
842    }
843
844    #[tokio::test]
845    async fn a_body_over_the_limit_is_not_classified_but_kept_whole() {
846        let response = body_429(vec![Ok("0123"), Ok("4567"), Ok("89")]);
847        let response = classify_429(response, &|_: &[u8]| true, 5).await;
848        assert!(response.extensions().get::<Permanent>().is_none());
849        let body = response.into_body().collect_bytes().await.unwrap();
850        assert_eq!(body, "0123456789");
851    }
852
853    #[tokio::test]
854    async fn a_body_that_fails_is_not_classified_and_keeps_its_error() {
855        let response = body_429(vec![Ok("01"), Err("reset")]);
856        let response = classify_429(response, &|_: &[u8]| true, 1024).await;
857        assert!(response.extensions().get::<Permanent>().is_none());
858        let error = response.into_body().collect_bytes().await.unwrap_err();
859        assert_eq!(error.to_string(), "reset");
860    }
861}