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