Skip to main content

vtcode_commons/
http.rs

1//! HTTP client utilities
2//!
3//! Timeouts here are **defaults, not laws**. A 5-second connect timeout is fine
4//! for a warm cache next to the registry and wrong for a first-ever TLS
5//! handshake over a slow link; a 30-second request timeout is generous for a
6//! metadata fetch and fatal for a cold-start local model. Callers that know
7//! better can pass explicit values, and users can override the defaults through
8//! `[timeouts] http_connect_seconds` / `http_request_seconds` /
9//! `http_download_seconds` (or the `VTCODE_HTTP_*_TIMEOUT_SECS` env vars), which
10//! reach this module via [`install_http_timeouts`].
11//!
12//! This module is the home of the timeout policy, so it is the one place that
13//! may build a bare `ClientBuilder`. Every other crate must go through the
14//! helpers below so the installed budgets apply.
15
16#![allow(
17    clippy::disallowed_methods,
18    reason = "This module implements the shared timeout policy; bare builders are the policy's own building blocks."
19)]
20
21use anyhow::anyhow;
22use reqwest::{Client, ClientBuilder};
23use std::future::Future;
24use std::sync::LazyLock;
25use std::time::Duration;
26
27use crate::retry::RetryPolicy;
28
29/// Default connect timeout for outbound HTTP clients.
30const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
31/// Default whole-request timeout for outbound HTTP clients.
32const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
33/// Default timeout for large artifact transfers (release downloads, assets).
34const DEFAULT_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(300);
35
36/// Resolved HTTP timeout defaults shared by every outbound client.
37///
38/// `None` means "no timeout of this kind" — reqwest then leaves the phase
39/// unbounded, which is the documented meaning of a `0` in `[timeouts]`. Keeping
40/// the distinction in the type (rather than a `Duration::ZERO` sentinel) means
41/// call sites cannot accidentally install a zero deadline that fails instantly.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct HttpTimeouts {
44    /// Timeout for the TCP/TLS connect phase.
45    pub connect: Option<Duration>,
46    /// Timeout for the whole request, including the response body.
47    pub request: Option<Duration>,
48    /// Timeout for large artifact transfers.
49    pub download: Option<Duration>,
50}
51
52/// Post-quantum TLS key-exchange policy for Rustls clients.
53///
54/// `Require` enforces hybrid ML-KEM key exchange and AES-256-GCM. It does not
55/// provide post-quantum certificate authentication; Rustls still verifies
56/// certificates with its configured signature algorithms.
57#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
58#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
59#[serde(rename_all = "snake_case")]
60pub enum PostQuantumTlsPolicy {
61    /// Prefer hybrid ML-KEM while retaining classical interoperability.
62    #[default]
63    Prefer,
64    /// Reject handshakes that cannot use hybrid ML-KEM and AES-256-GCM.
65    Require,
66}
67
68impl Default for HttpTimeouts {
69    fn default() -> Self {
70        Self {
71            connect: Some(DEFAULT_CONNECT_TIMEOUT),
72            request: Some(DEFAULT_REQUEST_TIMEOUT),
73            download: Some(DEFAULT_DOWNLOAD_TIMEOUT),
74        }
75    }
76}
77
78impl HttpTimeouts {
79    /// Resolve a configured number of `[timeouts]` seconds into an optional
80    /// duration, where `0` disables the phase.
81    #[must_use]
82    pub const fn from_seconds(connect: u64, request: u64, download: u64) -> Self {
83        Self {
84            connect: duration_or_disabled(connect),
85            request: duration_or_disabled(request),
86            download: duration_or_disabled(download),
87        }
88    }
89
90    /// Apply the connect and request phases to a builder, skipping disabled
91    /// phases instead of installing a zero deadline.
92    fn apply_to(self, mut builder: ClientBuilder) -> ClientBuilder {
93        if let Some(request) = self.request {
94            builder = builder.timeout(request);
95        }
96        if let Some(connect) = self.connect {
97            builder = builder.connect_timeout(connect);
98        }
99        builder
100    }
101}
102
103/// `0` means "disabled" throughout `[timeouts]`; keep that convention here so an
104/// explicit `0` never turns into an instant-fail `Duration::ZERO` deadline.
105const fn duration_or_disabled(seconds: u64) -> Option<Duration> {
106    if seconds == 0 {
107        None
108    } else {
109        Some(Duration::from_secs(seconds))
110    }
111}
112
113static HTTP_TIMEOUTS: LazyLock<arc_swap::ArcSwap<HttpTimeouts>> =
114    LazyLock::new(|| arc_swap::ArcSwap::from_pointee(HttpTimeouts::default()));
115
116static HTTP_TLS_POLICY: LazyLock<std::sync::Mutex<Option<PostQuantumTlsPolicy>>> =
117    LazyLock::new(|| std::sync::Mutex::new(None));
118
119/// Install the process-wide Rustls policy before creating outbound clients.
120///
121/// reqwest uses `CryptoProvider::get_default()` when one is installed and
122/// otherwise falls back to `ring`, which has no ML-KEM support. aws-lc-rs
123/// offers the X25519MLKEM768 hybrid exchange. `Require` filters the provider to
124/// that key exchange and TLS 1.3 AES-256-GCM; its lack of a TLS 1.2-capable key
125/// exchange prevents a classical protocol downgrade.
126///
127/// The process-wide Rustls provider cannot be replaced after installation.
128/// Changing the configured policy therefore requires restarting the process.
129pub fn install_http_tls_policy(policy: PostQuantumTlsPolicy) -> anyhow::Result<()> {
130    let mut installed_policy = HTTP_TLS_POLICY
131        .lock()
132        .map_err(|error| anyhow!("HTTP TLS policy state is poisoned: {error}"))?;
133
134    validate_policy_change(*installed_policy, policy)?;
135    if installed_policy.is_some() {
136        return Ok(());
137    }
138
139    install_crypto_provider(policy)?;
140    *installed_policy = Some(policy);
141    Ok(())
142}
143
144fn validate_policy_change(
145    installed: Option<PostQuantumTlsPolicy>,
146    requested: PostQuantumTlsPolicy,
147) -> anyhow::Result<()> {
148    if installed.is_some_and(|installed| installed != requested) {
149        return Err(anyhow!(
150            "HTTP TLS policy cannot change from {:?} to {requested:?} after startup; restart VT Code",
151            installed
152        ));
153    }
154    Ok(())
155}
156
157/// The effective process-wide Rustls policy; defaults to `Prefer` before setup.
158pub fn post_quantum_tls_policy() -> anyhow::Result<PostQuantumTlsPolicy> {
159    let installed_policy = HTTP_TLS_POLICY
160        .lock()
161        .map_err(|error| anyhow!("HTTP TLS policy state is poisoned: {error}"))?;
162    Ok((*installed_policy).unwrap_or_default())
163}
164
165/// Build the aws-lc-rs provider used by VT Code's custom Rustls clients.
166///
167/// Custom clients must use this function rather than constructing an
168/// unfiltered provider so `Require` cannot be bypassed.
169pub fn rustls_crypto_provider() -> anyhow::Result<rustls::crypto::CryptoProvider> {
170    crypto_provider(post_quantum_tls_policy()?)
171}
172
173fn crypto_provider(policy: PostQuantumTlsPolicy) -> anyhow::Result<rustls::crypto::CryptoProvider> {
174    let mut provider = rustls::crypto::aws_lc_rs::default_provider();
175    if policy == PostQuantumTlsPolicy::Require {
176        provider
177            .kx_groups
178            .retain(|group| group.name() == rustls::NamedGroup::X25519MLKEM768);
179        provider
180            .cipher_suites
181            .retain(|suite| suite.suite() == rustls::CipherSuite::TLS13_AES_256_GCM_SHA384);
182        validate_strict_provider(&provider)?;
183    }
184    Ok(provider)
185}
186
187fn validate_strict_provider(provider: &rustls::crypto::CryptoProvider) -> anyhow::Result<()> {
188    if provider.kx_groups.len() != 1
189        || provider
190            .kx_groups
191            .first()
192            .is_none_or(|group| group.name() != rustls::NamedGroup::X25519MLKEM768)
193        || provider.cipher_suites.len() != 1
194        || provider
195            .cipher_suites
196            .first()
197            .is_none_or(|suite| suite.suite() != rustls::CipherSuite::TLS13_AES_256_GCM_SHA384)
198    {
199        return Err(anyhow!("strict post-quantum TLS requires only X25519MLKEM768 and TLS13_AES_256_GCM_SHA384"));
200    }
201    Ok(())
202}
203
204fn install_crypto_provider(policy: PostQuantumTlsPolicy) -> anyhow::Result<()> {
205    if let Some(provider) = rustls::crypto::CryptoProvider::get_default() {
206        return if policy == PostQuantumTlsPolicy::Require {
207            validate_strict_provider(provider)
208        } else {
209            Ok(())
210        };
211    }
212
213    let provider = crypto_provider(policy)?;
214    if provider.clone().install_default().is_ok() {
215        return Ok(());
216    }
217
218    let installed = rustls::crypto::CryptoProvider::get_default()
219        .ok_or_else(|| anyhow!("Rustls default provider installation failed"))?;
220    if policy == PostQuantumTlsPolicy::Require {
221        validate_strict_provider(installed)?;
222    }
223    Ok(())
224}
225
226fn initialize_default_tls_policy() -> anyhow::Result<()> {
227    let mut installed_policy = HTTP_TLS_POLICY
228        .lock()
229        .map_err(|error| anyhow!("HTTP TLS policy state is poisoned: {error}"))?;
230    if installed_policy.is_none() {
231        install_crypto_provider(PostQuantumTlsPolicy::Prefer)?;
232        *installed_policy = Some(PostQuantumTlsPolicy::Prefer);
233    }
234    Ok(())
235}
236
237/// Install process-wide HTTP timeout defaults and the post-quantum TLS provider.
238///
239/// Called once at startup from the loaded configuration and again on live
240/// reload, so `[timeouts]` edits apply without a restart. Clients already built
241/// keep the values they were created with; new clients pick these up. This
242/// compatibility entry point initializes the TLS policy to `Prefer` if no
243/// explicit policy has been installed.
244pub fn install_http_timeouts(timeouts: HttpTimeouts) {
245    if let Err(error) = initialize_default_tls_policy() {
246        tracing::error!(%error, "failed to initialize the default HTTP TLS policy");
247    }
248    HTTP_TIMEOUTS.store(std::sync::Arc::new(timeouts));
249}
250
251/// Current process-wide HTTP timeout defaults.
252#[must_use]
253pub fn http_timeouts() -> HttpTimeouts {
254    **HTTP_TIMEOUTS.load()
255}
256
257fn apply_platform_proxy_policy(builder: ClientBuilder) -> ClientBuilder {
258    #[cfg(target_os = "macos")]
259    {
260        // Avoid system proxy discovery on macOS because it can panic in restricted environments.
261        builder.no_proxy()
262    }
263    #[cfg(not(target_os = "macos"))]
264    {
265        builder
266    }
267}
268
269/// Try to build an HTTP client, returning an error if both primary and fallback builders fail.
270///
271/// This is the fallible version of `build_client`. Use this when you want to handle
272/// the error gracefully (e.g., return an error to the caller) instead of panicking.
273fn try_build_client<F>(configure: F) -> Result<Client, reqwest::Error>
274where
275    F: Fn(ClientBuilder) -> ClientBuilder,
276{
277    let primary_builder = configure(apply_platform_proxy_policy(ClientBuilder::new()));
278    match primary_builder.build() {
279        Ok(client) => Ok(client),
280        Err(primary_err) => {
281            let fallback_builder = HttpTimeouts::default().apply_to(apply_platform_proxy_policy(ClientBuilder::new()));
282            match fallback_builder.build() {
283                Ok(client) => Ok(client),
284                Err(fallback_err) => {
285                    tracing::error!(
286                        primary_error = %primary_err,
287                        fallback_error = %fallback_err,
288                        "HTTP client creation failed with both primary and fallback configurations"
289                    );
290                    Err(fallback_err)
291                }
292            }
293        }
294    }
295}
296
297/// Create a default HTTP client with standard timeouts.
298///
299/// Falls back to a bare default client if the configured builder and its
300/// fallback both fail (e.g., TLS misconfiguration, resource exhaustion).
301/// The fallback mirrors the resilience pattern in `http_client_pool`: a
302/// `tracing::error!` is logged so the failure is observable, but the process
303/// does not crash — callers get a working (if unconfigured) client.
304fn build_client<F>(configure: F) -> Client
305where
306    F: Fn(ClientBuilder) -> ClientBuilder,
307{
308    try_build_client(configure).unwrap_or_else(|e| {
309        tracing::error!(
310            error = %e,
311            "HTTP client build failed (primary + fallback); falling back to bare default client. \
312             This usually indicates a TLS configuration issue or system resource exhaustion."
313        );
314        Client::new()
315    })
316}
317
318/// Create a default HTTP client with the installed timeout defaults.
319pub fn create_default_client() -> Client {
320    build_client(|builder| http_timeouts().apply_to(builder))
321}
322
323/// Create an HTTP client with a custom request timeout.
324///
325/// The connect phase keeps the installed default so a stalled TCP/TLS handshake
326/// never inherits the (usually much longer) request budget.
327pub fn create_client_with_timeout(timeout: Duration) -> Client {
328    let connect = http_timeouts().connect;
329    build_client(move |builder| {
330        let builder = builder.timeout(timeout);
331        match connect {
332            Some(connect) => builder.connect_timeout(connect),
333            None => builder,
334        }
335    })
336}
337
338/// Create an HTTP client with custom connect and request timeouts.
339pub fn create_client_with_timeouts(connect_timeout: Duration, request_timeout: Duration) -> Client {
340    build_client(|builder| builder.timeout(request_timeout).connect_timeout(connect_timeout))
341}
342
343/// Maximum followed redirects in the same-origin policy (mirrors reqwest's default limit).
344const SAME_ORIGIN_REDIRECT_LIMIT: usize = 10;
345
346/// Redirect policy that follows only same-origin redirects without a scheme downgrade.
347///
348/// Credentialed API clients must not follow cross-origin redirects: reqwest strips only the
349/// `Authorization`/`Cookie`-family headers there, so custom key headers (`x-api-key`,
350/// `x-goog-api-key`, `anthropic-version`) would replay to the redirect target. Same-origin
351/// redirects (trailing-slash normalization, `http`→`https` upgrades on self-hosted gateways)
352/// stay within the origin the caller already trusts with the key, so they are followed.
353/// Cross-origin targets, `https`→`http` downgrades, and redirect loops stop with the 3xx
354/// response instead of an error, matching `Policy::none` surfacing so provider error paths
355/// handle both uniformly.
356pub fn same_origin_redirect_policy() -> reqwest::redirect::Policy {
357    reqwest::redirect::Policy::custom(|attempt| {
358        if attempt.previous().len() > SAME_ORIGIN_REDIRECT_LIMIT {
359            return attempt.stop();
360        }
361        let next = attempt.url();
362        let allowed = attempt
363            .previous()
364            .last()
365            .is_some_and(|previous| redirect_target_allowed(next, previous));
366        if allowed { attempt.follow() } else { attempt.stop() }
367    })
368}
369
370/// Whether a redirect from `previous` to `next` may be followed with credentials attached.
371///
372/// Same host and same effective port (mirroring reqwest's own cross-host notion), except the
373/// standard `http`→`https` upgrade; `https`→`http` downgrades never qualify. A missing host
374/// fails closed.
375fn redirect_target_allowed(next: &reqwest::Url, previous: &reqwest::Url) -> bool {
376    if next.host_str().is_none() || next.host_str() != previous.host_str() {
377        return false;
378    }
379    if previous.scheme() == "https" && next.scheme() == "http" {
380        return false;
381    }
382    next.port_or_known_default() == previous.port_or_known_default()
383        || (previous.scheme() == "http" && next.scheme() == "https")
384}
385
386/// Create an origin-bound HTTP client with custom connect and request timeouts.
387///
388/// Credentials never leave the configured origin: same-origin redirects are followed while
389/// cross-origin targets stop (see [`same_origin_redirect_policy`]). The fallback path keeps
390/// the same policy — a timeout misconfiguration must not silently re-enable following.
391pub fn create_origin_bound_client_with_timeouts(connect_timeout: Duration, request_timeout: Duration) -> Client {
392    let build = |connect: Duration, request: Duration| {
393        apply_platform_proxy_policy(ClientBuilder::new())
394            .timeout(request)
395            .connect_timeout(connect)
396            .redirect(same_origin_redirect_policy())
397            .build()
398    };
399    match build(connect_timeout, request_timeout) {
400        Ok(client) => client,
401        Err(primary_err) => {
402            let fallback = HttpTimeouts::default()
403                .apply_to(apply_platform_proxy_policy(ClientBuilder::new()))
404                .redirect(same_origin_redirect_policy())
405                .build();
406            match fallback {
407                Ok(client) => client,
408                Err(fallback_err) => {
409                    tracing::error!(
410                        primary_error = %primary_err,
411                        fallback_error = %fallback_err,
412                        "Origin-bound HTTP client creation failed; falling back to a bare origin-bound client"
413                    );
414                    ClientBuilder::new()
415                        .redirect(same_origin_redirect_policy())
416                        .build()
417                        .unwrap_or_else(|_| Client::new())
418                }
419            }
420        }
421    }
422}
423
424/// Build an origin-bound client without a fallback that could enable redirects.
425pub fn create_client_without_redirects(
426    connect_timeout: Duration,
427    request_timeout: Duration,
428) -> Result<Client, reqwest::Error> {
429    apply_platform_proxy_policy(ClientBuilder::new())
430        .timeout(request_timeout)
431        .connect_timeout(connect_timeout)
432        .redirect(reqwest::redirect::Policy::none())
433        .build()
434}
435
436/// Build an origin-bound client without redirects, using the installed defaults.
437///
438/// For call sites that must not follow redirects (credentials could otherwise be
439/// replayed to a new origin) but still need a bounded request.
440pub fn create_default_client_without_redirects() -> Result<Client, reqwest::Error> {
441    let timeouts = http_timeouts();
442    let mut builder = apply_platform_proxy_policy(ClientBuilder::new()).redirect(reqwest::redirect::Policy::none());
443    if let Some(request) = timeouts.request {
444        builder = builder.timeout(request);
445    }
446    if let Some(connect) = timeouts.connect {
447        builder = builder.connect_timeout(connect);
448    }
449    builder.build()
450}
451
452/// Create an HTTP client with a specific user agent.
453pub fn create_client_with_user_agent(user_agent: &str) -> Client {
454    let timeouts = http_timeouts();
455    build_client(move |mut builder| {
456        builder = builder.user_agent(user_agent);
457        timeouts.apply_to(builder)
458    })
459}
460
461/// Create an origin-bound streaming HTTP client.
462///
463/// Same credential-replay rationale as [`create_origin_bound_client_with_timeouts`]:
464/// streaming LLM responses carry API-key headers on the initiating request, so cross-origin
465/// redirects stop instead of replaying them. No whole-request timeout by design (see
466/// [`create_streaming_client`]); the connect phase stays bounded.
467pub fn create_origin_bound_streaming_client() -> Client {
468    let connect = http_timeouts().connect;
469    let build = |builder: ClientBuilder| {
470        let builder = builder
471            .tcp_keepalive(Some(Duration::from_secs(60)))
472            .redirect(same_origin_redirect_policy());
473        match connect {
474            Some(connect) => builder.connect_timeout(connect),
475            None => builder,
476        }
477    };
478    match build(apply_platform_proxy_policy(ClientBuilder::new())).build() {
479        Ok(client) => client,
480        Err(primary_err) => {
481            tracing::error!(
482                primary_error = %primary_err,
483                "Origin-bound streaming HTTP client creation failed; using bare origin-bound client"
484            );
485            ClientBuilder::new()
486                .redirect(same_origin_redirect_policy())
487                .build()
488                .unwrap_or_else(|_| Client::new())
489        }
490    }
491}
492
493/// Create an HTTP client optimized for streaming.
494///
495/// Streaming intentionally has **no** whole-request timeout: a chat completion
496/// that trickles tokens for longer than the request budget is healthy, not hung.
497/// The connect phase stays bounded, and callers that need a stall detector should
498/// set an idle/`read_timeout` instead of a total deadline.
499///
500/// This variant follows redirects. Credentialed callers must use
501/// [`create_origin_bound_streaming_client`] instead.
502pub fn create_streaming_client() -> Client {
503    let connect = http_timeouts().connect;
504    build_client(move |builder| {
505        let builder = builder.tcp_keepalive(Some(Duration::from_secs(60)));
506        match connect {
507            Some(connect) => builder.connect_timeout(connect),
508            None => builder,
509        }
510    })
511}
512
513/// Create a client for large artifact transfers (release downloads, assets).
514///
515/// Uses the installed `download` budget instead of the request budget: a
516/// multi-megabyte archive on a cold cache routinely needs longer than the
517/// interactive request default, and failing it silently is how installers end up
518/// "hanging for 60 seconds and dying" on slower connections.
519pub fn create_download_client(user_agent: &str) -> Client {
520    let timeouts = http_timeouts();
521    build_client(move |mut builder| {
522        builder = builder.user_agent(user_agent).tcp_keepalive(Some(Duration::from_secs(60)));
523        if let Some(download) = timeouts.download {
524            builder = builder.timeout(download);
525        }
526        if let Some(connect) = timeouts.connect {
527            builder = builder.connect_timeout(connect);
528        }
529        builder
530    })
531}
532
533/// Get a default client or create one
534pub fn get_or_create_default_client(existing: Option<Client>) -> Client {
535    existing.unwrap_or_else(create_default_client)
536}
537
538/// Apply the installed connect budget to an explicit client builder.
539///
540/// Prefer the `create_*` constructors; use this only where a call site needs
541/// builder options they do not offer (redirect or retry policy tweaks).
542/// A `None` budget (the phase was disabled) leaves the builder untouched.
543pub fn apply_connect_timeout(builder: ClientBuilder) -> ClientBuilder {
544    match http_timeouts().connect {
545        Some(connect) => builder.connect_timeout(connect),
546        None => builder,
547    }
548}
549
550/// Send one request per attempt with capped exponential backoff and jitter.
551///
552/// The caller rebuilds the request on every attempt via `make_request` (a
553/// `RequestBuilder` is consumed by `send()`, so it cannot be reused).
554/// Transport failures (connect errors, timeouts) are retried; builder errors
555/// fail fast because retrying a malformed request can never succeed.
556/// Responses with a retryable status (429/500/502/503/504 per
557/// [`RetryPolicy::classify_status`]) are retried while attempts remain;
558/// otherwise the final response is returned for the caller to handle.
559///
560/// This is the shared helper for idempotent background fetches (release
561/// metadata, asset downloads, catalog refreshes). Interactive LLM requests
562/// must NOT use it: the runloop already retries those under its own budget,
563/// and stacking a transport retry underneath would multiply dispatches and
564/// provider billing.
565///
566/// What this does NOT do: it never honors `Retry-After` (policy backoff
567/// only; `Retry-After` cooperation stays at the tool-registry layer where the
568/// server relationship exists), and it never retries a response body failure —
569/// only the initial `send()`.
570pub async fn send_with_retry<F, Fut>(policy: &RetryPolicy, make_request: F) -> Result<reqwest::Response, reqwest::Error>
571where
572    F: Fn() -> Fut,
573    Fut: Future<Output = Result<reqwest::Response, reqwest::Error>>,
574{
575    send_with_retry_inner(policy, true, make_request).await
576}
577
578/// Retry only when no response was received (transport failure), never on an
579/// HTTP status. For non-idempotent OAuth token POSTs: an authorization code
580/// may already be consumed when a 5xx arrives, so a status-triggered retry
581/// would just burn the login; a transport error means the server likely never
582/// saw the request, making one more attempt strictly better than failing.
583pub async fn send_with_retry_transport_only<F, Fut>(
584    policy: &RetryPolicy,
585    make_request: F,
586) -> Result<reqwest::Response, reqwest::Error>
587where
588    F: Fn() -> Fut,
589    Fut: Future<Output = Result<reqwest::Response, reqwest::Error>>,
590{
591    send_with_retry_inner(policy, false, make_request).await
592}
593
594async fn send_with_retry_inner<F, Fut>(
595    policy: &RetryPolicy,
596    retry_status: bool,
597    make_request: F,
598) -> Result<reqwest::Response, reqwest::Error>
599where
600    F: Fn() -> Fut,
601    Fut: Future<Output = Result<reqwest::Response, reqwest::Error>>,
602{
603    // Termination variant: `attempt` rises toward `attempts`, and the `last`
604    // arm returns on the final iteration, so the loop always exits.
605    let attempts = policy.max_attempts.max(1);
606    let mut attempt: u32 = 0;
607    loop {
608        if attempt > 0 {
609            tokio::time::sleep(policy.delay_for_attempt(attempt - 1)).await;
610        }
611        let last = attempt + 1 >= attempts;
612        match make_request().await {
613            Ok(response) if !retry_status || last || !policy.classify_status(response.status().as_u16()).retryable => {
614                return Ok(response);
615            }
616            Ok(_) => {}
617            Err(error) if error.is_builder() || last => return Err(error),
618            Err(_) => {}
619        }
620        attempt += 1;
621    }
622}
623
624#[cfg(test)]
625mod tests;