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