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 the HTTPS-downgrade rule for redirects without replacing the
1050    /// rest of the redirect policy.
1051    ///
1052    /// Select
1053    /// [`RedirectDowngradePolicy::Deny`](crate::redirect::RedirectDowngradePolicy::Deny)
1054    /// to reject HTTPS -> HTTP downgrades before the downgraded request
1055    /// is dispatched. The default is
1056    /// [`Allow`](crate::redirect::RedirectDowngradePolicy::Allow) for
1057    /// compatibility.
1058    #[must_use]
1059    pub fn redirect_downgrade_policy(
1060        mut self,
1061        policy: crate::redirect::RedirectDowngradePolicy,
1062    ) -> Self {
1063        self.redirect.downgrade = policy;
1064        self
1065    }
1066
1067    /// Set a shared cookie jar for this client.
1068    ///
1069    /// When set, the client will automatically inject matching cookies
1070    /// into requests and update the jar from `Set-Cookie` response headers.
1071    ///
1072    /// Only available when the `cookies` feature is enabled.
1073    #[cfg(feature = "cookies")]
1074    #[must_use]
1075    pub fn cookie_jar(mut self, jar: CookieJar) -> Self {
1076        self.cookie_jar = Some(jar);
1077        self
1078    }
1079
1080    /// Set default authentication for all requests made by this client.
1081    ///
1082    /// The configured auth is applied to every request unless overridden
1083    /// or disabled at the request level. Auth is recomputed per redirect
1084    /// hop; cross-origin redirects never carry client auth.
1085    #[must_use]
1086    pub fn auth(mut self, auth: impl Into<crate::auth::AuthScheme>) -> Self {
1087        self.auth = Some(auth.into());
1088        self
1089    }
1090
1091    /// Set the default proxy for all requests made by this client.
1092    ///
1093    /// When set, all matching requests are routed through the specified
1094    /// proxy. Can be overridden or disabled per-request.
1095    #[cfg(feature = "proxy")]
1096    #[must_use]
1097    pub fn proxy(mut self, proxy: Proxy) -> Self {
1098        self.proxy = Some(proxy);
1099        self
1100    }
1101
1102    /// Add a scheme-specific proxy used when no explicit proxy is configured.
1103    #[cfg(feature = "proxy")]
1104    #[must_use]
1105    pub fn environment_proxy(mut self, proxy: Proxy) -> Self {
1106        self.environment_proxies.push(proxy);
1107        self
1108    }
1109
1110    /// Opt into environment-proxy routing from an explicit snapshot.
1111    ///
1112    /// The native default stays environment-independent: without this call
1113    /// the client never reads proxy environment variables. Pass
1114    /// [`crate::proxy::ProxyEnvironment::from_env`] at the call site to
1115    /// preserve command-line environment reachability, or
1116    /// [`crate::proxy::ProxyEnvironment::from_map`] in tests for a pure
1117    /// snapshot without global environment mutation.
1118    ///
1119    /// Each configured value becomes a scheme-scoped fallback proxy
1120    /// (specific before `ALL_PROXY`); `NO_PROXY` bypass is attached to
1121    /// every proxy. Invalid values fail closed with a redacted error.
1122    ///
1123    /// # Errors
1124    ///
1125    /// Returns [`crate::error::Error::InvalidProxyUrl`] when a configured
1126    /// proxy URL or the `NO_PROXY` value cannot be parsed.
1127    #[cfg(feature = "proxy")]
1128    pub fn proxy_environment(
1129        mut self,
1130        env: &crate::proxy::ProxyEnvironment,
1131    ) -> crate::error::Result<Self> {
1132        for proxy in env.client_proxies()? {
1133            self.environment_proxies.push(proxy);
1134        }
1135        Ok(self)
1136    }
1137
1138    /// Set `NO_PROXY` bypass rules for the default proxy.
1139    ///
1140    /// When set, URLs matching any bypass rule are sent directly
1141    /// without going through the proxy.
1142    #[cfg(feature = "proxy")]
1143    #[must_use]
1144    pub fn no_proxy(mut self, no_proxy: crate::proxy::NoProxy) -> Self {
1145        if let Some(proxy) = self.proxy.take() {
1146            self.proxy = Some(proxy.no_proxy(no_proxy));
1147        }
1148        self
1149    }
1150
1151    /// Set a custom TLS configuration for this client.
1152    ///
1153    /// When set, the client uses the provided [`crate::tls::TlsConfig`] for all
1154    /// TLS connections instead of the default native-root-with-WebPKI-fallback
1155    /// strategy (or the packaged-WebPKI default when `tls-native-roots` is not
1156    /// enabled).
1157    #[cfg(feature = "tls-rustls")]
1158    #[must_use]
1159    pub fn tls_config(mut self, config: crate::tls::TlsConfig) -> Self {
1160        self.tls_config = Some(config);
1161        self
1162    }
1163
1164    /// Enable or disable insecure TLS verification while retaining other
1165    /// TLS configuration already applied to this builder.
1166    #[cfg(feature = "tls-rustls")]
1167    #[must_use]
1168    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
1169        let config = self.tls_config.take().unwrap_or_default();
1170        self.tls_config = Some(config.danger_accept_invalid_certs(accept));
1171        self
1172    }
1173
1174    /// Enable or disable automatic response decompression.
1175    ///
1176    /// When enabled (the default), the client sends an
1177    /// `Accept-Encoding` header and transparently decompresses
1178    /// response bodies. Decoded `Content-Encoding` and
1179    /// `Content-Length` headers are removed from the response.
1180    ///
1181    /// Can be overridden per-request via
1182    /// [`RequestBuilder::decompress`].
1183    #[must_use]
1184    pub fn automatic_decompression(mut self, enabled: bool) -> Self {
1185        self.automatic_decompression = Some(enabled);
1186        self
1187    }
1188
1189    /// Set the maximum decoded response body size in bytes.
1190    ///
1191    /// The limit applies to bytes made available after decoding and also to
1192    /// ordinary unencoded/identity response bodies, in both buffered and
1193    /// streaming paths. Exceeding it produces [`Error::DecodedBodyTooLarge`]
1194    /// without requiring a second caller-side accumulation loop. A wire
1195    /// `Content-Length` may be used for an early metadata check, but this
1196    /// body limit remains authoritative when the header is absent, incorrect,
1197    /// or describes encoded bytes.
1198    #[must_use]
1199    pub fn max_decoded_body_size(mut self, max: usize) -> Self {
1200        self.max_decoded_body_size = Some(max);
1201        self
1202    }
1203
1204    /// Set the maximum decompression ratio (decoded bytes / compressed bytes).
1205    /// When set, responses whose expansion ratio exceeds this limit produce
1206    /// an error. This guards against zip-bomb style attacks.
1207    ///
1208    /// # Panics
1209    ///
1210    /// Panics if `ratio` is not finite or not positive.
1211    #[must_use]
1212    pub fn max_decompression_ratio(mut self, ratio: f64) -> Self {
1213        assert!(
1214            ratio.is_finite() && ratio > 0.0,
1215            "max_decompression_ratio must be finite and positive, got {ratio}"
1216        );
1217        self.max_decompression_ratio = Some(ratio);
1218        self
1219    }
1220
1221    /// Set the retry policy for this client.
1222    ///
1223    /// When set, failed requests that match the policy (safe methods,
1224    /// retryable statuses/errors, replayable bodies) are automatically
1225    /// retried with exponential backoff.
1226    #[must_use]
1227    pub fn retry(mut self, policy: RetryPolicy) -> Self {
1228        self.retry = Some(policy);
1229        self
1230    }
1231
1232    /// Allow or disallow Hyper's implicit retry when a reused idle
1233    /// connection is found unusable before a request starts writing.
1234    ///
1235    /// This is separate from eggfetch's explicit [`RetryPolicy`]. The
1236    /// default is `true`, preserving Hyper's existing behavior.
1237    #[must_use]
1238    pub fn retry_canceled_requests(mut self, enabled: bool) -> Self {
1239        self.retry_canceled_requests = enabled;
1240        self
1241    }
1242
1243    /// Install a client-scoped caller-owned raw-stream dialer.
1244    ///
1245    /// Eggfetch continues to own HTTP framing, destination TLS, SNI,
1246    /// certificate verification, redirects, retries, and response bodies.
1247    /// The dialer is incompatible with built-in proxy, UDS, resolved-target,
1248    /// local-address, and socket-option routing; those combinations fail
1249    /// closed before network I/O.
1250    #[must_use]
1251    pub fn dialer<D>(mut self, dialer: D) -> Self
1252    where
1253        D: Dialer,
1254    {
1255        self.dialer = Some(Arc::new(dialer));
1256        self
1257    }
1258
1259    /// Install a shared caller-scoped live physical-connection policy.
1260    ///
1261    /// This controls established Hyper connections, including idle pooled
1262    /// connections. It does not change the logical request limits in
1263    /// [`PoolConfig`]. A `max_live` value of zero fails
1264    /// requests closed because no useful client can be created from it.
1265    #[must_use]
1266    pub fn physical_connection_policy(mut self, policy: PhysicalConnectionPolicy) -> Self {
1267        self.physical_connection_policy = policy;
1268        self
1269    }
1270
1271    /// Install established-transport read/write inactivity guardrails.
1272    ///
1273    /// These timers are distinct from [`Timeout`]'s request
1274    /// body and response-stream semantics and are disabled by default.
1275    #[must_use]
1276    pub fn transport_io_timeout(mut self, timeout: TransportIoTimeout) -> Self {
1277        self.transport_io_timeout = timeout;
1278        self
1279    }
1280
1281    /// Set the HTTP version policy for this client.
1282    ///
1283    /// Controls which HTTP protocol versions the client may negotiate.
1284    /// The default is [`HttpVersionPolicy::Auto`], which allows HTTP/2
1285    /// negotiation via ALPN when the `http2` feature is enabled.
1286    ///
1287    /// When the `http2` feature is not compiled in, `Http2Only` and `Auto`
1288    /// are silently downgraded to `Http1Only`.
1289    #[must_use]
1290    pub fn http_version_policy(mut self, policy: HttpVersionPolicy) -> Self {
1291        self.http_version_policy = policy;
1292        self
1293    }
1294
1295    /// Set a local address to bind outbound sockets to before connecting.
1296    ///
1297    /// When set, all direct (non-proxy, non-UDS) connections will bind
1298    /// to the specified local address before connecting to the remote.
1299    /// This uses a custom connector path instead of the standard
1300    /// hyper-rustls connector.
1301    #[must_use]
1302    pub fn local_address(mut self, addr: std::net::SocketAddr) -> Self {
1303        let config = self.direct_connector_config.get_or_insert_with(|| {
1304            crate::transport::direct_connector::DirectConnectorConfig {
1305                local_address: None,
1306                socket_options: Vec::new(),
1307            }
1308        });
1309        config.local_address = Some(addr);
1310        self
1311    }
1312
1313    /// Set socket options to apply to outbound TCP connections.
1314    ///
1315    /// Options are applied to the socket before the connect operation.
1316    /// Recognized options are applied via `tokio::net::TcpSocket` setters;
1317    /// unrecognized options produce a connection error (never silently
1318    /// ignored, per the plan's Track 2.4 requirement).
1319    #[must_use]
1320    pub fn socket_options(
1321        mut self,
1322        options: Vec<crate::transport::direct_connector::SocketOption>,
1323    ) -> Self {
1324        let config = self.direct_connector_config.get_or_insert_with(|| {
1325            crate::transport::direct_connector::DirectConnectorConfig {
1326                local_address: None,
1327                socket_options: Vec::new(),
1328            }
1329        });
1330        config.socket_options = options;
1331        self
1332    }
1333
1334    /// Set a Unix domain socket path for all connections.
1335    ///
1336    /// When set, all requests are routed through the specified UDS path
1337    /// instead of making TCP connections. The URL in the request still
1338    /// provides HTTP scheme/authority/path semantics.
1339    ///
1340    /// Only supported on Unix platforms. On non-Unix platforms, this
1341    /// option is accepted but will produce an error at request time.
1342    #[must_use]
1343    pub fn uds_path(mut self, path: String) -> Self {
1344        self.uds_path = Some(path);
1345        self
1346    }
1347
1348    /// Build the client.
1349    ///
1350    /// Native system roots are preferred. If the platform root store is
1351    /// unavailable, the client falls back to the packaged Mozilla root set
1352    /// while retaining certificate and hostname verification.
1353    #[must_use]
1354    #[allow(clippy::too_many_lines)]
1355    pub fn build(self) -> Client {
1356        #[cfg(any(feature = "http1", feature = "http2"))]
1357        use crate::http_version::HttpVersionPolicyEnabler;
1358        #[cfg(any(feature = "http1", feature = "http2"))]
1359        let enabler = HttpVersionPolicyEnabler::from_policy(self.http_version_policy);
1360        let transport_metrics = Arc::new(crate::transport::metrics::TransportMetrics::new());
1361
1362        let mut pool_config = self.pool_config;
1363        if let Some(limits) = self.limits {
1364            let limits_config: PoolConfig = limits.into();
1365            if limits_config.max_connections.is_some() {
1366                pool_config.max_connections = limits_config.max_connections;
1367            }
1368            if limits_config.max_connections_per_host.is_some() {
1369                pool_config.max_connections_per_host = limits_config.max_connections_per_host;
1370            }
1371            if limits_config.max_in_flight_requests.is_some() {
1372                pool_config.max_in_flight_requests = limits_config.max_in_flight_requests;
1373            }
1374            if limits_config.max_in_flight_requests_per_origin.is_some() {
1375                pool_config.max_in_flight_requests_per_origin =
1376                    limits_config.max_in_flight_requests_per_origin;
1377            }
1378            if limits_config.max_idle_connections.is_some() {
1379                pool_config.max_idle_connections = limits_config.max_idle_connections;
1380            }
1381            if limits_config.max_idle_connections_per_host.is_some() {
1382                pool_config.max_idle_connections_per_host =
1383                    limits_config.max_idle_connections_per_host;
1384            }
1385            if limits_config.idle_timeout.is_some() {
1386                pool_config.idle_timeout = limits_config.idle_timeout;
1387            }
1388        }
1389        #[cfg(any(feature = "http1", feature = "http2"))]
1390        let lifecycle = Arc::new(LifecycleConfig::from_policy(
1391            self.physical_connection_policy,
1392            self.transport_io_timeout,
1393            transport_metrics.clone(),
1394        ));
1395        // Shared builder policy for the persistent per-client Hyper
1396        // singletons below (standard, direct, UDS, custom dialer). Cached and
1397        // isolated route clients resolve their own narrower policy at use.
1398        #[cfg(any(feature = "http1", feature = "http2"))]
1399        let persistent_policy = HyperClientPolicy::persistent(
1400            self.retry_canceled_requests,
1401            pool_config.idle_timeout,
1402            pool_config.effective_max_idle_per_host(),
1403            enabler,
1404        );
1405
1406        #[cfg(feature = "cookies")]
1407        let cookie_jar = self.cookie_jar.unwrap_or_default();
1408
1409        let automatic_decompression = self.automatic_decompression.unwrap_or(true);
1410        #[cfg(feature = "tls-rustls")]
1411        let tls_config_result = self
1412            .tls_config
1413            .clone()
1414            .unwrap_or_default()
1415            .build_rustls_config();
1416        #[cfg(feature = "tls-rustls")]
1417        let tls_config_error = tls_config_result
1418            .as_ref()
1419            .err()
1420            .map(|error| format!("failed to build TLS config: {error}"));
1421        // `Http3Only` is strict direct-QUIC and needs no Hyper client.
1422        // `Auto { allow_http3: true }` needs both: H1/H2 for discovery and
1423        // safe fallback plus QUIC for discovered routes. All other policies
1424        // need Hyper only.
1425        #[cfg(feature = "tls-rustls")]
1426        let hyper_client = if matches!(
1427            self.http_version_policy,
1428            crate::HttpVersionPolicy::Http3Only
1429        ) || tls_config_error.is_some()
1430        {
1431            None
1432        } else if let Ok(rc) = tls_config_result {
1433            let https = build_standard_connector(rc, enabler);
1434            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1435            Some(build_hyper_client(
1436                https,
1437                &persistent_policy,
1438                connect_timeout,
1439                &lifecycle,
1440            ))
1441        } else {
1442            None
1443        };
1444
1445        #[cfg(all(not(feature = "tls-rustls"), any(feature = "http1", feature = "http2")))]
1446        let hyper_client = if matches!(
1447            self.http_version_policy,
1448            crate::HttpVersionPolicy::Http3Only
1449        ) {
1450            None
1451        } else {
1452            let connector = build_standard_connector(enabler);
1453            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1454            Some(build_hyper_client(
1455                connector,
1456                &persistent_policy,
1457                connect_timeout,
1458                &lifecycle,
1459            ))
1460        };
1461        #[cfg(feature = "http3")]
1462        let h3_connector = if enabler.use_http3() {
1463            crate::transport::http3::H3Connector::with_metrics(
1464                self.tls_config.clone(),
1465                &pool_config,
1466                Some(transport_metrics.clone()),
1467            )
1468            .ok()
1469        } else {
1470            None
1471        };
1472
1473        // Build the direct connector client for advanced socket options / local
1474        // address binding. This uses a custom connector path instead of the
1475        // standard hyper-rustls connector.
1476        #[cfg(any(feature = "http1", feature = "http2"))]
1477        let stored_direct_config = self.direct_connector_config.clone();
1478        #[cfg(any(feature = "http1", feature = "http2"))]
1479        let direct_client = if let Some(dc_config) = self.direct_connector_config {
1480            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1481
1482            // Build a TLS connector for HTTPS through the direct path.
1483            #[cfg(feature = "tls-rustls")]
1484            let tls_connector = match self
1485                .tls_config
1486                .clone()
1487                .unwrap_or_default()
1488                .build_rustls_config()
1489            {
1490                Ok(rc) => Some(tokio_rustls::TlsConnector::from(Arc::new(
1491                    configure_tls_alpn(
1492                        rc,
1493                        crate::http_version::HttpVersionPolicyEnabler::from_policy(
1494                            self.http_version_policy,
1495                        ),
1496                    ),
1497                ))),
1498                Err(_) => None,
1499            };
1500            #[cfg(not(feature = "tls-rustls"))]
1501            let tls_connector = None;
1502
1503            let direct_connector =
1504                crate::transport::direct_connector::DirectConnector::with_metrics(
1505                    dc_config,
1506                    tls_connector,
1507                    transport_metrics.clone(),
1508                );
1509            Some(build_hyper_client(
1510                direct_connector,
1511                &persistent_policy,
1512                connect_timeout,
1513                &lifecycle,
1514            ))
1515        } else {
1516            None
1517        };
1518
1519        // The UDS path is accepted on all platforms (see `uds_path`) but
1520        // only consumed on Unix; without this the field is never read on
1521        // non-Unix targets.
1522        #[cfg(not(unix))]
1523        let _ = &self.uds_path;
1524
1525        #[cfg(all(unix, any(feature = "http1", feature = "http2")))]
1526        let uds_client = self.uds_path.clone().map(|path| {
1527            #[cfg(feature = "tls-rustls")]
1528            let tls_connector = self
1529                .tls_config
1530                .clone()
1531                .unwrap_or_default()
1532                .build_rustls_config()
1533                .ok()
1534                .map(|rc| {
1535                    tokio_rustls::TlsConnector::from(Arc::new(configure_tls_alpn(
1536                        rc,
1537                        crate::http_version::HttpVersionPolicyEnabler::from_policy(
1538                            self.http_version_policy,
1539                        ),
1540                    )))
1541                });
1542            #[cfg(not(feature = "tls-rustls"))]
1543            let tls_connector = None;
1544            let connector = crate::transport::uds::UdsConnector::with_metrics(
1545                path,
1546                tls_connector,
1547                transport_metrics.clone(),
1548            );
1549            let connect_timeout = self.timeout.as_ref().and_then(|timeout| timeout.connect);
1550            build_hyper_client(connector, &persistent_policy, connect_timeout, &lifecycle)
1551        });
1552
1553        #[cfg(any(feature = "http1", feature = "http2"))]
1554        let custom_client = if let Some(dialer) = self.dialer.clone() {
1555            #[cfg(feature = "tls-rustls")]
1556            let custom_config = self
1557                .tls_config
1558                .clone()
1559                .unwrap_or_default()
1560                .build_rustls_config()
1561                .ok();
1562            #[cfg(not(feature = "tls-rustls"))]
1563            let custom_config = Some(());
1564
1565            custom_config.and_then(|custom_config| {
1566                let connector =
1567                    build_custom_connector(custom_config, dialer, enabler, None).ok()?;
1568                let connect_timeout = self.timeout.as_ref().and_then(|timeout| timeout.connect);
1569                Some(build_hyper_client(
1570                    connector,
1571                    &persistent_policy,
1572                    connect_timeout,
1573                    &lifecycle,
1574                ))
1575            })
1576        } else {
1577            None
1578        };
1579        let config = ClientConfig {
1580            default_headers: self.default_headers,
1581            user_agent: self.user_agent,
1582            timeout: self.timeout,
1583            redirect: self.redirect,
1584            auth: self.auth,
1585            #[cfg(feature = "cookies")]
1586            cookie_jar,
1587            automatic_decompression,
1588            max_decoded_body_size: self.max_decoded_body_size,
1589            max_decompression_ratio: self.max_decompression_ratio,
1590            #[cfg(feature = "proxy")]
1591            proxy: self.proxy,
1592            #[cfg(feature = "proxy")]
1593            environment_proxies: self.environment_proxies,
1594            #[cfg(feature = "tls-rustls")]
1595            tls_config: self.tls_config,
1596            retry: self.retry,
1597            retry_canceled_requests: self.retry_canceled_requests,
1598            dialer: self.dialer,
1599            uds_configured: self.uds_path.is_some(),
1600            http_version_policy: self.http_version_policy,
1601        };
1602
1603        let pool = Pool::new(pool_config);
1604
1605        Client {
1606            inner: Arc::new(ClientInner {
1607                #[cfg(any(feature = "http1", feature = "http2"))]
1608                hyper_client,
1609                #[cfg(any(feature = "http1", feature = "http2"))]
1610                custom_client,
1611                #[cfg(feature = "tls-rustls")]
1612                tls_config_error,
1613                #[cfg(any(feature = "http1", feature = "http2"))]
1614                direct_client,
1615                #[cfg(any(feature = "http1", feature = "http2"))]
1616                direct_connector_config: stored_direct_config,
1617                #[cfg(any(feature = "http1", feature = "http2"))]
1618                sni_clients: Mutex::new(BoundedClientCache::new(SNI_CLIENT_CACHE_MAX_ENTRIES)),
1619                #[cfg(any(feature = "http1", feature = "http2"))]
1620                sni_custom_clients: Mutex::new(BoundedClientCache::new(
1621                    SNI_CLIENT_CACHE_MAX_ENTRIES,
1622                )),
1623                #[cfg(all(unix, any(feature = "http1", feature = "http2")))]
1624                uds_client,
1625                #[cfg(feature = "proxy")]
1626                socks_clients: Mutex::new(BoundedClientCache::new(SOCKS_CLIENT_CACHE_MAX_ENTRIES)),
1627                #[cfg(feature = "proxy")]
1628                forward_clients: Mutex::new(BoundedClientCache::new(
1629                    FORWARD_CLIENT_CACHE_MAX_ENTRIES,
1630                )),
1631                #[cfg(feature = "proxy")]
1632                connect_clients: Mutex::new(BoundedClientCache::new(
1633                    CONNECT_CLIENT_CACHE_MAX_ENTRIES,
1634                )),
1635                config,
1636                pool,
1637                transport_metrics,
1638                #[cfg(any(feature = "http1", feature = "http2"))]
1639                lifecycle,
1640                #[cfg(feature = "http3")]
1641                h3_connector,
1642                #[cfg(feature = "http3")]
1643                alt_svc_state: Arc::new(crate::transport::alt_svc::AltSvcState::new()),
1644            }),
1645        }
1646    }
1647}
1648
1649/// Build the standard cleartext connector.
1650#[cfg(not(feature = "tls-rustls"))]
1651fn build_standard_connector(enabler: crate::http_version::HttpVersionPolicyEnabler) -> Connector {
1652    build_standard_connector_with_resolver(
1653        hyper_util::client::legacy::connect::dns::GaiResolver::new(),
1654        enabler,
1655    )
1656}
1657
1658/// Build a standard cleartext connector with a caller-selected private
1659/// resolver. Production callers use the default system resolver; tests use
1660/// this generic seam to keep resolver provenance deterministic.
1661#[cfg(not(feature = "tls-rustls"))]
1662fn build_standard_connector_with_resolver<R>(
1663    resolver: R,
1664    enabler: crate::http_version::HttpVersionPolicyEnabler,
1665) -> hyper_util::client::legacy::connect::HttpConnector<
1666    crate::transport::standard_resolver::ClassifyingResolver<R>,
1667>
1668where
1669    R: tower_service::Service<hyper_util::client::legacy::connect::dns::Name>
1670        + Clone
1671        + Send
1672        + Sync
1673        + 'static,
1674    R::Response: Iterator<Item = std::net::SocketAddr>,
1675    R::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
1676    R::Future: Send + 'static,
1677{
1678    let _ = enabler;
1679    let mut connector = hyper_util::client::legacy::connect::HttpConnector::new_with_resolver(
1680        crate::transport::standard_resolver::ClassifyingResolver::new(resolver),
1681    );
1682    connector.enforce_http(true);
1683    connector
1684}
1685
1686/// Build the standard TLS connector from the authoritative [`TlsConfig`].
1687#[cfg(feature = "tls-rustls")]
1688fn build_standard_connector(
1689    config: rustls::ClientConfig,
1690    enabler: crate::http_version::HttpVersionPolicyEnabler,
1691) -> Connector {
1692    build_standard_connector_with_resolver(
1693        config,
1694        enabler,
1695        hyper_util::client::legacy::connect::dns::GaiResolver::new(),
1696    )
1697}
1698
1699/// Build the standard Rustls connector around an explicitly constructed
1700/// Hyper resolver connector so DNS provenance survives the TLS wrapper.
1701#[cfg(feature = "tls-rustls")]
1702fn build_standard_connector_with_resolver<R>(
1703    mut config: rustls::ClientConfig,
1704    enabler: crate::http_version::HttpVersionPolicyEnabler,
1705    resolver: R,
1706) -> hyper_rustls::HttpsConnector<
1707    hyper_util::client::legacy::connect::HttpConnector<
1708        crate::transport::standard_resolver::ClassifyingResolver<R>,
1709    >,
1710>
1711where
1712    R: tower_service::Service<hyper_util::client::legacy::connect::dns::Name>
1713        + Clone
1714        + Send
1715        + Sync
1716        + 'static,
1717    R::Response: Iterator<Item = std::net::SocketAddr>,
1718    R::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
1719    R::Future: Send + 'static,
1720{
1721    // hyper-rustls fills ALPN from the selected protocol methods.
1722    config.alpn_protocols.clear();
1723    let mut http = hyper_util::client::legacy::connect::HttpConnector::new_with_resolver(
1724        crate::transport::standard_resolver::ClassifyingResolver::new(resolver),
1725    );
1726    http.enforce_http(false);
1727    let builder = hyper_rustls::HttpsConnectorBuilder::new()
1728        .with_tls_config(config)
1729        .https_or_http();
1730    #[cfg(feature = "http2")]
1731    {
1732        match (enabler.enable_http1(), enabler.enable_http2()) {
1733            (true, true) => builder.enable_http1().enable_http2().wrap_connector(http),
1734            (true | false, false) => builder.enable_http1().wrap_connector(http),
1735            (false, true) => builder.enable_http2().wrap_connector(http),
1736        }
1737    }
1738    #[cfg(not(feature = "http2"))]
1739    {
1740        let _ = enabler;
1741        builder.enable_http1().wrap_connector(http)
1742    }
1743}
1744
1745#[cfg(all(feature = "tls-rustls", any(feature = "http1", feature = "http2")))]
1746fn build_custom_connector(
1747    config: rustls::ClientConfig,
1748    dialer: Arc<dyn Dialer>,
1749    enabler: crate::http_version::HttpVersionPolicyEnabler,
1750    sni_hostname: Option<&str>,
1751) -> Result<crate::transport::CustomConnector> {
1752    let config = configure_tls_alpn(config, enabler);
1753    let resolver: Arc<dyn hyper_rustls::ResolveServerName + Send + Sync> =
1754        if let Some(sni_hostname) = sni_hostname {
1755            let server_name = rustls::pki_types::ServerName::try_from(sni_hostname.to_owned())
1756                .map_err(|error| Error::Tls(format!("invalid SNI hostname: {error}")))?;
1757            Arc::new(hyper_rustls::FixedServerNameResolver::new(server_name))
1758        } else {
1759            Arc::new(hyper_rustls::DefaultServerNameResolver::default())
1760        };
1761    Ok(hyper_rustls::HttpsConnector::new(
1762        crate::transport::dialer::DialerConnector::new(dialer),
1763        Arc::new(config),
1764        false,
1765        resolver,
1766    ))
1767}
1768
1769#[cfg(all(not(feature = "tls-rustls"), any(feature = "http1", feature = "http2")))]
1770fn build_custom_connector(
1771    _config: (),
1772    dialer: Arc<dyn Dialer>,
1773    _enabler: crate::http_version::HttpVersionPolicyEnabler,
1774    _sni_hostname: Option<&str>,
1775) -> Result<crate::transport::CustomConnector> {
1776    Ok(crate::transport::dialer::DialerConnector::new(dialer))
1777}
1778
1779impl Default for ClientBuilder {
1780    fn default() -> Self {
1781        Self::new()
1782    }
1783}
1784
1785fn parse_url(url_str: &str) -> Result<url::Url> {
1786    // Deliberately do not echo `url_str` into the error: parsing has
1787    // failed, so `redact_url_string` would fall back to the raw input
1788    // (potentially containing credentials). `url::ParseError` renders
1789    // only a static description and never embeds the input.
1790    let url = url::Url::parse(url_str).map_err(|e| Error::InvalidUrl(e.to_string()))?;
1791    if !url.username().is_empty() || url.password().is_some() {
1792        // URL userinfo is both easy to leak through diagnostics and
1793        // surprising for an HTTP client with explicit auth APIs.
1794        return Err(Error::InvalidUrl(
1795            "URL userinfo is not supported; configure authentication explicitly".into(),
1796        ));
1797    }
1798    match url.scheme() {
1799        "http" | "https" => Ok(url),
1800        other => Err(Error::Unsupported(format!(
1801            "URL scheme '{other}' is not supported; use http or https"
1802        ))),
1803    }
1804}
1805
1806#[cfg(test)]
1807mod tests {
1808    use super::*;
1809    #[cfg(feature = "proxy")]
1810    use crate::proxy::ProxyAuth;
1811    use bytes::Bytes;
1812    #[cfg(any(feature = "http1", feature = "http2"))]
1813    use hyper_util::rt::TokioExecutor;
1814    #[cfg(any(feature = "http1", feature = "http2"))]
1815    use std::future::{ready, Ready};
1816    #[cfg(any(feature = "http1", feature = "http2"))]
1817    use std::net::SocketAddr;
1818    #[cfg(any(feature = "http1", feature = "http2"))]
1819    use std::task::{Context, Poll};
1820    #[cfg(any(feature = "http1", feature = "http2"))]
1821    use tower_service::Service;
1822
1823    #[test]
1824    fn client_constructs() {
1825        let _client = Client::new();
1826    }
1827
1828    #[test]
1829    fn client_config_debug_redacts_secrets() {
1830        let mut config = ClientConfig::default();
1831        config
1832            .default_headers
1833            .insert("authorization", "Bearer header-secret-token")
1834            .unwrap();
1835        #[cfg(feature = "cookies")]
1836        config
1837            .cookie_jar
1838            .set_default_cookie("session".to_owned(), "jar-secret-token".to_owned())
1839            .expect("valid test cookie");
1840        let debug = format!("{config:?}");
1841        assert!(
1842            !debug.contains("header-secret-token"),
1843            "ClientConfig Debug must not leak header secrets: {debug}"
1844        );
1845        #[cfg(feature = "cookies")]
1846        assert!(
1847            !debug.contains("jar-secret-token"),
1848            "ClientConfig Debug must not leak jar secrets: {debug}"
1849        );
1850    }
1851
1852    #[test]
1853    fn client_default() {
1854        let _client = Client::default();
1855    }
1856
1857    #[test]
1858    fn client_builder() {
1859        let _client = Client::builder().user_agent("test-agent").build();
1860    }
1861
1862    #[cfg(any(feature = "http1", feature = "http2"))]
1863    #[tokio::test]
1864    async fn standard_connector_preserves_resolver_failure_for_detailed_mapping() {
1865        #[derive(Clone, Copy)]
1866        struct FailingResolver;
1867
1868        impl Service<hyper_util::client::legacy::connect::dns::Name> for FailingResolver {
1869            type Response = std::vec::IntoIter<SocketAddr>;
1870            type Error = std::io::Error;
1871            type Future = Ready<std::result::Result<Self::Response, Self::Error>>;
1872
1873            fn poll_ready(
1874                &mut self,
1875                _: &mut Context<'_>,
1876            ) -> Poll<std::result::Result<(), Self::Error>> {
1877                Poll::Ready(Ok(()))
1878            }
1879
1880            fn call(&mut self, _: hyper_util::client::legacy::connect::dns::Name) -> Self::Future {
1881                ready(Err(std::io::Error::new(
1882                    std::io::ErrorKind::NotFound,
1883                    "synthetic standard resolver failure",
1884                )))
1885            }
1886        }
1887
1888        let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(
1889            HttpVersionPolicy::Http1Only,
1890        );
1891        #[cfg(feature = "tls-rustls")]
1892        let connector = build_standard_connector_with_resolver(
1893            rustls::ClientConfig::builder()
1894                .with_root_certificates(rustls::RootCertStore::empty())
1895                .with_no_client_auth(),
1896            enabler,
1897            FailingResolver,
1898        );
1899        #[cfg(not(feature = "tls-rustls"))]
1900        let connector = build_standard_connector_with_resolver(FailingResolver, enabler);
1901
1902        let client =
1903            hyper_util::client::legacy::Client::builder(TokioExecutor::new()).build(connector);
1904        #[cfg(feature = "tls-rustls")]
1905        let uri = "https://synthetic.example/";
1906        #[cfg(not(feature = "tls-rustls"))]
1907        let uri = "http://synthetic.example/";
1908        let request = http::Request::get(uri)
1909            .body(http_body_util::Empty::<Bytes>::new())
1910            .expect("synthetic request is valid");
1911        let error = client
1912            .request(request)
1913            .await
1914            .expect_err("synthetic resolver should fail");
1915        let context = crate::error::RequestFailureContext::new();
1916        let mapped = crate::transport::direct::map_send_error_with_context(error, Some(&context));
1917
1918        assert_eq!(mapped.kind(), "hyper_client");
1919        let failure = crate::error::RequestFailure::from_context(mapped, &context);
1920        assert_eq!(
1921            failure.network_failure_kind(),
1922            Some(crate::error::NetworkFailureKind::Dns)
1923        );
1924    }
1925
1926    #[test]
1927    fn client_builder_merge_timeout_preserves_other_phases() {
1928        // Phase-specific setters must merge into any existing timeout
1929        // configuration instead of replacing it wholesale.
1930        let client = Client::builder()
1931            .timeout(Timeout::from_secs(30))
1932            .merge_timeout(
1933                Timeout::builder()
1934                    .connect(std::time::Duration::from_secs(5))
1935                    .build(),
1936            )
1937            .merge_timeout(
1938                Timeout::builder()
1939                    .read(std::time::Duration::from_secs(10))
1940                    .build(),
1941            )
1942            .build();
1943
1944        let timeout = client.inner.config.timeout.expect("timeout configured");
1945        let d = |secs: u64| std::time::Duration::from_secs(secs);
1946        assert_eq!(timeout.connect, Some(d(5)), "last connect wins");
1947        assert_eq!(timeout.read, Some(d(10)), "last read wins");
1948        assert_eq!(
1949            timeout.write,
1950            Some(d(30)),
1951            "unset phases keep earlier values"
1952        );
1953        assert_eq!(timeout.pool, Some(d(30)));
1954    }
1955
1956    #[test]
1957    fn client_builder_merge_timeout_without_prior_config() {
1958        let client = Client::builder()
1959            .merge_timeout(
1960                Timeout::builder()
1961                    .connect(std::time::Duration::from_secs(5))
1962                    .build(),
1963            )
1964            .build();
1965
1966        let timeout = client.inner.config.timeout.expect("timeout configured");
1967        assert_eq!(timeout.connect, Some(std::time::Duration::from_secs(5)));
1968        assert_eq!(timeout.read, None);
1969    }
1970
1971    #[cfg(any(feature = "proxy", feature = "http3"))]
1972    #[test]
1973    fn client_builder_danger_accept_invalid_certs_preserves_tls_config() {
1974        let client = Client::builder()
1975            .tls_config(crate::tls::TlsConfig::builder().sni(false).build())
1976            .danger_accept_invalid_certs(true)
1977            .build();
1978        let tls = client
1979            .inner
1980            .config
1981            .tls_config
1982            .as_ref()
1983            .expect("TLS config should be retained");
1984        assert!(!tls.sni_enabled());
1985        assert!(!tls.verify_certificate());
1986        assert!(!tls.verify_hostname());
1987    }
1988
1989    #[test]
1990    #[cfg(feature = "tls-rustls")]
1991    fn tls_root_store_paths_construct() {
1992        // Native roots are environment-dependent; the production connector
1993        // always receives the same policy-built config as direct connectors.
1994        let enabler =
1995            crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
1996                allow_http3: false,
1997            });
1998        let config = crate::tls::TlsConfig::default()
1999            .build_rustls_config()
2000            .expect("default TLS policy builds");
2001        let _ = build_standard_connector(config, enabler);
2002    }
2003
2004    #[test]
2005    fn client_builder_http1_only() {
2006        let client = Client::builder()
2007            .http_version_policy(HttpVersionPolicy::Http1Only)
2008            .build();
2009        assert_eq!(
2010            client.inner.config.http_version_policy,
2011            HttpVersionPolicy::Http1Only
2012        );
2013    }
2014
2015    #[test]
2016    fn client_builder_http2_auto() {
2017        let client = Client::builder()
2018            .http_version_policy(HttpVersionPolicy::Auto { allow_http3: false })
2019            .build();
2020        assert_eq!(
2021            client.inner.config.http_version_policy,
2022            HttpVersionPolicy::Auto { allow_http3: false }
2023        );
2024    }
2025
2026    #[test]
2027    #[cfg(feature = "http2")]
2028    fn client_builder_http2_only() {
2029        let client = Client::builder()
2030            .http_version_policy(HttpVersionPolicy::Http2Only)
2031            .build();
2032        assert_eq!(
2033            client.inner.config.http_version_policy,
2034            HttpVersionPolicy::Http2Only
2035        );
2036    }
2037
2038    #[test]
2039    fn connector_builds_for_all_policies() {
2040        for policy in [
2041            HttpVersionPolicy::Http1Only,
2042            HttpVersionPolicy::Auto { allow_http3: false },
2043            #[cfg(feature = "http2")]
2044            HttpVersionPolicy::Http2Only,
2045            #[cfg(feature = "http3")]
2046            HttpVersionPolicy::Http3Only,
2047        ] {
2048            let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(policy);
2049            if !enabler.use_http3() {
2050                #[cfg(feature = "tls-rustls")]
2051                let config = crate::tls::TlsConfig::default()
2052                    .build_rustls_config()
2053                    .expect("default TLS policy builds");
2054                #[cfg(feature = "tls-rustls")]
2055                let _ = build_standard_connector(config, enabler);
2056            }
2057        }
2058    }
2059
2060    #[cfg(feature = "http2")]
2061    #[test]
2062    fn custom_connector_alpn_matches_http_version_policy() {
2063        let config = rustls::ClientConfig::builder()
2064            .with_root_certificates(rustls::RootCertStore::empty())
2065            .with_no_client_auth();
2066        let h2_only = configure_tls_alpn(
2067            config.clone(),
2068            crate::http_version::HttpVersionPolicyEnabler::from_policy(
2069                HttpVersionPolicy::Http2Only,
2070            ),
2071        );
2072        assert_eq!(h2_only.alpn_protocols, vec![b"h2".to_vec()]);
2073
2074        let auto = configure_tls_alpn(
2075            config,
2076            crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
2077                allow_http3: false,
2078            }),
2079        );
2080        assert_eq!(
2081            auto.alpn_protocols,
2082            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
2083        );
2084    }
2085
2086    #[test]
2087    fn parse_valid_urls() {
2088        assert!(parse_url("https://example.com").is_ok());
2089        assert!(parse_url("http://localhost:8080").is_ok());
2090    }
2091
2092    #[test]
2093    fn parse_invalid_schemes() {
2094        assert!(parse_url("ftp://example.com").is_err());
2095        assert!(parse_url("file:///tmp/test").is_err());
2096    }
2097
2098    #[test]
2099    fn parse_invalid_urls() {
2100        assert!(parse_url("not a url").is_err());
2101    }
2102
2103    #[test]
2104    fn get_request_builder() {
2105        let client = Client::new();
2106        let builder = client.get("https://example.com").unwrap();
2107        let req = builder.build().unwrap();
2108        assert_eq!(*req.method(), Method::GET);
2109    }
2110
2111    #[test]
2112    fn hyper_canceled_request_retry_defaults_on_and_is_independently_configurable() {
2113        assert!(Client::new().inner.config.retry_canceled_requests);
2114        let strict = Client::builder().retry_canceled_requests(false).build();
2115        assert!(!strict.inner.config.retry_canceled_requests);
2116        assert!(strict.inner.config.retry.is_none());
2117    }
2118
2119    #[test]
2120    fn physical_policy_and_transport_io_timeout_are_separate_from_logical_pooling() {
2121        let client = Client::builder()
2122            .physical_connection_policy(PhysicalConnectionPolicy {
2123                max_live: Some(2),
2124                admission_timeout: Some(Duration::from_secs(1)),
2125            })
2126            .transport_io_timeout(TransportIoTimeout {
2127                read: Some(Duration::from_secs(2)),
2128                write: Some(Duration::from_secs(3)),
2129            })
2130            .build();
2131        assert_eq!(
2132            client.inner.lifecycle.admission_timeout,
2133            Some(Duration::from_secs(1))
2134        );
2135        assert_eq!(
2136            client.inner.lifecycle.io_timeout.read,
2137            Some(Duration::from_secs(2))
2138        );
2139        assert_eq!(
2140            client.inner.lifecycle.io_timeout.write,
2141            Some(Duration::from_secs(3))
2142        );
2143    }
2144
2145    #[test]
2146    fn apply_content_length_empty_body() {
2147        let headers = Headers::new();
2148        let body = crate::body::RequestBody::Empty;
2149        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
2150        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "0");
2151    }
2152
2153    #[test]
2154    fn apply_content_length_bytes_body() {
2155        let headers = Headers::new();
2156        let body = crate::body::RequestBody::from(Bytes::from("hello"));
2157        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
2158        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
2159    }
2160
2161    #[test]
2162    fn apply_content_length_stream_known() {
2163        let headers = Headers::new();
2164        let stream = futures_util::stream::empty::<Result<Bytes>>();
2165        let body = crate::body::RequestBody::from_stream(stream, Some(7));
2166        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
2167        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "7");
2168    }
2169
2170    #[test]
2171    fn apply_content_length_stream_unknown() {
2172        let headers = Headers::new();
2173        let stream = futures_util::stream::empty::<Result<Bytes>>();
2174        let body = crate::body::RequestBody::from_stream(stream, None);
2175        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
2176        assert!(out.get("content-length").is_none());
2177    }
2178
2179    #[test]
2180    fn apply_content_length_user_matches() {
2181        let mut headers = Headers::new();
2182        headers.insert("content-length", "5").unwrap();
2183        let body = crate::body::RequestBody::from(Bytes::from("hello"));
2184        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
2185        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
2186    }
2187
2188    #[test]
2189    fn apply_content_length_user_mismatch_errors() {
2190        let mut headers = Headers::new();
2191        headers.insert("content-length", "10").unwrap();
2192        let body = crate::body::RequestBody::from(Bytes::from("hello"));
2193        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
2194        assert_eq!(err.kind(), "request_build");
2195    }
2196
2197    #[test]
2198    fn apply_content_length_rejects_invalid_value() {
2199        let mut headers = Headers::new();
2200        headers.insert("content-length", "not-a-number").unwrap();
2201        let body = crate::body::RequestBody::from(Bytes::from("hello"));
2202        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
2203        assert_eq!(err.kind(), "invalid_header_value");
2204    }
2205
2206    #[test]
2207    fn apply_content_length_rejects_unknown_stream_override() {
2208        let mut headers = Headers::new();
2209        headers.insert("content-length", "5").unwrap();
2210        let stream = futures_util::stream::empty::<Result<Bytes>>();
2211        let body = crate::body::RequestBody::from_stream(stream, None);
2212        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
2213        assert_eq!(err.kind(), "request_build");
2214    }
2215
2216    #[test]
2217    fn parse_url_rejects_userinfo_without_echoing_credentials() {
2218        let err = parse_url("https://user:secret@example.com").unwrap_err();
2219        assert_eq!(err.kind(), "invalid_url");
2220        assert!(!err.to_string().contains("secret"));
2221    }
2222
2223    #[cfg(feature = "proxy")]
2224    #[tokio::test]
2225    async fn proxy_auth_conflict_with_header() {
2226        let proxy = Proxy::all("http://proxy.example:8080")
2227            .unwrap()
2228            .auth(ProxyAuth::basic("user", "pass").unwrap());
2229        let client = Client::builder().proxy(proxy).build();
2230        let request = client
2231            .get("http://destination.example")
2232            .unwrap()
2233            .header("proxy-authorization", "Basic dXNlcjpwYXNz")
2234            .build()
2235            .unwrap();
2236        let err = client.send(request).await.unwrap_err();
2237        assert_eq!(err.kind(), "conflicting_auth");
2238        assert!(err.to_string().contains("Proxy-Authorization"));
2239    }
2240
2241    #[cfg(feature = "proxy")]
2242    #[tokio::test]
2243    async fn proxy_auth_no_conflict_without_header() {
2244        let proxy = Proxy::all("http://proxy.example:8080")
2245            .unwrap()
2246            .auth(ProxyAuth::basic("user", "pass").unwrap());
2247        let client = Client::builder().proxy(proxy).build();
2248        let request = client
2249            .get("http://destination.example")
2250            .unwrap()
2251            .build()
2252            .unwrap();
2253        let err = client.send(request).await.unwrap_err();
2254        assert_ne!(err.kind(), "conflicting_auth");
2255    }
2256
2257    #[cfg(feature = "proxy")]
2258    #[tokio::test]
2259    async fn proxy_auth_no_conflict_with_header_only() {
2260        let proxy = Proxy::all("http://proxy.example:8080").unwrap();
2261        let client = Client::builder().proxy(proxy).build();
2262        let request = client
2263            .get("http://destination.example")
2264            .unwrap()
2265            .header("proxy-authorization", "Basic dXNlcjpwYXNz")
2266            .build()
2267            .unwrap();
2268        let err = client.send(request).await.unwrap_err();
2269        assert_ne!(err.kind(), "conflicting_auth");
2270    }
2271}