Skip to main content

eggfetch_core/
client.rs

1//! Async client entry point.
2
3use std::sync::Arc;
4use std::time::Duration;
5
6#[cfg(any(feature = "http1", feature = "http2"))]
7use crate::transport::hyper_client::{
8    build_hyper_client, BoundedClientCache, HyperClientPolicy, SNI_CLIENT_CACHE_MAX_ENTRIES,
9};
10#[cfg(feature = "proxy")]
11use crate::transport::hyper_client::{
12    CONNECT_CLIENT_CACHE_MAX_ENTRIES, FORWARD_CLIENT_CACHE_MAX_ENTRIES,
13    SOCKS_CLIENT_CACHE_MAX_ENTRIES,
14};
15use http::Method;
16#[cfg(any(feature = "http1", feature = "http2"))]
17use tokio::sync::Mutex;
18
19use crate::error::{Error, Result};
20use crate::headers::Headers;
21use crate::http_version::HttpVersionPolicy;
22use crate::limits::Limits;
23use crate::pool::{Pool, PoolConfig, PoolMetrics};
24#[cfg(feature = "proxy")]
25use crate::proxy::Proxy;
26use crate::redirect::RedirectPolicy;
27use crate::request::{NativeRequestOptions, Request, RequestBuilder};
28use crate::response::Response;
29use crate::retry::RetryPolicy;
30use crate::timeout::Timeout;
31use crate::transport::dialer::Dialer;
32#[cfg(any(feature = "http1", feature = "http2"))]
33use crate::transport::lifecycle::LifecycleConfig;
34use crate::transport::lifecycle::{PhysicalConnectionPolicy, TransportIoTimeout};
35use crate::transport::Connector;
36
37#[cfg(feature = "cookies")]
38use crate::cookie::CookieJar;
39
40/// Shared client configuration.
41///
42/// `Debug` is intentionally manual: several fields hold secrets (notably
43/// the cookie jar), so the implementation redacts them instead of deriving
44/// a verbatim dump. See [`crate::redact`].
45#[derive(Clone)]
46pub(crate) struct ClientConfig {
47    pub(crate) default_headers: Headers,
48    pub(crate) user_agent: Option<String>,
49    pub(crate) timeout: Option<Timeout>,
50    pub(crate) redirect: RedirectPolicy,
51    pub(crate) auth: Option<crate::auth::AuthScheme>,
52    #[cfg(feature = "cookies")]
53    pub(crate) cookie_jar: CookieJar,
54    pub(crate) automatic_decompression: bool,
55    pub(crate) max_decoded_body_size: Option<usize>,
56    pub(crate) max_decompression_ratio: Option<f64>,
57    #[cfg(feature = "proxy")]
58    pub(crate) proxy: Option<Proxy>,
59    #[cfg(feature = "proxy")]
60    pub(crate) environment_proxies: Vec<Proxy>,
61    #[cfg(feature = "tls-rustls")]
62    pub(crate) tls_config: Option<crate::tls::TlsConfig>,
63    pub(crate) retry: Option<RetryPolicy>,
64    pub(crate) retry_canceled_requests: bool,
65    pub(crate) dialer: Option<Arc<dyn Dialer>>,
66    pub(crate) uds_configured: bool,
67    #[allow(
68        dead_code,
69        reason = "stored for inspection and future request-level use"
70    )]
71    pub(crate) http_version_policy: HttpVersionPolicy,
72}
73
74impl std::fmt::Debug for ClientConfig {
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        let mut debug = f.debug_struct("ClientConfig");
77        debug
78            .field("default_headers", &self.default_headers)
79            .field("user_agent", &self.user_agent)
80            .field("timeout", &self.timeout)
81            .field("redirect", &self.redirect)
82            .field("auth", &self.auth);
83        #[cfg(feature = "cookies")]
84        debug.field("cookie_jar", &self.cookie_jar);
85        debug
86            .field("automatic_decompression", &self.automatic_decompression)
87            .field("max_decoded_body_size", &self.max_decoded_body_size)
88            .field("max_decompression_ratio", &self.max_decompression_ratio);
89        #[cfg(feature = "proxy")]
90        debug
91            .field("proxy", &self.proxy)
92            .field("environment_proxies", &self.environment_proxies);
93        #[cfg(feature = "tls-rustls")]
94        debug.field("tls_config", &self.tls_config);
95        debug
96            .field("retry", &self.retry)
97            .field("retry_canceled_requests", &self.retry_canceled_requests)
98            .field("dialer", &self.dialer.as_ref().map(|_| "configured"))
99            .field("uds_configured", &self.uds_configured)
100            .field("http_version_policy", &self.http_version_policy)
101            .finish_non_exhaustive()
102    }
103}
104
105impl Default for ClientConfig {
106    fn default() -> Self {
107        Self {
108            default_headers: Headers::new(),
109            user_agent: None,
110            timeout: None,
111            redirect: RedirectPolicy::default(),
112            auth: None,
113            #[cfg(feature = "cookies")]
114            cookie_jar: CookieJar::new(),
115            automatic_decompression: true,
116            max_decoded_body_size: None,
117            max_decompression_ratio: None,
118            #[cfg(feature = "proxy")]
119            proxy: None,
120            #[cfg(feature = "proxy")]
121            environment_proxies: Vec::new(),
122            #[cfg(feature = "tls-rustls")]
123            tls_config: None,
124            retry: None,
125            retry_canceled_requests: true,
126            dialer: None,
127            uds_configured: false,
128            http_version_policy: HttpVersionPolicy::default(),
129        }
130    }
131}
132
133/// Async HTTP client.
134///
135/// The client manages connection pooling and shared configuration. Create one
136/// with [`Client::new`] or [`Client::builder`].
137#[derive(Clone)]
138pub struct Client {
139    inner: Arc<ClientInner>,
140}
141
142impl std::fmt::Debug for Client {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        f.debug_struct("Client").finish_non_exhaustive()
145    }
146}
147
148pub(crate) struct ClientInner {
149    #[cfg(any(feature = "http1", feature = "http2"))]
150    pub(crate) hyper_client: Option<crate::transport::TimeoutHyperClient>,
151    /// Hyper client backed by the caller-supplied native dialer.
152    #[cfg(any(feature = "http1", feature = "http2"))]
153    pub(crate) custom_client: Option<crate::transport::TimeoutCustomClient>,
154    /// Error captured while building the configured TLS policy, if any.
155    ///
156    /// `ClientBuilder::build` is intentionally infallible, so HTTPS requests
157    /// surface this error at dispatch time instead of falling back to a
158    /// different trust policy.
159    #[cfg(feature = "tls-rustls")]
160    pub(crate) tls_config_error: Option<String>,
161    /// Direct connector for requests with advanced socket options or local
162    /// address binding. Uses a custom connector instead of the standard
163    /// hyper-rustls connector path.
164    #[cfg(any(feature = "http1", feature = "http2"))]
165    pub(crate) direct_client: Option<crate::transport::TimeoutDirectClient>,
166    /// Base direct-connector configuration (local address / socket options)
167    /// used to construct SNI-override clients so they preserve source
168    /// binding and socket tuning.
169    #[cfg(any(feature = "http1", feature = "http2"))]
170    pub(crate) direct_connector_config:
171        Option<crate::transport::direct_connector::DirectConnectorConfig>,
172    /// Cached hyper clients keyed by TLS SNI hostname override.
173    ///
174    /// When a request carries `TransportHints.sni_hostname`, the pipeline
175    /// uses a DirectConnector-based client from this cache. The connector
176    /// separates DNS/TCP (to the original URL host) from TLS (with the
177    /// SNI override hostname), keeping the default path unchanged.
178    ///
179    /// Bounded by [`SNI_CLIENT_CACHE_MAX_ENTRIES`] via the shared
180    /// [`BoundedClientCache`] mechanics (see `transport::hyper_client`).
181    ///
182    /// The cache is keyed only by hostname because every other
183    /// connection-affecting dimension is immutable at `ClientInner` scope
184    /// after `ClientBuilder::build`: `http_version_policy` and `tls_config`
185    /// ALPN, `direct_connector_config` socket/local-address policy,
186    /// `timeout.connect` phase policy, and the absence of a custom dialer
187    /// on this path. If any of those became per-request mutable, this
188    /// cache would need to include the changed dimension in the key to
189    /// avoid serving a client with stale policy (e.g. H2 vs H1) for the
190    /// same hostname. Request-scoped state (total/read/write/pool
191    /// deadlines, retry/redirect, body, trace/failure context,
192    /// decompression limits, cookies/auth headers) is never keyed and
193    /// never retained by the cached connector.
194    #[cfg(any(feature = "http1", feature = "http2"))]
195    pub(crate) sni_clients:
196        Mutex<BoundedClientCache<String, crate::transport::TimeoutDirectClient>>,
197    /// Cached custom-dialer clients for per-request SNI overrides.
198    #[cfg(any(feature = "http1", feature = "http2"))]
199    pub(crate) sni_custom_clients:
200        Mutex<BoundedClientCache<String, crate::transport::TimeoutCustomClient>>,
201    /// Hyper client for Unix domain socket requests.
202    #[cfg(unix)]
203    #[cfg(any(feature = "http1", feature = "http2"))]
204    pub(crate) uds_client: Option<crate::transport::TimeoutUdsClient>,
205    /// Persistent Hyper clients keyed by effective SOCKS route.
206    ///
207    /// Bounded like [`ClientInner::sni_clients`] via the shared
208    /// [`BoundedClientCache`] mechanics (see `transport::hyper_client`).
209    /// SOCKS route clients share the resolved Hyper idle-pool policy with
210    /// every other persistent Hyper family.
211    #[cfg(feature = "proxy")]
212    pub(crate) socks_clients: Mutex<
213        BoundedClientCache<
214            crate::transport::socks::SocksRouteKey,
215            crate::transport::TimeoutSocksClient,
216        >,
217    >,
218    /// Persistent Hyper clients for ordinary HTTP forward-proxy routes.
219    /// Keys include the destination origin and every proxy-leg policy that
220    /// can affect a reusable connection. The cache is bounded because
221    /// request-scoped proxy overrides are allowed.
222    #[cfg(feature = "proxy")]
223    pub(crate) forward_clients: Mutex<
224        BoundedClientCache<
225            crate::transport::proxy::ForwardRouteKey,
226            crate::transport::TimeoutForwardClient,
227        >,
228    >,
229    /// Persistent Hyper clients for one HTTPS origin reached through CONNECT.
230    #[cfg(feature = "proxy")]
231    pub(crate) connect_clients: Mutex<
232        BoundedClientCache<
233            crate::transport::connect::ConnectRouteKey,
234            crate::transport::TimeoutConnectClient,
235        >,
236    >,
237    pub(crate) config: ClientConfig,
238    pub(crate) pool: Pool,
239    /// Transport observability counters shared by all connectors owned by
240    /// this client. Distinct from [`Pool`] logical-permit metrics.
241    pub(crate) transport_metrics: Arc<crate::transport::metrics::TransportMetrics>,
242    /// Shared admission permits and established-I/O timeout policy.
243    #[cfg(any(feature = "http1", feature = "http2"))]
244    pub(crate) lifecycle: Arc<LifecycleConfig>,
245    #[cfg(feature = "http3")]
246    pub(crate) h3_connector: Option<crate::transport::http3::H3Connector>,
247    /// Bounded Alt-Svc discovery state (separate from QUIC sessions).
248    /// Owned here so all routes share one view. Only present with `http3`;
249    /// without it there is no discovery and no state to keep.
250    #[cfg(feature = "http3")]
251    pub(crate) alt_svc_state: Arc<crate::transport::alt_svc::AltSvcState>,
252}
253
254/// Apply the selected HTTP protocol policy to a rustls client configuration.
255///
256/// The standard hyper-rustls connector applies this policy while building its
257/// connector. Custom connectors must set the same ALPN list themselves.
258#[cfg(feature = "tls-rustls")]
259pub(crate) fn configure_tls_alpn(
260    mut config: rustls::ClientConfig,
261    policy: crate::http_version::HttpVersionPolicyEnabler,
262) -> rustls::ClientConfig {
263    config.alpn_protocols.clear();
264    if policy.enable_http2() {
265        config.alpn_protocols.push(b"h2".to_vec());
266    }
267    if policy.enable_http1() {
268        config.alpn_protocols.push(b"http/1.1".to_vec());
269    }
270    config
271}
272
273impl ClientInner {
274    /// Build an isolated direct Hyper client for a request-scoped resolved
275    /// destination. Isolation prevents a connection established for ordinary
276    /// DNS routing, or for another address snapshot, from being reused.
277    #[cfg(any(feature = "http1", feature = "http2"))]
278    pub(crate) fn resolved_client(
279        &self,
280        target: &crate::request::ResolvedTarget,
281        sni_hostname: Option<&str>,
282    ) -> Result<crate::transport::TimeoutDirectClient> {
283        let connect_timeout = self.config.timeout.as_ref().and_then(|t| t.connect);
284        #[cfg(feature = "tls-rustls")]
285        let tls_connector = {
286            let tls_config = self.config.tls_config.clone().unwrap_or_default();
287            let rustls_config = tls_config
288                .build_rustls_config()
289                .map_err(|e| Error::Tls(format!("failed to build TLS config: {e}")))?;
290            let rustls_config = configure_tls_alpn(
291                rustls_config,
292                crate::http_version::HttpVersionPolicyEnabler::from_policy(
293                    self.config.http_version_policy,
294                ),
295            );
296            Some(tokio_rustls::TlsConnector::from(Arc::new(rustls_config)))
297        };
298        #[cfg(not(feature = "tls-rustls"))]
299        let tls_connector = None;
300
301        let base_config = self.direct_connector_config.clone().unwrap_or(
302            crate::transport::direct_connector::DirectConnectorConfig {
303                local_address: None,
304                socket_options: Vec::new(),
305            },
306        );
307        let mut connector = crate::transport::direct_connector::DirectConnector::with_metrics(
308            base_config,
309            tls_connector,
310            self.transport_metrics.clone(),
311        )
312        .with_resolved_target(target);
313        if let Some(sni_hostname) = sni_hostname {
314            connector = connector.with_sni(sni_hostname.to_owned());
315        }
316        let policy = HyperClientPolicy::cached_route(
317            self.config.retry_canceled_requests,
318            self.pool.idle_timeout(),
319            self.pool.max_idle_per_host(),
320            crate::http_version::HttpVersionPolicyEnabler::from_policy(
321                self.config.http_version_policy,
322            ),
323        );
324        Ok(build_hyper_client(
325            connector,
326            &policy,
327            connect_timeout,
328            &self.lifecycle,
329        ))
330    }
331
332    /// Get or create a cached hyper client with TLS SNI hostname override.
333    ///
334    /// The returned client uses a [`DirectConnector`](crate::transport::direct_connector::DirectConnector)
335    /// that separates DNS/TCP resolution (to the original URL host) from
336    /// TLS negotiation (with the SNI hostname). Clients are cached by
337    /// SNI hostname for connection reuse.
338    #[cfg(any(feature = "http1", feature = "http2"))]
339    pub(crate) async fn sni_client(
340        &self,
341        sni_hostname: &str,
342    ) -> Result<crate::transport::TimeoutDirectClient> {
343        let mut clients = self.sni_clients.lock().await;
344        if let Some(client) = clients.get(sni_hostname) {
345            return Ok(client.clone());
346        }
347
348        let connect_timeout = self.config.timeout.as_ref().and_then(|t| t.connect);
349        let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(
350            self.config.http_version_policy,
351        );
352
353        #[cfg(feature = "tls-rustls")]
354        let tls_connector = {
355            let tls_config = self.config.tls_config.clone().unwrap_or_default();
356            let rc = tls_config
357                .build_rustls_config()
358                .map_err(|e| Error::Tls(format!("failed to build TLS config: {e}")))?;
359            let rc = configure_tls_alpn(rc, enabler);
360            Some(tokio_rustls::TlsConnector::from(Arc::new(rc)))
361        };
362        #[cfg(not(feature = "tls-rustls"))]
363        let tls_connector = None;
364
365        let base_config = self.direct_connector_config.clone().unwrap_or(
366            crate::transport::direct_connector::DirectConnectorConfig {
367                local_address: None,
368                socket_options: Vec::new(),
369            },
370        );
371        let base_connector = crate::transport::direct_connector::DirectConnector::with_metrics(
372            base_config,
373            tls_connector,
374            self.transport_metrics.clone(),
375        );
376        let sni_connector = base_connector.with_sni(sni_hostname.to_owned());
377        // Idle-connection lifetime comes from the pool configuration
378        // (`Limits::keepalive_expiry`), matching the standard, direct,
379        // and UDS paths. `Timeout.pool`/`total` are acquisition budgets
380        // and must not close idle connections early. The effective
381        // per-host idle cap is shared as well; see `Pool::max_idle_per_host`.
382        let policy = HyperClientPolicy::cached_route(
383            self.config.retry_canceled_requests,
384            self.pool.idle_timeout(),
385            self.pool.max_idle_per_host(),
386            enabler,
387        );
388        let client = build_hyper_client(sni_connector, &policy, connect_timeout, &self.lifecycle);
389        clients.insert(sni_hostname.to_owned(), client.clone());
390        Ok(client)
391    }
392
393    /// Get or create a custom-dialer Hyper client with a fixed SNI override.
394    #[cfg(any(feature = "http1", feature = "http2"))]
395    pub(crate) async fn sni_custom_client(
396        &self,
397        sni_hostname: &str,
398    ) -> Result<crate::transport::TimeoutCustomClient> {
399        let mut clients = self.sni_custom_clients.lock().await;
400        if let Some(client) = clients.get(sni_hostname) {
401            return Ok(client.clone());
402        }
403        let dialer = self
404            .config
405            .dialer
406            .clone()
407            .ok_or_else(|| Error::Unsupported("custom dialer is not configured".into()))?;
408        #[cfg(feature = "tls-rustls")]
409        let tls_config = self
410            .config
411            .tls_config
412            .clone()
413            .unwrap_or_default()
414            .build_rustls_config()
415            .map_err(|error| Error::Tls(format!("failed to build TLS config: {error}")))?;
416        #[cfg(not(feature = "tls-rustls"))]
417        let tls_config = ();
418        let connector = build_custom_connector(
419            tls_config,
420            dialer,
421            crate::http_version::HttpVersionPolicyEnabler::from_policy(
422                self.config.http_version_policy,
423            ),
424            Some(sni_hostname),
425        )?;
426        let policy = HyperClientPolicy::cached_route(
427            self.config.retry_canceled_requests,
428            self.pool.idle_timeout(),
429            self.pool.max_idle_per_host(),
430            crate::http_version::HttpVersionPolicyEnabler::from_policy(
431                self.config.http_version_policy,
432            ),
433        );
434        let client = build_hyper_client(
435            connector,
436            &policy,
437            self.config
438                .timeout
439                .as_ref()
440                .and_then(|timeout| timeout.connect),
441            &self.lifecycle,
442        );
443        clients.insert(sni_hostname.to_owned(), client.clone());
444        Ok(client)
445    }
446}
447
448#[cfg(feature = "proxy")]
449impl ClientInner {
450    pub(crate) async fn socks_client(
451        &self,
452        proxy: &crate::proxy::ProxyConfig,
453        target: Option<&crate::request::ResolvedTarget>,
454    ) -> Result<crate::transport::TimeoutSocksClient> {
455        let key = crate::transport::socks::SocksRouteKey::from_proxy(proxy, target)?;
456        let mut clients = self.socks_clients.lock().await;
457        if let Some(client) = clients.get(&key) {
458            return Ok(client.clone());
459        }
460
461        let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(
462            self.config.http_version_policy,
463        );
464
465        let tls_config = if let Some(config) = self.config.tls_config.as_ref() {
466            config
467                .build_rustls_config()
468                .map_err(|e| Error::Tls(format!("failed to build SOCKS TLS config: {e}")))?
469        } else {
470            crate::tls::TlsConfig::default()
471                .build_rustls_config()
472                .map_err(|e| Error::Tls(format!("failed to build default SOCKS TLS config: {e}")))?
473        };
474        let tls_config = configure_tls_alpn(tls_config, enabler);
475        let connector = crate::transport::socks::SocksConnector::new(
476            proxy.clone(),
477            Some(tokio_rustls::TlsConnector::from(Arc::new(tls_config))),
478            None,
479            target,
480        );
481        // SOCKS route clients share the resolved Hyper idle-pool policy
482        // (timeout plus effective per-host cap) with every other persistent
483        // Hyper family. `HyperClientPolicy::apply` installs the pool timer
484        // the timeout requires.
485        let policy = HyperClientPolicy::cached_route(
486            self.config.retry_canceled_requests,
487            self.pool.idle_timeout(),
488            self.pool.max_idle_per_host(),
489            enabler,
490        );
491        let client = build_hyper_client(
492            connector,
493            &policy,
494            self.config
495                .timeout
496                .as_ref()
497                .and_then(|timeout| timeout.connect),
498            &self.lifecycle,
499        );
500        clients.insert(key, client.clone());
501        Ok(client)
502    }
503
504    /// Get or create a Hyper client for one HTTP forward-proxy route.
505    ///
506    /// The client is scoped to the destination origin rather than sharing a
507    /// pool across arbitrary origins. Hyper still owns keep-alive handling,
508    /// framing, response bodies, and stale-idle recovery for each entry.
509    #[cfg(any(feature = "http1", feature = "http2"))]
510    pub(crate) async fn forward_client(
511        &self,
512        proxy: &crate::proxy::ProxyConfig,
513        origin: &url::Url,
514        connect_timeout: Option<Duration>,
515    ) -> Result<crate::transport::TimeoutForwardClient> {
516        let proxy_tls_timeout = connect_timeout;
517        let key = crate::transport::proxy::ForwardRouteKey::new(
518            proxy,
519            origin,
520            connect_timeout,
521            proxy_tls_timeout,
522        );
523        let mut clients = self.forward_clients.lock().await;
524        if let Some(client) = clients.get(&key) {
525            return Ok(client.clone());
526        }
527
528        let connector = crate::transport::proxy::ForwardProxyConnector::new(
529            proxy.clone(),
530            connect_timeout,
531            proxy_tls_timeout,
532            self.transport_metrics.clone(),
533        );
534        let policy = HyperClientPolicy::forward_route(
535            self.config.retry_canceled_requests,
536            self.pool.idle_timeout(),
537            self.pool.max_idle_per_host(),
538        );
539        let client = build_hyper_client(connector, &policy, connect_timeout, &self.lifecycle);
540        clients.insert(key, client.clone());
541        Ok(client)
542    }
543
544    /// Get or create a Hyper client for one compatible HTTPS CONNECT route.
545    /// Multi-address target snapshots remain on the legacy path so their
546    /// typed 502/504 fallback semantics are not weakened.
547    #[cfg(any(feature = "http1", feature = "http2"))]
548    pub(crate) async fn connect_client(
549        &self,
550        proxy: &crate::proxy::ProxyConfig,
551        origin: &url::Url,
552        transport_hints: &crate::request::TransportHints,
553        target: Option<std::net::SocketAddr>,
554        connect_timeout: Option<Duration>,
555    ) -> Result<crate::transport::TimeoutConnectClient> {
556        let key = crate::transport::connect::ConnectRouteKey::new(
557            proxy,
558            origin,
559            target,
560            self.config.tls_config.as_ref(),
561            transport_hints.sni_hostname.as_deref(),
562            self.config.http_version_policy,
563            connect_timeout,
564            connect_timeout,
565        );
566        let mut clients = self.connect_clients.lock().await;
567        if let Some(client) = clients.get(&key) {
568            return Ok(client.clone());
569        }
570        let connector = crate::transport::connect::ConnectProxyConnector::new(
571            origin.clone(),
572            proxy.clone(),
573            transport_hints,
574            target,
575            self.config.tls_config.clone(),
576            connect_timeout,
577            connect_timeout,
578            connect_timeout,
579            self.config.http_version_policy,
580            self.transport_metrics.clone(),
581        );
582        let policy = HyperClientPolicy::cached_route(
583            self.config.retry_canceled_requests,
584            self.pool.idle_timeout(),
585            self.pool.max_idle_per_host(),
586            crate::http_version::HttpVersionPolicyEnabler::from_policy(
587                self.config.http_version_policy,
588            ),
589        );
590        let client = build_hyper_client(connector, &policy, connect_timeout, &self.lifecycle);
591        clients.insert(key, client.clone());
592        Ok(client)
593    }
594}
595
596impl Client {
597    /// Create a new client with default settings.
598    #[must_use]
599    pub fn new() -> Self {
600        Self::builder().build()
601    }
602
603    /// Create a [`ClientBuilder`] for configuring a client.
604    #[must_use]
605    pub fn builder() -> ClientBuilder {
606        ClientBuilder::new()
607    }
608
609    /// Create a GET request builder for the given URL.
610    ///
611    /// # Errors
612    ///
613    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
614    pub fn get(&self, url: &str) -> Result<RequestBuilder> {
615        self.request(Method::GET, url)
616    }
617
618    /// Create a POST request builder for the given URL.
619    ///
620    /// # Errors
621    ///
622    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
623    pub fn post(&self, url: &str) -> Result<RequestBuilder> {
624        self.request(Method::POST, url)
625    }
626
627    /// Create a PUT request builder for the given URL.
628    ///
629    /// # Errors
630    ///
631    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
632    pub fn put(&self, url: &str) -> Result<RequestBuilder> {
633        self.request(Method::PUT, url)
634    }
635
636    /// Create a PATCH request builder for the given URL.
637    ///
638    /// # Errors
639    ///
640    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
641    pub fn patch(&self, url: &str) -> Result<RequestBuilder> {
642        self.request(Method::PATCH, url)
643    }
644
645    /// Create a DELETE request builder for the given URL.
646    ///
647    /// # Errors
648    ///
649    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
650    pub fn delete(&self, url: &str) -> Result<RequestBuilder> {
651        self.request(Method::DELETE, url)
652    }
653
654    /// Create a HEAD request builder for the given URL.
655    ///
656    /// # Errors
657    ///
658    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
659    pub fn head(&self, url: &str) -> Result<RequestBuilder> {
660        self.request(Method::HEAD, url)
661    }
662
663    /// Create an OPTIONS request builder for the given URL.
664    ///
665    /// # Errors
666    ///
667    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
668    pub fn options(&self, url: &str) -> Result<RequestBuilder> {
669        self.request(Method::OPTIONS, url)
670    }
671
672    /// Create a request builder for the given method and URL.
673    ///
674    /// # Errors
675    ///
676    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
677    pub fn request(&self, method: Method, url: &str) -> Result<RequestBuilder> {
678        let parsed = parse_url(url)?;
679        Ok(RequestBuilder::new(self.clone(), method, parsed))
680    }
681
682    /// Returns a reference to the connection pool metrics.
683    ///
684    /// These count logical request-permit waits/cancellations. For
685    /// connector/protocol observations see [`Self::transport_metrics`].
686    #[must_use]
687    pub fn pool_metrics(&self) -> &PoolMetrics {
688        self.inner.pool.metrics()
689    }
690
691    /// Returns a reference to the transport observability counters.
692    ///
693    /// Counts connector events (DNS/connect/TLS attempts) and protocol
694    /// connections (H3 sessions, 101 upgrades) where observable. Hyper
695    /// socket-reuse counts are intentionally absent.
696    #[must_use]
697    pub fn transport_metrics(&self) -> &crate::transport::metrics::TransportMetrics {
698        &self.inner.transport_metrics
699    }
700
701    /// Returns a reference to the client's cookie jar.
702    ///
703    /// Only available when the `cookies` feature is enabled.
704    #[cfg(feature = "cookies")]
705    #[must_use]
706    pub fn cookies(&self) -> &CookieJar {
707        &self.inner.config.cookie_jar
708    }
709
710    /// Returns a reference to the shared client configuration.
711    #[must_use]
712    pub(crate) fn config(&self) -> &ClientConfig {
713        &self.inner.config
714    }
715
716    /// Send a request and return the response, following redirects if
717    /// the client's redirect policy allows.
718    ///
719    /// The redirect loop enforces `max_redirects`, performs method
720    /// rewrites per HTTP semantics, strips sensitive headers on
721    /// cross-origin hops, and records redirect history.
722    ///
723    /// If a retry policy is configured (on the client or request), the
724    /// entire logical request is retried on failure according to the
725    /// policy.
726    ///
727    /// # Errors
728    ///
729    /// Returns an error if the request fails at any stage (connect, TLS,
730    /// protocol, body) or if a timeout elapses.
731    pub(crate) async fn send(&self, request: Request) -> Result<Response> {
732        Box::pin(crate::pipeline::send_with_retry(self, request)).await
733    }
734
735    /// Send a request and return optional structured native failure detail.
736    ///
737    /// The ordinary [`Error`] remains unchanged and can be recovered with
738    /// [`RequestFailure::into_error`](crate::RequestFailure::into_error).
739    /// Network classifications are reported only when the selected route
740    /// exposes typed evidence; callers must not treat an absent subtype as a
741    /// positive diagnosis.
742    ///
743    /// # Errors
744    ///
745    /// Returns the original request error wrapped in [`crate::RequestFailure`].
746    pub async fn send_detailed(
747        &self,
748        mut request: Request,
749    ) -> std::result::Result<Response, crate::RequestFailure> {
750        let context = crate::error::RequestFailureContext::new();
751        context.clear();
752        request.set_failure_context(Some(context.clone()));
753        match Box::pin(crate::pipeline::send_with_retry(self, request)).await {
754            Ok(response) => Ok(response),
755            Err(error) => Err(crate::RequestFailure::from_context(error, &context)),
756        }
757    }
758
759    /// Send a single HTTP request and return the streaming response.
760    ///
761    /// This handles pool acquisition, timeout application, and body
762    /// processing for one request/response cycle. It does NOT handle
763    /// redirects—that is the responsibility of [`Client::send`].
764    pub(crate) async fn send_single_request(
765        &self,
766        request: Request,
767        timeout: &Timeout,
768    ) -> Result<Response> {
769        crate::pipeline::send_single_request(&self.inner, request, timeout).await
770    }
771
772    /// Execute a native `http_body::Body` using eggfetch's HTTP/TLS
773    /// transport engine.
774    ///
775    /// This is the lower-level native embedding API. Request DATA and
776    /// trailer frames are passed through without flattening. The response is
777    /// an ordinary `http::Response` whose opaque [`crate::NativeResponseBody`]
778    /// preserves DATA and trailer frames and holds the logical pool lease
779    /// until the body reaches EOF, errors, or is dropped.
780    ///
781    /// Native execution does not implicitly apply redirects, logical
782    /// retries, cookies, authentication, response decompression, or decoded
783    /// body limits. The request body is one-shot. Built-in proxy, HTTP/3,
784    /// and protocol-upgrade routes are rejected because their current
785    /// adapters do not expose the frame-preserving contract.
786    ///
787    /// # Errors
788    ///
789    /// Returns an error for an invalid logical URI, unsupported route, pool
790    /// or transport failure, or a timeout.
791    pub async fn execute_http_body<B>(
792        &self,
793        request: http::Request<B>,
794        options: NativeRequestOptions,
795    ) -> Result<http::Response<crate::NativeResponseBody>>
796    where
797        B: http_body::Body<Data = bytes::Bytes> + Send + 'static,
798        B::Error: std::error::Error + Send + Sync + 'static,
799    {
800        crate::pipeline::send_native_http_body(&self.inner, request, options).await
801    }
802
803    /// Execute a native body request with default native transport options.
804    ///
805    /// # Errors
806    ///
807    /// Returns the same URI, pool, transport, and timeout errors as
808    /// [`Self::execute_http_body`].
809    pub async fn execute_http_body_default<B>(
810        &self,
811        request: http::Request<B>,
812    ) -> Result<http::Response<crate::NativeResponseBody>>
813    where
814        B: http_body::Body<Data = bytes::Bytes> + Send + 'static,
815        B::Error: std::error::Error + Send + Sync + 'static,
816    {
817        self.execute_http_body(request, NativeRequestOptions::default())
818            .await
819    }
820}
821
822impl Default for Client {
823    fn default() -> Self {
824        Self::new()
825    }
826}
827
828/// Builder for configuring a [`Client`].
829pub struct ClientBuilder {
830    default_headers: Headers,
831    user_agent: Option<String>,
832    pool_config: PoolConfig,
833    timeout: Option<Timeout>,
834    limits: Option<Limits>,
835    redirect: RedirectPolicy,
836    auth: Option<crate::auth::AuthScheme>,
837    #[cfg(feature = "cookies")]
838    cookie_jar: Option<CookieJar>,
839    automatic_decompression: Option<bool>,
840    max_decoded_body_size: Option<usize>,
841    max_decompression_ratio: Option<f64>,
842    #[cfg(feature = "proxy")]
843    proxy: Option<Proxy>,
844    #[cfg(feature = "proxy")]
845    environment_proxies: Vec<Proxy>,
846    #[cfg(feature = "tls-rustls")]
847    tls_config: Option<crate::tls::TlsConfig>,
848    retry: Option<RetryPolicy>,
849    retry_canceled_requests: bool,
850    dialer: Option<Arc<dyn Dialer>>,
851    physical_connection_policy: PhysicalConnectionPolicy,
852    transport_io_timeout: TransportIoTimeout,
853    http_version_policy: HttpVersionPolicy,
854    /// Advanced direct-connector config for socket options / local address.
855    direct_connector_config: Option<crate::transport::direct_connector::DirectConnectorConfig>,
856    /// Unix domain socket path. When set, all requests use UDS transport.
857    uds_path: Option<String>,
858}
859
860impl ClientBuilder {
861    /// Create a new client builder with defaults.
862    #[must_use]
863    pub fn new() -> Self {
864        Self {
865            default_headers: Headers::new(),
866            user_agent: None,
867            pool_config: PoolConfig::default(),
868            timeout: None,
869            limits: None,
870            redirect: RedirectPolicy::default(),
871            auth: None,
872            #[cfg(feature = "cookies")]
873            cookie_jar: None,
874            automatic_decompression: None,
875            max_decoded_body_size: None,
876            max_decompression_ratio: None,
877            #[cfg(feature = "proxy")]
878            proxy: None,
879            #[cfg(feature = "proxy")]
880            environment_proxies: Vec::new(),
881            #[cfg(feature = "tls-rustls")]
882            tls_config: None,
883            retry: None,
884            retry_canceled_requests: true,
885            dialer: None,
886            physical_connection_policy: PhysicalConnectionPolicy::default(),
887            transport_io_timeout: TransportIoTimeout::default(),
888            http_version_policy: HttpVersionPolicy::default(),
889            direct_connector_config: None,
890            uds_path: None,
891        }
892    }
893
894    /// Add a default header to all requests made by this client.
895    ///
896    /// # Errors
897    ///
898    /// Returns an error if `name` or `value` is not a valid header field.
899    pub fn default_header(mut self, name: &str, value: &str) -> Result<Self> {
900        self.default_headers.insert(name, value)?;
901        Ok(self)
902    }
903
904    /// Set the default headers for all requests made by this client.
905    ///
906    /// This preserves valid header values containing HTTP `obs-text` bytes.
907    #[must_use]
908    pub fn default_headers(mut self, headers: Headers) -> Self {
909        self.default_headers = headers;
910        self
911    }
912
913    /// Set the default user-agent header.
914    #[must_use]
915    pub fn user_agent(mut self, agent: &str) -> Self {
916        self.user_agent = Some(agent.to_owned());
917        self
918    }
919
920    /// Set the maximum number of idle (unused) connections kept per host.
921    ///
922    /// This is a convenience alias for [`max_idle_connections_per_host`]:
923    /// the transport enforces the limit on a per-host basis, so total
924    /// idle connections grow with the number of distinct origins. Use
925    /// [`max_connections`] for a global concurrency cap.
926    ///
927    /// [`max_idle_connections_per_host`]: Self::max_idle_connections_per_host
928    /// [`max_connections`]: Self::max_connections
929    #[must_use]
930    pub fn max_idle_connections(mut self, max: usize) -> Self {
931        self.pool_config.max_idle_connections = Some(max);
932        self
933    }
934
935    /// Set the maximum number of idle connections per individual host.
936    #[must_use]
937    pub fn max_idle_connections_per_host(mut self, max: usize) -> Self {
938        self.pool_config.max_idle_connections_per_host = Some(max);
939        self
940    }
941
942    /// Set the maximum total number of concurrent in-flight requests.
943    ///
944    /// Compatibility alias for [`Self::max_in_flight_requests`] kept for
945    /// the pre-1.0 line. One permit equals one logical request, not one
946    /// TCP connection (H2/H3 multiplex many requests over one
947    /// connection). Prefer `max_in_flight_requests` in new code.
948    #[must_use]
949    pub fn max_connections(mut self, max: usize) -> Self {
950        self.pool_config.max_connections = Some(max);
951        self
952    }
953
954    /// Set the maximum number of concurrent in-flight requests per origin.
955    ///
956    /// Compatibility alias for [`Self::max_in_flight_requests_per_origin`].
957    #[must_use]
958    pub fn max_connections_per_host(mut self, max: usize) -> Self {
959        self.pool_config.max_connections_per_host = Some(max);
960        self
961    }
962
963    /// Set the maximum total number of concurrent in-flight requests.
964    ///
965    /// Preferred native name. Bounds logical request concurrency (one
966    /// permit per request). Under H1 one request typically owns its
967    /// connection slot; under H2/H3 many permits multiplex over one
968    /// TCP/QUIC connection. When both this and `max_connections` are
969    /// set, this wins.
970    #[must_use]
971    pub fn max_in_flight_requests(mut self, max: usize) -> Self {
972        self.pool_config.max_in_flight_requests = Some(max);
973        self
974    }
975
976    /// Set the maximum number of concurrent in-flight requests per origin.
977    ///
978    /// Preferred native name. When both this and
979    /// `max_connections_per_host` are set, this wins.
980    #[must_use]
981    pub fn max_in_flight_requests_per_origin(mut self, max: usize) -> Self {
982        self.pool_config.max_in_flight_requests_per_origin = Some(max);
983        self
984    }
985
986    /// Set the duration after which idle connections are closed.
987    #[must_use]
988    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
989        self.pool_config.idle_timeout = Some(timeout);
990        self
991    }
992
993    /// Set the default timeout for all requests made by this client.
994    #[must_use]
995    pub fn timeout(mut self, timeout: Timeout) -> Self {
996        self.timeout = Some(timeout);
997        self
998    }
999
1000    /// Merge a partial timeout configuration into the currently configured
1001    /// timeout.
1002    ///
1003    /// Unlike [`timeout`](Self::timeout), which replaces the entire
1004    /// configuration, each phase set in `timeout` overrides only that
1005    /// phase; unset phases keep any previously configured value (or
1006    /// remain unset when no timeout was configured yet).
1007    #[must_use]
1008    pub fn merge_timeout(mut self, timeout: Timeout) -> Self {
1009        let merged = match self.timeout {
1010            Some(existing) => existing.merge(Some(timeout)),
1011            None => timeout,
1012        };
1013        self.timeout = Some(merged);
1014        self
1015    }
1016
1017    /// Set resource limits for the connection pool.
1018    ///
1019    /// Limits control logical request concurrency (pool permits) and
1020    /// physical connection behavior (idle connection caps and expiry).
1021    /// When set, the limits are applied to the pool configuration.
1022    #[must_use]
1023    pub fn limits(mut self, limits: Limits) -> Self {
1024        self.limits = Some(limits);
1025        self
1026    }
1027
1028    /// Set the redirect policy for this client.
1029    #[must_use]
1030    pub fn follow_redirects(mut self, follow: bool) -> Self {
1031        self.redirect.follow = follow;
1032        self
1033    }
1034
1035    /// Set the maximum number of redirects to follow.
1036    #[must_use]
1037    pub fn max_redirects(mut self, max: usize) -> Self {
1038        self.redirect.max_redirects = max;
1039        self
1040    }
1041
1042    /// Set the full redirect policy.
1043    #[must_use]
1044    pub fn redirect_policy(mut self, policy: RedirectPolicy) -> Self {
1045        self.redirect = policy;
1046        self
1047    }
1048
1049    /// Set a shared cookie jar for this client.
1050    ///
1051    /// When set, the client will automatically inject matching cookies
1052    /// into requests and update the jar from `Set-Cookie` response headers.
1053    ///
1054    /// Only available when the `cookies` feature is enabled.
1055    #[cfg(feature = "cookies")]
1056    #[must_use]
1057    pub fn cookie_jar(mut self, jar: CookieJar) -> Self {
1058        self.cookie_jar = Some(jar);
1059        self
1060    }
1061
1062    /// Set default authentication for all requests made by this client.
1063    ///
1064    /// The configured auth is applied to every request unless overridden
1065    /// or disabled at the request level. Auth is recomputed per redirect
1066    /// hop; cross-origin redirects never carry client auth.
1067    #[must_use]
1068    pub fn auth(mut self, auth: impl Into<crate::auth::AuthScheme>) -> Self {
1069        self.auth = Some(auth.into());
1070        self
1071    }
1072
1073    /// Set the default proxy for all requests made by this client.
1074    ///
1075    /// When set, all matching requests are routed through the specified
1076    /// proxy. Can be overridden or disabled per-request.
1077    #[cfg(feature = "proxy")]
1078    #[must_use]
1079    pub fn proxy(mut self, proxy: Proxy) -> Self {
1080        self.proxy = Some(proxy);
1081        self
1082    }
1083
1084    /// Add a scheme-specific proxy used when no explicit proxy is configured.
1085    #[cfg(feature = "proxy")]
1086    #[must_use]
1087    pub fn environment_proxy(mut self, proxy: Proxy) -> Self {
1088        self.environment_proxies.push(proxy);
1089        self
1090    }
1091
1092    /// Set `NO_PROXY` bypass rules for the default proxy.
1093    ///
1094    /// When set, URLs matching any bypass rule are sent directly
1095    /// without going through the proxy.
1096    #[cfg(feature = "proxy")]
1097    #[must_use]
1098    pub fn no_proxy(mut self, no_proxy: crate::proxy::NoProxy) -> Self {
1099        if let Some(proxy) = self.proxy.take() {
1100            self.proxy = Some(proxy.no_proxy(no_proxy));
1101        }
1102        self
1103    }
1104
1105    /// Set a custom TLS configuration for this client.
1106    ///
1107    /// When set, the client uses the provided [`crate::tls::TlsConfig`] for all
1108    /// TLS connections instead of the default native-root-with-WebPKI-fallback
1109    /// strategy (or the packaged-WebPKI default when `tls-native-roots` is not
1110    /// enabled).
1111    #[cfg(feature = "tls-rustls")]
1112    #[must_use]
1113    pub fn tls_config(mut self, config: crate::tls::TlsConfig) -> Self {
1114        self.tls_config = Some(config);
1115        self
1116    }
1117
1118    /// Enable or disable insecure TLS verification while retaining other
1119    /// TLS configuration already applied to this builder.
1120    #[cfg(feature = "tls-rustls")]
1121    #[must_use]
1122    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
1123        let config = self.tls_config.take().unwrap_or_default();
1124        self.tls_config = Some(config.danger_accept_invalid_certs(accept));
1125        self
1126    }
1127
1128    /// Enable or disable automatic response decompression.
1129    ///
1130    /// When enabled (the default), the client sends an
1131    /// `Accept-Encoding` header and transparently decompresses
1132    /// response bodies. Decoded `Content-Encoding` and
1133    /// `Content-Length` headers are removed from the response.
1134    ///
1135    /// Can be overridden per-request via
1136    /// [`RequestBuilder::decompress`].
1137    #[must_use]
1138    pub fn automatic_decompression(mut self, enabled: bool) -> Self {
1139        self.automatic_decompression = Some(enabled);
1140        self
1141    }
1142
1143    /// Set the maximum decoded response body size in bytes.
1144    ///
1145    /// The limit applies to bytes made available after decoding and also to
1146    /// ordinary unencoded/identity response bodies, in both buffered and
1147    /// streaming paths. Exceeding it produces [`Error::DecodedBodyTooLarge`]
1148    /// without requiring a second caller-side accumulation loop. A wire
1149    /// `Content-Length` may be used for an early metadata check, but this
1150    /// body limit remains authoritative when the header is absent, incorrect,
1151    /// or describes encoded bytes.
1152    #[must_use]
1153    pub fn max_decoded_body_size(mut self, max: usize) -> Self {
1154        self.max_decoded_body_size = Some(max);
1155        self
1156    }
1157
1158    /// Set the maximum decompression ratio (decoded bytes / compressed bytes).
1159    /// When set, responses whose expansion ratio exceeds this limit produce
1160    /// an error. This guards against zip-bomb style attacks.
1161    ///
1162    /// # Panics
1163    ///
1164    /// Panics if `ratio` is not finite or not positive.
1165    #[must_use]
1166    pub fn max_decompression_ratio(mut self, ratio: f64) -> Self {
1167        assert!(
1168            ratio.is_finite() && ratio > 0.0,
1169            "max_decompression_ratio must be finite and positive, got {ratio}"
1170        );
1171        self.max_decompression_ratio = Some(ratio);
1172        self
1173    }
1174
1175    /// Set the retry policy for this client.
1176    ///
1177    /// When set, failed requests that match the policy (safe methods,
1178    /// retryable statuses/errors, replayable bodies) are automatically
1179    /// retried with exponential backoff.
1180    #[must_use]
1181    pub fn retry(mut self, policy: RetryPolicy) -> Self {
1182        self.retry = Some(policy);
1183        self
1184    }
1185
1186    /// Allow or disallow Hyper's implicit retry when a reused idle
1187    /// connection is found unusable before a request starts writing.
1188    ///
1189    /// This is separate from eggfetch's explicit [`RetryPolicy`]. The
1190    /// default is `true`, preserving Hyper's existing behavior.
1191    #[must_use]
1192    pub fn retry_canceled_requests(mut self, enabled: bool) -> Self {
1193        self.retry_canceled_requests = enabled;
1194        self
1195    }
1196
1197    /// Install a client-scoped caller-owned raw-stream dialer.
1198    ///
1199    /// Eggfetch continues to own HTTP framing, destination TLS, SNI,
1200    /// certificate verification, redirects, retries, and response bodies.
1201    /// The dialer is incompatible with built-in proxy, UDS, resolved-target,
1202    /// local-address, and socket-option routing; those combinations fail
1203    /// closed before network I/O.
1204    #[must_use]
1205    pub fn dialer<D>(mut self, dialer: D) -> Self
1206    where
1207        D: Dialer,
1208    {
1209        self.dialer = Some(Arc::new(dialer));
1210        self
1211    }
1212
1213    /// Install a shared caller-scoped live physical-connection policy.
1214    ///
1215    /// This controls established Hyper connections, including idle pooled
1216    /// connections. It does not change the logical request limits in
1217    /// [`PoolConfig`]. A `max_live` value of zero fails
1218    /// requests closed because no useful client can be created from it.
1219    #[must_use]
1220    pub fn physical_connection_policy(mut self, policy: PhysicalConnectionPolicy) -> Self {
1221        self.physical_connection_policy = policy;
1222        self
1223    }
1224
1225    /// Install established-transport read/write inactivity guardrails.
1226    ///
1227    /// These timers are distinct from [`Timeout`]'s request
1228    /// body and response-stream semantics and are disabled by default.
1229    #[must_use]
1230    pub fn transport_io_timeout(mut self, timeout: TransportIoTimeout) -> Self {
1231        self.transport_io_timeout = timeout;
1232        self
1233    }
1234
1235    /// Set the HTTP version policy for this client.
1236    ///
1237    /// Controls which HTTP protocol versions the client may negotiate.
1238    /// The default is [`HttpVersionPolicy::Auto`], which allows HTTP/2
1239    /// negotiation via ALPN when the `http2` feature is enabled.
1240    ///
1241    /// When the `http2` feature is not compiled in, `Http2Only` and `Auto`
1242    /// are silently downgraded to `Http1Only`.
1243    #[must_use]
1244    pub fn http_version_policy(mut self, policy: HttpVersionPolicy) -> Self {
1245        self.http_version_policy = policy;
1246        self
1247    }
1248
1249    /// Set a local address to bind outbound sockets to before connecting.
1250    ///
1251    /// When set, all direct (non-proxy, non-UDS) connections will bind
1252    /// to the specified local address before connecting to the remote.
1253    /// This uses a custom connector path instead of the standard
1254    /// hyper-rustls connector.
1255    #[must_use]
1256    pub fn local_address(mut self, addr: std::net::SocketAddr) -> Self {
1257        let config = self.direct_connector_config.get_or_insert_with(|| {
1258            crate::transport::direct_connector::DirectConnectorConfig {
1259                local_address: None,
1260                socket_options: Vec::new(),
1261            }
1262        });
1263        config.local_address = Some(addr);
1264        self
1265    }
1266
1267    /// Set socket options to apply to outbound TCP connections.
1268    ///
1269    /// Options are applied to the socket before the connect operation.
1270    /// Recognized options are applied via `tokio::net::TcpSocket` setters;
1271    /// unrecognized options produce a connection error (never silently
1272    /// ignored, per the plan's Track 2.4 requirement).
1273    #[must_use]
1274    pub fn socket_options(
1275        mut self,
1276        options: Vec<crate::transport::direct_connector::SocketOption>,
1277    ) -> Self {
1278        let config = self.direct_connector_config.get_or_insert_with(|| {
1279            crate::transport::direct_connector::DirectConnectorConfig {
1280                local_address: None,
1281                socket_options: Vec::new(),
1282            }
1283        });
1284        config.socket_options = options;
1285        self
1286    }
1287
1288    /// Set a Unix domain socket path for all connections.
1289    ///
1290    /// When set, all requests are routed through the specified UDS path
1291    /// instead of making TCP connections. The URL in the request still
1292    /// provides HTTP scheme/authority/path semantics.
1293    ///
1294    /// Only supported on Unix platforms. On non-Unix platforms, this
1295    /// option is accepted but will produce an error at request time.
1296    #[must_use]
1297    pub fn uds_path(mut self, path: String) -> Self {
1298        self.uds_path = Some(path);
1299        self
1300    }
1301
1302    /// Build the client.
1303    ///
1304    /// Native system roots are preferred. If the platform root store is
1305    /// unavailable, the client falls back to the packaged Mozilla root set
1306    /// while retaining certificate and hostname verification.
1307    #[must_use]
1308    #[allow(clippy::too_many_lines)]
1309    pub fn build(self) -> Client {
1310        #[cfg(any(feature = "http1", feature = "http2"))]
1311        use crate::http_version::HttpVersionPolicyEnabler;
1312        #[cfg(any(feature = "http1", feature = "http2"))]
1313        let enabler = HttpVersionPolicyEnabler::from_policy(self.http_version_policy);
1314        let transport_metrics = Arc::new(crate::transport::metrics::TransportMetrics::new());
1315
1316        let mut pool_config = self.pool_config;
1317        if let Some(limits) = self.limits {
1318            let limits_config: PoolConfig = limits.into();
1319            if limits_config.max_connections.is_some() {
1320                pool_config.max_connections = limits_config.max_connections;
1321            }
1322            if limits_config.max_connections_per_host.is_some() {
1323                pool_config.max_connections_per_host = limits_config.max_connections_per_host;
1324            }
1325            if limits_config.max_in_flight_requests.is_some() {
1326                pool_config.max_in_flight_requests = limits_config.max_in_flight_requests;
1327            }
1328            if limits_config.max_in_flight_requests_per_origin.is_some() {
1329                pool_config.max_in_flight_requests_per_origin =
1330                    limits_config.max_in_flight_requests_per_origin;
1331            }
1332            if limits_config.max_idle_connections.is_some() {
1333                pool_config.max_idle_connections = limits_config.max_idle_connections;
1334            }
1335            if limits_config.max_idle_connections_per_host.is_some() {
1336                pool_config.max_idle_connections_per_host =
1337                    limits_config.max_idle_connections_per_host;
1338            }
1339            if limits_config.idle_timeout.is_some() {
1340                pool_config.idle_timeout = limits_config.idle_timeout;
1341            }
1342        }
1343        #[cfg(any(feature = "http1", feature = "http2"))]
1344        let lifecycle = Arc::new(LifecycleConfig::from_policy(
1345            self.physical_connection_policy,
1346            self.transport_io_timeout,
1347            transport_metrics.clone(),
1348        ));
1349        // Shared builder policy for the persistent per-client Hyper
1350        // singletons below (standard, direct, UDS, custom dialer). Cached and
1351        // isolated route clients resolve their own narrower policy at use.
1352        #[cfg(any(feature = "http1", feature = "http2"))]
1353        let persistent_policy = HyperClientPolicy::persistent(
1354            self.retry_canceled_requests,
1355            pool_config.idle_timeout,
1356            pool_config.effective_max_idle_per_host(),
1357            enabler,
1358        );
1359
1360        #[cfg(feature = "cookies")]
1361        let cookie_jar = self.cookie_jar.unwrap_or_default();
1362
1363        let automatic_decompression = self.automatic_decompression.unwrap_or(true);
1364        #[cfg(feature = "tls-rustls")]
1365        let tls_config_result = self
1366            .tls_config
1367            .clone()
1368            .unwrap_or_default()
1369            .build_rustls_config();
1370        #[cfg(feature = "tls-rustls")]
1371        let tls_config_error = tls_config_result
1372            .as_ref()
1373            .err()
1374            .map(|error| format!("failed to build TLS config: {error}"));
1375        // `Http3Only` is strict direct-QUIC and needs no Hyper client.
1376        // `Auto { allow_http3: true }` needs both: H1/H2 for discovery and
1377        // safe fallback plus QUIC for discovered routes. All other policies
1378        // need Hyper only.
1379        #[cfg(feature = "tls-rustls")]
1380        let hyper_client = if matches!(
1381            self.http_version_policy,
1382            crate::HttpVersionPolicy::Http3Only
1383        ) || tls_config_error.is_some()
1384        {
1385            None
1386        } else if let Ok(rc) = tls_config_result {
1387            let https = build_standard_connector(rc, enabler);
1388            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1389            Some(build_hyper_client(
1390                https,
1391                &persistent_policy,
1392                connect_timeout,
1393                &lifecycle,
1394            ))
1395        } else {
1396            None
1397        };
1398
1399        #[cfg(all(not(feature = "tls-rustls"), any(feature = "http1", feature = "http2")))]
1400        let hyper_client = if matches!(
1401            self.http_version_policy,
1402            crate::HttpVersionPolicy::Http3Only
1403        ) {
1404            None
1405        } else {
1406            let connector = build_standard_connector(enabler);
1407            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1408            Some(build_hyper_client(
1409                connector,
1410                &persistent_policy,
1411                connect_timeout,
1412                &lifecycle,
1413            ))
1414        };
1415        #[cfg(feature = "http3")]
1416        let h3_connector = if enabler.use_http3() {
1417            crate::transport::http3::H3Connector::with_metrics(
1418                self.tls_config.clone(),
1419                &pool_config,
1420                Some(transport_metrics.clone()),
1421            )
1422            .ok()
1423        } else {
1424            None
1425        };
1426
1427        // Build the direct connector client for advanced socket options / local
1428        // address binding. This uses a custom connector path instead of the
1429        // standard hyper-rustls connector.
1430        #[cfg(any(feature = "http1", feature = "http2"))]
1431        let stored_direct_config = self.direct_connector_config.clone();
1432        #[cfg(any(feature = "http1", feature = "http2"))]
1433        let direct_client = if let Some(dc_config) = self.direct_connector_config {
1434            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1435
1436            // Build a TLS connector for HTTPS through the direct path.
1437            #[cfg(feature = "tls-rustls")]
1438            let tls_connector = match self
1439                .tls_config
1440                .clone()
1441                .unwrap_or_default()
1442                .build_rustls_config()
1443            {
1444                Ok(rc) => Some(tokio_rustls::TlsConnector::from(Arc::new(
1445                    configure_tls_alpn(
1446                        rc,
1447                        crate::http_version::HttpVersionPolicyEnabler::from_policy(
1448                            self.http_version_policy,
1449                        ),
1450                    ),
1451                ))),
1452                Err(_) => None,
1453            };
1454            #[cfg(not(feature = "tls-rustls"))]
1455            let tls_connector = None;
1456
1457            let direct_connector =
1458                crate::transport::direct_connector::DirectConnector::with_metrics(
1459                    dc_config,
1460                    tls_connector,
1461                    transport_metrics.clone(),
1462                );
1463            Some(build_hyper_client(
1464                direct_connector,
1465                &persistent_policy,
1466                connect_timeout,
1467                &lifecycle,
1468            ))
1469        } else {
1470            None
1471        };
1472
1473        // The UDS path is accepted on all platforms (see `uds_path`) but
1474        // only consumed on Unix; without this the field is never read on
1475        // non-Unix targets.
1476        #[cfg(not(unix))]
1477        let _ = &self.uds_path;
1478
1479        #[cfg(all(unix, any(feature = "http1", feature = "http2")))]
1480        let uds_client = self.uds_path.clone().map(|path| {
1481            #[cfg(feature = "tls-rustls")]
1482            let tls_connector = self
1483                .tls_config
1484                .clone()
1485                .unwrap_or_default()
1486                .build_rustls_config()
1487                .ok()
1488                .map(|rc| {
1489                    tokio_rustls::TlsConnector::from(Arc::new(configure_tls_alpn(
1490                        rc,
1491                        crate::http_version::HttpVersionPolicyEnabler::from_policy(
1492                            self.http_version_policy,
1493                        ),
1494                    )))
1495                });
1496            #[cfg(not(feature = "tls-rustls"))]
1497            let tls_connector = None;
1498            let connector = crate::transport::uds::UdsConnector::with_metrics(
1499                path,
1500                tls_connector,
1501                transport_metrics.clone(),
1502            );
1503            let connect_timeout = self.timeout.as_ref().and_then(|timeout| timeout.connect);
1504            build_hyper_client(connector, &persistent_policy, connect_timeout, &lifecycle)
1505        });
1506
1507        #[cfg(any(feature = "http1", feature = "http2"))]
1508        let custom_client = if let Some(dialer) = self.dialer.clone() {
1509            #[cfg(feature = "tls-rustls")]
1510            let custom_config = self
1511                .tls_config
1512                .clone()
1513                .unwrap_or_default()
1514                .build_rustls_config()
1515                .ok();
1516            #[cfg(not(feature = "tls-rustls"))]
1517            let custom_config = Some(());
1518
1519            custom_config.and_then(|custom_config| {
1520                let connector =
1521                    build_custom_connector(custom_config, dialer, enabler, None).ok()?;
1522                let connect_timeout = self.timeout.as_ref().and_then(|timeout| timeout.connect);
1523                Some(build_hyper_client(
1524                    connector,
1525                    &persistent_policy,
1526                    connect_timeout,
1527                    &lifecycle,
1528                ))
1529            })
1530        } else {
1531            None
1532        };
1533        let config = ClientConfig {
1534            default_headers: self.default_headers,
1535            user_agent: self.user_agent,
1536            timeout: self.timeout,
1537            redirect: self.redirect,
1538            auth: self.auth,
1539            #[cfg(feature = "cookies")]
1540            cookie_jar,
1541            automatic_decompression,
1542            max_decoded_body_size: self.max_decoded_body_size,
1543            max_decompression_ratio: self.max_decompression_ratio,
1544            #[cfg(feature = "proxy")]
1545            proxy: self.proxy,
1546            #[cfg(feature = "proxy")]
1547            environment_proxies: self.environment_proxies,
1548            #[cfg(feature = "tls-rustls")]
1549            tls_config: self.tls_config,
1550            retry: self.retry,
1551            retry_canceled_requests: self.retry_canceled_requests,
1552            dialer: self.dialer,
1553            uds_configured: self.uds_path.is_some(),
1554            http_version_policy: self.http_version_policy,
1555        };
1556
1557        let pool = Pool::new(pool_config);
1558
1559        Client {
1560            inner: Arc::new(ClientInner {
1561                #[cfg(any(feature = "http1", feature = "http2"))]
1562                hyper_client,
1563                #[cfg(any(feature = "http1", feature = "http2"))]
1564                custom_client,
1565                #[cfg(feature = "tls-rustls")]
1566                tls_config_error,
1567                #[cfg(any(feature = "http1", feature = "http2"))]
1568                direct_client,
1569                #[cfg(any(feature = "http1", feature = "http2"))]
1570                direct_connector_config: stored_direct_config,
1571                #[cfg(any(feature = "http1", feature = "http2"))]
1572                sni_clients: Mutex::new(BoundedClientCache::new(SNI_CLIENT_CACHE_MAX_ENTRIES)),
1573                #[cfg(any(feature = "http1", feature = "http2"))]
1574                sni_custom_clients: Mutex::new(BoundedClientCache::new(
1575                    SNI_CLIENT_CACHE_MAX_ENTRIES,
1576                )),
1577                #[cfg(all(unix, any(feature = "http1", feature = "http2")))]
1578                uds_client,
1579                #[cfg(feature = "proxy")]
1580                socks_clients: Mutex::new(BoundedClientCache::new(SOCKS_CLIENT_CACHE_MAX_ENTRIES)),
1581                #[cfg(feature = "proxy")]
1582                forward_clients: Mutex::new(BoundedClientCache::new(
1583                    FORWARD_CLIENT_CACHE_MAX_ENTRIES,
1584                )),
1585                #[cfg(feature = "proxy")]
1586                connect_clients: Mutex::new(BoundedClientCache::new(
1587                    CONNECT_CLIENT_CACHE_MAX_ENTRIES,
1588                )),
1589                config,
1590                pool,
1591                transport_metrics,
1592                #[cfg(any(feature = "http1", feature = "http2"))]
1593                lifecycle,
1594                #[cfg(feature = "http3")]
1595                h3_connector,
1596                #[cfg(feature = "http3")]
1597                alt_svc_state: Arc::new(crate::transport::alt_svc::AltSvcState::new()),
1598            }),
1599        }
1600    }
1601}
1602
1603/// Build the standard cleartext connector.
1604#[cfg(not(feature = "tls-rustls"))]
1605fn build_standard_connector(enabler: crate::http_version::HttpVersionPolicyEnabler) -> Connector {
1606    build_standard_connector_with_resolver(
1607        hyper_util::client::legacy::connect::dns::GaiResolver::new(),
1608        enabler,
1609    )
1610}
1611
1612/// Build a standard cleartext connector with a caller-selected private
1613/// resolver. Production callers use the default system resolver; tests use
1614/// this generic seam to keep resolver provenance deterministic.
1615#[cfg(not(feature = "tls-rustls"))]
1616fn build_standard_connector_with_resolver<R>(
1617    resolver: R,
1618    enabler: crate::http_version::HttpVersionPolicyEnabler,
1619) -> hyper_util::client::legacy::connect::HttpConnector<
1620    crate::transport::standard_resolver::ClassifyingResolver<R>,
1621>
1622where
1623    R: tower_service::Service<hyper_util::client::legacy::connect::dns::Name>
1624        + Clone
1625        + Send
1626        + Sync
1627        + 'static,
1628    R::Response: Iterator<Item = std::net::SocketAddr>,
1629    R::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
1630    R::Future: Send + 'static,
1631{
1632    let _ = enabler;
1633    let mut connector = hyper_util::client::legacy::connect::HttpConnector::new_with_resolver(
1634        crate::transport::standard_resolver::ClassifyingResolver::new(resolver),
1635    );
1636    connector.enforce_http(true);
1637    connector
1638}
1639
1640/// Build the standard TLS connector from the authoritative [`TlsConfig`].
1641#[cfg(feature = "tls-rustls")]
1642fn build_standard_connector(
1643    config: rustls::ClientConfig,
1644    enabler: crate::http_version::HttpVersionPolicyEnabler,
1645) -> Connector {
1646    build_standard_connector_with_resolver(
1647        config,
1648        enabler,
1649        hyper_util::client::legacy::connect::dns::GaiResolver::new(),
1650    )
1651}
1652
1653/// Build the standard Rustls connector around an explicitly constructed
1654/// Hyper resolver connector so DNS provenance survives the TLS wrapper.
1655#[cfg(feature = "tls-rustls")]
1656fn build_standard_connector_with_resolver<R>(
1657    mut config: rustls::ClientConfig,
1658    enabler: crate::http_version::HttpVersionPolicyEnabler,
1659    resolver: R,
1660) -> hyper_rustls::HttpsConnector<
1661    hyper_util::client::legacy::connect::HttpConnector<
1662        crate::transport::standard_resolver::ClassifyingResolver<R>,
1663    >,
1664>
1665where
1666    R: tower_service::Service<hyper_util::client::legacy::connect::dns::Name>
1667        + Clone
1668        + Send
1669        + Sync
1670        + 'static,
1671    R::Response: Iterator<Item = std::net::SocketAddr>,
1672    R::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
1673    R::Future: Send + 'static,
1674{
1675    // hyper-rustls fills ALPN from the selected protocol methods.
1676    config.alpn_protocols.clear();
1677    let mut http = hyper_util::client::legacy::connect::HttpConnector::new_with_resolver(
1678        crate::transport::standard_resolver::ClassifyingResolver::new(resolver),
1679    );
1680    http.enforce_http(false);
1681    let builder = hyper_rustls::HttpsConnectorBuilder::new()
1682        .with_tls_config(config)
1683        .https_or_http();
1684    #[cfg(feature = "http2")]
1685    {
1686        match (enabler.enable_http1(), enabler.enable_http2()) {
1687            (true, true) => builder.enable_http1().enable_http2().wrap_connector(http),
1688            (true | false, false) => builder.enable_http1().wrap_connector(http),
1689            (false, true) => builder.enable_http2().wrap_connector(http),
1690        }
1691    }
1692    #[cfg(not(feature = "http2"))]
1693    {
1694        let _ = enabler;
1695        builder.enable_http1().wrap_connector(http)
1696    }
1697}
1698
1699#[cfg(all(feature = "tls-rustls", any(feature = "http1", feature = "http2")))]
1700fn build_custom_connector(
1701    config: rustls::ClientConfig,
1702    dialer: Arc<dyn Dialer>,
1703    enabler: crate::http_version::HttpVersionPolicyEnabler,
1704    sni_hostname: Option<&str>,
1705) -> Result<crate::transport::CustomConnector> {
1706    let config = configure_tls_alpn(config, enabler);
1707    let resolver: Arc<dyn hyper_rustls::ResolveServerName + Send + Sync> =
1708        if let Some(sni_hostname) = sni_hostname {
1709            let server_name = rustls::pki_types::ServerName::try_from(sni_hostname.to_owned())
1710                .map_err(|error| Error::Tls(format!("invalid SNI hostname: {error}")))?;
1711            Arc::new(hyper_rustls::FixedServerNameResolver::new(server_name))
1712        } else {
1713            Arc::new(hyper_rustls::DefaultServerNameResolver::default())
1714        };
1715    Ok(hyper_rustls::HttpsConnector::new(
1716        crate::transport::dialer::DialerConnector::new(dialer),
1717        Arc::new(config),
1718        false,
1719        resolver,
1720    ))
1721}
1722
1723#[cfg(all(not(feature = "tls-rustls"), any(feature = "http1", feature = "http2")))]
1724fn build_custom_connector(
1725    _config: (),
1726    dialer: Arc<dyn Dialer>,
1727    _enabler: crate::http_version::HttpVersionPolicyEnabler,
1728    _sni_hostname: Option<&str>,
1729) -> Result<crate::transport::CustomConnector> {
1730    Ok(crate::transport::dialer::DialerConnector::new(dialer))
1731}
1732
1733impl Default for ClientBuilder {
1734    fn default() -> Self {
1735        Self::new()
1736    }
1737}
1738
1739fn parse_url(url_str: &str) -> Result<url::Url> {
1740    // Deliberately do not echo `url_str` into the error: parsing has
1741    // failed, so `redact_url_string` would fall back to the raw input
1742    // (potentially containing credentials). `url::ParseError` renders
1743    // only a static description and never embeds the input.
1744    let url = url::Url::parse(url_str).map_err(|e| Error::InvalidUrl(e.to_string()))?;
1745    if !url.username().is_empty() || url.password().is_some() {
1746        // URL userinfo is both easy to leak through diagnostics and
1747        // surprising for an HTTP client with explicit auth APIs.
1748        return Err(Error::InvalidUrl(
1749            "URL userinfo is not supported; configure authentication explicitly".into(),
1750        ));
1751    }
1752    match url.scheme() {
1753        "http" | "https" => Ok(url),
1754        other => Err(Error::Unsupported(format!(
1755            "URL scheme '{other}' is not supported; use http or https"
1756        ))),
1757    }
1758}
1759
1760#[cfg(test)]
1761mod tests {
1762    use super::*;
1763    #[cfg(feature = "proxy")]
1764    use crate::proxy::ProxyAuth;
1765    use bytes::Bytes;
1766    #[cfg(any(feature = "http1", feature = "http2"))]
1767    use hyper_util::rt::TokioExecutor;
1768    #[cfg(any(feature = "http1", feature = "http2"))]
1769    use std::future::{ready, Ready};
1770    #[cfg(any(feature = "http1", feature = "http2"))]
1771    use std::net::SocketAddr;
1772    #[cfg(any(feature = "http1", feature = "http2"))]
1773    use std::task::{Context, Poll};
1774    #[cfg(any(feature = "http1", feature = "http2"))]
1775    use tower_service::Service;
1776
1777    #[test]
1778    fn client_constructs() {
1779        let _client = Client::new();
1780    }
1781
1782    #[test]
1783    fn client_config_debug_redacts_secrets() {
1784        let mut config = ClientConfig::default();
1785        config
1786            .default_headers
1787            .insert("authorization", "Bearer header-secret-token")
1788            .unwrap();
1789        #[cfg(feature = "cookies")]
1790        config
1791            .cookie_jar
1792            .set_default_cookie("session".to_owned(), "jar-secret-token".to_owned())
1793            .expect("valid test cookie");
1794        let debug = format!("{config:?}");
1795        assert!(
1796            !debug.contains("header-secret-token"),
1797            "ClientConfig Debug must not leak header secrets: {debug}"
1798        );
1799        #[cfg(feature = "cookies")]
1800        assert!(
1801            !debug.contains("jar-secret-token"),
1802            "ClientConfig Debug must not leak jar secrets: {debug}"
1803        );
1804    }
1805
1806    #[test]
1807    fn client_default() {
1808        let _client = Client::default();
1809    }
1810
1811    #[test]
1812    fn client_builder() {
1813        let _client = Client::builder().user_agent("test-agent").build();
1814    }
1815
1816    #[cfg(any(feature = "http1", feature = "http2"))]
1817    #[tokio::test]
1818    async fn standard_connector_preserves_resolver_failure_for_detailed_mapping() {
1819        #[derive(Clone, Copy)]
1820        struct FailingResolver;
1821
1822        impl Service<hyper_util::client::legacy::connect::dns::Name> for FailingResolver {
1823            type Response = std::vec::IntoIter<SocketAddr>;
1824            type Error = std::io::Error;
1825            type Future = Ready<std::result::Result<Self::Response, Self::Error>>;
1826
1827            fn poll_ready(
1828                &mut self,
1829                _: &mut Context<'_>,
1830            ) -> Poll<std::result::Result<(), Self::Error>> {
1831                Poll::Ready(Ok(()))
1832            }
1833
1834            fn call(&mut self, _: hyper_util::client::legacy::connect::dns::Name) -> Self::Future {
1835                ready(Err(std::io::Error::new(
1836                    std::io::ErrorKind::NotFound,
1837                    "synthetic standard resolver failure",
1838                )))
1839            }
1840        }
1841
1842        let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(
1843            HttpVersionPolicy::Http1Only,
1844        );
1845        #[cfg(feature = "tls-rustls")]
1846        let connector = build_standard_connector_with_resolver(
1847            rustls::ClientConfig::builder()
1848                .with_root_certificates(rustls::RootCertStore::empty())
1849                .with_no_client_auth(),
1850            enabler,
1851            FailingResolver,
1852        );
1853        #[cfg(not(feature = "tls-rustls"))]
1854        let connector = build_standard_connector_with_resolver(FailingResolver, enabler);
1855
1856        let client =
1857            hyper_util::client::legacy::Client::builder(TokioExecutor::new()).build(connector);
1858        #[cfg(feature = "tls-rustls")]
1859        let uri = "https://synthetic.example/";
1860        #[cfg(not(feature = "tls-rustls"))]
1861        let uri = "http://synthetic.example/";
1862        let request = http::Request::get(uri)
1863            .body(http_body_util::Empty::<Bytes>::new())
1864            .expect("synthetic request is valid");
1865        let error = client
1866            .request(request)
1867            .await
1868            .expect_err("synthetic resolver should fail");
1869        let context = crate::error::RequestFailureContext::new();
1870        let mapped = crate::transport::direct::map_send_error_with_context(error, Some(&context));
1871
1872        assert_eq!(mapped.kind(), "hyper_client");
1873        let failure = crate::error::RequestFailure::from_context(mapped, &context);
1874        assert_eq!(
1875            failure.network_failure_kind(),
1876            Some(crate::error::NetworkFailureKind::Dns)
1877        );
1878    }
1879
1880    #[test]
1881    fn client_builder_merge_timeout_preserves_other_phases() {
1882        // Phase-specific setters must merge into any existing timeout
1883        // configuration instead of replacing it wholesale.
1884        let client = Client::builder()
1885            .timeout(Timeout::from_secs(30))
1886            .merge_timeout(
1887                Timeout::builder()
1888                    .connect(std::time::Duration::from_secs(5))
1889                    .build(),
1890            )
1891            .merge_timeout(
1892                Timeout::builder()
1893                    .read(std::time::Duration::from_secs(10))
1894                    .build(),
1895            )
1896            .build();
1897
1898        let timeout = client.inner.config.timeout.expect("timeout configured");
1899        let d = |secs: u64| std::time::Duration::from_secs(secs);
1900        assert_eq!(timeout.connect, Some(d(5)), "last connect wins");
1901        assert_eq!(timeout.read, Some(d(10)), "last read wins");
1902        assert_eq!(
1903            timeout.write,
1904            Some(d(30)),
1905            "unset phases keep earlier values"
1906        );
1907        assert_eq!(timeout.pool, Some(d(30)));
1908    }
1909
1910    #[test]
1911    fn client_builder_merge_timeout_without_prior_config() {
1912        let client = Client::builder()
1913            .merge_timeout(
1914                Timeout::builder()
1915                    .connect(std::time::Duration::from_secs(5))
1916                    .build(),
1917            )
1918            .build();
1919
1920        let timeout = client.inner.config.timeout.expect("timeout configured");
1921        assert_eq!(timeout.connect, Some(std::time::Duration::from_secs(5)));
1922        assert_eq!(timeout.read, None);
1923    }
1924
1925    #[cfg(any(feature = "proxy", feature = "http3"))]
1926    #[test]
1927    fn client_builder_danger_accept_invalid_certs_preserves_tls_config() {
1928        let client = Client::builder()
1929            .tls_config(crate::tls::TlsConfig::builder().sni(false).build())
1930            .danger_accept_invalid_certs(true)
1931            .build();
1932        let tls = client
1933            .inner
1934            .config
1935            .tls_config
1936            .as_ref()
1937            .expect("TLS config should be retained");
1938        assert!(!tls.sni_enabled());
1939        assert!(!tls.verify_certificate());
1940        assert!(!tls.verify_hostname());
1941    }
1942
1943    #[test]
1944    #[cfg(feature = "tls-rustls")]
1945    fn tls_root_store_paths_construct() {
1946        // Native roots are environment-dependent; the production connector
1947        // always receives the same policy-built config as direct connectors.
1948        let enabler =
1949            crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
1950                allow_http3: false,
1951            });
1952        let config = crate::tls::TlsConfig::default()
1953            .build_rustls_config()
1954            .expect("default TLS policy builds");
1955        let _ = build_standard_connector(config, enabler);
1956    }
1957
1958    #[test]
1959    fn client_builder_http1_only() {
1960        let client = Client::builder()
1961            .http_version_policy(HttpVersionPolicy::Http1Only)
1962            .build();
1963        assert_eq!(
1964            client.inner.config.http_version_policy,
1965            HttpVersionPolicy::Http1Only
1966        );
1967    }
1968
1969    #[test]
1970    fn client_builder_http2_auto() {
1971        let client = Client::builder()
1972            .http_version_policy(HttpVersionPolicy::Auto { allow_http3: false })
1973            .build();
1974        assert_eq!(
1975            client.inner.config.http_version_policy,
1976            HttpVersionPolicy::Auto { allow_http3: false }
1977        );
1978    }
1979
1980    #[test]
1981    #[cfg(feature = "http2")]
1982    fn client_builder_http2_only() {
1983        let client = Client::builder()
1984            .http_version_policy(HttpVersionPolicy::Http2Only)
1985            .build();
1986        assert_eq!(
1987            client.inner.config.http_version_policy,
1988            HttpVersionPolicy::Http2Only
1989        );
1990    }
1991
1992    #[test]
1993    fn connector_builds_for_all_policies() {
1994        for policy in [
1995            HttpVersionPolicy::Http1Only,
1996            HttpVersionPolicy::Auto { allow_http3: false },
1997            #[cfg(feature = "http2")]
1998            HttpVersionPolicy::Http2Only,
1999            #[cfg(feature = "http3")]
2000            HttpVersionPolicy::Http3Only,
2001        ] {
2002            let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(policy);
2003            if !enabler.use_http3() {
2004                #[cfg(feature = "tls-rustls")]
2005                let config = crate::tls::TlsConfig::default()
2006                    .build_rustls_config()
2007                    .expect("default TLS policy builds");
2008                #[cfg(feature = "tls-rustls")]
2009                let _ = build_standard_connector(config, enabler);
2010            }
2011        }
2012    }
2013
2014    #[cfg(feature = "http2")]
2015    #[test]
2016    fn custom_connector_alpn_matches_http_version_policy() {
2017        let config = rustls::ClientConfig::builder()
2018            .with_root_certificates(rustls::RootCertStore::empty())
2019            .with_no_client_auth();
2020        let h2_only = configure_tls_alpn(
2021            config.clone(),
2022            crate::http_version::HttpVersionPolicyEnabler::from_policy(
2023                HttpVersionPolicy::Http2Only,
2024            ),
2025        );
2026        assert_eq!(h2_only.alpn_protocols, vec![b"h2".to_vec()]);
2027
2028        let auto = configure_tls_alpn(
2029            config,
2030            crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
2031                allow_http3: false,
2032            }),
2033        );
2034        assert_eq!(
2035            auto.alpn_protocols,
2036            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
2037        );
2038    }
2039
2040    #[test]
2041    fn parse_valid_urls() {
2042        assert!(parse_url("https://example.com").is_ok());
2043        assert!(parse_url("http://localhost:8080").is_ok());
2044    }
2045
2046    #[test]
2047    fn parse_invalid_schemes() {
2048        assert!(parse_url("ftp://example.com").is_err());
2049        assert!(parse_url("file:///tmp/test").is_err());
2050    }
2051
2052    #[test]
2053    fn parse_invalid_urls() {
2054        assert!(parse_url("not a url").is_err());
2055    }
2056
2057    #[test]
2058    fn get_request_builder() {
2059        let client = Client::new();
2060        let builder = client.get("https://example.com").unwrap();
2061        let req = builder.build().unwrap();
2062        assert_eq!(*req.method(), Method::GET);
2063    }
2064
2065    #[test]
2066    fn hyper_canceled_request_retry_defaults_on_and_is_independently_configurable() {
2067        assert!(Client::new().inner.config.retry_canceled_requests);
2068        let strict = Client::builder().retry_canceled_requests(false).build();
2069        assert!(!strict.inner.config.retry_canceled_requests);
2070        assert!(strict.inner.config.retry.is_none());
2071    }
2072
2073    #[test]
2074    fn physical_policy_and_transport_io_timeout_are_separate_from_logical_pooling() {
2075        let client = Client::builder()
2076            .physical_connection_policy(PhysicalConnectionPolicy {
2077                max_live: Some(2),
2078                admission_timeout: Some(Duration::from_secs(1)),
2079            })
2080            .transport_io_timeout(TransportIoTimeout {
2081                read: Some(Duration::from_secs(2)),
2082                write: Some(Duration::from_secs(3)),
2083            })
2084            .build();
2085        assert_eq!(
2086            client.inner.lifecycle.admission_timeout,
2087            Some(Duration::from_secs(1))
2088        );
2089        assert_eq!(
2090            client.inner.lifecycle.io_timeout.read,
2091            Some(Duration::from_secs(2))
2092        );
2093        assert_eq!(
2094            client.inner.lifecycle.io_timeout.write,
2095            Some(Duration::from_secs(3))
2096        );
2097    }
2098
2099    #[test]
2100    fn apply_content_length_empty_body() {
2101        let headers = Headers::new();
2102        let body = crate::body::RequestBody::Empty;
2103        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
2104        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "0");
2105    }
2106
2107    #[test]
2108    fn apply_content_length_bytes_body() {
2109        let headers = Headers::new();
2110        let body = crate::body::RequestBody::from(Bytes::from("hello"));
2111        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
2112        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
2113    }
2114
2115    #[test]
2116    fn apply_content_length_stream_known() {
2117        let headers = Headers::new();
2118        let stream = futures_util::stream::empty::<Result<Bytes>>();
2119        let body = crate::body::RequestBody::from_stream(stream, Some(7));
2120        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
2121        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "7");
2122    }
2123
2124    #[test]
2125    fn apply_content_length_stream_unknown() {
2126        let headers = Headers::new();
2127        let stream = futures_util::stream::empty::<Result<Bytes>>();
2128        let body = crate::body::RequestBody::from_stream(stream, None);
2129        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
2130        assert!(out.get("content-length").is_none());
2131    }
2132
2133    #[test]
2134    fn apply_content_length_user_matches() {
2135        let mut headers = Headers::new();
2136        headers.insert("content-length", "5").unwrap();
2137        let body = crate::body::RequestBody::from(Bytes::from("hello"));
2138        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
2139        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
2140    }
2141
2142    #[test]
2143    fn apply_content_length_user_mismatch_errors() {
2144        let mut headers = Headers::new();
2145        headers.insert("content-length", "10").unwrap();
2146        let body = crate::body::RequestBody::from(Bytes::from("hello"));
2147        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
2148        assert_eq!(err.kind(), "request_build");
2149    }
2150
2151    #[test]
2152    fn apply_content_length_rejects_invalid_value() {
2153        let mut headers = Headers::new();
2154        headers.insert("content-length", "not-a-number").unwrap();
2155        let body = crate::body::RequestBody::from(Bytes::from("hello"));
2156        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
2157        assert_eq!(err.kind(), "invalid_header_value");
2158    }
2159
2160    #[test]
2161    fn apply_content_length_rejects_unknown_stream_override() {
2162        let mut headers = Headers::new();
2163        headers.insert("content-length", "5").unwrap();
2164        let stream = futures_util::stream::empty::<Result<Bytes>>();
2165        let body = crate::body::RequestBody::from_stream(stream, None);
2166        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
2167        assert_eq!(err.kind(), "request_build");
2168    }
2169
2170    #[test]
2171    fn parse_url_rejects_userinfo_without_echoing_credentials() {
2172        let err = parse_url("https://user:secret@example.com").unwrap_err();
2173        assert_eq!(err.kind(), "invalid_url");
2174        assert!(!err.to_string().contains("secret"));
2175    }
2176
2177    #[cfg(feature = "proxy")]
2178    #[tokio::test]
2179    async fn proxy_auth_conflict_with_header() {
2180        let proxy = Proxy::all("http://proxy.example:8080")
2181            .unwrap()
2182            .auth(ProxyAuth::basic("user", "pass").unwrap());
2183        let client = Client::builder().proxy(proxy).build();
2184        let request = client
2185            .get("http://destination.example")
2186            .unwrap()
2187            .header("proxy-authorization", "Basic dXNlcjpwYXNz")
2188            .build()
2189            .unwrap();
2190        let err = client.send(request).await.unwrap_err();
2191        assert_eq!(err.kind(), "conflicting_auth");
2192        assert!(err.to_string().contains("Proxy-Authorization"));
2193    }
2194
2195    #[cfg(feature = "proxy")]
2196    #[tokio::test]
2197    async fn proxy_auth_no_conflict_without_header() {
2198        let proxy = Proxy::all("http://proxy.example:8080")
2199            .unwrap()
2200            .auth(ProxyAuth::basic("user", "pass").unwrap());
2201        let client = Client::builder().proxy(proxy).build();
2202        let request = client
2203            .get("http://destination.example")
2204            .unwrap()
2205            .build()
2206            .unwrap();
2207        let err = client.send(request).await.unwrap_err();
2208        assert_ne!(err.kind(), "conflicting_auth");
2209    }
2210
2211    #[cfg(feature = "proxy")]
2212    #[tokio::test]
2213    async fn proxy_auth_no_conflict_with_header_only() {
2214        let proxy = Proxy::all("http://proxy.example:8080").unwrap();
2215        let client = Client::builder().proxy(proxy).build();
2216        let request = client
2217            .get("http://destination.example")
2218            .unwrap()
2219            .header("proxy-authorization", "Basic dXNlcjpwYXNz")
2220            .build()
2221            .unwrap();
2222        let err = client.send(request).await.unwrap_err();
2223        assert_ne!(err.kind(), "conflicting_auth");
2224    }
2225}