vtcode-commons 0.186.0

Shared traits for paths, telemetry, and error reporting reused across VT Code component extractions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! HTTP client utilities
//!
//! Timeouts here are **defaults, not laws**. A 5-second connect timeout is fine
//! for a warm cache next to the registry and wrong for a first-ever TLS
//! handshake over a slow link; a 30-second request timeout is generous for a
//! metadata fetch and fatal for a cold-start local model. Callers that know
//! better can pass explicit values, and users can override the defaults through
//! `[timeouts] http_connect_seconds` / `http_request_seconds` /
//! `http_download_seconds` (or the `VTCODE_HTTP_*_TIMEOUT_SECS` env vars), which
//! reach this module via [`install_http_timeouts`].
//!
//! This module is the home of the timeout policy, so it is the one place that
//! may build a bare `ClientBuilder`. Every other crate must go through the
//! helpers below so the installed budgets apply.

#![allow(
    clippy::disallowed_methods,
    reason = "This module implements the shared timeout policy; bare builders are the policy's own building blocks."
)]

use reqwest::{Client, ClientBuilder};
use std::future::Future;
use std::sync::LazyLock;
use std::time::Duration;

use crate::retry::RetryPolicy;

/// Default connect timeout for outbound HTTP clients.
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Default whole-request timeout for outbound HTTP clients.
const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
/// Default timeout for large artifact transfers (release downloads, assets).
const DEFAULT_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(300);

/// Resolved HTTP timeout defaults shared by every outbound client.
///
/// `None` means "no timeout of this kind" — reqwest then leaves the phase
/// unbounded, which is the documented meaning of a `0` in `[timeouts]`. Keeping
/// the distinction in the type (rather than a `Duration::ZERO` sentinel) means
/// call sites cannot accidentally install a zero deadline that fails instantly.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HttpTimeouts {
    /// Timeout for the TCP/TLS connect phase.
    pub connect: Option<Duration>,
    /// Timeout for the whole request, including the response body.
    pub request: Option<Duration>,
    /// Timeout for large artifact transfers.
    pub download: Option<Duration>,
}

impl Default for HttpTimeouts {
    fn default() -> Self {
        Self {
            connect: Some(DEFAULT_CONNECT_TIMEOUT),
            request: Some(DEFAULT_REQUEST_TIMEOUT),
            download: Some(DEFAULT_DOWNLOAD_TIMEOUT),
        }
    }
}

impl HttpTimeouts {
    /// Resolve a configured number of `[timeouts]` seconds into an optional
    /// duration, where `0` disables the phase.
    #[must_use]
    pub const fn from_seconds(connect: u64, request: u64, download: u64) -> Self {
        Self {
            connect: duration_or_disabled(connect),
            request: duration_or_disabled(request),
            download: duration_or_disabled(download),
        }
    }

    /// Apply the connect and request phases to a builder, skipping disabled
    /// phases instead of installing a zero deadline.
    fn apply_to(self, mut builder: ClientBuilder) -> ClientBuilder {
        if let Some(request) = self.request {
            builder = builder.timeout(request);
        }
        if let Some(connect) = self.connect {
            builder = builder.connect_timeout(connect);
        }
        builder
    }
}

/// `0` means "disabled" throughout `[timeouts]`; keep that convention here so an
/// explicit `0` never turns into an instant-fail `Duration::ZERO` deadline.
const fn duration_or_disabled(seconds: u64) -> Option<Duration> {
    if seconds == 0 {
        None
    } else {
        Some(Duration::from_secs(seconds))
    }
}

static HTTP_TIMEOUTS: LazyLock<arc_swap::ArcSwap<HttpTimeouts>> =
    LazyLock::new(|| arc_swap::ArcSwap::from_pointee(HttpTimeouts::default()));

/// Install process-wide HTTP timeout defaults.
///
/// Called once at startup from the loaded configuration and again on live
/// reload, so `[timeouts]` edits apply without a restart. Clients already built
/// keep the values they were created with; new clients pick these up.
pub fn install_http_timeouts(timeouts: HttpTimeouts) {
    HTTP_TIMEOUTS.store(std::sync::Arc::new(timeouts));
}

/// Current process-wide HTTP timeout defaults.
#[must_use]
pub fn http_timeouts() -> HttpTimeouts {
    **HTTP_TIMEOUTS.load()
}

fn apply_platform_proxy_policy(builder: ClientBuilder) -> ClientBuilder {
    #[cfg(target_os = "macos")]
    {
        // Avoid system proxy discovery on macOS because it can panic in restricted environments.
        builder.no_proxy()
    }
    #[cfg(not(target_os = "macos"))]
    {
        builder
    }
}

