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 reqwest::{Client, ClientBuilder};
22use std::future::Future;
23use std::sync::LazyLock;
24use std::time::Duration;
25
26use crate::retry::RetryPolicy;
27
28/// Default connect timeout for outbound HTTP clients.
29const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
30/// Default whole-request timeout for outbound HTTP clients.
31const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
32/// Default timeout for large artifact transfers (release downloads, assets).
33const DEFAULT_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(300);
34
35/// Resolved HTTP timeout defaults shared by every outbound client.
36///
37/// `None` means "no timeout of this kind" — reqwest then leaves the phase
38/// unbounded, which is the documented meaning of a `0` in `[timeouts]`. Keeping
39/// the distinction in the type (rather than a `Duration::ZERO` sentinel) means
40/// call sites cannot accidentally install a zero deadline that fails instantly.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub struct HttpTimeouts {
43    /// Timeout for the TCP/TLS connect phase.
44    pub connect: Option<Duration>,
45    /// Timeout for the whole request, including the response body.
46    pub request: Option<Duration>,
47    /// Timeout for large artifact transfers.
48    pub download: Option<Duration>,
49}
50
51impl Default for HttpTimeouts {
52    fn default() -> Self {
53        Self {
54            connect: Some(DEFAULT_CONNECT_TIMEOUT),
55            request: Some(DEFAULT_REQUEST_TIMEOUT),
56            download: Some(DEFAULT_DOWNLOAD_TIMEOUT),
57        }
58    }
59}
60
61impl HttpTimeouts {
62    /// Resolve a configured number of `[timeouts]` seconds into an optional
63    /// duration, where `0` disables the phase.
64    #[must_use]
65    pub const fn from_seconds(connect: u64, request: u64, download: u64) -> Self {
66        Self {
67            connect: duration_or_disabled(connect),
68            request: duration_or_disabled(request),
69            download: duration_or_disabled(download),
70        }
71    }
72
73    /// Apply the connect and request phases to a builder, skipping disabled
74    /// phases instead of installing a zero deadline.
75    fn apply_to(self, mut builder: ClientBuilder) -> ClientBuilder {
76        if let Some(request) = self.request {
77            builder = builder.timeout(request);
78        }
79        if let Some(connect) = self.connect {
80            builder = builder.connect_timeout(connect);
81        }
82        builder
83    }
84}
85
86/// `0` means "disabled" throughout `[timeouts]`; keep that convention here so an
87/// explicit `0` never turns into an instant-fail `Duration::ZERO` deadline.
88const fn duration_or_disabled(seconds: u64) -> Option<Duration> {
89    if seconds == 0 {
90        None
91    } else {
92        Some(Duration::from_secs(seconds))
93    }
94}
95
96static HTTP_TIMEOUTS: LazyLock<arc_swap::ArcSwap<HttpTimeouts>> =
97    LazyLock::new(|| arc_swap::ArcSwap::from_pointee(HttpTimeouts::default()));
98
99/// Install process-wide HTTP timeout defaults.
100///
101/// Called once at startup from the loaded configuration and again on live
102/// reload, so `[timeouts]` edits apply without a restart. Clients already built
103/// keep the values they were created with; new clients pick these up.
104pub fn install_http_timeouts(timeouts: HttpTimeouts) {
105    HTTP_TIMEOUTS.store(std::sync::Arc::new(timeouts));
106}
107
108/// Current process-wide HTTP timeout defaults.
109#[must_use]
110pub fn http_timeouts() -> HttpTimeouts {
111    **HTTP_TIMEOUTS.load()
112}
113
114fn apply_platform_proxy_policy(builder: ClientBuilder) -> ClientBuilder {
115    #[cfg(target_os = "macos")]
116    {
117        // Avoid system proxy discovery on macOS because it can panic in restricted environments.
118        builder.no_proxy()
119    }
120    #[cfg(not(target_os = "macos"))]
121    {
122        builder
123    }
124}
125
126/// Try to build an HTTP client, returning an error if both primary and fallback builders fail.
127///
128/// This is the fallible version of `build_client`. Use this when you want to handle
129/// the error gracefully (e.g., return an error to the caller) instead of panicking.
130fn try_build_client<F>(configure: F) -> Result<Client, reqwest::Error>
131where
132    F: Fn(ClientBuilder) -> ClientBuilder,
133{
134    let primary_builder = configure(apply_platform_proxy_policy(ClientBuilder::new()));
135    match primary_builder.build() {
136        Ok(client) => Ok(client),
137        Err(primary_err) => {
138            let fallback_builder = HttpTimeouts::default().apply_to(apply_platform_proxy_policy(ClientBuilder::new()));
139            match fallback_builder.build() {
140                Ok(client) => Ok(client),
141                Err(fallback_err) => {
142                    tracing::error!(
143                        primary_error = %primary_err,
144                        fallback_error = %fallback_err,
145                        "HTTP client creation failed with both primary and fallback configurations"
146                    );
147                    Err(fallback_err)
148                }
149            }
150        }
151    }
152}
153
154/// Create a default HTTP client with standard timeouts.
155///
156/// Falls back to a bare default client if the configured builder and its
157/// fallback both fail (e.g., TLS misconfiguration, resource exhaustion).
158/// The fallback mirrors the resilience pattern in `http_client_pool`: a
159/// `tracing::error!` is logged so the failure is observable, but the process
160/// does not crash — callers get a working (if unconfigured) client.
161fn build_client<F>(configure: F) -> Client
162where
163    F: Fn(ClientBuilder) -> ClientBuilder,
164{
165    try_build_client(configure).unwrap_or_else(|e| {
166        tracing::error!(
167            error = %e,
168            "HTTP client build failed (primary + fallback); falling back to bare default client. \
169             This usually indicates a TLS configuration issue or system resource exhaustion."
170        );
171        Client::new()
172    })
173}
174
175/// Create a default HTTP client with the installed timeout defaults.
176pub fn create_default_client() -> Client {
177    build_client(|builder| http_timeouts().apply_to(builder))
178}
179
180/// Create an HTTP client with a custom request timeout.
181///
182/// The connect phase keeps the installed default so a stalled TCP/TLS handshake
183/// never inherits the (usually much longer) request budget.
184pub fn create_client_with_timeout(timeout: Duration) -> Client {
185    let connect = http_timeouts().connect;
186    build_client(move |builder| {
187        let builder = builder.timeout(timeout);
188        match connect {
189            Some(connect) => builder.connect_timeout(connect),
190            None => builder,
191        }
192    })
193}
194
195/// Create an HTTP client with custom connect and request timeouts.
196pub fn create_client_with_timeouts(connect_timeout: Duration, request_timeout: Duration) -> Client {
197    build_client(|builder| builder.timeout(request_timeout).connect_timeout(connect_timeout))
198}
199
200/// Maximum followed redirects in the same-origin policy (mirrors reqwest's default limit).
201const SAME_ORIGIN_REDIRECT_LIMIT: usize = 10;
202
203/// Redirect policy that follows only same-origin redirects without a scheme downgrade.
204///
205/// Credentialed API clients must not follow cross-origin redirects: reqwest strips only the
206/// `Authorization`/`Cookie`-family headers there, so custom key headers (`x-api-key`,
207/// `x-goog-api-key`, `anthropic-version`) would replay to the redirect target. Same-origin
208/// redirects (trailing-slash normalization, `http`→`https` upgrades on self-hosted gateways)
209/// stay within the origin the caller already trusts with the key, so they are followed.
210/// Cross-origin targets, `https`→`http` downgrades, and redirect loops stop with the 3xx
211/// response instead of an error, matching `Policy::none` surfacing so provider error paths
212/// handle both uniformly.
213pub fn same_origin_redirect_policy() -> reqwest::redirect::Policy {
214    reqwest::redirect::Policy::custom(|attempt| {
215        if attempt.previous().len() > SAME_ORIGIN_REDIRECT_LIMIT {
216            return attempt.stop();
217        }
218        let next = attempt.url();
219        let allowed = attempt
220            .previous()
221            .last()
222            .is_some_and(|previous| redirect_target_allowed(next, previous));
223        if allowed { attempt.follow() } else { attempt.stop() }
224    })
225}
226
227/// Whether a redirect from `previous` to `next` may be followed with credentials attached.
228///
229/// Same host and same effective port (mirroring reqwest's own cross-host notion), except the
230/// standard `http`→`https` upgrade; `https`→`http` downgrades never qualify. A missing host
231/// fails closed.
232fn redirect_target_allowed(next: &reqwest::Url, previous: &reqwest::Url) -> bool {
233    if next.host_str().is_none() || next.host_str() != previous.host_str() {
234        return false;
235    }
236    if previous.scheme() == "https" && next.scheme() == "http" {
237        return false;
238    }
239    next.port_or_known_default() == previous.port_or_known_default()
240        || (previous.scheme() == "http" && next.scheme() == "https")
241}
242
243/// Create an origin-bound HTTP client with custom connect and request timeouts.
244///
245/// Credentials never leave the configured origin: same-origin redirects are followed while
246/// cross-origin targets stop (see [`same_origin_redirect_policy`]). The fallback path keeps
247/// the same policy — a timeout misconfiguration must not silently re-enable following.
248pub fn create_origin_bound_client_with_timeouts(connect_timeout: Duration, request_timeout: Duration) -> Client {
249    let build = |connect: Duration, request: Duration| {
250        apply_platform_proxy_policy(ClientBuilder::new())
251            .timeout(request)
252            .connect_timeout(connect)
253            .redirect(same_origin_redirect_policy())
254            .build()
255    };
256    match build(connect_timeout, request_timeout) {
257        Ok(client) => client,
258        Err(primary_err) => {
259            let fallback = HttpTimeouts::default()
260                .apply_to(apply_platform_proxy_policy(ClientBuilder::new()))
261                .redirect(same_origin_redirect_policy())
262                .build();
263            match fallback {
264                Ok(client) => client,
265                Err(fallback_err) => {
266                    tracing::error!(
267                        primary_error = %primary_err,
268                        fallback_error = %fallback_err,
269                        "Origin-bound HTTP client creation failed; falling back to a bare origin-bound client"
270                    );
271                    ClientBuilder::new()
272                        .redirect(same_origin_redirect_policy())
273                        .build()
274                        .unwrap_or_else(|_| Client::new())
275                }
276            }
277        }
278    }
279}
280
281/// Build an origin-bound client without a fallback that could enable redirects.
282pub fn create_client_without_redirects(
283    connect_timeout: Duration,
284    request_timeout: Duration,
285) -> Result<Client, reqwest::Error> {
286    apply_platform_proxy_policy(ClientBuilder::new())
287        .timeout(request_timeout)
288        .connect_timeout(connect_timeout)
289        .redirect(reqwest::redirect::Policy::none())
290        .build()
291}
292
293/// Build an origin-bound client without redirects, using the installed defaults.
294///
295/// For call sites that must not follow redirects (credentials could otherwise be
296/// replayed to a new origin) but still need a bounded request.
297pub fn create_default_client_without_redirects() -> Result<Client, reqwest::Error> {
298    let timeouts = http_timeouts();
299    let mut builder = apply_platform_proxy_policy(ClientBuilder::new()).redirect(reqwest::redirect::Policy::none());
300    if let Some(request) = timeouts.request {
301        builder = builder.timeout(request);
302    }
303    if let Some(connect) = timeouts.connect {
304        builder = builder.connect_timeout(connect);
305    }
306    builder.build()
307}
308
309/// Create an HTTP client with a specific user agent.
310pub fn create_client_with_user_agent(user_agent: &str) -> Client {
311    let timeouts = http_timeouts();
312    build_client(move |mut builder| {
313        builder = builder.user_agent(user_agent);
314        timeouts.apply_to(builder)
315    })
316}
317
318/// Create an origin-bound streaming HTTP client.
319///
320/// Same credential-replay rationale as [`create_origin_bound_client_with_timeouts`]:
321/// streaming LLM responses carry API-key headers on the initiating request, so cross-origin
322/// redirects stop instead of replaying them. No whole-request timeout by design (see
323/// [`create_streaming_client`]); the connect phase stays bounded.
324pub fn create_origin_bound_streaming_client() -> Client {
325    let connect = http_timeouts().connect;
326    let build = |builder: ClientBuilder| {
327        let builder = builder
328            .tcp_keepalive(Some(Duration::from_secs(60)))
329            .redirect(same_origin_redirect_policy());
330        match connect {
331            Some(connect) => builder.connect_timeout(connect),
332            None => builder,
333        }
334    };
335    match build(apply_platform_proxy_policy(ClientBuilder::new())).build() {
336        Ok(client) => client,
337        Err(primary_err) => {
338            tracing::error!(
339                primary_error = %primary_err,
340                "Origin-bound streaming HTTP client creation failed; using bare origin-bound client"
341            );
342            ClientBuilder::new()
343                .redirect(same_origin_redirect_policy())
344                .build()
345                .unwrap_or_else(|_| Client::new())
346        }
347    }
348}
349
350/// Create an HTTP client optimized for streaming.
351///
352/// Streaming intentionally has **no** whole-request timeout: a chat completion
353/// that trickles tokens for longer than the request budget is healthy, not hung.
354/// The connect phase stays bounded, and callers that need a stall detector should
355/// set an idle/`read_timeout` instead of a total deadline.
356///
357/// This variant follows redirects. Credentialed callers must use
358/// [`create_origin_bound_streaming_client`] instead.
359pub fn create_streaming_client() -> Client {
360    let connect = http_timeouts().connect;
361    build_client(move |builder| {
362        let builder = builder.tcp_keepalive(Some(Duration::from_secs(60)));
363        match connect {
364            Some(connect) => builder.connect_timeout(connect),
365            None => builder,
366        }
367    })
368}
369
370/// Create a client for large artifact transfers (release downloads, assets).
371///
372/// Uses the installed `download` budget instead of the request budget: a
373/// multi-megabyte archive on a cold cache routinely needs longer than the
374/// interactive request default, and failing it silently is how installers end up
375/// "hanging for 60 seconds and dying" on slower connections.
376pub fn create_download_client(user_agent: &str) -> Client {
377    let timeouts = http_timeouts();
378    build_client(move |mut builder| {
379        builder = builder.user_agent(user_agent).tcp_keepalive(Some(Duration::from_secs(60)));
380        if let Some(download) = timeouts.download {
381            builder = builder.timeout(download);
382        }
383        if let Some(connect) = timeouts.connect {
384            builder = builder.connect_timeout(connect);
385        }
386        builder
387    })
388}
389
390/// Get a default client or create one
391pub fn get_or_create_default_client(existing: Option<Client>) -> Client {
392    existing.unwrap_or_else(create_default_client)
393}
394
395/// Apply the installed connect budget to an explicit client builder.
396///
397/// Prefer the `create_*` constructors; use this only where a call site needs
398/// builder options they do not offer (redirect or retry policy tweaks).
399/// A `None` budget (the phase was disabled) leaves the builder untouched.
400pub fn apply_connect_timeout(builder: ClientBuilder) -> ClientBuilder {
401    match http_timeouts().connect {
402        Some(connect) => builder.connect_timeout(connect),
403        None => builder,
404    }
405}
406
407/// Send one request per attempt with capped exponential backoff and jitter.
408///
409/// The caller rebuilds the request on every attempt via `make_request` (a
410/// `RequestBuilder` is consumed by `send()`, so it cannot be reused).
411/// Transport failures (connect errors, timeouts) are retried; builder errors
412/// fail fast because retrying a malformed request can never succeed.
413/// Responses with a retryable status (429/500/502/503/504 per
414/// [`RetryPolicy::classify_status`]) are retried while attempts remain;
415/// otherwise the final response is returned for the caller to handle.
416///
417/// This is the shared helper for idempotent background fetches (release
418/// metadata, asset downloads, catalog refreshes). Interactive LLM requests
419/// must NOT use it: the runloop already retries those under its own budget,
420/// and stacking a transport retry underneath would multiply dispatches and
421/// provider billing.
422///
423/// What this does NOT do: it never honors `Retry-After` (policy backoff
424/// only; `Retry-After` cooperation stays at the tool-registry layer where the
425/// server relationship exists), and it never retries a response body failure —
426/// only the initial `send()`.
427pub async fn send_with_retry<F, Fut>(policy: &RetryPolicy, make_request: F) -> Result<reqwest::Response, reqwest::Error>
428where
429    F: Fn() -> Fut,
430    Fut: Future<Output = Result<reqwest::Response, reqwest::Error>>,
431{
432    send_with_retry_inner(policy, true, make_request).await
433}
434
435/// Retry only when no response was received (transport failure), never on an
436/// HTTP status. For non-idempotent OAuth token POSTs: an authorization code
437/// may already be consumed when a 5xx arrives, so a status-triggered retry
438/// would just burn the login; a transport error means the server likely never
439/// saw the request, making one more attempt strictly better than failing.
440pub async fn send_with_retry_transport_only<F, Fut>(
441    policy: &RetryPolicy,
442    make_request: F,
443) -> Result<reqwest::Response, reqwest::Error>
444where
445    F: Fn() -> Fut,
446    Fut: Future<Output = Result<reqwest::Response, reqwest::Error>>,
447{
448    send_with_retry_inner(policy, false, make_request).await
449}
450
451async fn send_with_retry_inner<F, Fut>(
452    policy: &RetryPolicy,
453    retry_status: bool,
454    make_request: F,
455) -> Result<reqwest::Response, reqwest::Error>
456where
457    F: Fn() -> Fut,
458    Fut: Future<Output = Result<reqwest::Response, reqwest::Error>>,
459{
460    // Termination variant: `attempt` rises toward `attempts`, and the `last`
461    // arm returns on the final iteration, so the loop always exits.
462    let attempts = policy.max_attempts.max(1);
463    let mut attempt: u32 = 0;
464    loop {
465        if attempt > 0 {
466            tokio::time::sleep(policy.delay_for_attempt(attempt - 1)).await;
467        }
468        let last = attempt + 1 >= attempts;
469        match make_request().await {
470            Ok(response) if !retry_status || last || !policy.classify_status(response.status().as_u16()).retryable => {
471                return Ok(response);
472            }
473            Ok(_) => {}
474            Err(error) if error.is_builder() || last => return Err(error),
475            Err(_) => {}
476        }
477        attempt += 1;
478    }
479}
480
481#[cfg(test)]
482mod tests;