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