/// Try to build an HTTP client, returning an error if both primary and fallback builders fail.
///
/// This is the fallible version of `build_client`. Use this when you want to handle
/// the error gracefully (e.g., return an error to the caller) instead of panicking.
fn try_build_client<F>(configure: F) -> Result<Client, reqwest::Error>
where
    F: Fn(ClientBuilder) -> ClientBuilder,
{
    let primary_builder = configure(apply_platform_proxy_policy(ClientBuilder::new()));
    match primary_builder.build() {
        Ok(client) => Ok(client),
        Err(primary_err) => {
            let fallback_builder = HttpTimeouts::default().apply_to(apply_platform_proxy_policy(ClientBuilder::new()));
            match fallback_builder.build() {
                Ok(client) => Ok(client),
                Err(fallback_err) => {
                    tracing::error!(
                        primary_error = %primary_err,
                        fallback_error = %fallback_err,
                        "HTTP client creation failed with both primary and fallback configurations"
                    );
                    Err(fallback_err)
                }
            }
        }
    }
}

/// Create a default HTTP client with standard timeouts.
///
/// Falls back to a bare default client if the configured builder and its
/// fallback both fail (e.g., TLS misconfiguration, resource exhaustion).
/// The fallback mirrors the resilience pattern in `http_client_pool`: a
/// `tracing::error!` is logged so the failure is observable, but the process
/// does not crash — callers get a working (if unconfigured) client.
fn build_client<F>(configure: F) -> Client
where
    F: Fn(ClientBuilder) -> ClientBuilder,
{
    try_build_client(configure).unwrap_or_else(|e| {
        tracing::error!(
            error = %e,
            "HTTP client build failed (primary + fallback); falling back to bare default client. \
             This usually indicates a TLS configuration issue or system resource exhaustion."
        );
        Client::new()
    })
}

/// Create a default HTTP client with the installed timeout defaults.
pub fn create_default_client() -> Client {
    build_client(|builder| http_timeouts().apply_to(builder))
}

/// Create an HTTP client with a custom request timeout.
///
/// The connect phase keeps the installed default so a stalled TCP/TLS handshake
/// never inherits the (usually much longer) request budget.
pub fn create_client_with_timeout(timeout: Duration) -> Client {
    let connect = http_timeouts().connect;
    build_client(move |builder| {
        let builder = builder.timeout(timeout);
        match connect {
            Some(connect) => builder.connect_timeout(connect),
            None => builder,
        }
    })
}

/// Create an HTTP client with custom connect and request timeouts.
pub fn create_client_with_timeouts(connect_timeout: Duration, request_timeout: Duration) -> Client {
    build_client(|builder| builder.timeout(request_timeout).connect_timeout(connect_timeout))
}

/// Maximum followed redirects in the same-origin policy (mirrors reqwest's default limit).
const SAME_ORIGIN_REDIRECT_LIMIT: usize = 10;

/// Redirect policy that follows only same-origin redirects without a scheme downgrade.
///
/// Credentialed API clients must not follow cross-origin redirects: reqwest strips only the
/// `Authorization`/`Cookie`-family headers there, so custom key headers (`x-api-key`,
/// `x-goog-api-key`, `anthropic-version`) would replay to the redirect target. Same-origin
/// redirects (trailing-slash normalization, `http`→`https` upgrades on self-hosted gateways)
/// stay within the origin the caller already trusts with the key, so they are followed.
/// Cross-origin targets, `https`→`http` downgrades, and redirect loops stop with the 3xx
/// response instead of an error, matching `Policy::none` surfacing so provider error paths
/// handle both uniformly.
pub fn same_origin_redirect_policy() -> reqwest::redirect::Policy {
    reqwest::redirect::Policy::custom(|attempt| {
        if attempt.previous().len() > SAME_ORIGIN_REDIRECT_LIMIT {
            return attempt.stop();
        }
        let next = attempt.url();
        let allowed = attempt
            .previous()
            .last()
            .is_some_and(|previous| redirect_target_allowed(next, previous));
        if allowed { attempt.follow() } else { attempt.stop() }
    })
}

/// Whether a redirect from `previous` to `next` may be followed with credentials attached.
///
/// Same host and same effective port (mirroring reqwest's own cross-host notion), except the
/// standard `http`→`https` upgrade; `https`→`http` downgrades never qualify. A missing host
/// fails closed.
fn redirect_target_allowed(next: &reqwest::Url, previous: &reqwest::Url) -> bool {
    if next.host_str().is_none() || next.host_str() != previous.host_str() {
        return false;
    }
    if previous.scheme() == "https" && next.scheme() == "http" {
        return false;
    }
    next.port_or_known_default() == previous.port_or_known_default()
        || (previous.scheme() == "http" && next.scheme() == "https")
}

