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