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    /// Caller-owned datagram dialer for experimental HTTP/3 routing.
518    #[cfg(feature = "http3")]
519    datagram_dialer: Option<Arc<dyn crate::transport::datagram::DatagramDialer>>,
520}
521
522impl Default for ClientBuilder {
523    fn default() -> Self {
524        Self::new()
525    }
526}
527
528impl ClientBuilder {
529    /// Create a new client builder with defaults.
530    #[must_use]
531    pub fn new() -> Self {
532        Self {
533            default_headers: Headers::new(),
534            user_agent: None,
535            pool_config: PoolConfig::default(),
536            timeout: None,
537            limits: None,
538            #[cfg(feature = "redirects")]
539            redirect: RedirectPolicy::default(),
540            auth: None,
541            #[cfg(feature = "cookies")]
542            cookie_jar: None,
543            automatic_decompression: None,
544            max_decoded_body_size: None,
545            max_decompression_ratio: None,
546            #[cfg(feature = "proxy")]
547            proxy: None,
548            #[cfg(feature = "proxy")]
549            environment_proxies: Vec::new(),
550            #[cfg(feature = "tls-rustls")]
551            tls_config: None,
552            #[cfg(feature = "logical-retry")]
553            retry: None,
554            retry_canceled_requests: true,
555            #[cfg(feature = "advanced-routing")]
556            dialer: None,
557            physical_connection_policy: PhysicalConnectionPolicy::default(),
558            transport_io_timeout: TransportIoTimeout::default(),
559            http_version_policy: HttpVersionPolicy::default(),
560            #[cfg(feature = "advanced-routing")]
561            direct_connector_config: None,
562            #[cfg(feature = "advanced-routing")]
563            uds_path: None,
564            #[cfg(feature = "http3")]
565            datagram_dialer: None,
566        }
567    }
568
569    /// Add a default header to all requests made by this client.
570    ///
571    /// # Errors
572    ///
573    /// Returns an error if `name` or `value` is not a valid header field.
574    pub fn default_header(mut self, name: &str, value: &str) -> Result<Self> {
575        self.default_headers.insert(name, value)?;
576        Ok(self)
577    }
578
579    /// Set the default headers for all requests made by this client.
580    ///
581    /// This preserves valid header values containing HTTP `obs-text` bytes.
582    #[must_use]
583    pub fn default_headers(mut self, headers: Headers) -> Self {
584        self.default_headers = headers;
585        self
586    }
587
588    /// Set the default user-agent header.
589    #[must_use]
590    pub fn user_agent(mut self, agent: &str) -> Self {
591        self.user_agent = Some(agent.to_owned());
592        self
593    }
594
595    /// Set the maximum number of idle (unused) connections kept per host.
596    ///
597    /// This is a convenience alias for [`max_idle_connections_per_host`]:
598    /// the transport enforces the limit on a per-host basis, so total
599    /// idle connections grow with the number of distinct origins. Use
600    /// [`max_connections`] for a global concurrency cap.
601    ///
602    /// [`max_idle_connections_per_host`]: Self::max_idle_connections_per_host
603    /// [`max_connections`]: Self::max_connections
604    #[must_use]
605    pub fn max_idle_connections(mut self, max: usize) -> Self {
606        self.pool_config.max_idle_connections = Some(max);
607        self
608    }
609
610    /// Set the maximum number of idle connections per individual host.
611    #[must_use]
612    pub fn max_idle_connections_per_host(mut self, max: usize) -> Self {
613        self.pool_config.max_idle_connections_per_host = Some(max);
614        self
615    }
616
617    /// Set the maximum total number of concurrent in-flight requests.
618    ///
619    /// Compatibility alias for [`Self::max_in_flight_requests`] kept for
620    /// the pre-1.0 line. One permit equals one logical request, not one
621    /// TCP connection (H2/H3 multiplex many requests over one
622    /// connection). Prefer `max_in_flight_requests` in new code.
623    #[must_use]
624    pub fn max_connections(mut self, max: usize) -> Self {
625        self.pool_config.max_connections = Some(max);
626        self
627    }
628
629    /// Set the maximum number of concurrent in-flight requests per origin.
630    ///
631    /// Compatibility alias for [`Self::max_in_flight_requests_per_origin`].
632    #[must_use]
633    pub fn max_connections_per_host(mut self, max: usize) -> Self {
634        self.pool_config.max_connections_per_host = Some(max);
635        self
636    }
637
638    /// Set the maximum total number of concurrent in-flight requests.
639    ///
640    /// Preferred native name. Bounds logical request concurrency (one
641    /// permit per request). Under H1 one request typically owns its
642    /// connection slot; under H2/H3 many permits multiplex over one
643    /// TCP/QUIC connection. When both this and `max_connections` are
644    /// set, this wins.
645    #[must_use]
646    pub fn max_in_flight_requests(mut self, max: usize) -> Self {
647        self.pool_config.max_in_flight_requests = Some(max);
648        self
649    }
650
651    /// Set the maximum number of concurrent in-flight requests per origin.
652    ///
653    /// Preferred native name. When both this and
654    /// `max_connections_per_host` are set, this wins.
655    #[must_use]
656    pub fn max_in_flight_requests_per_origin(mut self, max: usize) -> Self {
657        self.pool_config.max_in_flight_requests_per_origin = Some(max);
658        self
659    }
660
661    /// Set the duration after which idle connections are closed.
662    #[must_use]
663    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
664        self.pool_config.idle_timeout = Some(timeout);
665        self
666    }
667
668    /// Set the default timeout for all requests made by this client.
669    #[must_use]
670    pub fn timeout(mut self, timeout: Timeout) -> Self {
671        self.timeout = Some(timeout);
672        self
673    }
674
675    /// Merge a partial timeout configuration into the currently configured
676    /// timeout.
677    ///
678    /// Unlike [`timeout`](Self::timeout), which replaces the entire
679    /// configuration, each phase set in `timeout` overrides only that
680    /// phase; unset phases keep any previously configured value (or
681    /// remain unset when no timeout was configured yet).
682    #[must_use]
683    pub fn merge_timeout(mut self, timeout: Timeout) -> Self {
684        let merged = match self.timeout {
685            Some(existing) => existing.merge(Some(timeout)),
686            None => timeout,
687        };
688        self.timeout = Some(merged);
689        self
690    }
691
692    /// Set resource limits for the connection pool.
693    ///
694    /// Limits control logical request concurrency (pool permits) and
695    /// physical connection behavior (idle connection caps and expiry).
696    /// When set, the limits are applied to the pool configuration.
697    #[must_use]
698    pub fn limits(mut self, limits: Limits) -> Self {
699        self.limits = Some(limits);
700        self
701    }
702
703    /// Set the redirect policy for this client.
704    ///
705    /// Only available with the `redirects` feature (enabled by the `http1`/`http2`
706    /// compatibility aliases). The lean profile omits redirect following and
707    /// returns 3xx responses without a second hop.
708    #[cfg(feature = "redirects")]
709    #[must_use]
710    pub fn follow_redirects(mut self, follow: bool) -> Self {
711        self.redirect.follow = follow;
712        self
713    }
714
715    /// Set the maximum number of redirects to follow.
716    ///
717    /// Only available with the `redirects` feature.
718    #[cfg(feature = "redirects")]
719    #[must_use]
720    pub fn max_redirects(mut self, max: usize) -> Self {
721        self.redirect.max_redirects = max;
722        self
723    }
724
725    /// Set the full redirect policy.
726    ///
727    /// Only available with the `redirects` feature.
728    #[cfg(feature = "redirects")]
729    #[must_use]
730    pub fn redirect_policy(mut self, policy: RedirectPolicy) -> Self {
731        self.redirect = policy;
732        self
733    }
734
735    /// Set the HTTPS-downgrade rule for redirects without replacing the
736    /// rest of the redirect policy.
737    ///
738    /// Only available with the `redirects` feature.
739    ///
740    /// Select
741    /// [`RedirectDowngradePolicy::Deny`](crate::redirect::RedirectDowngradePolicy::Deny)
742    /// to reject HTTPS -> HTTP downgrades before the downgraded request
743    /// is dispatched. The default is
744    /// [`Allow`](crate::redirect::RedirectDowngradePolicy::Allow) for
745    /// compatibility.
746    #[cfg(feature = "redirects")]
747    #[must_use]
748    pub fn redirect_downgrade_policy(
749        mut self,
750        policy: crate::redirect::RedirectDowngradePolicy,
751    ) -> Self {
752        self.redirect.downgrade = policy;
753        self
754    }
755
756    /// Set a shared cookie jar for this client.
757    ///
758    /// When set, the client will automatically inject matching cookies
759    /// into requests and update the jar from `Set-Cookie` response headers.
760    ///
761    /// Only available when the `cookies` feature is enabled.
762    #[cfg(feature = "cookies")]
763    #[must_use]
764    pub fn cookie_jar(mut self, jar: CookieJar) -> Self {
765        self.cookie_jar = Some(jar);
766        self
767    }
768
769    /// Set default authentication for all requests made by this client.
770    ///
771    /// The configured auth is applied to every request unless overridden
772    /// or disabled at the request level. Auth is recomputed per redirect
773    /// hop; cross-origin redirects never carry client auth.
774    #[must_use]
775    pub fn auth(mut self, auth: impl Into<crate::auth::AuthScheme>) -> Self {
776        self.auth = Some(auth.into());
777        self
778    }
779
780    /// Set the default proxy for all requests made by this client.
781    ///
782    /// When set, all matching requests are routed through the specified
783    /// proxy. Can be overridden or disabled per-request.
784    #[cfg(feature = "proxy")]
785    #[must_use]
786    pub fn proxy(mut self, proxy: Proxy) -> Self {
787        self.proxy = Some(proxy);
788        self
789    }
790
791    /// Add a scheme-specific proxy used when no explicit proxy is configured.
792    #[cfg(feature = "proxy")]
793    #[must_use]
794    pub fn environment_proxy(mut self, proxy: Proxy) -> Self {
795        self.environment_proxies.push(proxy);
796        self
797    }
798
799    /// Opt into environment-proxy routing from an explicit snapshot.
800    ///
801    /// The native default stays environment-independent: without this call
802    /// the client never reads proxy environment variables. Pass
803    /// [`crate::proxy::ProxyEnvironment::from_env`] at the call site to
804    /// preserve command-line environment reachability, or
805    /// [`crate::proxy::ProxyEnvironment::from_map`] in tests for a pure
806    /// snapshot without global environment mutation.
807    ///
808    /// Each configured value becomes a scheme-scoped fallback proxy
809    /// (specific before `ALL_PROXY`); `NO_PROXY` bypass is attached to
810    /// every proxy. Invalid values fail closed with a redacted error.
811    ///
812    /// # Errors
813    ///
814    /// Returns [`crate::error::Error::InvalidProxyUrl`] when a configured
815    /// proxy URL or the `NO_PROXY` value cannot be parsed.
816    #[cfg(feature = "proxy")]
817    pub fn proxy_environment(
818        mut self,
819        env: &crate::proxy::ProxyEnvironment,
820    ) -> crate::error::Result<Self> {
821        for proxy in env.client_proxies()? {
822            self.environment_proxies.push(proxy);
823        }
824        Ok(self)
825    }
826
827    /// Set `NO_PROXY` bypass rules for the default proxy.
828    ///
829    /// When set, URLs matching any bypass rule are sent directly
830    /// without going through the proxy.
831    #[cfg(feature = "proxy")]
832    #[must_use]
833    pub fn no_proxy(mut self, no_proxy: crate::proxy::NoProxy) -> Self {
834        if let Some(proxy) = self.proxy.take() {
835            self.proxy = Some(proxy.no_proxy(no_proxy));
836        }
837        self
838    }
839
840    /// Set a custom TLS configuration for this client.
841    ///
842    /// When set, the client uses the provided [`crate::tls::TlsConfig`] for all
843    /// TLS connections instead of the default native-root-with-WebPKI-fallback
844    /// strategy (or the packaged-WebPKI default when `tls-native-roots` is not
845    /// enabled).
846    #[cfg(feature = "tls-rustls")]
847    #[must_use]
848    pub fn tls_config(mut self, config: crate::tls::TlsConfig) -> Self {
849        self.tls_config = Some(config);
850        self
851    }
852
853    /// Enable or disable insecure TLS verification while retaining other
854    /// TLS configuration already applied to this builder.
855    #[cfg(feature = "tls-rustls")]
856    #[must_use]
857    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
858        let config = self.tls_config.take().unwrap_or_default();
859        self.tls_config = Some(config.danger_accept_invalid_certs(accept));
860        self
861    }
862
863    /// Enable or disable automatic response decompression.
864    ///
865    /// When enabled (the default), the client sends an
866    /// `Accept-Encoding` header and transparently decompresses
867    /// response bodies. Decoded `Content-Encoding` and
868    /// `Content-Length` headers are removed from the response.
869    ///
870    /// Can be overridden per-request via
871    /// [`RequestBuilder::decompress`].
872    #[must_use]
873    pub fn automatic_decompression(mut self, enabled: bool) -> Self {
874        self.automatic_decompression = Some(enabled);
875        self
876    }
877
878    /// Set the maximum decoded response body size in bytes.
879    ///
880    /// The limit applies to bytes made available after decoding and also to
881    /// ordinary unencoded/identity response bodies, in both buffered and
882    /// streaming paths. Exceeding it produces [`Error::DecodedBodyTooLarge`]
883    /// without requiring a second caller-side accumulation loop. A wire
884    /// `Content-Length` may be used for an early metadata check, but this
885    /// body limit remains authoritative when the header is absent, incorrect,
886    /// or describes encoded bytes.
887    #[must_use]
888    pub fn max_decoded_body_size(mut self, max: usize) -> Self {
889        self.max_decoded_body_size = Some(max);
890        self
891    }
892
893    /// Set the maximum decompression ratio (decoded bytes / compressed bytes).
894    /// When set, responses whose expansion ratio exceeds this limit produce
895    /// an error. This guards against zip-bomb style attacks.
896    ///
897    /// # Panics
898    ///
899    /// Panics if `ratio` is not finite or not positive.
900    #[must_use]
901    pub fn max_decompression_ratio(mut self, ratio: f64) -> Self {
902        assert!(
903            ratio.is_finite() && ratio > 0.0,
904            "max_decompression_ratio must be finite and positive, got {ratio}"
905        );
906        self.max_decompression_ratio = Some(ratio);
907        self
908    }
909
910    /// Set the retry policy for this client.
911    ///
912    /// Only available with the `logical-retry` feature (enabled by the `http1`/`http2`
913    /// compatibility aliases). The lean profile dispatches once under the outer
914    /// total deadline with no retry backoff/jitter/status policy.
915    ///
916    /// When set, failed requests that match the policy (safe methods,
917    /// retryable statuses/errors, replayable bodies) are automatically
918    /// retried with exponential backoff.
919    #[cfg(feature = "logical-retry")]
920    #[must_use]
921    pub fn retry(mut self, policy: RetryPolicy) -> Self {
922        self.retry = Some(policy);
923        self
924    }
925
926    /// Allow or disallow Hyper's implicit retry when a reused idle
927    /// connection is found unusable before a request starts writing.
928    ///
929    /// This is separate from eggfetch's explicit logical retry (the
930    /// `logical-retry` feature and [`RetryPolicy`]). The
931    /// default is `true`, preserving Hyper's existing behavior.
932    #[must_use]
933    pub fn retry_canceled_requests(mut self, enabled: bool) -> Self {
934        self.retry_canceled_requests = enabled;
935        self
936    }
937
938    /// Install a client-scoped caller-owned raw-stream dialer.
939    ///
940    /// Eggfetch continues to own HTTP framing, destination TLS, SNI,
941    /// certificate verification, redirects, retries, and response bodies.
942    /// The dialer is incompatible with built-in proxy, UDS, resolved-target,
943    /// local-address, and socket-option routing; those combinations fail
944    /// closed before network I/O.
945    ///
946    /// Only available with the `advanced-routing` feature (enabled by the
947    /// `native-http1`/`native-http2` compatibility slices). The lean
948    /// standard-route profile omits custom dialing.
949    #[cfg(feature = "advanced-routing")]
950    #[must_use]
951    pub fn dialer<D>(mut self, dialer: D) -> Self
952    where
953        D: Dialer,
954    {
955        self.dialer = Some(Arc::new(dialer));
956        self
957    }
958
959    /// Install a caller-owned datagram dialer for experimental HTTP/3 routing.
960    ///
961    /// Every HTTP/3 connection generation, whether it comes from an explicit
962    /// `Http3Only` request or from an Alt-Svc alternative, is established over
963    /// one fixed-target [`DatagramRoute`](crate::DatagramRoute) returned by this
964    /// dialer. TCP requests are unaffected: [`Self::dialer`] still governs
965    /// HTTP/1.1 and HTTP/2.
966    ///
967    /// Configuring a dialer means Eggfetch creates **no** direct QUIC UDP
968    /// socket. A route that fails or refuses can therefore never fall back to
969    /// silently opening one; the request fails with the dialer's typed
970    /// [`DialErrorKind`](crate::DialErrorKind) instead.
971    ///
972    /// Eggfetch still owns the whole QUIC stack. The dialer supplies a datagram
973    /// carrier only: no handshake, no certificate material, and no QUIC frames
974    /// cross this boundary. SNI and certificate validation always use the
975    /// logical origin, even when the route's physical peer is a relay.
976    ///
977    /// Requires `http3` plus `advanced-routing`, which `http3` always enables.
978    /// Lean profiles without `http3` omit this hook entirely.
979    #[cfg(feature = "http3")]
980    #[must_use]
981    pub fn datagram_dialer<D>(mut self, dialer: D) -> Self
982    where
983        D: crate::transport::datagram::DatagramDialer,
984    {
985        self.datagram_dialer = Some(Arc::new(dialer));
986        self
987    }
988
989    /// Install a shared caller-scoped live physical-connection policy.
990    ///
991    /// This controls established Hyper connections, including idle pooled
992    /// connections. It does not change the logical request limits in
993    /// [`PoolConfig`]. A `max_live` value of zero fails
994    /// requests closed because no useful client can be created from it.
995    #[must_use]
996    pub fn physical_connection_policy(mut self, policy: PhysicalConnectionPolicy) -> Self {
997        self.physical_connection_policy = policy;
998        self
999    }
1000
1001    /// Install established-transport read/write inactivity guardrails.
1002    ///
1003    /// These timers are distinct from [`Timeout`]'s request
1004    /// body and response-stream semantics and are disabled by default.
1005    #[must_use]
1006    pub fn transport_io_timeout(mut self, timeout: TransportIoTimeout) -> Self {
1007        self.transport_io_timeout = timeout;
1008        self
1009    }
1010
1011    /// Set the HTTP version policy for this client.
1012    ///
1013    /// Controls which HTTP protocol versions the client may negotiate.
1014    /// The default is [`HttpVersionPolicy::Auto`], which allows HTTP/2
1015    /// negotiation via ALPN when the `http2` feature is enabled.
1016    ///
1017    /// When the `http2` feature is not compiled in, `Http2Only` and `Auto`
1018    /// are silently downgraded to `Http1Only`.
1019    #[must_use]
1020    pub fn http_version_policy(mut self, policy: HttpVersionPolicy) -> Self {
1021        self.http_version_policy = policy;
1022        self
1023    }
1024
1025    /// Set a local address to bind outbound sockets to before connecting.
1026    ///
1027    /// When set, all direct (non-proxy, non-UDS) connections will bind
1028    /// to the specified local address before connecting to the remote.
1029    /// This uses a custom connector path instead of the standard
1030    /// hyper-rustls connector.
1031    ///
1032    /// Only available with `advanced-routing`; omitted by the lean profile.
1033    #[cfg(feature = "advanced-routing")]
1034    #[must_use]
1035    pub fn local_address(mut self, addr: std::net::SocketAddr) -> Self {
1036        let config = self.direct_connector_config.get_or_insert_with(|| {
1037            crate::transport::direct_connector::DirectConnectorConfig {
1038                local_address: None,
1039                socket_options: Vec::new(),
1040            }
1041        });
1042        config.local_address = Some(addr);
1043        self
1044    }
1045
1046    /// Set socket options to apply to outbound TCP connections.
1047    ///
1048    /// Options are applied to the socket before the connect operation.
1049    /// Recognized options are applied via `tokio::net::TcpSocket` setters;
1050    /// unrecognized options produce a connection error (never silently
1051    /// ignored, per the plan's Track 2.4 requirement).
1052    ///
1053    /// Only available with `advanced-routing`; omitted by the lean profile.
1054    #[cfg(feature = "advanced-routing")]
1055    #[must_use]
1056    pub fn socket_options(
1057        mut self,
1058        options: Vec<crate::transport::direct_connector::SocketOption>,
1059    ) -> Self {
1060        let config = self.direct_connector_config.get_or_insert_with(|| {
1061            crate::transport::direct_connector::DirectConnectorConfig {
1062                local_address: None,
1063                socket_options: Vec::new(),
1064            }
1065        });
1066        config.socket_options = options;
1067        self
1068    }
1069
1070    /// Set a Unix domain socket path for all connections.
1071    ///
1072    /// When set, all requests are routed through the specified UDS path
1073    /// instead of making TCP connections. The URL in the request still
1074    /// provides HTTP scheme/authority/path semantics.
1075    ///
1076    /// Only supported on Unix platforms. On non-Unix platforms, this
1077    /// option is accepted but will produce an error at request time.
1078    ///
1079    /// Only available with `advanced-routing`; omitted by the lean profile.
1080    #[cfg(feature = "advanced-routing")]
1081    #[must_use]
1082    pub fn uds_path(mut self, path: String) -> Self {
1083        self.uds_path = Some(path);
1084        self
1085    }
1086
1087    /// Build the client.
1088    ///
1089    /// Native system roots are preferred. If the platform root store is
1090    /// unavailable, the client falls back to the packaged Mozilla root set
1091    /// while retaining certificate and hostname verification.
1092    #[must_use]
1093    #[allow(
1094        clippy::too_many_lines,
1095        reason = "the builder resolves the root store, the HTTP version policy and the pool limits in one pass, and splitting it would scatter the cfg-gated branches across helpers"
1096    )]
1097    pub fn build(self) -> Client {
1098        #[cfg(any(
1099            feature = "transport-http1",
1100            feature = "transport-http2",
1101            feature = "advanced-routing"
1102        ))]
1103        use crate::http_version::HttpVersionPolicyEnabler;
1104        #[cfg(any(
1105            feature = "transport-http1",
1106            feature = "transport-http2",
1107            feature = "advanced-routing"
1108        ))]
1109        let enabler = HttpVersionPolicyEnabler::from_policy(self.http_version_policy);
1110        let transport_metrics = Arc::new(crate::transport::metrics::TransportMetrics::new());
1111
1112        let mut pool_config = self.pool_config;
1113        if let Some(limits) = self.limits {
1114            let limits_config: PoolConfig = limits.into();
1115            if limits_config.max_connections.is_some() {
1116                pool_config.max_connections = limits_config.max_connections;
1117            }
1118            if limits_config.max_connections_per_host.is_some() {
1119                pool_config.max_connections_per_host = limits_config.max_connections_per_host;
1120            }
1121            if limits_config.max_in_flight_requests.is_some() {
1122                pool_config.max_in_flight_requests = limits_config.max_in_flight_requests;
1123            }
1124            if limits_config.max_in_flight_requests_per_origin.is_some() {
1125                pool_config.max_in_flight_requests_per_origin =
1126                    limits_config.max_in_flight_requests_per_origin;
1127            }
1128            if limits_config.max_idle_connections.is_some() {
1129                pool_config.max_idle_connections = limits_config.max_idle_connections;
1130            }
1131            if limits_config.max_idle_connections_per_host.is_some() {
1132                pool_config.max_idle_connections_per_host =
1133                    limits_config.max_idle_connections_per_host;
1134            }
1135            if limits_config.idle_timeout.is_some() {
1136                pool_config.idle_timeout = limits_config.idle_timeout;
1137            }
1138        }
1139        #[cfg(any(
1140            feature = "transport-http1",
1141            feature = "transport-http2",
1142            feature = "advanced-routing"
1143        ))]
1144        let lifecycle = Arc::new(LifecycleConfig::from_policy(
1145            self.physical_connection_policy,
1146            self.transport_io_timeout,
1147            transport_metrics.clone(),
1148        ));
1149        // Shared builder policy for the persistent per-client Hyper
1150        // singletons below (standard, direct, UDS, custom dialer). The cached
1151        // and isolated route clients resolve the same policy at use time from
1152        // the live pool, so the two families never diverge.
1153        #[cfg(any(
1154            feature = "transport-http1",
1155            feature = "transport-http2",
1156            feature = "advanced-routing"
1157        ))]
1158        let persistent_policy = HyperClientPolicy::new(
1159            self.retry_canceled_requests,
1160            pool_config.idle_timeout,
1161            pool_config.effective_max_idle_per_host(),
1162            enabler,
1163        );
1164
1165        #[cfg(feature = "cookies")]
1166        let cookie_jar = self.cookie_jar.unwrap_or_default();
1167
1168        let automatic_decompression = self.automatic_decompression.unwrap_or(true);
1169        #[cfg(feature = "tls-rustls")]
1170        let tls_config_result = self
1171            .tls_config
1172            .clone()
1173            .unwrap_or_default()
1174            .build_rustls_config();
1175        #[cfg(feature = "tls-rustls")]
1176        let tls_config_error = tls_config_result
1177            .as_ref()
1178            .err()
1179            .map(|error| format!("failed to build TLS config: {error}"));
1180        // `Http3Only` is strict direct-QUIC and needs no Hyper client.
1181        // `Auto { allow_http3: true }` needs both: H1/H2 for discovery and
1182        // safe fallback plus QUIC for discovered routes. All other policies
1183        // need Hyper only.
1184        #[cfg(feature = "tls-rustls")]
1185        let hyper_client = if matches!(
1186            self.http_version_policy,
1187            crate::HttpVersionPolicy::Http3Only
1188        ) || tls_config_error.is_some()
1189        {
1190            None
1191        } else if let Ok(rc) = tls_config_result {
1192            let https = build_standard_connector(rc, enabler);
1193            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1194            Some(build_hyper_client(
1195                https,
1196                &persistent_policy,
1197                connect_timeout,
1198                &lifecycle,
1199            ))
1200        } else {
1201            None
1202        };
1203
1204        #[cfg(all(
1205            not(feature = "tls-rustls"),
1206            any(feature = "transport-http1", feature = "transport-http2")
1207        ))]
1208        let hyper_client = if matches!(
1209            self.http_version_policy,
1210            crate::HttpVersionPolicy::Http3Only
1211        ) {
1212            None
1213        } else {
1214            let connector = build_standard_connector(enabler);
1215            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1216            Some(build_hyper_client(
1217                connector,
1218                &persistent_policy,
1219                connect_timeout,
1220                &lifecycle,
1221            ))
1222        };
1223        #[cfg(feature = "http3")]
1224        let h3_connector = if enabler.use_http3() {
1225            crate::transport::http3::H3Connector::with_datagram_route(
1226                self.tls_config.clone(),
1227                &pool_config,
1228                Some(transport_metrics.clone()),
1229                self.datagram_dialer.clone(),
1230            )
1231            .ok()
1232        } else {
1233            None
1234        };
1235
1236        // Build the direct connector client for advanced socket options / local
1237        // address binding. This uses a custom connector path instead of the
1238        // standard hyper-rustls connector.
1239        #[cfg(feature = "advanced-routing")]
1240        let stored_direct_config = self.direct_connector_config.clone();
1241        #[cfg(feature = "advanced-routing")]
1242        let direct_client = if let Some(dc_config) = self.direct_connector_config {
1243            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1244
1245            // Build a TLS connector for HTTPS through the direct path.
1246            #[cfg(feature = "tls-rustls")]
1247            let tls_connector = match self
1248                .tls_config
1249                .clone()
1250                .unwrap_or_default()
1251                .build_rustls_config()
1252            {
1253                Ok(rc) => Some(tokio_rustls::TlsConnector::from(Arc::new(
1254                    configure_tls_alpn(
1255                        rc,
1256                        crate::http_version::HttpVersionPolicyEnabler::from_policy(
1257                            self.http_version_policy,
1258                        ),
1259                    ),
1260                ))),
1261                Err(_) => None,
1262            };
1263            #[cfg(not(feature = "tls-rustls"))]
1264            let tls_connector = None;
1265
1266            let direct_connector =
1267                crate::transport::direct_connector::DirectConnector::with_metrics(
1268                    dc_config,
1269                    tls_connector,
1270                    transport_metrics.clone(),
1271                );
1272            Some(build_hyper_client(
1273                direct_connector,
1274                &persistent_policy,
1275                connect_timeout,
1276                &lifecycle,
1277            ))
1278        } else {
1279            None
1280        };
1281
1282        // The UDS path is accepted on all platforms (see `uds_path`) but
1283        // only consumed on Unix; without this the field is never read on
1284        // non-Unix targets.
1285        #[cfg(all(not(unix), feature = "advanced-routing"))]
1286        let _ = &self.uds_path;
1287
1288        #[cfg(all(unix, feature = "advanced-routing"))]
1289        let uds_client = self.uds_path.clone().map(|path| {
1290            #[cfg(feature = "tls-rustls")]
1291            let tls_connector = self
1292                .tls_config
1293                .clone()
1294                .unwrap_or_default()
1295                .build_rustls_config()
1296                .ok()
1297                .map(|rc| {
1298                    tokio_rustls::TlsConnector::from(Arc::new(configure_tls_alpn(
1299                        rc,
1300                        crate::http_version::HttpVersionPolicyEnabler::from_policy(
1301                            self.http_version_policy,
1302                        ),
1303                    )))
1304                });
1305            #[cfg(not(feature = "tls-rustls"))]
1306            let tls_connector = None;
1307            let connector = crate::transport::uds::UdsConnector::with_metrics(
1308                path,
1309                tls_connector,
1310                transport_metrics.clone(),
1311            );
1312            let connect_timeout = self.timeout.as_ref().and_then(|timeout| timeout.connect);
1313            build_hyper_client(connector, &persistent_policy, connect_timeout, &lifecycle)
1314        });
1315
1316        #[cfg(feature = "advanced-routing")]
1317        let custom_client = if let Some(dialer) = self.dialer.clone() {
1318            #[cfg(feature = "tls-rustls")]
1319            let custom_config = match self
1320                .tls_config
1321                .clone()
1322                .unwrap_or_default()
1323                .build_rustls_config()
1324            {
1325                Ok(config) => Some(config),
1326                Err(e) => {
1327                    #[cfg(feature = "tracing")]
1328                    tracing::warn!("eggfetch: custom-route TLS config failed: {e}");
1329                    #[cfg(not(feature = "tracing"))]
1330                    let _ = &e;
1331                    None
1332                }
1333            };
1334            #[cfg(not(feature = "tls-rustls"))]
1335            let custom_config = Some(());
1336
1337            custom_config.and_then(|custom_config| {
1338                let connector = match build_custom_connector(custom_config, dialer, enabler, None) {
1339                    Ok(connector) => connector,
1340                    Err(e) => {
1341                        // Surface the root cause: returning `None` here falls
1342                        // back to the standard route with no diagnostic.
1343                        #[cfg(feature = "tracing")]
1344                        tracing::warn!("eggfetch: custom connector build failed: {e}");
1345                        #[cfg(not(feature = "tracing"))]
1346                        let _ = &e;
1347                        return None;
1348                    }
1349                };
1350                let connect_timeout = self.timeout.as_ref().and_then(|timeout| timeout.connect);
1351                Some(build_hyper_client(
1352                    connector,
1353                    &persistent_policy,
1354                    connect_timeout,
1355                    &lifecycle,
1356                ))
1357            })
1358        } else {
1359            None
1360        };
1361        let config = ClientConfig {
1362            default_headers: self.default_headers,
1363            user_agent: self.user_agent,
1364            timeout: self.timeout,
1365            #[cfg(feature = "redirects")]
1366            redirect: self.redirect,
1367            auth: self.auth,
1368            #[cfg(feature = "cookies")]
1369            cookie_jar,
1370            automatic_decompression,
1371            max_decoded_body_size: self.max_decoded_body_size,
1372            max_decompression_ratio: self.max_decompression_ratio,
1373            #[cfg(feature = "proxy")]
1374            proxy: self.proxy,
1375            #[cfg(feature = "proxy")]
1376            environment_proxies: self.environment_proxies,
1377            #[cfg(feature = "tls-rustls")]
1378            tls_config: self.tls_config,
1379            #[cfg(feature = "logical-retry")]
1380            retry: self.retry,
1381            retry_canceled_requests: self.retry_canceled_requests,
1382            #[cfg(feature = "advanced-routing")]
1383            dialer: self.dialer,
1384            #[cfg(feature = "advanced-routing")]
1385            uds_configured: self.uds_path.is_some(),
1386            http_version_policy: self.http_version_policy,
1387        };
1388
1389        let pool = Pool::new(pool_config);
1390
1391        Client {
1392            inner: Arc::new(ClientInner {
1393                #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1394                hyper_client,
1395                #[cfg(feature = "advanced-routing")]
1396                custom_client,
1397                #[cfg(feature = "tls-rustls")]
1398                tls_config_error,
1399                #[cfg(feature = "advanced-routing")]
1400                direct_client,
1401                #[cfg(feature = "advanced-routing")]
1402                direct_connector_config: stored_direct_config,
1403                #[cfg(feature = "advanced-routing")]
1404                sni_clients: Mutex::new(BoundedClientCache::new(SNI_CLIENT_CACHE_MAX_ENTRIES)),
1405                #[cfg(feature = "advanced-routing")]
1406                sni_custom_clients: Mutex::new(BoundedClientCache::new(
1407                    SNI_CLIENT_CACHE_MAX_ENTRIES,
1408                )),
1409                #[cfg(feature = "advanced-routing")]
1410                resolved_clients: Mutex::new(BoundedClientCache::new(
1411                    RESOLVED_CLIENT_CACHE_MAX_ENTRIES,
1412                )),
1413                #[cfg(all(unix, feature = "advanced-routing"))]
1414                uds_client,
1415                #[cfg(feature = "proxy")]
1416                socks_clients: Mutex::new(BoundedClientCache::new(SOCKS_CLIENT_CACHE_MAX_ENTRIES)),
1417                #[cfg(feature = "proxy")]
1418                forward_clients: Mutex::new(BoundedClientCache::new(
1419                    FORWARD_CLIENT_CACHE_MAX_ENTRIES,
1420                )),
1421                #[cfg(feature = "proxy")]
1422                connect_clients: Mutex::new(BoundedClientCache::new(
1423                    CONNECT_CLIENT_CACHE_MAX_ENTRIES,
1424                )),
1425                config,
1426                pool,
1427                transport_metrics,
1428                #[cfg(any(
1429                    feature = "transport-http1",
1430                    feature = "transport-http2",
1431                    feature = "advanced-routing"
1432                ))]
1433                lifecycle,
1434                #[cfg(feature = "http3")]
1435                h3_connector,
1436                #[cfg(feature = "http3")]
1437                alt_svc_state: Arc::new(crate::transport::alt_svc::AltSvcState::new()),
1438            }),
1439        }
1440    }
1441}
1442
1443#[cfg(feature = "high-level-url")]
1444fn parse_url(url_str: &str) -> Result<url::Url> {
1445    // Deliberately do not echo url_str into the error: parsing has
1446    // failed, so redact_url_string would fall back to the raw input
1447    // (potentially containing credentials). url::ParseError renders
1448    // only a static description and never embeds the input.
1449    let url = url::Url::parse(url_str).map_err(|e| Error::InvalidUrl(e.to_string()))?;
1450    if !url.username().is_empty() || url.password().is_some() {
1451        // URL userinfo is both easy to leak through diagnostics and
1452        // surprising for an HTTP client with explicit auth APIs.
1453        return Err(Error::InvalidUrl(
1454            "URL userinfo is not supported; configure authentication explicitly".into(),
1455        ));
1456    }
1457    match url.scheme() {
1458        "http" | "https" => Ok(url),
1459        other => Err(Error::Unsupported(format!(
1460            "URL scheme '{other}' is not supported; use http or https"
1461        ))),
1462    }
1463}
1464
1465#[cfg(test)]
1466mod tests {
1467    use super::*;
1468    #[cfg(feature = "proxy")]
1469    use crate::proxy::ProxyAuth;
1470    use bytes::Bytes;
1471    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1472    use hyper_util::rt::TokioExecutor;
1473    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1474    use std::future::{ready, Ready};
1475    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1476    use std::net::SocketAddr;
1477    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1478    use std::task::{Context, Poll};
1479    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1480    use tower_service::Service;
1481
1482    #[test]
1483    fn client_constructs() {
1484        let _client = Client::new();
1485    }
1486
1487    #[test]
1488    fn client_config_debug_redacts_secrets() {
1489        let mut config = ClientConfig::default();
1490        config
1491            .default_headers
1492            .insert("authorization", "Bearer header-secret-token")
1493            .unwrap();
1494        #[cfg(feature = "cookies")]
1495        config
1496            .cookie_jar
1497            .set_default_cookie("session".to_owned(), "jar-secret-token".to_owned())
1498            .expect("valid test cookie");
1499        let debug = format!("{config:?}");
1500        assert!(
1501            !debug.contains("header-secret-token"),
1502            "ClientConfig Debug must not leak header secrets: {debug}"
1503        );
1504        #[cfg(feature = "cookies")]
1505        assert!(
1506            !debug.contains("jar-secret-token"),
1507            "ClientConfig Debug must not leak jar secrets: {debug}"
1508        );
1509    }
1510
1511    #[cfg(feature = "high-level-url")]
1512    #[test]
1513    fn client_default() {
1514        let _client = Client::default();
1515    }
1516
1517    #[cfg(feature = "high-level-url")]
1518    #[test]
1519    fn client_builder() {
1520        let _client = Client::builder().user_agent("test-agent").build();
1521    }
1522
1523    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
1524    #[cfg(feature = "high-level-url")]
1525    #[tokio::test]
1526    async fn standard_connector_preserves_resolver_failure_for_detailed_mapping() {
1527        #[derive(Clone, Copy)]
1528        struct FailingResolver;
1529
1530        impl Service<hyper_util::client::legacy::connect::dns::Name> for FailingResolver {
1531            type Response = std::vec::IntoIter<SocketAddr>;
1532            type Error = std::io::Error;
1533            type Future = Ready<std::result::Result<Self::Response, Self::Error>>;
1534
1535            fn poll_ready(
1536                &mut self,
1537                _: &mut Context<'_>,
1538            ) -> Poll<std::result::Result<(), Self::Error>> {
1539                Poll::Ready(Ok(()))
1540            }
1541
1542            fn call(&mut self, _: hyper_util::client::legacy::connect::dns::Name) -> Self::Future {
1543                ready(Err(std::io::Error::new(
1544                    std::io::ErrorKind::NotFound,
1545                    "synthetic standard resolver failure",
1546                )))
1547            }
1548        }
1549
1550        let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(
1551            HttpVersionPolicy::Http1Only,
1552        );
1553        #[cfg(feature = "tls-rustls")]
1554        let connector = build_standard_connector_with_resolver(
1555            rustls::ClientConfig::builder()
1556                .with_root_certificates(rustls::RootCertStore::empty())
1557                .with_no_client_auth(),
1558            enabler,
1559            FailingResolver,
1560        );
1561        #[cfg(not(feature = "tls-rustls"))]
1562        let connector = build_standard_connector_with_resolver(FailingResolver, enabler);
1563
1564        let client =
1565            hyper_util::client::legacy::Client::builder(TokioExecutor::new()).build(connector);
1566        #[cfg(feature = "tls-rustls")]
1567        let uri = "https://synthetic.example/";
1568        #[cfg(not(feature = "tls-rustls"))]
1569        let uri = "http://synthetic.example/";
1570        let request = http::Request::get(uri)
1571            .body(http_body_util::Empty::<Bytes>::new())
1572            .expect("synthetic request is valid");
1573        let error = client
1574            .request(request)
1575            .await
1576            .expect_err("synthetic resolver should fail");
1577        let context = crate::error::RequestFailureContext::new();
1578        let mapped = crate::transport::direct::map_send_error_with_context(error, Some(&context));
1579
1580        assert_eq!(mapped.kind(), "hyper_client");
1581        let failure = crate::error::RequestFailure::from_context(mapped, &context);
1582        assert_eq!(
1583            failure.network_failure_kind(),
1584            Some(crate::error::NetworkFailureKind::Dns)
1585        );
1586    }
1587
1588    #[test]
1589    fn client_builder_merge_timeout_preserves_other_phases() {
1590        // Phase-specific setters must merge into any existing timeout
1591        // configuration instead of replacing it wholesale.
1592        let client = Client::builder()
1593            .timeout(Timeout::from_secs(30))
1594            .merge_timeout(
1595                Timeout::builder()
1596                    .connect(std::time::Duration::from_secs(5))
1597                    .build(),
1598            )
1599            .merge_timeout(
1600                Timeout::builder()
1601                    .read(std::time::Duration::from_secs(10))
1602                    .build(),
1603            )
1604            .build();
1605
1606        let timeout = client.inner.config.timeout.expect("timeout configured");
1607        let d = |secs: u64| std::time::Duration::from_secs(secs);
1608        assert_eq!(timeout.connect, Some(d(5)), "last connect wins");
1609        assert_eq!(timeout.read, Some(d(10)), "last read wins");
1610        assert_eq!(
1611            timeout.write,
1612            Some(d(30)),
1613            "unset phases keep earlier values"
1614        );
1615        assert_eq!(timeout.pool, Some(d(30)));
1616    }
1617
1618    #[test]
1619    fn client_builder_merge_timeout_without_prior_config() {
1620        let client = Client::builder()
1621            .merge_timeout(
1622                Timeout::builder()
1623                    .connect(std::time::Duration::from_secs(5))
1624                    .build(),
1625            )
1626            .build();
1627
1628        let timeout = client.inner.config.timeout.expect("timeout configured");
1629        assert_eq!(timeout.connect, Some(std::time::Duration::from_secs(5)));
1630        assert_eq!(timeout.read, None);
1631    }
1632
1633    #[cfg(any(feature = "proxy", feature = "http3"))]
1634    #[test]
1635    fn client_builder_danger_accept_invalid_certs_preserves_tls_config() {
1636        let client = Client::builder()
1637            .tls_config(crate::tls::TlsConfig::builder().sni(false).build())
1638            .danger_accept_invalid_certs(true)
1639            .build();
1640        let tls = client
1641            .inner
1642            .config
1643            .tls_config
1644            .as_ref()
1645            .expect("TLS config should be retained");
1646        assert!(!tls.sni_enabled());
1647        assert!(!tls.verify_certificate());
1648        assert!(!tls.verify_hostname());
1649    }
1650
1651    #[test]
1652    #[cfg(feature = "tls-rustls")]
1653    fn tls_root_store_paths_construct() {
1654        // Native roots are environment-dependent; the production connector
1655        // always receives the same policy-built config as direct connectors.
1656        let enabler =
1657            crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
1658                allow_http3: false,
1659            });
1660        let config = crate::tls::TlsConfig::default()
1661            .build_rustls_config()
1662            .expect("default TLS policy builds");
1663        let _ = build_standard_connector(config, enabler);
1664    }
1665
1666    #[test]
1667    fn client_builder_http1_only() {
1668        let client = Client::builder()
1669            .http_version_policy(HttpVersionPolicy::Http1Only)
1670            .build();
1671        assert_eq!(
1672            client.inner.config.http_version_policy,
1673            HttpVersionPolicy::Http1Only
1674        );
1675    }
1676
1677    #[test]
1678    fn client_builder_http2_auto() {
1679        let client = Client::builder()
1680            .http_version_policy(HttpVersionPolicy::Auto { allow_http3: false })
1681            .build();
1682        assert_eq!(
1683            client.inner.config.http_version_policy,
1684            HttpVersionPolicy::Auto { allow_http3: false }
1685        );
1686    }
1687
1688    #[test]
1689    #[cfg(feature = "transport-http2")]
1690    fn client_builder_http2_only() {
1691        let client = Client::builder()
1692            .http_version_policy(HttpVersionPolicy::Http2Only)
1693            .build();
1694        assert_eq!(
1695            client.inner.config.http_version_policy,
1696            HttpVersionPolicy::Http2Only
1697        );
1698    }
1699
1700    #[cfg(feature = "high-level-url")]
1701    #[test]
1702    fn connector_builds_for_all_policies() {
1703        for policy in [
1704            HttpVersionPolicy::Http1Only,
1705            HttpVersionPolicy::Auto { allow_http3: false },
1706            #[cfg(feature = "transport-http2")]
1707            HttpVersionPolicy::Http2Only,
1708            #[cfg(feature = "http3")]
1709            HttpVersionPolicy::Http3Only,
1710        ] {
1711            let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(policy);
1712            if !enabler.use_http3() {
1713                #[cfg(feature = "tls-rustls")]
1714                let config = crate::tls::TlsConfig::default()
1715                    .build_rustls_config()
1716                    .expect("default TLS policy builds");
1717                #[cfg(feature = "tls-rustls")]
1718                let _ = build_standard_connector(config, enabler);
1719            }
1720        }
1721    }
1722
1723    #[cfg(feature = "transport-http2")]
1724    #[cfg(feature = "high-level-url")]
1725    #[test]
1726    fn custom_connector_alpn_matches_http_version_policy() {
1727        let config = rustls::ClientConfig::builder()
1728            .with_root_certificates(rustls::RootCertStore::empty())
1729            .with_no_client_auth();
1730        let h2_only = configure_tls_alpn(
1731            config.clone(),
1732            crate::http_version::HttpVersionPolicyEnabler::from_policy(
1733                HttpVersionPolicy::Http2Only,
1734            ),
1735        );
1736        assert_eq!(h2_only.alpn_protocols, vec![b"h2".to_vec()]);
1737
1738        let auto = configure_tls_alpn(
1739            config,
1740            crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
1741                allow_http3: false,
1742            }),
1743        );
1744        assert_eq!(
1745            auto.alpn_protocols,
1746            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
1747        );
1748    }
1749
1750    #[cfg(feature = "high-level-url")]
1751    #[test]
1752    fn parse_valid_urls() {
1753        assert!(parse_url("https://example.com").is_ok());
1754        assert!(parse_url("http://localhost:8080").is_ok());
1755    }
1756
1757    #[cfg(feature = "high-level-url")]
1758    #[test]
1759    fn parse_invalid_schemes() {
1760        assert!(parse_url("ftp://example.com").is_err());
1761        assert!(parse_url("file:///tmp/test").is_err());
1762    }
1763
1764    #[cfg(feature = "high-level-url")]
1765    #[test]
1766    fn parse_invalid_urls() {
1767        assert!(parse_url("not a url").is_err());
1768    }
1769
1770    #[cfg(feature = "high-level-url")]
1771    #[test]
1772    fn get_request_builder() {
1773        let client = Client::new();
1774        let builder = client.get("https://example.com").unwrap();
1775        let req = builder.build().unwrap();
1776        assert_eq!(*req.method(), Method::GET);
1777    }
1778
1779    #[cfg(feature = "high-level-url")]
1780    #[test]
1781    fn hyper_canceled_request_retry_defaults_on_and_is_independently_configurable() {
1782        assert!(Client::new().inner.config.retry_canceled_requests);
1783        let strict = Client::builder().retry_canceled_requests(false).build();
1784        assert!(!strict.inner.config.retry_canceled_requests);
1785        #[cfg(feature = "logical-retry")]
1786        assert!(strict.inner.config.retry.is_none());
1787    }
1788
1789    #[cfg(feature = "high-level-url")]
1790    #[test]
1791    fn physical_policy_and_transport_io_timeout_are_separate_from_logical_pooling() {
1792        let client = Client::builder()
1793            .physical_connection_policy(PhysicalConnectionPolicy {
1794                max_live: Some(2),
1795                admission_timeout: Some(Duration::from_secs(1)),
1796            })
1797            .transport_io_timeout(TransportIoTimeout {
1798                read: Some(Duration::from_secs(2)),
1799                write: Some(Duration::from_secs(3)),
1800            })
1801            .build();
1802        assert_eq!(
1803            client.inner.lifecycle.admission_timeout,
1804            Some(Duration::from_secs(1))
1805        );
1806        assert_eq!(
1807            client.inner.lifecycle.io_timeout.read,
1808            Some(Duration::from_secs(2))
1809        );
1810        assert_eq!(
1811            client.inner.lifecycle.io_timeout.write,
1812            Some(Duration::from_secs(3))
1813        );
1814    }
1815
1816    #[cfg(feature = "high-level-url")]
1817    #[test]
1818    fn apply_content_length_empty_body() {
1819        let headers = Headers::new();
1820        let body = crate::body::RequestBody::Empty;
1821        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1822        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "0");
1823    }
1824
1825    #[cfg(feature = "high-level-url")]
1826    #[test]
1827    fn apply_content_length_bytes_body() {
1828        let headers = Headers::new();
1829        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1830        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1831        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
1832    }
1833
1834    #[cfg(feature = "high-level-url")]
1835    #[test]
1836    fn apply_content_length_stream_known() {
1837        let headers = Headers::new();
1838        let stream = futures_util::stream::empty::<Result<Bytes>>();
1839        let body = crate::body::RequestBody::from_stream(stream, Some(7));
1840        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1841        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "7");
1842    }
1843
1844    #[cfg(feature = "high-level-url")]
1845    #[test]
1846    fn apply_content_length_stream_unknown() {
1847        let headers = Headers::new();
1848        let stream = futures_util::stream::empty::<Result<Bytes>>();
1849        let body = crate::body::RequestBody::from_stream(stream, None);
1850        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1851        assert!(out.get("content-length").is_none());
1852    }
1853
1854    #[cfg(feature = "high-level-url")]
1855    #[test]
1856    fn apply_content_length_user_matches() {
1857        let mut headers = Headers::new();
1858        headers.insert("content-length", "5").unwrap();
1859        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1860        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1861        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
1862    }
1863
1864    #[cfg(feature = "high-level-url")]
1865    #[test]
1866    fn apply_content_length_user_mismatch_errors() {
1867        let mut headers = Headers::new();
1868        headers.insert("content-length", "10").unwrap();
1869        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1870        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1871        assert_eq!(err.kind(), "request_build");
1872    }
1873
1874    #[cfg(feature = "high-level-url")]
1875    #[test]
1876    fn apply_content_length_rejects_invalid_value() {
1877        let mut headers = Headers::new();
1878        headers.insert("content-length", "not-a-number").unwrap();
1879        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1880        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1881        assert_eq!(err.kind(), "invalid_header_value");
1882    }
1883
1884    #[cfg(feature = "high-level-url")]
1885    #[test]
1886    fn apply_content_length_rejects_unknown_stream_override() {
1887        let mut headers = Headers::new();
1888        headers.insert("content-length", "5").unwrap();
1889        let stream = futures_util::stream::empty::<Result<Bytes>>();
1890        let body = crate::body::RequestBody::from_stream(stream, None);
1891        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1892        assert_eq!(err.kind(), "request_build");
1893    }
1894
1895    #[cfg(feature = "high-level-url")]
1896    #[test]
1897    fn parse_url_rejects_userinfo_without_echoing_credentials() {
1898        let err = parse_url("https://user:secret@example.com").unwrap_err();
1899        assert_eq!(err.kind(), "invalid_url");
1900        assert!(!err.to_string().contains("secret"));
1901    }
1902
1903    #[cfg(feature = "proxy")]
1904    #[cfg(feature = "high-level-url")]
1905    #[tokio::test]
1906    async fn proxy_auth_conflict_with_header() {
1907        let proxy = Proxy::all("http://proxy.example:8080")
1908            .unwrap()
1909            .auth(ProxyAuth::basic("user", "pass").unwrap());
1910        let client = Client::builder().proxy(proxy).build();
1911        let request = client
1912            .get("http://destination.example")
1913            .unwrap()
1914            .header("proxy-authorization", "Basic dXNlcjpwYXNz")
1915            .build()
1916            .unwrap();
1917        let err = client.send(request).await.unwrap_err();
1918        assert_eq!(err.kind(), "conflicting_auth");
1919        assert!(err.to_string().contains("Proxy-Authorization"));
1920    }
1921
1922    #[cfg(feature = "proxy")]
1923    #[cfg(feature = "high-level-url")]
1924    #[tokio::test]
1925    async fn proxy_auth_no_conflict_without_header() {
1926        let proxy = Proxy::all("http://proxy.example:8080")
1927            .unwrap()
1928            .auth(ProxyAuth::basic("user", "pass").unwrap());
1929        let client = Client::builder().proxy(proxy).build();
1930        let request = client
1931            .get("http://destination.example")
1932            .unwrap()
1933            .build()
1934            .unwrap();
1935        let err = client.send(request).await.unwrap_err();
1936        assert_ne!(err.kind(), "conflicting_auth");
1937    }
1938
1939    #[cfg(feature = "proxy")]
1940    #[cfg(feature = "high-level-url")]
1941    #[tokio::test]
1942    async fn proxy_auth_no_conflict_with_header_only() {
1943        let proxy = Proxy::all("http://proxy.example:8080").unwrap();
1944        let client = Client::builder().proxy(proxy).build();
1945        let request = client
1946            .get("http://destination.example")
1947            .unwrap()
1948            .header("proxy-authorization", "Basic dXNlcjpwYXNz")
1949            .build()
1950            .unwrap();
1951        let err = client.send(request).await.unwrap_err();
1952        assert_ne!(err.kind(), "conflicting_auth");
1953    }
1954
1955    #[cfg(feature = "advanced-routing")]
1956    #[cfg(feature = "high-level-url")]
1957    #[test]
1958    fn resolved_route_key_matrix() {
1959        use crate::transport_hints::ResolvedTarget;
1960
1961        // Keys intentionally lack `Debug`/`Display` (connection identity
1962        // only, never request state), so compare with `==`/`!=`.
1963        let origin = url::Url::parse("http://origin.example/").unwrap();
1964        let target: ResolvedTarget =
1965            ResolvedTarget::new(["127.0.0.1:80".parse::<SocketAddr>().unwrap()]).unwrap();
1966        let base = ResolvedRouteKey::new(&origin, &target, None);
1967        let same = ResolvedRouteKey::new(&origin, &target, None);
1968        assert!(
1969            base == same,
1970            "same origin + same ordered addresses + same SNI must reuse"
1971        );
1972
1973        // Path/query/fragment never participate: same logical origin.
1974        let with_path = url::Url::parse("http://origin.example/a?b=1#f").unwrap();
1975        let other_path = url::Url::parse("http://origin.example/other").unwrap();
1976        assert!(
1977            ResolvedRouteKey::new(&with_path, &target, None)
1978                == ResolvedRouteKey::new(&other_path, &target, None),
1979            "path/query/fragment must not fragment resolved identity"
1980        );
1981        // Explicit default port normalizes to the same origin.
1982        let explicit_default = url::Url::parse("http://origin.example:80/").unwrap();
1983        assert!(
1984            ResolvedRouteKey::new(&origin, &target, None)
1985                == ResolvedRouteKey::new(&explicit_default, &target, None),
1986            "explicit default port must reuse"
1987        );
1988
1989        // HTTP vs HTTPS: logical/TLS origin differs.
1990        let https = url::Url::parse("https://origin.example/").unwrap();
1991        let https_target: ResolvedTarget =
1992            ResolvedTarget::new(["127.0.0.1:443".parse::<SocketAddr>().unwrap()]).unwrap();
1993        assert!(
1994            base != ResolvedRouteKey::new(&https, &https_target, None),
1995            "scheme change must fragment resolved identity"
1996        );
1997
1998        // Host differs: logical Host/TLS identity differs.
1999        let other_host = url::Url::parse("http://other.example/").unwrap();
2000        assert!(
2001            base != ResolvedRouteKey::new(&other_host, &target, None),
2002            "host change must fragment resolved identity"
2003        );
2004
2005        // Effective port differs: origin/socket identity differs.
2006        let other_port = url::Url::parse("http://origin.example:8080/").unwrap();
2007        let other_port_target: ResolvedTarget =
2008            ResolvedTarget::new(["127.0.0.1:8080".parse::<SocketAddr>().unwrap()]).unwrap();
2009        assert!(
2010            base != ResolvedRouteKey::new(&other_port, &other_port_target, None),
2011            "effective port change must fragment resolved identity"
2012        );
2013
2014        // One address differs: physical route differs.
2015        let other_addr: ResolvedTarget =
2016            ResolvedTarget::new(["127.0.0.2:80".parse::<SocketAddr>().unwrap()]).unwrap();
2017        assert!(
2018            base != ResolvedRouteKey::new(&origin, &other_addr, None),
2019            "address change must fragment resolved identity"
2020        );
2021
2022        // Same addresses, different order: attempt/failover order differs.
2023        let ordered: ResolvedTarget = ResolvedTarget::new([
2024            "127.0.0.1:80".parse::<SocketAddr>().unwrap(),
2025            "127.0.0.2:80".parse::<SocketAddr>().unwrap(),
2026        ])
2027        .unwrap();
2028        let reordered: ResolvedTarget = ResolvedTarget::new([
2029            "127.0.0.2:80".parse::<SocketAddr>().unwrap(),
2030            "127.0.0.1:80".parse::<SocketAddr>().unwrap(),
2031        ])
2032        .unwrap();
2033        assert!(
2034            ResolvedRouteKey::new(&origin, &ordered, None)
2035                != ResolvedRouteKey::new(&origin, &reordered, None),
2036            "address reorder must fragment resolved identity"
2037        );
2038
2039        // SNI None vs override: TLS identity differs.
2040        assert!(
2041            base != ResolvedRouteKey::new(&origin, &target, Some("sni.example")),
2042            "adding an SNI override must fragment resolved identity"
2043        );
2044
2045        // SNI override A vs B: TLS identity differs.
2046        assert!(
2047            ResolvedRouteKey::new(&origin, &target, Some("a.example"))
2048                != ResolvedRouteKey::new(&origin, &target, Some("b.example")),
2049            "SNI override change must fragment resolved identity"
2050        );
2051        assert!(
2052            ResolvedRouteKey::new(&origin, &target, Some("a.example"))
2053                == ResolvedRouteKey::new(&origin, &target, Some("a.example")),
2054            "same SNI override must reuse"
2055        );
2056    }
2057
2058    #[cfg(feature = "advanced-routing")]
2059    #[test]
2060    fn resolved_route_key_from_native_origin() {
2061        use crate::http_origin::HttpOrigin;
2062        use crate::transport_hints::ResolvedTarget;
2063
2064        let uri: http::Uri = "http://origin.example/".parse().expect("valid URI");
2065        let origin = HttpOrigin::from_uri(&uri).expect("native origin parses");
2066        let target = ResolvedTarget::new(["127.0.0.1:80".parse::<SocketAddr>().unwrap()]).unwrap();
2067        let base = ResolvedRouteKey::from_origin(&origin, &target, None);
2068        let same = ResolvedRouteKey::from_origin(&origin, &target, None);
2069        // Keys intentionally lack `Debug`/`Display`; compare with `==`/`!=`.
2070        assert!(
2071            base == same,
2072            "same native origin + addresses + SNI must reuse"
2073        );
2074
2075        // Explicit default port shares identity; scheme/host/port changes
2076        // fragment; address order and SNI fragment.
2077        let explicit: http::Uri = "http://origin.example:80/a?b=1".parse().expect("valid URI");
2078        let explicit_origin = HttpOrigin::from_uri(&explicit).expect("origin parses");
2079        assert!(
2080            base == ResolvedRouteKey::from_origin(&explicit_origin, &target, None),
2081            "explicit default port must reuse"
2082        );
2083
2084        let https: http::Uri = "https://origin.example/".parse().expect("valid URI");
2085        let https_origin = HttpOrigin::from_uri(&https).expect("origin parses");
2086        let https_target =
2087            ResolvedTarget::new(["127.0.0.1:443".parse::<SocketAddr>().unwrap()]).unwrap();
2088        assert!(
2089            base != ResolvedRouteKey::from_origin(&https_origin, &https_target, None),
2090            "scheme change must fragment resolved identity"
2091        );
2092        assert!(
2093            base != ResolvedRouteKey::from_origin(&origin, &target, Some("sni.example")),
2094            "SNI override must fragment resolved identity"
2095        );
2096    }
2097
2098    #[cfg(any(feature = "transport-http1", feature = "transport-http2"))]
2099    #[cfg(feature = "high-level-url")]
2100    #[cfg(feature = "advanced-routing")]
2101    #[test]
2102    fn resolved_route_cache_is_bounded() {
2103        use crate::transport::hyper_client::{
2104            BoundedClientCache, RESOLVED_CLIENT_CACHE_MAX_ENTRIES,
2105        };
2106        use crate::transport_hints::ResolvedTarget;
2107
2108        assert_eq!(
2109            RESOLVED_CLIENT_CACHE_MAX_ENTRIES, 64,
2110            "resolved-route cache uses the conservative 64-entry bound"
2111        );
2112        let mut cache: BoundedClientCache<ResolvedRouteKey, usize> =
2113            BoundedClientCache::new(RESOLVED_CLIENT_CACHE_MAX_ENTRIES);
2114        for index in 0..(RESOLVED_CLIENT_CACHE_MAX_ENTRIES + 16) {
2115            let origin =
2116                url::Url::parse(&format!("http://host-{index}.example/")).expect("valid URL");
2117            let target =
2118                ResolvedTarget::new(["127.0.0.1:80".parse::<SocketAddr>().expect("valid addr")])
2119                    .expect("non-empty");
2120            cache.insert(ResolvedRouteKey::new(&origin, &target, None), index);
2121            assert!(
2122                cache.len() <= RESOLVED_CLIENT_CACHE_MAX_ENTRIES,
2123                "insertion beyond capacity must not grow the cache"
2124            );
2125        }
2126        assert_eq!(cache.len(), RESOLVED_CLIENT_CACHE_MAX_ENTRIES);
2127    }
2128}