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 = match self
1280                .tls_config
1281                .clone()
1282                .unwrap_or_default()
1283                .build_rustls_config()
1284            {
1285                Ok(config) => Some(config),
1286                Err(e) => {
1287                    #[cfg(feature = "tracing")]
1288                    tracing::warn!("eggfetch: custom-route TLS config failed: {e}");
1289                    #[cfg(not(feature = "tracing"))]
1290                    let _ = &e;
1291                    None
1292                }
1293            };
1294            #[cfg(not(feature = "tls-rustls"))]
1295            let custom_config = Some(());
1296
1297            custom_config.and_then(|custom_config| {
1298                let connector = match build_custom_connector(custom_config, dialer, enabler, None) {
1299                    Ok(connector) => connector,
1300                    Err(e) => {
1301                        // Surface the root cause: returning `None` here falls
1302                        // back to the standard route with no diagnostic.
1303                        #[cfg(feature = "tracing")]
1304                        tracing::warn!("eggfetch: custom connector build failed: {e}");
1305                        #[cfg(not(feature = "tracing"))]
1306                        let _ = &e;
1307                        return None;
1308                    }
1309                };
1310                let connect_timeout = self.timeout.as_ref().and_then(|timeout| timeout.connect);
1311                Some(build_hyper_client(
1312                    connector,
1313                    &persistent_policy,
1314                    connect_timeout,
1315                    &lifecycle,
1316                ))
1317            })
1318        } else {
1319            None
1320        };
1321        let config = ClientConfig {
1322            default_headers: self.default_headers,
1323            user_agent: self.user_agent,
1324            timeout: self.timeout,
1325            #[cfg(feature = "redirects")]
1326            redirect: self.redirect,
1327            auth: self.auth,
1328            #[cfg(feature = "cookies")]
1329            cookie_jar,
1330            automatic_decompression,
1331            max_decoded_body_size: self.max_decoded_body_size,
1332            max_decompression_ratio: self.max_decompression_ratio,
1333            #[cfg(feature = "proxy")]
1334            proxy: self.proxy,
1335            #[cfg(feature = "proxy")]
1336            environment_proxies: self.environment_proxies,
1337            #[cfg(feature = "tls-rustls")]
1338            tls_config: self.tls_config,
1339            #[cfg(feature = "logical-retry")]
1340            retry: self.retry,
1341            retry_canceled_requests: self.retry_canceled_requests,
1342            #[cfg(feature = "advanced-routing")]
1343            dialer: self.dialer,
1344            #[cfg(feature = "advanced-routing")]
1345            uds_configured: self.uds_path.is_some(),
1346            http_version_policy: self.http_version_policy,
1347        };
1348
1349        let pool = Pool::new(pool_config);
1350
1351        Client {
1352            inner: Arc::new(ClientInner {
1353                #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1354                hyper_client,
1355                #[cfg(feature = "advanced-routing")]
1356                custom_client,
1357                #[cfg(feature = "tls-rustls")]
1358                tls_config_error,
1359                #[cfg(feature = "advanced-routing")]
1360                direct_client,
1361                #[cfg(feature = "advanced-routing")]
1362                direct_connector_config: stored_direct_config,
1363                #[cfg(feature = "advanced-routing")]
1364                sni_clients: Mutex::new(BoundedClientCache::new(SNI_CLIENT_CACHE_MAX_ENTRIES)),
1365                #[cfg(feature = "advanced-routing")]
1366                sni_custom_clients: Mutex::new(BoundedClientCache::new(
1367                    SNI_CLIENT_CACHE_MAX_ENTRIES,
1368                )),
1369                #[cfg(feature = "advanced-routing")]
1370                resolved_clients: Mutex::new(BoundedClientCache::new(
1371                    RESOLVED_CLIENT_CACHE_MAX_ENTRIES,
1372                )),
1373                #[cfg(all(unix, feature = "advanced-routing"))]
1374                uds_client,
1375                #[cfg(feature = "proxy")]
1376                socks_clients: Mutex::new(BoundedClientCache::new(SOCKS_CLIENT_CACHE_MAX_ENTRIES)),
1377                #[cfg(feature = "proxy")]
1378                forward_clients: Mutex::new(BoundedClientCache::new(
1379                    FORWARD_CLIENT_CACHE_MAX_ENTRIES,
1380                )),
1381                #[cfg(feature = "proxy")]
1382                connect_clients: Mutex::new(BoundedClientCache::new(
1383                    CONNECT_CLIENT_CACHE_MAX_ENTRIES,
1384                )),
1385                config,
1386                pool,
1387                transport_metrics,
1388                #[cfg(any(
1389                    feature = "transport-http1",
1390                    feature = "transport-http2",
1391                    feature = "advanced-routing"
1392                ))]
1393                lifecycle,
1394                #[cfg(feature = "http3")]
1395                h3_connector,
1396                #[cfg(feature = "http3")]
1397                alt_svc_state: Arc::new(crate::transport::alt_svc::AltSvcState::new()),
1398            }),
1399        }
1400    }
1401}
1402
1403#[cfg(feature = "high-level-url")]
1404fn parse_url(url_str: &str) -> Result<url::Url> {
1405    // Deliberately do not echo url_str into the error: parsing has
1406    // failed, so redact_url_string would fall back to the raw input
1407    // (potentially containing credentials). url::ParseError renders
1408    // only a static description and never embeds the input.
1409    let url = url::Url::parse(url_str).map_err(|e| Error::InvalidUrl(e.to_string()))?;
1410    if !url.username().is_empty() || url.password().is_some() {
1411        // URL userinfo is both easy to leak through diagnostics and
1412        // surprising for an HTTP client with explicit auth APIs.
1413        return Err(Error::InvalidUrl(
1414            "URL userinfo is not supported; configure authentication explicitly".into(),
1415        ));
1416    }
1417    match url.scheme() {
1418        "http" | "https" => Ok(url),
1419        other => Err(Error::Unsupported(format!(
1420            "URL scheme '{other}' is not supported; use http or https"
1421        ))),
1422    }
1423}
1424
1425#[cfg(test)]
1426mod tests {
1427    use super::*;
1428    #[cfg(feature = "proxy")]
1429    use crate::proxy::ProxyAuth;
1430    use bytes::Bytes;
1431    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1432    use hyper_util::rt::TokioExecutor;
1433    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1434    use std::future::{ready, Ready};
1435    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1436    use std::net::SocketAddr;
1437    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1438    use std::task::{Context, Poll};
1439    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1440    use tower_service::Service;
1441
1442    #[test]
1443    fn client_constructs() {
1444        let _client = Client::new();
1445    }
1446
1447    #[test]
1448    fn client_config_debug_redacts_secrets() {
1449        let mut config = ClientConfig::default();
1450        config
1451            .default_headers
1452            .insert("authorization", "Bearer header-secret-token")
1453            .unwrap();
1454        #[cfg(feature = "cookies")]
1455        config
1456            .cookie_jar
1457            .set_default_cookie("session".to_owned(), "jar-secret-token".to_owned())
1458            .expect("valid test cookie");
1459        let debug = format!("{config:?}");
1460        assert!(
1461            !debug.contains("header-secret-token"),
1462            "ClientConfig Debug must not leak header secrets: {debug}"
1463        );
1464        #[cfg(feature = "cookies")]
1465        assert!(
1466            !debug.contains("jar-secret-token"),
1467            "ClientConfig Debug must not leak jar secrets: {debug}"
1468        );
1469    }
1470
1471    #[cfg(feature = "high-level-url")]
1472    #[test]
1473    fn client_default() {
1474        let _client = Client::default();
1475    }
1476
1477    #[cfg(feature = "high-level-url")]
1478    #[test]
1479    fn client_builder() {
1480        let _client = Client::builder().user_agent("test-agent").build();
1481    }
1482
1483    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1484    #[cfg(feature = "high-level-url")]
1485    #[tokio::test]
1486    async fn standard_connector_preserves_resolver_failure_for_detailed_mapping() {
1487        #[derive(Clone, Copy)]
1488        struct FailingResolver;
1489
1490        impl Service<hyper_util::client::legacy::connect::dns::Name> for FailingResolver {
1491            type Response = std::vec::IntoIter<SocketAddr>;
1492            type Error = std::io::Error;
1493            type Future = Ready<std::result::Result<Self::Response, Self::Error>>;
1494
1495            fn poll_ready(
1496                &mut self,
1497                _: &mut Context<'_>,
1498            ) -> Poll<std::result::Result<(), Self::Error>> {
1499                Poll::Ready(Ok(()))
1500            }
1501
1502            fn call(&mut self, _: hyper_util::client::legacy::connect::dns::Name) -> Self::Future {
1503                ready(Err(std::io::Error::new(
1504                    std::io::ErrorKind::NotFound,
1505                    "synthetic standard resolver failure",
1506                )))
1507            }
1508        }
1509
1510        let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(
1511            HttpVersionPolicy::Http1Only,
1512        );
1513        #[cfg(feature = "tls-rustls")]
1514        let connector = build_standard_connector_with_resolver(
1515            rustls::ClientConfig::builder()
1516                .with_root_certificates(rustls::RootCertStore::empty())
1517                .with_no_client_auth(),
1518            enabler,
1519            FailingResolver,
1520        );
1521        #[cfg(not(feature = "tls-rustls"))]
1522        let connector = build_standard_connector_with_resolver(FailingResolver, enabler);
1523
1524        let client =
1525            hyper_util::client::legacy::Client::builder(TokioExecutor::new()).build(connector);
1526        #[cfg(feature = "tls-rustls")]
1527        let uri = "https://synthetic.example/";
1528        #[cfg(not(feature = "tls-rustls"))]
1529        let uri = "http://synthetic.example/";
1530        let request = http::Request::get(uri)
1531            .body(http_body_util::Empty::<Bytes>::new())
1532            .expect("synthetic request is valid");
1533        let error = client
1534            .request(request)
1535            .await
1536            .expect_err("synthetic resolver should fail");
1537        let context = crate::error::RequestFailureContext::new();
1538        let mapped = crate::transport::direct::map_send_error_with_context(error, Some(&context));
1539
1540        assert_eq!(mapped.kind(), "hyper_client");
1541        let failure = crate::error::RequestFailure::from_context(mapped, &context);
1542        assert_eq!(
1543            failure.network_failure_kind(),
1544            Some(crate::error::NetworkFailureKind::Dns)
1545        );
1546    }
1547
1548    #[test]
1549    fn client_builder_merge_timeout_preserves_other_phases() {
1550        // Phase-specific setters must merge into any existing timeout
1551        // configuration instead of replacing it wholesale.
1552        let client = Client::builder()
1553            .timeout(Timeout::from_secs(30))
1554            .merge_timeout(
1555                Timeout::builder()
1556                    .connect(std::time::Duration::from_secs(5))
1557                    .build(),
1558            )
1559            .merge_timeout(
1560                Timeout::builder()
1561                    .read(std::time::Duration::from_secs(10))
1562                    .build(),
1563            )
1564            .build();
1565
1566        let timeout = client.inner.config.timeout.expect("timeout configured");
1567        let d = |secs: u64| std::time::Duration::from_secs(secs);
1568        assert_eq!(timeout.connect, Some(d(5)), "last connect wins");
1569        assert_eq!(timeout.read, Some(d(10)), "last read wins");
1570        assert_eq!(
1571            timeout.write,
1572            Some(d(30)),
1573            "unset phases keep earlier values"
1574        );
1575        assert_eq!(timeout.pool, Some(d(30)));
1576    }
1577
1578    #[test]
1579    fn client_builder_merge_timeout_without_prior_config() {
1580        let client = Client::builder()
1581            .merge_timeout(
1582                Timeout::builder()
1583                    .connect(std::time::Duration::from_secs(5))
1584                    .build(),
1585            )
1586            .build();
1587
1588        let timeout = client.inner.config.timeout.expect("timeout configured");
1589        assert_eq!(timeout.connect, Some(std::time::Duration::from_secs(5)));
1590        assert_eq!(timeout.read, None);
1591    }
1592
1593    #[cfg(any(feature = "proxy", feature = "http3"))]
1594    #[test]
1595    fn client_builder_danger_accept_invalid_certs_preserves_tls_config() {
1596        let client = Client::builder()
1597            .tls_config(crate::tls::TlsConfig::builder().sni(false).build())
1598            .danger_accept_invalid_certs(true)
1599            .build();
1600        let tls = client
1601            .inner
1602            .config
1603            .tls_config
1604            .as_ref()
1605            .expect("TLS config should be retained");
1606        assert!(!tls.sni_enabled());
1607        assert!(!tls.verify_certificate());
1608        assert!(!tls.verify_hostname());
1609    }
1610
1611    #[test]
1612    #[cfg(feature = "tls-rustls")]
1613    fn tls_root_store_paths_construct() {
1614        // Native roots are environment-dependent; the production connector
1615        // always receives the same policy-built config as direct connectors.
1616        let enabler =
1617            crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
1618                allow_http3: false,
1619            });
1620        let config = crate::tls::TlsConfig::default()
1621            .build_rustls_config()
1622            .expect("default TLS policy builds");
1623        let _ = build_standard_connector(config, enabler);
1624    }
1625
1626    #[test]
1627    fn client_builder_http1_only() {
1628        let client = Client::builder()
1629            .http_version_policy(HttpVersionPolicy::Http1Only)
1630            .build();
1631        assert_eq!(
1632            client.inner.config.http_version_policy,
1633            HttpVersionPolicy::Http1Only
1634        );
1635    }
1636
1637    #[test]
1638    fn client_builder_http2_auto() {
1639        let client = Client::builder()
1640            .http_version_policy(HttpVersionPolicy::Auto { allow_http3: false })
1641            .build();
1642        assert_eq!(
1643            client.inner.config.http_version_policy,
1644            HttpVersionPolicy::Auto { allow_http3: false }
1645        );
1646    }
1647
1648    #[test]
1649    #[cfg(feature = "transport-http2")]
1650    fn client_builder_http2_only() {
1651        let client = Client::builder()
1652            .http_version_policy(HttpVersionPolicy::Http2Only)
1653            .build();
1654        assert_eq!(
1655            client.inner.config.http_version_policy,
1656            HttpVersionPolicy::Http2Only
1657        );
1658    }
1659
1660    #[cfg(feature = "high-level-url")]
1661    #[test]
1662    fn connector_builds_for_all_policies() {
1663        for policy in [
1664            HttpVersionPolicy::Http1Only,
1665            HttpVersionPolicy::Auto { allow_http3: false },
1666            #[cfg(feature = "transport-http2")]
1667            HttpVersionPolicy::Http2Only,
1668            #[cfg(feature = "http3")]
1669            HttpVersionPolicy::Http3Only,
1670        ] {
1671            let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(policy);
1672            if !enabler.use_http3() {
1673                #[cfg(feature = "tls-rustls")]
1674                let config = crate::tls::TlsConfig::default()
1675                    .build_rustls_config()
1676                    .expect("default TLS policy builds");
1677                #[cfg(feature = "tls-rustls")]
1678                let _ = build_standard_connector(config, enabler);
1679            }
1680        }
1681    }
1682
1683    #[cfg(feature = "transport-http2")]
1684    #[cfg(feature = "high-level-url")]
1685    #[test]
1686    fn custom_connector_alpn_matches_http_version_policy() {
1687        let config = rustls::ClientConfig::builder()
1688            .with_root_certificates(rustls::RootCertStore::empty())
1689            .with_no_client_auth();
1690        let h2_only = configure_tls_alpn(
1691            config.clone(),
1692            crate::http_version::HttpVersionPolicyEnabler::from_policy(
1693                HttpVersionPolicy::Http2Only,
1694            ),
1695        );
1696        assert_eq!(h2_only.alpn_protocols, vec![b"h2".to_vec()]);
1697
1698        let auto = configure_tls_alpn(
1699            config,
1700            crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
1701                allow_http3: false,
1702            }),
1703        );
1704        assert_eq!(
1705            auto.alpn_protocols,
1706            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
1707        );
1708    }
1709
1710    #[cfg(feature = "high-level-url")]
1711    #[test]
1712    fn parse_valid_urls() {
1713        assert!(parse_url("https://example.com").is_ok());
1714        assert!(parse_url("http://localhost:8080").is_ok());
1715    }
1716
1717    #[cfg(feature = "high-level-url")]
1718    #[test]
1719    fn parse_invalid_schemes() {
1720        assert!(parse_url("ftp://example.com").is_err());
1721        assert!(parse_url("file:///tmp/test").is_err());
1722    }
1723
1724    #[cfg(feature = "high-level-url")]
1725    #[test]
1726    fn parse_invalid_urls() {
1727        assert!(parse_url("not a url").is_err());
1728    }
1729
1730    #[cfg(feature = "high-level-url")]
1731    #[test]
1732    fn get_request_builder() {
1733        let client = Client::new();
1734        let builder = client.get("https://example.com").unwrap();
1735        let req = builder.build().unwrap();
1736        assert_eq!(*req.method(), Method::GET);
1737    }
1738
1739    #[cfg(feature = "high-level-url")]
1740    #[test]
1741    fn hyper_canceled_request_retry_defaults_on_and_is_independently_configurable() {
1742        assert!(Client::new().inner.config.retry_canceled_requests);
1743        let strict = Client::builder().retry_canceled_requests(false).build();
1744        assert!(!strict.inner.config.retry_canceled_requests);
1745        #[cfg(feature = "logical-retry")]
1746        assert!(strict.inner.config.retry.is_none());
1747    }
1748
1749    #[cfg(feature = "high-level-url")]
1750    #[test]
1751    fn physical_policy_and_transport_io_timeout_are_separate_from_logical_pooling() {
1752        let client = Client::builder()
1753            .physical_connection_policy(PhysicalConnectionPolicy {
1754                max_live: Some(2),
1755                admission_timeout: Some(Duration::from_secs(1)),
1756            })
1757            .transport_io_timeout(TransportIoTimeout {
1758                read: Some(Duration::from_secs(2)),
1759                write: Some(Duration::from_secs(3)),
1760            })
1761            .build();
1762        assert_eq!(
1763            client.inner.lifecycle.admission_timeout,
1764            Some(Duration::from_secs(1))
1765        );
1766        assert_eq!(
1767            client.inner.lifecycle.io_timeout.read,
1768            Some(Duration::from_secs(2))
1769        );
1770        assert_eq!(
1771            client.inner.lifecycle.io_timeout.write,
1772            Some(Duration::from_secs(3))
1773        );
1774    }
1775
1776    #[cfg(feature = "high-level-url")]
1777    #[test]
1778    fn apply_content_length_empty_body() {
1779        let headers = Headers::new();
1780        let body = crate::body::RequestBody::Empty;
1781        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1782        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "0");
1783    }
1784
1785    #[cfg(feature = "high-level-url")]
1786    #[test]
1787    fn apply_content_length_bytes_body() {
1788        let headers = Headers::new();
1789        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1790        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1791        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
1792    }
1793
1794    #[cfg(feature = "high-level-url")]
1795    #[test]
1796    fn apply_content_length_stream_known() {
1797        let headers = Headers::new();
1798        let stream = futures_util::stream::empty::<Result<Bytes>>();
1799        let body = crate::body::RequestBody::from_stream(stream, Some(7));
1800        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1801        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "7");
1802    }
1803
1804    #[cfg(feature = "high-level-url")]
1805    #[test]
1806    fn apply_content_length_stream_unknown() {
1807        let headers = Headers::new();
1808        let stream = futures_util::stream::empty::<Result<Bytes>>();
1809        let body = crate::body::RequestBody::from_stream(stream, None);
1810        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1811        assert!(out.get("content-length").is_none());
1812    }
1813
1814    #[cfg(feature = "high-level-url")]
1815    #[test]
1816    fn apply_content_length_user_matches() {
1817        let mut headers = Headers::new();
1818        headers.insert("content-length", "5").unwrap();
1819        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1820        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1821        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
1822    }
1823
1824    #[cfg(feature = "high-level-url")]
1825    #[test]
1826    fn apply_content_length_user_mismatch_errors() {
1827        let mut headers = Headers::new();
1828        headers.insert("content-length", "10").unwrap();
1829        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1830        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1831        assert_eq!(err.kind(), "request_build");
1832    }
1833
1834    #[cfg(feature = "high-level-url")]
1835    #[test]
1836    fn apply_content_length_rejects_invalid_value() {
1837        let mut headers = Headers::new();
1838        headers.insert("content-length", "not-a-number").unwrap();
1839        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1840        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1841        assert_eq!(err.kind(), "invalid_header_value");
1842    }
1843
1844    #[cfg(feature = "high-level-url")]
1845    #[test]
1846    fn apply_content_length_rejects_unknown_stream_override() {
1847        let mut headers = Headers::new();
1848        headers.insert("content-length", "5").unwrap();
1849        let stream = futures_util::stream::empty::<Result<Bytes>>();
1850        let body = crate::body::RequestBody::from_stream(stream, None);
1851        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1852        assert_eq!(err.kind(), "request_build");
1853    }
1854
1855    #[cfg(feature = "high-level-url")]
1856    #[test]
1857    fn parse_url_rejects_userinfo_without_echoing_credentials() {
1858        let err = parse_url("https://user:secret@example.com").unwrap_err();
1859        assert_eq!(err.kind(), "invalid_url");
1860        assert!(!err.to_string().contains("secret"));
1861    }
1862
1863    #[cfg(feature = "proxy")]
1864    #[cfg(feature = "high-level-url")]
1865    #[tokio::test]
1866    async fn proxy_auth_conflict_with_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            .header("proxy-authorization", "Basic dXNlcjpwYXNz")
1875            .build()
1876            .unwrap();
1877        let err = client.send(request).await.unwrap_err();
1878        assert_eq!(err.kind(), "conflicting_auth");
1879        assert!(err.to_string().contains("Proxy-Authorization"));
1880    }
1881
1882    #[cfg(feature = "proxy")]
1883    #[cfg(feature = "high-level-url")]
1884    #[tokio::test]
1885    async fn proxy_auth_no_conflict_without_header() {
1886        let proxy = Proxy::all("http://proxy.example:8080")
1887            .unwrap()
1888            .auth(ProxyAuth::basic("user", "pass").unwrap());
1889        let client = Client::builder().proxy(proxy).build();
1890        let request = client
1891            .get("http://destination.example")
1892            .unwrap()
1893            .build()
1894            .unwrap();
1895        let err = client.send(request).await.unwrap_err();
1896        assert_ne!(err.kind(), "conflicting_auth");
1897    }
1898
1899    #[cfg(feature = "proxy")]
1900    #[cfg(feature = "high-level-url")]
1901    #[tokio::test]
1902    async fn proxy_auth_no_conflict_with_header_only() {
1903        let proxy = Proxy::all("http://proxy.example:8080").unwrap();
1904        let client = Client::builder().proxy(proxy).build();
1905        let request = client
1906            .get("http://destination.example")
1907            .unwrap()
1908            .header("proxy-authorization", "Basic dXNlcjpwYXNz")
1909            .build()
1910            .unwrap();
1911        let err = client.send(request).await.unwrap_err();
1912        assert_ne!(err.kind(), "conflicting_auth");
1913    }
1914
1915    #[cfg(feature = "advanced-routing")]
1916    #[cfg(feature = "high-level-url")]
1917    #[test]
1918    fn resolved_route_key_matrix() {
1919        use crate::transport_hints::ResolvedTarget;
1920
1921        // Keys intentionally lack `Debug`/`Display` (connection identity
1922        // only, never request state), so compare with `==`/`!=`.
1923        let origin = url::Url::parse("http://origin.example/").unwrap();
1924        let target: ResolvedTarget =
1925            ResolvedTarget::new(["127.0.0.1:80".parse::<SocketAddr>().unwrap()]).unwrap();
1926        let base = ResolvedRouteKey::new(&origin, &target, None);
1927        let same = ResolvedRouteKey::new(&origin, &target, None);
1928        assert!(
1929            base == same,
1930            "same origin + same ordered addresses + same SNI must reuse"
1931        );
1932
1933        // Path/query/fragment never participate: same logical origin.
1934        let with_path = url::Url::parse("http://origin.example/a?b=1#f").unwrap();
1935        let other_path = url::Url::parse("http://origin.example/other").unwrap();
1936        assert!(
1937            ResolvedRouteKey::new(&with_path, &target, None)
1938                == ResolvedRouteKey::new(&other_path, &target, None),
1939            "path/query/fragment must not fragment resolved identity"
1940        );
1941        // Explicit default port normalizes to the same origin.
1942        let explicit_default = url::Url::parse("http://origin.example:80/").unwrap();
1943        assert!(
1944            ResolvedRouteKey::new(&origin, &target, None)
1945                == ResolvedRouteKey::new(&explicit_default, &target, None),
1946            "explicit default port must reuse"
1947        );
1948
1949        // HTTP vs HTTPS: logical/TLS origin differs.
1950        let https = url::Url::parse("https://origin.example/").unwrap();
1951        let https_target: ResolvedTarget =
1952            ResolvedTarget::new(["127.0.0.1:443".parse::<SocketAddr>().unwrap()]).unwrap();
1953        assert!(
1954            base != ResolvedRouteKey::new(&https, &https_target, None),
1955            "scheme change must fragment resolved identity"
1956        );
1957
1958        // Host differs: logical Host/TLS identity differs.
1959        let other_host = url::Url::parse("http://other.example/").unwrap();
1960        assert!(
1961            base != ResolvedRouteKey::new(&other_host, &target, None),
1962            "host change must fragment resolved identity"
1963        );
1964
1965        // Effective port differs: origin/socket identity differs.
1966        let other_port = url::Url::parse("http://origin.example:8080/").unwrap();
1967        let other_port_target: ResolvedTarget =
1968            ResolvedTarget::new(["127.0.0.1:8080".parse::<SocketAddr>().unwrap()]).unwrap();
1969        assert!(
1970            base != ResolvedRouteKey::new(&other_port, &other_port_target, None),
1971            "effective port change must fragment resolved identity"
1972        );
1973
1974        // One address differs: physical route differs.
1975        let other_addr: ResolvedTarget =
1976            ResolvedTarget::new(["127.0.0.2:80".parse::<SocketAddr>().unwrap()]).unwrap();
1977        assert!(
1978            base != ResolvedRouteKey::new(&origin, &other_addr, None),
1979            "address change must fragment resolved identity"
1980        );
1981
1982        // Same addresses, different order: attempt/failover order differs.
1983        let ordered: ResolvedTarget = ResolvedTarget::new([
1984            "127.0.0.1:80".parse::<SocketAddr>().unwrap(),
1985            "127.0.0.2:80".parse::<SocketAddr>().unwrap(),
1986        ])
1987        .unwrap();
1988        let reordered: ResolvedTarget = ResolvedTarget::new([
1989            "127.0.0.2:80".parse::<SocketAddr>().unwrap(),
1990            "127.0.0.1:80".parse::<SocketAddr>().unwrap(),
1991        ])
1992        .unwrap();
1993        assert!(
1994            ResolvedRouteKey::new(&origin, &ordered, None)
1995                != ResolvedRouteKey::new(&origin, &reordered, None),
1996            "address reorder must fragment resolved identity"
1997        );
1998
1999        // SNI None vs override: TLS identity differs.
2000        assert!(
2001            base != ResolvedRouteKey::new(&origin, &target, Some("sni.example")),
2002            "adding an SNI override must fragment resolved identity"
2003        );
2004
2005        // SNI override A vs B: TLS identity differs.
2006        assert!(
2007            ResolvedRouteKey::new(&origin, &target, Some("a.example"))
2008                != ResolvedRouteKey::new(&origin, &target, Some("b.example")),
2009            "SNI override change must fragment resolved identity"
2010        );
2011        assert!(
2012            ResolvedRouteKey::new(&origin, &target, Some("a.example"))
2013                == ResolvedRouteKey::new(&origin, &target, Some("a.example")),
2014            "same SNI override must reuse"
2015        );
2016    }
2017
2018    #[cfg(feature = "advanced-routing")]
2019    #[test]
2020    fn resolved_route_key_from_native_origin() {
2021        use crate::http_origin::HttpOrigin;
2022        use crate::transport_hints::ResolvedTarget;
2023
2024        let uri: http::Uri = "http://origin.example/".parse().expect("valid URI");
2025        let origin = HttpOrigin::from_uri(&uri).expect("native origin parses");
2026        let target = ResolvedTarget::new(["127.0.0.1:80".parse::<SocketAddr>().unwrap()]).unwrap();
2027        let base = ResolvedRouteKey::from_origin(&origin, &target, None);
2028        let same = ResolvedRouteKey::from_origin(&origin, &target, None);
2029        // Keys intentionally lack `Debug`/`Display`; compare with `==`/`!=`.
2030        assert!(
2031            base == same,
2032            "same native origin + addresses + SNI must reuse"
2033        );
2034
2035        // Explicit default port shares identity; scheme/host/port changes
2036        // fragment; address order and SNI fragment.
2037        let explicit: http::Uri = "http://origin.example:80/a?b=1".parse().expect("valid URI");
2038        let explicit_origin = HttpOrigin::from_uri(&explicit).expect("origin parses");
2039        assert!(
2040            base == ResolvedRouteKey::from_origin(&explicit_origin, &target, None),
2041            "explicit default port must reuse"
2042        );
2043
2044        let https: http::Uri = "https://origin.example/".parse().expect("valid URI");
2045        let https_origin = HttpOrigin::from_uri(&https).expect("origin parses");
2046        let https_target =
2047            ResolvedTarget::new(["127.0.0.1:443".parse::<SocketAddr>().unwrap()]).unwrap();
2048        assert!(
2049            base != ResolvedRouteKey::from_origin(&https_origin, &https_target, None),
2050            "scheme change must fragment resolved identity"
2051        );
2052        assert!(
2053            base != ResolvedRouteKey::from_origin(&origin, &target, Some("sni.example")),
2054            "SNI override must fragment resolved identity"
2055        );
2056    }
2057
2058    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
2059    #[cfg(feature = "high-level-url")]
2060    #[test]
2061    fn resolved_route_cache_is_bounded() {
2062        use crate::transport::hyper_client::{
2063            BoundedClientCache, RESOLVED_CLIENT_CACHE_MAX_ENTRIES,
2064        };
2065        use crate::transport_hints::ResolvedTarget;
2066
2067        assert_eq!(
2068            RESOLVED_CLIENT_CACHE_MAX_ENTRIES, 64,
2069            "resolved-route cache uses the conservative 64-entry bound"
2070        );
2071        let mut cache: BoundedClientCache<ResolvedRouteKey, usize> =
2072            BoundedClientCache::new(RESOLVED_CLIENT_CACHE_MAX_ENTRIES);
2073        for index in 0..(RESOLVED_CLIENT_CACHE_MAX_ENTRIES + 16) {
2074            let origin =
2075                url::Url::parse(&format!("http://host-{index}.example/")).expect("valid URL");
2076            let target =
2077                ResolvedTarget::new(["127.0.0.1:80".parse::<SocketAddr>().expect("valid addr")])
2078                    .expect("non-empty");
2079            cache.insert(ResolvedRouteKey::new(&origin, &target, None), index);
2080            assert!(
2081                cache.len() <= RESOLVED_CLIENT_CACHE_MAX_ENTRIES,
2082                "insertion beyond capacity must not grow the cache"
2083            );
2084        }
2085        assert_eq!(cache.len(), RESOLVED_CLIENT_CACHE_MAX_ENTRIES);
2086    }
2087}