/// Create an origin-bound HTTP client with custom connect and request timeouts.
///
/// Credentials never leave the configured origin: same-origin redirects are followed while
/// cross-origin targets stop (see [`same_origin_redirect_policy`]). The fallback path keeps
/// the same policy — a timeout misconfiguration must not silently re-enable following.
pub fn create_origin_bound_client_with_timeouts(connect_timeout: Duration, request_timeout: Duration) -> Client {
    let build = |connect: Duration, request: Duration| {
        apply_platform_proxy_policy(ClientBuilder::new())
            .timeout(request)
            .connect_timeout(connect)
            .redirect(same_origin_redirect_policy())
            .build()
    };
    match build(connect_timeout, request_timeout) {
        Ok(client) => client,
        Err(primary_err) => {
            let fallback = HttpTimeouts::default()
                .apply_to(apply_platform_proxy_policy(ClientBuilder::new()))
                .redirect(same_origin_redirect_policy())
                .build();
            match fallback {
                Ok(client) => client,
                Err(fallback_err) => {
                    tracing::error!(
                        primary_error = %primary_err,
                        fallback_error = %fallback_err,
                        "Origin-bound HTTP client creation failed; falling back to a bare origin-bound client"
                    );
                    ClientBuilder::new()
                        .redirect(same_origin_redirect_policy())
                        .build()
                        .unwrap_or_else(|_| Client::new())
                }
            }
        }
    }
}

/// Build an origin-bound client without a fallback that could enable redirects.
pub fn create_client_without_redirects(
    connect_timeout: Duration,
    request_timeout: Duration,
) -> Result<Client, reqwest::Error> {
    apply_platform_proxy_policy(ClientBuilder::new())
        .timeout(request_timeout)
        .connect_timeout(connect_timeout)
        .redirect(reqwest::redirect::Policy::none())
        .build()
}

/// Build an origin-bound client without redirects, using the installed defaults.
///
/// For call sites that must not follow redirects (credentials could otherwise be
/// replayed to a new origin) but still need a bounded request.
pub fn create_default_client_without_redirects() -> Result<Client, reqwest::Error> {
    let timeouts = http_timeouts();
    let mut builder = apply_platform_proxy_policy(ClientBuilder::new()).redirect(reqwest::redirect::Policy::none());
    if let Some(request) = timeouts.request {
        builder = builder.timeout(request);
    }
    if let Some(connect) = timeouts.connect {
        builder = builder.connect_timeout(connect);
    }
    builder.build()
}

/// Create an HTTP client with a specific user agent.
pub fn create_client_with_user_agent(user_agent: &str) -> Client {
    let timeouts = http_timeouts();
    build_client(move |mut builder| {
        builder = builder.user_agent(user_agent);
        timeouts.apply_to(builder)
    })
}

/// Create an origin-bound streaming HTTP client.
///
/// Same credential-replay rationale as [`create_origin_bound_client_with_timeouts`]:
/// streaming LLM responses carry API-key headers on the initiating request, so cross-origin
/// redirects stop instead of replaying them. No whole-request timeout by design (see
/// [`create_streaming_client`]); the connect phase stays bounded.
pub fn create_origin_bound_streaming_client() -> Client {
    let connect = http_timeouts().connect;
    let build = |builder: ClientBuilder| {
        let builder = builder
            .tcp_keepalive(Some(Duration::from_secs(60)))
            .redirect(same_origin_redirect_policy());
        match connect {
            Some(connect) => builder.connect_timeout(connect),
            None => builder,
        }
    };
    match build(apply_platform_proxy_policy(ClientBuilder::new())).build() {
        Ok(client) => client,
        Err(primary_err) => {
            tracing::error!(
                primary_error = %primary_err,
                "Origin-bound streaming HTTP client creation failed; using bare origin-bound client"
            );
            ClientBuilder::new()
                .redirect(same_origin_redirect_policy())
                .build()
                .unwrap_or_else(|_| Client::new())
        }
    }
}

/// Create an HTTP client optimized for streaming.
///
/// Streaming intentionally has **no** whole-request timeout: a chat completion
/// that trickles tokens for longer than the request budget is healthy, not hung.
/// The connect phase stays bounded, and callers that need a stall detector should
/// set an idle/`read_timeout` instead of a total deadline.
///
/// This variant follows redirects. Credentialed callers must use
/// [`create_origin_bound_streaming_client`] instead.
pub fn create_streaming_client() -> Client {
    let connect = http_timeouts().connect;
    build_client(move |builder| {
        let builder = builder.tcp_keepalive(Some(Duration::from_secs(60)));
        match connect {
            Some(connect) => builder.connect_timeout(connect),
            None => builder,
        }
    })
}

