Skip to main content

eggfetch_core/
client.rs

1//! Async client entry point.
2
3use std::collections::HashMap;
4use std::sync::Arc;
5use std::time::Duration;
6
7use http::Method;
8use hyper_util::rt::TokioExecutor;
9use tokio::sync::Mutex;
10
11use crate::error::{Error, Result};
12use crate::headers::Headers;
13use crate::http_version::HttpVersionPolicy;
14use crate::limits::Limits;
15use crate::pool::{Pool, PoolConfig, PoolMetrics};
16#[cfg(feature = "proxy")]
17use crate::proxy::Proxy;
18use crate::redirect::RedirectPolicy;
19use crate::request::{Request, RequestBuilder};
20use crate::response::Response;
21use crate::retry::RetryPolicy;
22use crate::timeout::Timeout;
23use crate::transport::Connector;
24
25#[cfg(feature = "cookies")]
26use crate::cookie::CookieJar;
27
28/// Shared client configuration.
29///
30/// `Debug` is intentionally manual: several fields hold secrets (notably
31/// the cookie jar), so the implementation redacts them instead of deriving
32/// a verbatim dump. See [`crate::redact`].
33#[derive(Clone)]
34pub(crate) struct ClientConfig {
35    pub(crate) default_headers: Headers,
36    pub(crate) user_agent: Option<String>,
37    pub(crate) timeout: Option<Timeout>,
38    pub(crate) redirect: RedirectPolicy,
39    pub(crate) auth: Option<crate::auth::AuthScheme>,
40    #[cfg(feature = "cookies")]
41    pub(crate) cookie_jar: CookieJar,
42    pub(crate) automatic_decompression: bool,
43    pub(crate) max_decoded_body_size: Option<usize>,
44    pub(crate) max_decompression_ratio: Option<f64>,
45    #[cfg(feature = "proxy")]
46    pub(crate) proxy: Option<Proxy>,
47    #[cfg(feature = "proxy")]
48    pub(crate) environment_proxies: Vec<Proxy>,
49    #[cfg(any(feature = "proxy", feature = "http3"))]
50    pub(crate) tls_config: Option<crate::tls::TlsConfig>,
51    pub(crate) retry: Option<RetryPolicy>,
52    #[allow(
53        dead_code,
54        reason = "stored for inspection and future request-level use"
55    )]
56    pub(crate) http_version_policy: HttpVersionPolicy,
57}
58
59impl std::fmt::Debug for ClientConfig {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        let mut debug = f.debug_struct("ClientConfig");
62        debug
63            .field("default_headers", &self.default_headers)
64            .field("user_agent", &self.user_agent)
65            .field("timeout", &self.timeout)
66            .field("redirect", &self.redirect)
67            .field("auth", &self.auth);
68        #[cfg(feature = "cookies")]
69        debug.field("cookie_jar", &self.cookie_jar);
70        debug
71            .field("automatic_decompression", &self.automatic_decompression)
72            .field("max_decoded_body_size", &self.max_decoded_body_size)
73            .field("max_decompression_ratio", &self.max_decompression_ratio);
74        #[cfg(feature = "proxy")]
75        debug
76            .field("proxy", &self.proxy)
77            .field("environment_proxies", &self.environment_proxies);
78        #[cfg(any(feature = "proxy", feature = "http3"))]
79        debug.field("tls_config", &self.tls_config);
80        debug
81            .field("retry", &self.retry)
82            .field("http_version_policy", &self.http_version_policy)
83            .finish_non_exhaustive()
84    }
85}
86
87impl Default for ClientConfig {
88    fn default() -> Self {
89        Self {
90            default_headers: Headers::new(),
91            user_agent: None,
92            timeout: None,
93            redirect: RedirectPolicy::default(),
94            auth: None,
95            #[cfg(feature = "cookies")]
96            cookie_jar: CookieJar::new(),
97            automatic_decompression: true,
98            max_decoded_body_size: None,
99            max_decompression_ratio: None,
100            #[cfg(feature = "proxy")]
101            proxy: None,
102            #[cfg(feature = "proxy")]
103            environment_proxies: Vec::new(),
104            #[cfg(any(feature = "proxy", feature = "http3"))]
105            tls_config: None,
106            retry: None,
107            http_version_policy: HttpVersionPolicy::default(),
108        }
109    }
110}
111
112/// Async HTTP client.
113///
114/// The client manages connection pooling and shared configuration. Create one
115/// with [`Client::new`] or [`Client::builder`].
116#[derive(Clone)]
117pub struct Client {
118    inner: Arc<ClientInner>,
119}
120
121impl std::fmt::Debug for Client {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        f.debug_struct("Client").finish_non_exhaustive()
124    }
125}
126
127pub(crate) struct ClientInner {
128    pub(crate) hyper_client: Option<crate::transport::TimeoutHyperClient>,
129    /// Error captured while building the configured TLS policy, if any.
130    ///
131    /// `ClientBuilder::build` is intentionally infallible, so HTTPS requests
132    /// surface this error at dispatch time instead of falling back to a
133    /// different trust policy.
134    pub(crate) tls_config_error: Option<String>,
135    /// Direct connector for requests with advanced socket options or local
136    /// address binding. Uses a custom connector instead of the standard
137    /// hyper-rustls connector path.
138    pub(crate) direct_client: Option<crate::transport::TimeoutDirectClient>,
139    /// Base direct-connector configuration (local address / socket options)
140    /// used to construct SNI-override clients so they preserve source
141    /// binding and socket tuning.
142    pub(crate) direct_connector_config:
143        Option<crate::transport::direct_connector::DirectConnectorConfig>,
144    /// Cached hyper clients keyed by TLS SNI hostname override.
145    ///
146    /// When a request carries `TransportHints.sni_hostname`, the pipeline
147    /// uses a DirectConnector-based client from this cache. The connector
148    /// separates DNS/TCP (to the original URL host) from TLS (with the
149    /// SNI override hostname), keeping the default path unchanged.
150    ///
151    /// Bounded by [`SNI_CLIENT_CACHE_MAX_ENTRIES`] with arbitrary-entry
152    /// eviction so long-lived processes touching many hostnames cannot
153    /// grow it without limit.
154    ///
155    /// The cache is keyed only by hostname because `ClientInner::config`
156    /// (including `http_version_policy` and `tls_config` ALPN) is immutable
157    /// after `ClientBuilder::build`. If the TLS ALPN ever became mutable,
158    /// this cache would need to include `HttpVersionPolicy` (and
159    /// `tls_config` identity) in the key to avoid serving a client with
160    /// stale ALPN (e.g. H2 vs H1) for the same hostname.
161    pub(crate) sni_clients: Mutex<HashMap<String, crate::transport::TimeoutDirectClient>>,
162    /// Hyper client for Unix domain socket requests.
163    #[cfg(unix)]
164    pub(crate) uds_client: Option<crate::transport::TimeoutUdsClient>,
165    /// Persistent Hyper clients keyed by effective SOCKS route.
166    ///
167    /// Bounded like [`ClientInner::sni_clients`].
168    #[cfg(feature = "proxy")]
169    pub(crate) socks_clients: Mutex<
170        HashMap<crate::transport::socks::SocksRouteKey, crate::transport::TimeoutSocksClient>,
171    >,
172    pub(crate) config: ClientConfig,
173    pub(crate) pool: Pool,
174    /// Transport observability counters shared by all connectors owned by
175    /// this client. Distinct from [`Pool`] logical-permit metrics.
176    pub(crate) transport_metrics: Arc<crate::transport::metrics::TransportMetrics>,
177    #[cfg(feature = "http3")]
178    pub(crate) h3_connector: Option<crate::transport::http3::H3Connector>,
179    /// Bounded Alt-Svc discovery state (separate from QUIC sessions).
180    /// Owned here so all routes share one view. Only present with `http3`;
181    /// without it there is no discovery and no state to keep.
182    #[cfg(feature = "http3")]
183    pub(crate) alt_svc_state: Arc<crate::transport::alt_svc::AltSvcState>,
184}
185
186/// Upper bound on cached SNI-keyed hyper clients.
187const SNI_CLIENT_CACHE_MAX_ENTRIES: usize = 256;
188
189/// Upper bound on cached SOCKS-route hyper clients.
190#[cfg(feature = "proxy")]
191const SOCKS_CLIENT_CACHE_MAX_ENTRIES: usize = 64;
192
193/// Evict an arbitrary entry when a bounded client cache reaches capacity.
194///
195/// Entries hold pooled connections but no unsynchronized state, so any
196/// entry can be dropped safely; the next request recreates it lazily.
197/// Eviction is hash-order arbitrary via `HashMap::keys().next()`; with the
198/// bounded caps (`256` for SNI, `64` for SOCKS) this is acceptable and
199/// avoids an extra LRU dependency for a low-churn cache.
200fn evict_one<K: std::clone::Clone + Eq + std::hash::Hash, V>(map: &mut HashMap<K, V>) {
201    if let Some(key) = map.keys().next().cloned() {
202        map.remove(&key);
203    }
204}
205
206/// Apply the selected HTTP protocol policy to a rustls client configuration.
207///
208/// The standard hyper-rustls connector applies this policy while building its
209/// connector. Custom connectors must set the same ALPN list themselves.
210pub(crate) fn configure_tls_alpn(
211    mut config: rustls::ClientConfig,
212    policy: crate::http_version::HttpVersionPolicyEnabler,
213) -> rustls::ClientConfig {
214    config.alpn_protocols.clear();
215    if policy.enable_http2() {
216        config.alpn_protocols.push(b"h2".to_vec());
217    }
218    if policy.enable_http1() {
219        config.alpn_protocols.push(b"http/1.1".to_vec());
220    }
221    config
222}
223
224impl ClientInner {
225    /// Get or create a cached hyper client with TLS SNI hostname override.
226    ///
227    /// The returned client uses a [`DirectConnector`](crate::transport::direct_connector::DirectConnector)
228    /// that separates DNS/TCP resolution (to the original URL host) from
229    /// TLS negotiation (with the SNI hostname). Clients are cached by
230    /// SNI hostname for connection reuse.
231    pub(crate) async fn sni_client(
232        &self,
233        sni_hostname: &str,
234    ) -> Result<crate::transport::TimeoutDirectClient> {
235        let mut clients = self.sni_clients.lock().await;
236        if let Some(client) = clients.get(sni_hostname) {
237            return Ok(client.clone());
238        }
239
240        let connect_timeout = self.config.timeout.as_ref().and_then(|t| t.connect);
241        #[cfg(any(feature = "http2", feature = "http3", feature = "proxy"))]
242        let policy = self.config.http_version_policy;
243
244        #[cfg(any(feature = "proxy", feature = "http3"))]
245        let tls_connector = match self.config.tls_config.as_ref() {
246            Some(tls_config) => {
247                let rc = tls_config
248                    .build_rustls_config()
249                    .map_err(|e| Error::Tls(format!("failed to build TLS config: {e}")))?;
250                let rc = configure_tls_alpn(
251                    rc,
252                    crate::http_version::HttpVersionPolicyEnabler::from_policy(policy),
253                );
254                Some(tokio_rustls::TlsConnector::from(Arc::new(rc)))
255            }
256            None => None,
257        };
258        #[cfg(not(any(feature = "proxy", feature = "http3")))]
259        let tls_connector = None;
260
261        let base_config = self.direct_connector_config.clone().unwrap_or(
262            crate::transport::direct_connector::DirectConnectorConfig {
263                local_address: None,
264                socket_options: Vec::new(),
265            },
266        );
267        let base_connector = crate::transport::direct_connector::DirectConnector::with_metrics(
268            base_config,
269            tls_connector,
270            self.transport_metrics.clone(),
271        );
272        let sni_connector = base_connector.with_sni(sni_hostname.to_owned());
273        let connector =
274            crate::transport::connect_timeout::ConnectTimeout::new(sni_connector, connect_timeout);
275
276        let mut builder =
277            hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new());
278        #[cfg(feature = "http2")]
279        if matches!(policy, crate::HttpVersionPolicy::Http2Only) {
280            builder.http2_only(true);
281        }
282        // Idle-connection lifetime comes from the pool configuration
283        // (`Limits::keepalive_expiry`), matching the standard, direct,
284        // and UDS paths. `Timeout.pool`/`total` are acquisition budgets
285        // and must not close idle connections early.
286        if let Some(idle_timeout) = self.pool.idle_timeout() {
287            builder.pool_idle_timeout(idle_timeout);
288        }
289        let client = builder.build(connector);
290        if clients.len() >= SNI_CLIENT_CACHE_MAX_ENTRIES {
291            evict_one(&mut clients);
292        }
293        clients.insert(sni_hostname.to_owned(), client.clone());
294        Ok(client)
295    }
296}
297
298#[cfg(feature = "proxy")]
299impl ClientInner {
300    pub(crate) async fn socks_client(
301        &self,
302        proxy: &crate::proxy::ProxyConfig,
303    ) -> Result<crate::transport::TimeoutSocksClient> {
304        let key = crate::transport::socks::SocksRouteKey::from_proxy(proxy)?;
305        let mut clients = self.socks_clients.lock().await;
306        if let Some(client) = clients.get(&key) {
307            return Ok(client.clone());
308        }
309
310        let policy = self.config.http_version_policy;
311
312        let tls_config = if let Some(config) = self.config.tls_config.as_ref() {
313            config
314                .build_rustls_config()
315                .map_err(|e| Error::Tls(format!("failed to build SOCKS TLS config: {e}")))?
316        } else {
317            let roots = crate::tls::TlsConfig::fallback_root_store();
318            rustls::ClientConfig::builder()
319                .with_root_certificates(roots)
320                .with_no_client_auth()
321        };
322        let tls_config = configure_tls_alpn(
323            tls_config,
324            crate::http_version::HttpVersionPolicyEnabler::from_policy(policy),
325        );
326        let connector = crate::transport::socks::SocksConnector::new(
327            proxy.clone(),
328            Some(tokio_rustls::TlsConnector::from(Arc::new(tls_config))),
329            None,
330        );
331        let connector = crate::transport::connect_timeout::ConnectTimeout::new(
332            connector,
333            self.config
334                .timeout
335                .as_ref()
336                .and_then(|timeout| timeout.connect),
337        );
338        let mut builder =
339            hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new());
340        #[cfg(feature = "http2")]
341        if matches!(policy, crate::HttpVersionPolicy::Http2Only) {
342            builder.http2_only(true);
343        }
344        let client = builder.build(connector);
345        if clients.len() >= SOCKS_CLIENT_CACHE_MAX_ENTRIES {
346            evict_one(&mut clients);
347        }
348        clients.insert(key, client.clone());
349        Ok(client)
350    }
351}
352
353impl Client {
354    /// Create a new client with default settings.
355    #[must_use]
356    pub fn new() -> Self {
357        Self::builder().build()
358    }
359
360    /// Create a [`ClientBuilder`] for configuring a client.
361    #[must_use]
362    pub fn builder() -> ClientBuilder {
363        ClientBuilder::new()
364    }
365
366    /// Create a GET request builder for the given URL.
367    ///
368    /// # Errors
369    ///
370    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
371    pub fn get(&self, url: &str) -> Result<RequestBuilder> {
372        self.request(Method::GET, url)
373    }
374
375    /// Create a POST request builder for the given URL.
376    ///
377    /// # Errors
378    ///
379    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
380    pub fn post(&self, url: &str) -> Result<RequestBuilder> {
381        self.request(Method::POST, url)
382    }
383
384    /// Create a PUT request builder for the given URL.
385    ///
386    /// # Errors
387    ///
388    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
389    pub fn put(&self, url: &str) -> Result<RequestBuilder> {
390        self.request(Method::PUT, url)
391    }
392
393    /// Create a PATCH request builder for the given URL.
394    ///
395    /// # Errors
396    ///
397    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
398    pub fn patch(&self, url: &str) -> Result<RequestBuilder> {
399        self.request(Method::PATCH, url)
400    }
401
402    /// Create a DELETE request builder for the given URL.
403    ///
404    /// # Errors
405    ///
406    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
407    pub fn delete(&self, url: &str) -> Result<RequestBuilder> {
408        self.request(Method::DELETE, url)
409    }
410
411    /// Create a HEAD request builder for the given URL.
412    ///
413    /// # Errors
414    ///
415    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
416    pub fn head(&self, url: &str) -> Result<RequestBuilder> {
417        self.request(Method::HEAD, url)
418    }
419
420    /// Create an OPTIONS request builder for the given URL.
421    ///
422    /// # Errors
423    ///
424    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
425    pub fn options(&self, url: &str) -> Result<RequestBuilder> {
426        self.request(Method::OPTIONS, url)
427    }
428
429    /// Create a request builder for the given method and URL.
430    ///
431    /// # Errors
432    ///
433    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
434    pub fn request(&self, method: Method, url: &str) -> Result<RequestBuilder> {
435        let parsed = parse_url(url)?;
436        Ok(RequestBuilder::new(self.clone(), method, parsed))
437    }
438
439    /// Returns a reference to the connection pool metrics.
440    ///
441    /// These count logical request-permit waits/cancellations. For
442    /// connector/protocol observations see [`Self::transport_metrics`].
443    #[must_use]
444    pub fn pool_metrics(&self) -> &PoolMetrics {
445        self.inner.pool.metrics()
446    }
447
448    /// Returns a reference to the transport observability counters.
449    ///
450    /// Counts connector events (DNS/connect/TLS attempts) and protocol
451    /// connections (H3 sessions, 101 upgrades) where observable. Hyper
452    /// socket-reuse counts are intentionally absent.
453    #[must_use]
454    pub fn transport_metrics(&self) -> &crate::transport::metrics::TransportMetrics {
455        &self.inner.transport_metrics
456    }
457
458    /// Returns a reference to the client's cookie jar.
459    ///
460    /// Only available when the `cookies` feature is enabled.
461    #[cfg(feature = "cookies")]
462    #[must_use]
463    pub fn cookies(&self) -> &CookieJar {
464        &self.inner.config.cookie_jar
465    }
466
467    /// Returns a reference to the shared client configuration.
468    #[must_use]
469    pub(crate) fn config(&self) -> &ClientConfig {
470        &self.inner.config
471    }
472
473    /// Send a request and return the response, following redirects if
474    /// the client's redirect policy allows.
475    ///
476    /// The redirect loop enforces `max_redirects`, performs method
477    /// rewrites per HTTP semantics, strips sensitive headers on
478    /// cross-origin hops, and records redirect history.
479    ///
480    /// If a retry policy is configured (on the client or request), the
481    /// entire logical request is retried on failure according to the
482    /// policy.
483    ///
484    /// # Errors
485    ///
486    /// Returns an error if the request fails at any stage (connect, TLS,
487    /// protocol, body) or if a timeout elapses.
488    pub(crate) async fn send(&self, request: Request) -> Result<Response> {
489        Box::pin(crate::pipeline::send_with_retry(self, request)).await
490    }
491
492    /// Send a single HTTP request and return the streaming response.
493    ///
494    /// This handles pool acquisition, timeout application, and body
495    /// processing for one request/response cycle. It does NOT handle
496    /// redirects—that is the responsibility of [`Client::send`].
497    pub(crate) async fn send_single_request(
498        &self,
499        request: Request,
500        timeout: &Timeout,
501    ) -> Result<Response> {
502        crate::pipeline::send_single_request(&self.inner, request, timeout).await
503    }
504}
505
506impl Default for Client {
507    fn default() -> Self {
508        Self::new()
509    }
510}
511
512/// Builder for configuring a [`Client`].
513pub struct ClientBuilder {
514    default_headers: Headers,
515    user_agent: Option<String>,
516    pool_config: PoolConfig,
517    timeout: Option<Timeout>,
518    limits: Option<Limits>,
519    redirect: RedirectPolicy,
520    auth: Option<crate::auth::AuthScheme>,
521    #[cfg(feature = "cookies")]
522    cookie_jar: Option<CookieJar>,
523    automatic_decompression: Option<bool>,
524    max_decoded_body_size: Option<usize>,
525    max_decompression_ratio: Option<f64>,
526    #[cfg(feature = "proxy")]
527    proxy: Option<Proxy>,
528    #[cfg(feature = "proxy")]
529    environment_proxies: Vec<Proxy>,
530    tls_config: Option<crate::tls::TlsConfig>,
531    retry: Option<RetryPolicy>,
532    http_version_policy: HttpVersionPolicy,
533    /// Advanced direct-connector config for socket options / local address.
534    direct_connector_config: Option<crate::transport::direct_connector::DirectConnectorConfig>,
535    /// Unix domain socket path. When set, all requests use UDS transport.
536    uds_path: Option<String>,
537}
538
539impl ClientBuilder {
540    /// Create a new client builder with defaults.
541    #[must_use]
542    pub fn new() -> Self {
543        Self {
544            default_headers: Headers::new(),
545            user_agent: None,
546            pool_config: PoolConfig::default(),
547            timeout: None,
548            limits: None,
549            redirect: RedirectPolicy::default(),
550            auth: None,
551            #[cfg(feature = "cookies")]
552            cookie_jar: None,
553            automatic_decompression: None,
554            max_decoded_body_size: None,
555            max_decompression_ratio: None,
556            #[cfg(feature = "proxy")]
557            proxy: None,
558            #[cfg(feature = "proxy")]
559            environment_proxies: Vec::new(),
560            tls_config: None,
561            retry: None,
562            http_version_policy: HttpVersionPolicy::default(),
563            direct_connector_config: None,
564            uds_path: None,
565        }
566    }
567
568    /// Add a default header to all requests made by this client.
569    ///
570    /// # Errors
571    ///
572    /// Returns an error if `name` or `value` is not a valid header field.
573    pub fn default_header(mut self, name: &str, value: &str) -> Result<Self> {
574        self.default_headers.insert(name, value)?;
575        Ok(self)
576    }
577
578    /// Set the default headers for all requests made by this client.
579    ///
580    /// This preserves valid header values containing HTTP `obs-text` bytes.
581    #[must_use]
582    pub fn default_headers(mut self, headers: Headers) -> Self {
583        self.default_headers = headers;
584        self
585    }
586
587    /// Set the default user-agent header.
588    #[must_use]
589    pub fn user_agent(mut self, agent: &str) -> Self {
590        self.user_agent = Some(agent.to_owned());
591        self
592    }
593
594    /// Set the maximum number of idle (unused) connections kept per host.
595    ///
596    /// This is a convenience alias for [`max_idle_connections_per_host`]:
597    /// the transport enforces the limit on a per-host basis, so total
598    /// idle connections grow with the number of distinct origins. Use
599    /// [`max_connections`] for a global concurrency cap.
600    ///
601    /// [`max_idle_connections_per_host`]: Self::max_idle_connections_per_host
602    /// [`max_connections`]: Self::max_connections
603    #[must_use]
604    pub fn max_idle_connections(mut self, max: usize) -> Self {
605        self.pool_config.max_idle_connections = Some(max);
606        self
607    }
608
609    /// Set the maximum number of idle connections per individual host.
610    #[must_use]
611    pub fn max_idle_connections_per_host(mut self, max: usize) -> Self {
612        self.pool_config.max_idle_connections_per_host = Some(max);
613        self
614    }
615
616    /// Set the maximum total number of concurrent in-flight requests.
617    ///
618    /// Compatibility alias for [`Self::max_in_flight_requests`] kept for
619    /// the pre-1.0 line. One permit equals one logical request, not one
620    /// TCP connection (H2/H3 multiplex many requests over one
621    /// connection). Prefer `max_in_flight_requests` in new code.
622    #[must_use]
623    pub fn max_connections(mut self, max: usize) -> Self {
624        self.pool_config.max_connections = Some(max);
625        self
626    }
627
628    /// Set the maximum number of concurrent in-flight requests per origin.
629    ///
630    /// Compatibility alias for [`Self::max_in_flight_requests_per_origin`].
631    #[must_use]
632    pub fn max_connections_per_host(mut self, max: usize) -> Self {
633        self.pool_config.max_connections_per_host = Some(max);
634        self
635    }
636
637    /// Set the maximum total number of concurrent in-flight requests.
638    ///
639    /// Preferred native name. Bounds logical request concurrency (one
640    /// permit per request). Under H1 one request typically owns its
641    /// connection slot; under H2/H3 many permits multiplex over one
642    /// TCP/QUIC connection. When both this and `max_connections` are
643    /// set, this wins.
644    #[must_use]
645    pub fn max_in_flight_requests(mut self, max: usize) -> Self {
646        self.pool_config.max_in_flight_requests = Some(max);
647        self
648    }
649
650    /// Set the maximum number of concurrent in-flight requests per origin.
651    ///
652    /// Preferred native name. When both this and
653    /// `max_connections_per_host` are set, this wins.
654    #[must_use]
655    pub fn max_in_flight_requests_per_origin(mut self, max: usize) -> Self {
656        self.pool_config.max_in_flight_requests_per_origin = Some(max);
657        self
658    }
659
660    /// Set the duration after which idle connections are closed.
661    #[must_use]
662    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
663        self.pool_config.idle_timeout = Some(timeout);
664        self
665    }
666
667    /// Set the default timeout for all requests made by this client.
668    #[must_use]
669    pub fn timeout(mut self, timeout: Timeout) -> Self {
670        self.timeout = Some(timeout);
671        self
672    }
673
674    /// Merge a partial timeout configuration into the currently configured
675    /// timeout.
676    ///
677    /// Unlike [`timeout`](Self::timeout), which replaces the entire
678    /// configuration, each phase set in `timeout` overrides only that
679    /// phase; unset phases keep any previously configured value (or
680    /// remain unset when no timeout was configured yet).
681    #[must_use]
682    pub fn merge_timeout(mut self, timeout: Timeout) -> Self {
683        let merged = match self.timeout {
684            Some(existing) => existing.merge(Some(timeout)),
685            None => timeout,
686        };
687        self.timeout = Some(merged);
688        self
689    }
690
691    /// Set resource limits for the connection pool.
692    ///
693    /// Limits control logical request concurrency (pool permits) and
694    /// physical connection behavior (idle connection caps and expiry).
695    /// When set, the limits are applied to the pool configuration.
696    #[must_use]
697    pub fn limits(mut self, limits: Limits) -> Self {
698        self.limits = Some(limits);
699        self
700    }
701
702    /// Set the redirect policy for this client.
703    #[must_use]
704    pub fn follow_redirects(mut self, follow: bool) -> Self {
705        self.redirect.follow = follow;
706        self
707    }
708
709    /// Set the maximum number of redirects to follow.
710    #[must_use]
711    pub fn max_redirects(mut self, max: usize) -> Self {
712        self.redirect.max_redirects = max;
713        self
714    }
715
716    /// Set the full redirect policy.
717    #[must_use]
718    pub fn redirect_policy(mut self, policy: RedirectPolicy) -> Self {
719        self.redirect = policy;
720        self
721    }
722
723    /// Set a shared cookie jar for this client.
724    ///
725    /// When set, the client will automatically inject matching cookies
726    /// into requests and update the jar from `Set-Cookie` response headers.
727    ///
728    /// Only available when the `cookies` feature is enabled.
729    #[cfg(feature = "cookies")]
730    #[must_use]
731    pub fn cookie_jar(mut self, jar: CookieJar) -> Self {
732        self.cookie_jar = Some(jar);
733        self
734    }
735
736    /// Set default authentication for all requests made by this client.
737    ///
738    /// The configured auth is applied to every request unless overridden
739    /// or disabled at the request level. Auth is recomputed per redirect
740    /// hop; cross-origin redirects never carry client auth.
741    #[must_use]
742    pub fn auth(mut self, auth: impl Into<crate::auth::AuthScheme>) -> Self {
743        self.auth = Some(auth.into());
744        self
745    }
746
747    /// Set the default proxy for all requests made by this client.
748    ///
749    /// When set, all matching requests are routed through the specified
750    /// proxy. Can be overridden or disabled per-request.
751    #[cfg(feature = "proxy")]
752    #[must_use]
753    pub fn proxy(mut self, proxy: Proxy) -> Self {
754        self.proxy = Some(proxy);
755        self
756    }
757
758    /// Add a scheme-specific proxy used when no explicit proxy is configured.
759    #[cfg(feature = "proxy")]
760    #[must_use]
761    pub fn environment_proxy(mut self, proxy: Proxy) -> Self {
762        self.environment_proxies.push(proxy);
763        self
764    }
765
766    /// Set `NO_PROXY` bypass rules for the default proxy.
767    ///
768    /// When set, URLs matching any bypass rule are sent directly
769    /// without going through the proxy.
770    #[cfg(feature = "proxy")]
771    #[must_use]
772    pub fn no_proxy(mut self, no_proxy: crate::proxy::NoProxy) -> Self {
773        if let Some(proxy) = self.proxy.take() {
774            self.proxy = Some(proxy.no_proxy(no_proxy));
775        }
776        self
777    }
778
779    /// Set a custom TLS configuration for this client.
780    ///
781    /// When set, the client uses the provided [`crate::tls::TlsConfig`] for all
782    /// TLS connections instead of the default native-root-with-webpki-fallback
783    /// strategy.
784    #[must_use]
785    pub fn tls_config(mut self, config: crate::tls::TlsConfig) -> Self {
786        self.tls_config = Some(config);
787        self
788    }
789
790    /// Enable or disable insecure TLS verification while retaining other
791    /// TLS configuration already applied to this builder.
792    #[must_use]
793    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
794        let config = self.tls_config.take().unwrap_or_default();
795        self.tls_config = Some(config.danger_accept_invalid_certs(accept));
796        self
797    }
798
799    /// Enable or disable automatic response decompression.
800    ///
801    /// When enabled (the default), the client sends an
802    /// `Accept-Encoding` header and transparently decompresses
803    /// response bodies. Decoded `Content-Encoding` and
804    /// `Content-Length` headers are removed from the response.
805    ///
806    /// Can be overridden per-request via
807    /// [`RequestBuilder::decompress`].
808    #[must_use]
809    pub fn automatic_decompression(mut self, enabled: bool) -> Self {
810        self.automatic_decompression = Some(enabled);
811        self
812    }
813
814    /// Set the maximum decoded response body size in bytes.
815    /// When set, responses whose decompressed body exceeds this limit
816    /// produce an error instead of buffering the full content.
817    #[must_use]
818    pub fn max_decoded_body_size(mut self, max: usize) -> Self {
819        self.max_decoded_body_size = Some(max);
820        self
821    }
822
823    /// Set the maximum decompression ratio (decoded bytes / compressed bytes).
824    /// When set, responses whose expansion ratio exceeds this limit produce
825    /// an error. This guards against zip-bomb style attacks.
826    ///
827    /// # Panics
828    ///
829    /// Panics if `ratio` is not finite or not positive.
830    #[must_use]
831    pub fn max_decompression_ratio(mut self, ratio: f64) -> Self {
832        assert!(
833            ratio.is_finite() && ratio > 0.0,
834            "max_decompression_ratio must be finite and positive, got {ratio}"
835        );
836        self.max_decompression_ratio = Some(ratio);
837        self
838    }
839
840    /// Set the retry policy for this client.
841    ///
842    /// When set, failed requests that match the policy (safe methods,
843    /// retryable statuses/errors, replayable bodies) are automatically
844    /// retried with exponential backoff.
845    #[must_use]
846    pub fn retry(mut self, policy: RetryPolicy) -> Self {
847        self.retry = Some(policy);
848        self
849    }
850
851    /// Set the HTTP version policy for this client.
852    ///
853    /// Controls which HTTP protocol versions the client may negotiate.
854    /// The default is [`HttpVersionPolicy::Auto`], which allows HTTP/2
855    /// negotiation via ALPN when the `http2` feature is enabled.
856    ///
857    /// When the `http2` feature is not compiled in, `Http2Only` and `Auto`
858    /// are silently downgraded to `Http1Only`.
859    #[must_use]
860    pub fn http_version_policy(mut self, policy: HttpVersionPolicy) -> Self {
861        self.http_version_policy = policy;
862        self
863    }
864
865    /// Set a local address to bind outbound sockets to before connecting.
866    ///
867    /// When set, all direct (non-proxy, non-UDS) connections will bind
868    /// to the specified local address before connecting to the remote.
869    /// This uses a custom connector path instead of the standard
870    /// hyper-rustls connector.
871    #[must_use]
872    pub fn local_address(mut self, addr: std::net::SocketAddr) -> Self {
873        let config = self.direct_connector_config.get_or_insert_with(|| {
874            crate::transport::direct_connector::DirectConnectorConfig {
875                local_address: None,
876                socket_options: Vec::new(),
877            }
878        });
879        config.local_address = Some(addr);
880        self
881    }
882
883    /// Set socket options to apply to outbound TCP connections.
884    ///
885    /// Options are applied to the socket before the connect operation.
886    /// Recognized options are applied via `tokio::net::TcpSocket` setters;
887    /// unrecognized options produce a connection error (never silently
888    /// ignored, per the plan's Track 2.4 requirement).
889    #[must_use]
890    pub fn socket_options(
891        mut self,
892        options: Vec<crate::transport::direct_connector::SocketOption>,
893    ) -> Self {
894        let config = self.direct_connector_config.get_or_insert_with(|| {
895            crate::transport::direct_connector::DirectConnectorConfig {
896                local_address: None,
897                socket_options: Vec::new(),
898            }
899        });
900        config.socket_options = options;
901        self
902    }
903
904    /// Set a Unix domain socket path for all connections.
905    ///
906    /// When set, all requests are routed through the specified UDS path
907    /// instead of making TCP connections. The URL in the request still
908    /// provides HTTP scheme/authority/path semantics.
909    ///
910    /// Only supported on Unix platforms. On non-Unix platforms, this
911    /// option is accepted but will produce an error at request time.
912    #[must_use]
913    pub fn uds_path(mut self, path: String) -> Self {
914        self.uds_path = Some(path);
915        self
916    }
917
918    /// Build the client.
919    ///
920    /// Native system roots are preferred. If the platform root store is
921    /// unavailable, the client falls back to the packaged Mozilla root set
922    /// while retaining certificate and hostname verification.
923    #[must_use]
924    #[allow(clippy::too_many_lines)]
925    pub fn build(self) -> Client {
926        use crate::http_version::HttpVersionPolicyEnabler;
927        let enabler = HttpVersionPolicyEnabler::from_policy(self.http_version_policy);
928        let transport_metrics = Arc::new(crate::transport::metrics::TransportMetrics::new());
929
930        let mut pool_config = self.pool_config;
931        if let Some(limits) = self.limits {
932            let limits_config: PoolConfig = limits.into();
933            if limits_config.max_connections.is_some() {
934                pool_config.max_connections = limits_config.max_connections;
935            }
936            if limits_config.max_connections_per_host.is_some() {
937                pool_config.max_connections_per_host = limits_config.max_connections_per_host;
938            }
939            if limits_config.max_in_flight_requests.is_some() {
940                pool_config.max_in_flight_requests = limits_config.max_in_flight_requests;
941            }
942            if limits_config.max_in_flight_requests_per_origin.is_some() {
943                pool_config.max_in_flight_requests_per_origin =
944                    limits_config.max_in_flight_requests_per_origin;
945            }
946            if limits_config.max_idle_connections.is_some() {
947                pool_config.max_idle_connections = limits_config.max_idle_connections;
948            }
949            if limits_config.max_idle_connections_per_host.is_some() {
950                pool_config.max_idle_connections_per_host =
951                    limits_config.max_idle_connections_per_host;
952            }
953            if limits_config.idle_timeout.is_some() {
954                pool_config.idle_timeout = limits_config.idle_timeout;
955            }
956        }
957
958        #[cfg(feature = "cookies")]
959        let cookie_jar = self.cookie_jar.unwrap_or_default();
960
961        let automatic_decompression = self.automatic_decompression.unwrap_or(true);
962        let tls_config_result = self
963            .tls_config
964            .as_ref()
965            .map(crate::tls::TlsConfig::build_rustls_config);
966        let tls_config_error = tls_config_result.as_ref().and_then(|result| {
967            result
968                .as_ref()
969                .err()
970                .map(|error| format!("failed to build TLS config: {error}"))
971        });
972
973        // `Http3Only` is strict direct-QUIC and needs no Hyper client.
974        // `Auto { allow_http3: true }` needs both: H1/H2 for discovery and
975        // safe fallback plus QUIC for discovered routes. All other policies
976        // need Hyper only.
977        let hyper_client = if matches!(
978            self.http_version_policy,
979            crate::HttpVersionPolicy::Http3Only
980        ) || tls_config_error.is_some()
981        {
982            None
983        } else {
984            let https = match tls_config_result {
985                Some(Ok(mut rc)) => {
986                    // hyper-rustls requires empty ALPN; it rebuilds based
987                    // on enable_http1/enable_http2 calls.
988                    rc.alpn_protocols.clear();
989                    let builder = hyper_rustls::HttpsConnectorBuilder::new()
990                        .with_tls_config(rc)
991                        .https_or_http();
992                    #[cfg(feature = "http2")]
993                    {
994                        match (enabler.enable_http1(), enabler.enable_http2()) {
995                            (true, true) => builder.enable_http1().enable_http2().build(),
996                            (true | false, false) => builder.enable_http1().build(),
997                            (false, true) => builder.enable_http2().build(),
998                        }
999                    }
1000                    #[cfg(not(feature = "http2"))]
1001                    {
1002                        let _ = enabler;
1003                        builder.enable_http1().build()
1004                    }
1005                }
1006                Some(Err(_)) | None => build_fallback_connector(enabler),
1007            };
1008
1009            // Wrap the connector with connect-phase timeout if configured.
1010            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1011            let https =
1012                crate::transport::connect_timeout::ConnectTimeout::new(https, connect_timeout);
1013
1014            let mut builder = hyper_util::client::legacy::Client::builder(TokioExecutor::new());
1015            // When HTTP/1 is disabled and HTTP/2 is enabled, mark the legacy
1016            // client as HTTP/2-only. This is what enforces the protocol
1017            // contract: hyper-util will attempt an HTTP/2 handshake on every
1018            // socket (including cleartext, where it falls through to HTTP/2
1019            // prior knowledge). When ALPN does not negotiate `h2`, the
1020            // HTTP/2 handshake fails with a `Connect` error rather than
1021            // silently downgrading to HTTP/1.1.
1022            #[cfg(feature = "http2")]
1023            if !enabler.enable_http1() && enabler.enable_http2() {
1024                builder.http2_only(true);
1025            }
1026            if let Some(timeout) = pool_config.idle_timeout {
1027                builder.pool_idle_timeout(timeout);
1028            }
1029            if let Some(max_idle) = pool_config
1030                .max_idle_connections_per_host
1031                .or(pool_config.max_idle_connections)
1032            {
1033                builder.pool_max_idle_per_host(max_idle);
1034            }
1035            Some(builder.build(https))
1036        };
1037
1038        #[cfg(feature = "http3")]
1039        let h3_connector = if enabler.use_http3() {
1040            crate::transport::http3::H3Connector::with_metrics(
1041                self.tls_config.clone(),
1042                &pool_config,
1043                Some(transport_metrics.clone()),
1044            )
1045            .ok()
1046        } else {
1047            None
1048        };
1049
1050        // Build the direct connector client for advanced socket options / local
1051        // address binding. This uses a custom connector path instead of the
1052        // standard hyper-rustls connector.
1053        let stored_direct_config = self.direct_connector_config.clone();
1054        let direct_client = if let Some(dc_config) = self.direct_connector_config {
1055            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1056
1057            // Build a TLS connector for HTTPS through the direct path.
1058            let tls_connector = match self.tls_config.as_ref() {
1059                Some(tls_config) => match tls_config.build_rustls_config() {
1060                    Ok(rc) => Some(tokio_rustls::TlsConnector::from(Arc::new(
1061                        configure_tls_alpn(
1062                            rc,
1063                            crate::http_version::HttpVersionPolicyEnabler::from_policy(
1064                                self.http_version_policy,
1065                            ),
1066                        ),
1067                    ))),
1068                    Err(_) => None,
1069                },
1070                None => None,
1071            };
1072
1073            let direct_connector =
1074                crate::transport::direct_connector::DirectConnector::with_metrics(
1075                    dc_config,
1076                    tls_connector,
1077                    transport_metrics.clone(),
1078                );
1079            let direct_connector = crate::transport::connect_timeout::ConnectTimeout::new(
1080                direct_connector,
1081                connect_timeout,
1082            );
1083
1084            let mut builder = hyper_util::client::legacy::Client::builder(TokioExecutor::new());
1085            // Match the standard hyper-rustls path: when H2-only, force
1086            // http2_only on the legacy client so HTTP/2 handshake runs even
1087            // when the connector does not advertise ALPN h2. The
1088            // DirectConnector itself signals ALPN h2 via `Connected::negotiated_h2`
1089            // when TLS selected it.
1090            #[cfg(feature = "http2")]
1091            if !enabler.enable_http1() && enabler.enable_http2() {
1092                builder.http2_only(true);
1093            }
1094            if let Some(timeout) = pool_config.idle_timeout {
1095                builder.pool_idle_timeout(timeout);
1096            }
1097            if let Some(max_idle) = pool_config
1098                .max_idle_connections_per_host
1099                .or(pool_config.max_idle_connections)
1100            {
1101                builder.pool_max_idle_per_host(max_idle);
1102            }
1103            Some(builder.build(direct_connector))
1104        } else {
1105            None
1106        };
1107
1108        #[cfg(unix)]
1109        let uds_client = self.uds_path.map(|path| {
1110            let tls_connector = self.tls_config.as_ref().and_then(|config| {
1111                config.build_rustls_config().ok().map(|rc| {
1112                    tokio_rustls::TlsConnector::from(Arc::new(configure_tls_alpn(
1113                        rc,
1114                        crate::http_version::HttpVersionPolicyEnabler::from_policy(
1115                            self.http_version_policy,
1116                        ),
1117                    )))
1118                })
1119            });
1120            let connector = crate::transport::uds::UdsConnector::with_metrics(
1121                path,
1122                tls_connector,
1123                transport_metrics.clone(),
1124            );
1125            let connector = crate::transport::connect_timeout::ConnectTimeout::new(
1126                connector,
1127                self.timeout.as_ref().and_then(|timeout| timeout.connect),
1128            );
1129            let mut builder = hyper_util::client::legacy::Client::builder(TokioExecutor::new());
1130            // Mirror the standard and direct paths: when H2-only, force
1131            // http2_only on the legacy client. The UDS connector signals ALPN
1132            // h2 via `Connected::negotiated_h2` when TLS selected it.
1133            #[cfg(feature = "http2")]
1134            if !enabler.enable_http1() && enabler.enable_http2() {
1135                builder.http2_only(true);
1136            }
1137            if let Some(timeout) = pool_config.idle_timeout {
1138                builder.pool_idle_timeout(timeout);
1139            }
1140            if let Some(max_idle) = pool_config
1141                .max_idle_connections_per_host
1142                .or(pool_config.max_idle_connections)
1143            {
1144                builder.pool_max_idle_per_host(max_idle);
1145            }
1146            builder.build(connector)
1147        });
1148
1149        let config = ClientConfig {
1150            default_headers: self.default_headers,
1151            user_agent: self.user_agent,
1152            timeout: self.timeout,
1153            redirect: self.redirect,
1154            auth: self.auth,
1155            #[cfg(feature = "cookies")]
1156            cookie_jar,
1157            automatic_decompression,
1158            max_decoded_body_size: self.max_decoded_body_size,
1159            max_decompression_ratio: self.max_decompression_ratio,
1160            #[cfg(feature = "proxy")]
1161            proxy: self.proxy,
1162            #[cfg(feature = "proxy")]
1163            environment_proxies: self.environment_proxies,
1164            #[cfg(any(feature = "proxy", feature = "http3"))]
1165            tls_config: self.tls_config,
1166            retry: self.retry,
1167            http_version_policy: self.http_version_policy,
1168        };
1169
1170        let pool = Pool::new(pool_config);
1171
1172        Client {
1173            inner: Arc::new(ClientInner {
1174                hyper_client,
1175                tls_config_error,
1176                direct_client,
1177                direct_connector_config: stored_direct_config,
1178                sni_clients: Mutex::new(HashMap::new()),
1179                #[cfg(unix)]
1180                uds_client,
1181                #[cfg(feature = "proxy")]
1182                socks_clients: Mutex::new(HashMap::new()),
1183                config,
1184                pool,
1185                transport_metrics,
1186                #[cfg(feature = "http3")]
1187                h3_connector,
1188                #[cfg(feature = "http3")]
1189                alt_svc_state: Arc::new(crate::transport::alt_svc::AltSvcState::new()),
1190            }),
1191        }
1192    }
1193}
1194
1195/// Build a connector with fallback root stores.
1196///
1197/// Uses native roots when available, otherwise falls back to the packaged
1198/// Mozilla root set. Protocol versions are determined by the enabler.
1199fn build_fallback_connector(enabler: crate::http_version::HttpVersionPolicyEnabler) -> Connector {
1200    let builder = match hyper_rustls::HttpsConnectorBuilder::new().with_native_roots() {
1201        Ok(b) => b,
1202        Err(_) => hyper_rustls::HttpsConnectorBuilder::new().with_webpki_roots(),
1203    };
1204    #[cfg(feature = "http2")]
1205    {
1206        match (enabler.enable_http1(), enabler.enable_http2()) {
1207            (true, true) => builder
1208                .https_or_http()
1209                .enable_http1()
1210                .enable_http2()
1211                .build(),
1212            (true | false, false) => builder.https_or_http().enable_http1().build(),
1213            (false, true) => builder.https_or_http().enable_http2().build(),
1214        }
1215    }
1216    #[cfg(not(feature = "http2"))]
1217    {
1218        let _ = enabler;
1219        builder.https_or_http().enable_http1().build()
1220    }
1221}
1222
1223impl Default for ClientBuilder {
1224    fn default() -> Self {
1225        Self::new()
1226    }
1227}
1228
1229fn parse_url(url_str: &str) -> Result<url::Url> {
1230    // Deliberately do not echo `url_str` into the error: parsing has
1231    // failed, so `redact_url_string` would fall back to the raw input
1232    // (potentially containing credentials). `url::ParseError` renders
1233    // only a static description and never embeds the input.
1234    let url = url::Url::parse(url_str).map_err(|e| Error::InvalidUrl(e.to_string()))?;
1235    if !url.username().is_empty() || url.password().is_some() {
1236        // URL userinfo is both easy to leak through diagnostics and
1237        // surprising for an HTTP client with explicit auth APIs.
1238        return Err(Error::InvalidUrl(
1239            "URL userinfo is not supported; configure authentication explicitly".into(),
1240        ));
1241    }
1242    match url.scheme() {
1243        "http" | "https" => Ok(url),
1244        other => Err(Error::Unsupported(format!(
1245            "URL scheme '{other}' is not supported; use http or https"
1246        ))),
1247    }
1248}
1249
1250#[cfg(test)]
1251mod tests {
1252    use super::*;
1253    #[cfg(feature = "proxy")]
1254    use crate::proxy::ProxyAuth;
1255    use bytes::Bytes;
1256
1257    #[test]
1258    fn client_constructs() {
1259        let _client = Client::new();
1260    }
1261
1262    #[test]
1263    fn client_config_debug_redacts_secrets() {
1264        let mut config = ClientConfig::default();
1265        config
1266            .default_headers
1267            .insert("authorization", "Bearer header-secret-token")
1268            .unwrap();
1269        #[cfg(feature = "cookies")]
1270        config
1271            .cookie_jar
1272            .set_default_cookie("session".to_owned(), "jar-secret-token".to_owned())
1273            .expect("valid test cookie");
1274        let debug = format!("{config:?}");
1275        assert!(
1276            !debug.contains("header-secret-token"),
1277            "ClientConfig Debug must not leak header secrets: {debug}"
1278        );
1279        #[cfg(feature = "cookies")]
1280        assert!(
1281            !debug.contains("jar-secret-token"),
1282            "ClientConfig Debug must not leak jar secrets: {debug}"
1283        );
1284    }
1285
1286    #[test]
1287    fn client_default() {
1288        let _client = Client::default();
1289    }
1290
1291    #[test]
1292    fn client_builder() {
1293        let _client = Client::builder().user_agent("test-agent").build();
1294    }
1295
1296    #[test]
1297    fn client_builder_merge_timeout_preserves_other_phases() {
1298        // Phase-specific setters must merge into any existing timeout
1299        // configuration instead of replacing it wholesale.
1300        let client = Client::builder()
1301            .timeout(Timeout::from_secs(30))
1302            .merge_timeout(
1303                Timeout::builder()
1304                    .connect(std::time::Duration::from_secs(5))
1305                    .build(),
1306            )
1307            .merge_timeout(
1308                Timeout::builder()
1309                    .read(std::time::Duration::from_secs(10))
1310                    .build(),
1311            )
1312            .build();
1313
1314        let timeout = client.inner.config.timeout.expect("timeout configured");
1315        let d = |secs: u64| std::time::Duration::from_secs(secs);
1316        assert_eq!(timeout.connect, Some(d(5)), "last connect wins");
1317        assert_eq!(timeout.read, Some(d(10)), "last read wins");
1318        assert_eq!(
1319            timeout.write,
1320            Some(d(30)),
1321            "unset phases keep earlier values"
1322        );
1323        assert_eq!(timeout.pool, Some(d(30)));
1324    }
1325
1326    #[test]
1327    fn client_builder_merge_timeout_without_prior_config() {
1328        let client = Client::builder()
1329            .merge_timeout(
1330                Timeout::builder()
1331                    .connect(std::time::Duration::from_secs(5))
1332                    .build(),
1333            )
1334            .build();
1335
1336        let timeout = client.inner.config.timeout.expect("timeout configured");
1337        assert_eq!(timeout.connect, Some(std::time::Duration::from_secs(5)));
1338        assert_eq!(timeout.read, None);
1339    }
1340
1341    #[cfg(any(feature = "proxy", feature = "http3"))]
1342    #[test]
1343    fn client_builder_danger_accept_invalid_certs_preserves_tls_config() {
1344        let client = Client::builder()
1345            .tls_config(crate::tls::TlsConfig::builder().sni(false).build())
1346            .danger_accept_invalid_certs(true)
1347            .build();
1348        let tls = client
1349            .inner
1350            .config
1351            .tls_config
1352            .as_ref()
1353            .expect("TLS config should be retained");
1354        assert!(!tls.sni_enabled());
1355        assert!(!tls.verify_certificate());
1356        assert!(!tls.verify_hostname());
1357    }
1358
1359    #[test]
1360    fn tls_root_store_paths_construct() {
1361        // Native roots are environment-dependent, but when available the
1362        // production path must build the same verified connector shape.
1363        if let Ok(builder) = hyper_rustls::HttpsConnectorBuilder::new().with_native_roots() {
1364            let _ = builder.https_or_http().enable_http1().build();
1365        }
1366        let enabler =
1367            crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
1368                allow_http3: false,
1369            });
1370        let _ = build_fallback_connector(enabler);
1371    }
1372
1373    #[test]
1374    fn client_builder_http1_only() {
1375        let client = Client::builder()
1376            .http_version_policy(HttpVersionPolicy::Http1Only)
1377            .build();
1378        assert_eq!(
1379            client.inner.config.http_version_policy,
1380            HttpVersionPolicy::Http1Only
1381        );
1382    }
1383
1384    #[test]
1385    fn client_builder_http2_auto() {
1386        let client = Client::builder()
1387            .http_version_policy(HttpVersionPolicy::Auto { allow_http3: false })
1388            .build();
1389        assert_eq!(
1390            client.inner.config.http_version_policy,
1391            HttpVersionPolicy::Auto { allow_http3: false }
1392        );
1393    }
1394
1395    #[test]
1396    #[cfg(feature = "http2")]
1397    fn client_builder_http2_only() {
1398        let client = Client::builder()
1399            .http_version_policy(HttpVersionPolicy::Http2Only)
1400            .build();
1401        assert_eq!(
1402            client.inner.config.http_version_policy,
1403            HttpVersionPolicy::Http2Only
1404        );
1405    }
1406
1407    #[test]
1408    fn connector_builds_for_all_policies() {
1409        for policy in [
1410            HttpVersionPolicy::Http1Only,
1411            HttpVersionPolicy::Auto { allow_http3: false },
1412            #[cfg(feature = "http2")]
1413            HttpVersionPolicy::Http2Only,
1414            #[cfg(feature = "http3")]
1415            HttpVersionPolicy::Http3Only,
1416        ] {
1417            let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(policy);
1418            if !enabler.use_http3() {
1419                let _ = build_fallback_connector(enabler);
1420            }
1421        }
1422    }
1423
1424    #[cfg(feature = "http2")]
1425    #[test]
1426    fn custom_connector_alpn_matches_http_version_policy() {
1427        let config = rustls::ClientConfig::builder()
1428            .with_root_certificates(rustls::RootCertStore::empty())
1429            .with_no_client_auth();
1430        let h2_only = configure_tls_alpn(
1431            config.clone(),
1432            crate::http_version::HttpVersionPolicyEnabler::from_policy(
1433                HttpVersionPolicy::Http2Only,
1434            ),
1435        );
1436        assert_eq!(h2_only.alpn_protocols, vec![b"h2".to_vec()]);
1437
1438        let auto = configure_tls_alpn(
1439            config,
1440            crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
1441                allow_http3: false,
1442            }),
1443        );
1444        assert_eq!(
1445            auto.alpn_protocols,
1446            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
1447        );
1448    }
1449
1450    #[test]
1451    fn parse_valid_urls() {
1452        assert!(parse_url("https://example.com").is_ok());
1453        assert!(parse_url("http://localhost:8080").is_ok());
1454    }
1455
1456    #[test]
1457    fn parse_invalid_schemes() {
1458        assert!(parse_url("ftp://example.com").is_err());
1459        assert!(parse_url("file:///tmp/test").is_err());
1460    }
1461
1462    #[test]
1463    fn parse_invalid_urls() {
1464        assert!(parse_url("not a url").is_err());
1465    }
1466
1467    #[test]
1468    fn get_request_builder() {
1469        let client = Client::new();
1470        let builder = client.get("https://example.com").unwrap();
1471        let req = builder.build().unwrap();
1472        assert_eq!(*req.method(), Method::GET);
1473    }
1474
1475    #[test]
1476    fn apply_content_length_empty_body() {
1477        let headers = Headers::new();
1478        let body = crate::body::RequestBody::Empty;
1479        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1480        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "0");
1481    }
1482
1483    #[test]
1484    fn apply_content_length_bytes_body() {
1485        let headers = Headers::new();
1486        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1487        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1488        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
1489    }
1490
1491    #[test]
1492    fn apply_content_length_stream_known() {
1493        let headers = Headers::new();
1494        let stream = futures_util::stream::empty::<Result<Bytes>>();
1495        let body = crate::body::RequestBody::from_stream(stream, Some(7));
1496        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1497        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "7");
1498    }
1499
1500    #[test]
1501    fn apply_content_length_stream_unknown() {
1502        let headers = Headers::new();
1503        let stream = futures_util::stream::empty::<Result<Bytes>>();
1504        let body = crate::body::RequestBody::from_stream(stream, None);
1505        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1506        assert!(out.get("content-length").is_none());
1507    }
1508
1509    #[test]
1510    fn apply_content_length_user_matches() {
1511        let mut headers = Headers::new();
1512        headers.insert("content-length", "5").unwrap();
1513        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1514        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1515        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
1516    }
1517
1518    #[test]
1519    fn apply_content_length_user_mismatch_errors() {
1520        let mut headers = Headers::new();
1521        headers.insert("content-length", "10").unwrap();
1522        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1523        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1524        assert_eq!(err.kind(), "request_build");
1525    }
1526
1527    #[test]
1528    fn apply_content_length_rejects_invalid_value() {
1529        let mut headers = Headers::new();
1530        headers.insert("content-length", "not-a-number").unwrap();
1531        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1532        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1533        assert_eq!(err.kind(), "invalid_header_value");
1534    }
1535
1536    #[test]
1537    fn apply_content_length_rejects_unknown_stream_override() {
1538        let mut headers = Headers::new();
1539        headers.insert("content-length", "5").unwrap();
1540        let stream = futures_util::stream::empty::<Result<Bytes>>();
1541        let body = crate::body::RequestBody::from_stream(stream, None);
1542        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1543        assert_eq!(err.kind(), "request_build");
1544    }
1545
1546    #[test]
1547    fn parse_url_rejects_userinfo_without_echoing_credentials() {
1548        let err = parse_url("https://user:secret@example.com").unwrap_err();
1549        assert_eq!(err.kind(), "invalid_url");
1550        assert!(!err.to_string().contains("secret"));
1551    }
1552
1553    #[cfg(feature = "proxy")]
1554    #[tokio::test]
1555    async fn proxy_auth_conflict_with_header() {
1556        let proxy = Proxy::all("http://proxy.example:8080")
1557            .unwrap()
1558            .auth(ProxyAuth::basic("user", "pass").unwrap());
1559        let client = Client::builder().proxy(proxy).build();
1560        let request = client
1561            .get("http://destination.example")
1562            .unwrap()
1563            .header("proxy-authorization", "Basic dXNlcjpwYXNz")
1564            .build()
1565            .unwrap();
1566        let err = client.send(request).await.unwrap_err();
1567        assert_eq!(err.kind(), "conflicting_auth");
1568        assert!(err.to_string().contains("Proxy-Authorization"));
1569    }
1570
1571    #[cfg(feature = "proxy")]
1572    #[tokio::test]
1573    async fn proxy_auth_no_conflict_without_header() {
1574        let proxy = Proxy::all("http://proxy.example:8080")
1575            .unwrap()
1576            .auth(ProxyAuth::basic("user", "pass").unwrap());
1577        let client = Client::builder().proxy(proxy).build();
1578        let request = client
1579            .get("http://destination.example")
1580            .unwrap()
1581            .build()
1582            .unwrap();
1583        let err = client.send(request).await.unwrap_err();
1584        assert_ne!(err.kind(), "conflicting_auth");
1585    }
1586
1587    #[cfg(feature = "proxy")]
1588    #[tokio::test]
1589    async fn proxy_auth_no_conflict_with_header_only() {
1590        let proxy = Proxy::all("http://proxy.example:8080").unwrap();
1591        let client = Client::builder().proxy(proxy).build();
1592        let request = client
1593            .get("http://destination.example")
1594            .unwrap()
1595            .header("proxy-authorization", "Basic dXNlcjpwYXNz")
1596            .build()
1597            .unwrap();
1598        let err = client.send(request).await.unwrap_err();
1599        assert_ne!(err.kind(), "conflicting_auth");
1600    }
1601}