/// Create a client for large artifact transfers (release downloads, assets).
///
/// Uses the installed `download` budget instead of the request budget: a
/// multi-megabyte archive on a cold cache routinely needs longer than the
/// interactive request default, and failing it silently is how installers end up
/// "hanging for 60 seconds and dying" on slower connections.
pub fn create_download_client(user_agent: &str) -> Client {
    let timeouts = http_timeouts();
    build_client(move |mut builder| {
        builder = builder.user_agent(user_agent).tcp_keepalive(Some(Duration::from_secs(60)));
        if let Some(download) = timeouts.download {
            builder = builder.timeout(download);
        }
        if let Some(connect) = timeouts.connect {
            builder = builder.connect_timeout(connect);
        }
        builder
    })
}

/// Get a default client or create one
pub fn get_or_create_default_client(existing: Option<Client>) -> Client {
    existing.unwrap_or_else(create_default_client)
}

/// Apply the installed connect budget to an explicit client builder.
///
/// Prefer the `create_*` constructors; use this only where a call site needs
/// builder options they do not offer (redirect or retry policy tweaks).
/// A `None` budget (the phase was disabled) leaves the builder untouched.
pub fn apply_connect_timeout(builder: ClientBuilder) -> ClientBuilder {
    match http_timeouts().connect {
        Some(connect) => builder.connect_timeout(connect),
        None => builder,
    }
}

/// Send one request per attempt with capped exponential backoff and jitter.
///
/// The caller rebuilds the request on every attempt via `make_request` (a
/// `RequestBuilder` is consumed by `send()`, so it cannot be reused).
/// Transport failures (connect errors, timeouts) are retried; builder errors
/// fail fast because retrying a malformed request can never succeed.
/// Responses with a retryable status (429/500/502/503/504 per
/// [`RetryPolicy::classify_status`]) are retried while attempts remain;
/// otherwise the final response is returned for the caller to handle.
///
/// This is the shared helper for idempotent background fetches (release
/// metadata, asset downloads, catalog refreshes). Interactive LLM requests
/// must NOT use it: the runloop already retries those under its own budget,
/// and stacking a transport retry underneath would multiply dispatches and
/// provider billing.
///
/// What this does NOT do: it never honors `Retry-After` (policy backoff
/// only; `Retry-After` cooperation stays at the tool-registry layer where the
/// server relationship exists), and it never retries a response body failure —
/// only the initial `send()`.
pub async fn send_with_retry<F, Fut>(policy: &RetryPolicy, make_request: F) -> Result<reqwest::Response, reqwest::Error>
where
    F: Fn() -> Fut,
    Fut: Future<Output = Result<reqwest::Response, reqwest::Error>>,
{
    send_with_retry_inner(policy, true, make_request).await
}

/// Retry only when no response was received (transport failure), never on an
/// HTTP status. For non-idempotent OAuth token POSTs: an authorization code
/// may already be consumed when a 5xx arrives, so a status-triggered retry
/// would just burn the login; a transport error means the server likely never
/// saw the request, making one more attempt strictly better than failing.
pub async fn send_with_retry_transport_only<F, Fut>(
    policy: &RetryPolicy,
    make_request: F,
) -> Result<reqwest::Response, reqwest::Error>
where
    F: Fn() -> Fut,
    Fut: Future<Output = Result<reqwest::Response, reqwest::Error>>,
{
    send_with_retry_inner(policy, false, make_request).await
}

async fn send_with_retry_inner<F, Fut>(
    policy: &RetryPolicy,
    retry_status: bool,
    make_request: F,
) -> Result<reqwest::Response, reqwest::Error>
where
    F: Fn() -> Fut,
    Fut: Future<Output = Result<reqwest::Response, reqwest::Error>>,
{
    // Termination variant: `attempt` rises toward `attempts`, and the `last`
    // arm returns on the final iteration, so the loop always exits.
    let attempts = policy.max_attempts.max(1);
    let mut attempt: u32 = 0;
    loop {
        if attempt > 0 {
            tokio::time::sleep(policy.delay_for_attempt(attempt - 1)).await;
        }
        let last = attempt + 1 >= attempts;
        match make_request().await {
            Ok(response) if !retry_status || last || !policy.classify_status(response.status().as_u16()).retryable => {
                return Ok(response);
            }
            Ok(_) => {}
            Err(error) if error.is_builder() || last => return Err(error),
            Err(_) => {}
        }
        attempt += 1;
    }
}

#[cfg(test)]
mod tests;