Skip to main content

eggfetch_core/
client.rs

1//! Async client entry point.
2
3use std::collections::HashMap;
4use std::sync::Arc;
5use std::time::Duration;
6
7use http::Method;
8use hyper_util::rt::TokioExecutor;
9use tokio::sync::Mutex;
10
11use crate::error::{Error, Result};
12use crate::headers::Headers;
13use crate::http_version::HttpVersionPolicy;
14use crate::limits::Limits;
15use crate::pool::{Pool, PoolConfig, PoolMetrics};
16#[cfg(feature = "proxy")]
17use crate::proxy::Proxy;
18use crate::redirect::RedirectPolicy;
19use crate::request::{Request, RequestBuilder};
20use crate::response::Response;
21use crate::retry::RetryPolicy;
22use crate::timeout::Timeout;
23use crate::transport::Connector;
24
25#[cfg(feature = "cookies")]
26use crate::cookie::CookieJar;
27
28/// Shared client configuration.
29///
30/// `Debug` is intentionally manual: several fields hold secrets (notably
31/// the cookie jar), so the implementation redacts them instead of deriving
32/// a verbatim dump. See [`crate::redact`].
33#[derive(Clone)]
34pub(crate) struct ClientConfig {
35    pub(crate) default_headers: Headers,
36    pub(crate) user_agent: Option<String>,
37    pub(crate) timeout: Option<Timeout>,
38    pub(crate) redirect: RedirectPolicy,
39    pub(crate) auth: Option<crate::auth::AuthScheme>,
40    #[cfg(feature = "cookies")]
41    pub(crate) cookie_jar: CookieJar,
42    pub(crate) automatic_decompression: bool,
43    pub(crate) max_decoded_body_size: Option<usize>,
44    pub(crate) max_decompression_ratio: Option<f64>,
45    #[cfg(feature = "proxy")]
46    pub(crate) proxy: Option<Proxy>,
47    #[cfg(feature = "proxy")]
48    pub(crate) environment_proxies: Vec<Proxy>,
49    #[cfg(any(feature = "proxy", feature = "http3"))]
50    pub(crate) tls_config: Option<crate::tls::TlsConfig>,
51    pub(crate) retry: Option<RetryPolicy>,
52    #[allow(
53        dead_code,
54        reason = "stored for inspection and future request-level use"
55    )]
56    pub(crate) http_version_policy: HttpVersionPolicy,
57}
58
59impl std::fmt::Debug for ClientConfig {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        let mut debug = f.debug_struct("ClientConfig");
62        debug
63            .field("default_headers", &self.default_headers)
64            .field("user_agent", &self.user_agent)
65            .field("timeout", &self.timeout)
66            .field("redirect", &self.redirect)
67            .field("auth", &self.auth);
68        #[cfg(feature = "cookies")]
69        debug.field("cookie_jar", &self.cookie_jar);
70        debug
71            .field("automatic_decompression", &self.automatic_decompression)
72            .field("max_decoded_body_size", &self.max_decoded_body_size)
73            .field("max_decompression_ratio", &self.max_decompression_ratio);
74        #[cfg(feature = "proxy")]
75        debug
76            .field("proxy", &self.proxy)
77            .field("environment_proxies", &self.environment_proxies);
78        #[cfg(any(feature = "proxy", feature = "http3"))]
79        debug.field("tls_config", &self.tls_config);
80        debug
81            .field("retry", &self.retry)
82            .field("http_version_policy", &self.http_version_policy)
83            .finish_non_exhaustive()
84    }
85}
86
87impl Default for ClientConfig {
88    fn default() -> Self {
89        Self {
90            default_headers: Headers::new(),
91            user_agent: None,
92            timeout: None,
93            redirect: RedirectPolicy::default(),
94            auth: None,
95            #[cfg(feature = "cookies")]
96            cookie_jar: CookieJar::new(),
97            automatic_decompression: true,
98            max_decoded_body_size: None,
99            max_decompression_ratio: None,
100            #[cfg(feature = "proxy")]
101            proxy: None,
102            #[cfg(feature = "proxy")]
103            environment_proxies: Vec::new(),
104            #[cfg(any(feature = "proxy", feature = "http3"))]
105            tls_config: None,
106            retry: None,
107            http_version_policy: HttpVersionPolicy::default(),
108        }
109    }
110}
111
112/// Async HTTP client.
113///
114/// The client manages connection pooling and shared configuration. Create one
115/// with [`Client::new`] or [`Client::builder`].
116#[derive(Clone)]
117pub struct Client {
118    inner: Arc<ClientInner>,
119}
120
121impl std::fmt::Debug for Client {
122    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123        f.debug_struct("Client").finish_non_exhaustive()
124    }
125}
126
127pub(crate) struct ClientInner {
128    pub(crate) hyper_client: Option<crate::transport::TimeoutHyperClient>,
129    /// Error captured while building the configured TLS policy, if any.
130    ///
131    /// `ClientBuilder::build` is intentionally infallible, so HTTPS requests
132    /// surface this error at dispatch time instead of falling back to a
133    /// different trust policy.
134    pub(crate) tls_config_error: Option<String>,
135    /// Direct connector for requests with advanced socket options or local
136    /// address binding. Uses a custom connector instead of the standard
137    /// hyper-rustls connector path.
138    pub(crate) direct_client: Option<crate::transport::TimeoutDirectClient>,
139    /// Base direct-connector configuration (local address / socket options)
140    /// used to construct SNI-override clients so they preserve source
141    /// binding and socket tuning.
142    pub(crate) direct_connector_config:
143        Option<crate::transport::direct_connector::DirectConnectorConfig>,
144    /// Cached hyper clients keyed by TLS SNI hostname override.
145    ///
146    /// When a request carries `TransportHints.sni_hostname`, the pipeline
147    /// uses a DirectConnector-based client from this cache. The connector
148    /// separates DNS/TCP (to the original URL host) from TLS (with the
149    /// SNI override hostname), keeping the default path unchanged.
150    ///
151    /// Bounded by [`SNI_CLIENT_CACHE_MAX_ENTRIES`] with arbitrary-entry
152    /// eviction so long-lived processes touching many hostnames cannot
153    /// grow it without limit.
154    ///
155    /// The cache is keyed only by hostname because `ClientInner::config`
156    /// (including `http_version_policy` and `tls_config` ALPN) is immutable
157    /// after `ClientBuilder::build`. If the TLS ALPN ever became mutable,
158    /// this cache would need to include `HttpVersionPolicy` (and
159    /// `tls_config` identity) in the key to avoid serving a client with
160    /// stale ALPN (e.g. H2 vs H1) for the same hostname.
161    pub(crate) sni_clients: Mutex<HashMap<String, crate::transport::TimeoutDirectClient>>,
162    /// Hyper client for Unix domain socket requests.
163    #[cfg(unix)]
164    pub(crate) uds_client: Option<crate::transport::TimeoutUdsClient>,
165    /// Persistent Hyper clients keyed by effective SOCKS route.
166    ///
167    /// Bounded like [`ClientInner::sni_clients`].
168    #[cfg(feature = "proxy")]
169    pub(crate) socks_clients: Mutex<
170        HashMap<crate::transport::socks::SocksRouteKey, crate::transport::TimeoutSocksClient>,
171    >,
172    pub(crate) config: ClientConfig,
173    pub(crate) pool: Pool,
174    /// Transport observability counters shared by all connectors owned by
175    /// this client. Distinct from [`Pool`] logical-permit metrics.
176    pub(crate) transport_metrics: Arc<crate::transport::metrics::TransportMetrics>,
177    #[cfg(feature = "http3")]
178    pub(crate) h3_connector: Option<crate::transport::http3::H3Connector>,
179    /// Bounded Alt-Svc discovery state (separate from QUIC sessions).
180    /// Owned here so all routes share one view. Only present with `http3`;
181    /// without it there is no discovery and no state to keep.
182    #[cfg(feature = "http3")]
183    pub(crate) alt_svc_state: Arc<crate::transport::alt_svc::AltSvcState>,
184}
185
186/// Upper bound on cached SNI-keyed hyper clients.
187const SNI_CLIENT_CACHE_MAX_ENTRIES: usize = 256;
188
189/// Upper bound on cached SOCKS-route hyper clients.
190#[cfg(feature = "proxy")]
191const SOCKS_CLIENT_CACHE_MAX_ENTRIES: usize = 64;
192
193/// Evict an arbitrary entry when a bounded client cache reaches capacity.
194///
195/// Entries hold pooled connections but no unsynchronized state, so any
196/// entry can be dropped safely; the next request recreates it lazily.
197/// Eviction is hash-order arbitrary via `HashMap::keys().next()`; with the
198/// bounded caps (`256` for SNI, `64` for SOCKS) this is acceptable and
199/// avoids an extra LRU dependency for a low-churn cache.
200fn evict_one<K: std::clone::Clone + Eq + std::hash::Hash, V>(map: &mut HashMap<K, V>) {
201    if let Some(key) = map.keys().next().cloned() {
202        map.remove(&key);
203    }
204}
205
206/// Apply the selected HTTP protocol policy to a rustls client configuration.
207///
208/// The standard hyper-rustls connector applies this policy while building its
209/// connector. Custom connectors must set the same ALPN list themselves.
210pub(crate) fn configure_tls_alpn(
211    mut config: rustls::ClientConfig,
212    policy: crate::http_version::HttpVersionPolicyEnabler,
213) -> rustls::ClientConfig {
214    config.alpn_protocols.clear();
215    if policy.enable_http2() {
216        config.alpn_protocols.push(b"h2".to_vec());
217    }
218    if policy.enable_http1() {
219        config.alpn_protocols.push(b"http/1.1".to_vec());
220    }
221    config
222}
223
224impl ClientInner {
225    /// Get or create a cached hyper client with TLS SNI hostname override.
226    ///
227    /// The returned client uses a [`DirectConnector`](crate::transport::direct_connector::DirectConnector)
228    /// that separates DNS/TCP resolution (to the original URL host) from
229    /// TLS negotiation (with the SNI hostname). Clients are cached by
230    /// SNI hostname for connection reuse.
231    pub(crate) async fn sni_client(
232        &self,
233        sni_hostname: &str,
234    ) -> Result<crate::transport::TimeoutDirectClient> {
235        let mut clients = self.sni_clients.lock().await;
236        if let Some(client) = clients.get(sni_hostname) {
237            return Ok(client.clone());
238        }
239
240        let connect_timeout = self.config.timeout.as_ref().and_then(|t| t.connect);
241        #[cfg(any(feature = "http2", feature = "http3", feature = "proxy"))]
242        let policy = self.config.http_version_policy;
243
244        #[cfg(any(feature = "proxy", feature = "http3"))]
245        let tls_connector = match self.config.tls_config.as_ref() {
246            Some(tls_config) => {
247                let rc = tls_config
248                    .build_rustls_config()
249                    .map_err(|e| Error::Tls(format!("failed to build TLS config: {e}")))?;
250                let rc = configure_tls_alpn(
251                    rc,
252                    crate::http_version::HttpVersionPolicyEnabler::from_policy(policy),
253                );
254                Some(tokio_rustls::TlsConnector::from(Arc::new(rc)))
255            }
256            None => None,
257        };
258        #[cfg(not(any(feature = "proxy", feature = "http3")))]
259        let tls_connector = None;
260
261        let base_config = self.direct_connector_config.clone().unwrap_or(
262            crate::transport::direct_connector::DirectConnectorConfig {
263                local_address: None,
264                socket_options: Vec::new(),
265            },
266        );
267        let base_connector = crate::transport::direct_connector::DirectConnector::with_metrics(
268            base_config,
269            tls_connector,
270            self.transport_metrics.clone(),
271        );
272        let sni_connector = base_connector.with_sni(sni_hostname.to_owned());
273        let connector =
274            crate::transport::connect_timeout::ConnectTimeout::new(sni_connector, connect_timeout);
275
276        let mut builder =
277            hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new());
278        #[cfg(feature = "http2")]
279        if matches!(policy, crate::HttpVersionPolicy::Http2Only) {
280            builder.http2_only(true);
281        }
282        // Idle-connection lifetime comes from the pool configuration
283        // (`Limits::keepalive_expiry`), matching the standard, direct,
284        // and UDS paths. `Timeout.pool`/`total` are acquisition budgets
285        // and must not close idle connections early.
286        if let Some(idle_timeout) = self.pool.idle_timeout() {
287            builder.pool_idle_timeout(idle_timeout);
288        }
289        let client = builder.build(connector);
290        if clients.len() >= SNI_CLIENT_CACHE_MAX_ENTRIES {
291            evict_one(&mut clients);
292        }
293        clients.insert(sni_hostname.to_owned(), client.clone());
294        Ok(client)
295    }
296}
297
298#[cfg(feature = "proxy")]
299impl ClientInner {
300    pub(crate) async fn socks_client(
301        &self,
302        proxy: &crate::proxy::ProxyConfig,
303    ) -> Result<crate::transport::TimeoutSocksClient> {
304        let key = crate::transport::socks::SocksRouteKey::from_proxy(proxy)?;
305        let mut clients = self.socks_clients.lock().await;
306        if let Some(client) = clients.get(&key) {
307            return Ok(client.clone());
308        }
309
310        let policy = self.config.http_version_policy;
311
312        let tls_config = if let Some(config) = self.config.tls_config.as_ref() {
313            config
314                .build_rustls_config()
315                .map_err(|e| Error::Tls(format!("failed to build SOCKS TLS config: {e}")))?
316        } else {
317            let roots = crate::tls::TlsConfig::fallback_root_store();
318            rustls::ClientConfig::builder()
319                .with_root_certificates(roots)
320                .with_no_client_auth()
321        };
322        let tls_config = configure_tls_alpn(
323            tls_config,
324            crate::http_version::HttpVersionPolicyEnabler::from_policy(policy),
325        );
326        let connector = crate::transport::socks::SocksConnector::new(
327            proxy.clone(),
328            Some(tokio_rustls::TlsConnector::from(Arc::new(tls_config))),
329            None,
330        );
331        let connector = crate::transport::connect_timeout::ConnectTimeout::new(
332            connector,
333            self.config
334                .timeout
335                .as_ref()
336                .and_then(|timeout| timeout.connect),
337        );
338        let mut builder =
339            hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new());
340        #[cfg(feature = "http2")]
341        if matches!(policy, crate::HttpVersionPolicy::Http2Only) {
342            builder.http2_only(true);
343        }
344        let client = builder.build(connector);
345        if clients.len() >= SOCKS_CLIENT_CACHE_MAX_ENTRIES {
346            evict_one(&mut clients);
347        }
348        clients.insert(key, client.clone());
349        Ok(client)
350    }
351}
352
353impl Client {
354    /// Create a new client with default settings.
355    #[must_use]
356    pub fn new() -> Self {
357        Self::builder().build()
358    }
359
360    /// Create a [`ClientBuilder`] for configuring a client.
361    #[must_use]
362    pub fn builder() -> ClientBuilder {
363        ClientBuilder::new()
364    }
365
366    /// Create a GET request builder for the given URL.
367    ///
368    /// # Errors
369    ///
370    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
371    pub fn get(&self, url: &str) -> Result<RequestBuilder> {
372        self.request(Method::GET, url)
373    }
374
375    /// Create a POST request builder for the given URL.
376    ///
377    /// # Errors
378    ///
379    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
380    pub fn post(&self, url: &str) -> Result<RequestBuilder> {
381        self.request(Method::POST, url)
382    }
383
384    /// Create a PUT request builder for the given URL.
385    ///
386    /// # Errors
387    ///
388    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
389    pub fn put(&self, url: &str) -> Result<RequestBuilder> {
390        self.request(Method::PUT, url)
391    }
392
393    /// Create a PATCH request builder for the given URL.
394    ///
395    /// # Errors
396    ///
397    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
398    pub fn patch(&self, url: &str) -> Result<RequestBuilder> {
399        self.request(Method::PATCH, url)
400    }
401
402    /// Create a DELETE request builder for the given URL.
403    ///
404    /// # Errors
405    ///
406    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
407    pub fn delete(&self, url: &str) -> Result<RequestBuilder> {
408        self.request(Method::DELETE, url)
409    }
410
411    /// Create a HEAD request builder for the given URL.
412    ///
413    /// # Errors
414    ///
415    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
416    pub fn head(&self, url: &str) -> Result<RequestBuilder> {
417        self.request(Method::HEAD, url)
418    }
419
420    /// Create an OPTIONS request builder for the given URL.
421    ///
422    /// # Errors
423    ///
424    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
425    pub fn options(&self, url: &str) -> Result<RequestBuilder> {
426        self.request(Method::OPTIONS, url)
427    }
428
429    /// Create a request builder for the given method and URL.
430    ///
431    /// # Errors
432    ///
433    /// Returns [`Error::InvalidUrl`] if `url` cannot be parsed.
434    pub fn request(&self, method: Method, url: &str) -> Result<RequestBuilder> {
435        let parsed = parse_url(url)?;
436        Ok(RequestBuilder::new(self.clone(), method, parsed))
437    }
438
439    /// Returns a reference to the connection pool metrics.
440    ///
441    /// These count logical request-permit waits/cancellations. For
442    /// connector/protocol observations see [`Self::transport_metrics`].
443    #[must_use]
444    pub fn pool_metrics(&self) -> &PoolMetrics {
445        self.inner.pool.metrics()
446    }
447
448    /// Returns a reference to the transport observability counters.
449    ///
450    /// Counts connector events (DNS/connect/TLS attempts) and protocol
451    /// connections (H3 sessions, 101 upgrades) where observable. Hyper
452    /// socket-reuse counts are intentionally absent.
453    #[must_use]
454    pub fn transport_metrics(&self) -> &crate::transport::metrics::TransportMetrics {
455        &self.inner.transport_metrics
456    }
457
458    /// Returns a reference to the client's cookie jar.
459    ///
460    /// Only available when the `cookies` feature is enabled.
461    #[cfg(feature = "cookies")]
462    #[must_use]
463    pub fn cookies(&self) -> &CookieJar {
464        &self.inner.config.cookie_jar
465    }
466
467    /// Returns a reference to the shared client configuration.
468    #[must_use]
469    pub(crate) fn config(&self) -> &ClientConfig {
470        &self.inner.config
471    }
472
473    /// Send a request and return the response, following redirects if
474    /// the client's redirect policy allows.
475    ///
476    /// The redirect loop enforces `max_redirects`, performs method
477    /// rewrites per HTTP semantics, strips sensitive headers on
478    /// cross-origin hops, and records redirect history.
479    ///
480    /// If a retry policy is configured (on the client or request), the
481    /// entire logical request is retried on failure according to the
482    /// policy.
483    ///
484    /// # Errors
485    ///
486    /// Returns an error if the request fails at any stage (connect, TLS,
487    /// protocol, body) or if a timeout elapses.
488    pub(crate) async fn send(&self, request: Request) -> Result<Response> {
489        Box::pin(crate::pipeline::send_with_retry(self, request)).await
490    }
491
492    /// Send a single HTTP request and return the streaming response.
493    ///
494    /// This handles pool acquisition, timeout application, and body
495    /// processing for one request/response cycle. It does NOT handle
496    /// redirects—that is the responsibility of [`Client::send`].
497    pub(crate) async fn send_single_request(
498        &self,
499        request: Request,
500        timeout: &Timeout,
501    ) -> Result<Response> {
502        crate::pipeline::send_single_request(&self.inner, request, timeout).await
503    }
504}
505
506impl Default for Client {
507    fn default() -> Self {
508        Self::new()
509    }
510}
511
512/// Builder for configuring a [`Client`].
513pub struct ClientBuilder {
514    default_headers: Headers,
515    user_agent: Option<String>,
516    pool_config: PoolConfig,
517    timeout: Option<Timeout>,
518    limits: Option<Limits>,
519    redirect: RedirectPolicy,
520    auth: Option<crate::auth::AuthScheme>,
521    #[cfg(feature = "cookies")]
522    cookie_jar: Option<CookieJar>,
523    automatic_decompression: Option<bool>,
524    max_decoded_body_size: Option<usize>,
525    max_decompression_ratio: Option<f64>,
526    #[cfg(feature = "proxy")]
527    proxy: Option<Proxy>,
528    #[cfg(feature = "proxy")]
529    environment_proxies: Vec<Proxy>,
530    tls_config: Option<crate::tls::TlsConfig>,
531    retry: Option<RetryPolicy>,
532    http_version_policy: HttpVersionPolicy,
533    /// Advanced direct-connector config for socket options / local address.
534    direct_connector_config: Option<crate::transport::direct_connector::DirectConnectorConfig>,
535    /// Unix domain socket path. When set, all requests use UDS transport.
536    uds_path: Option<String>,
537}
538
539impl ClientBuilder {
540    /// Create a new client builder with defaults.
541    #[must_use]
542    pub fn new() -> Self {
543        Self {
544            default_headers: Headers::new(),
545            user_agent: None,
546            pool_config: PoolConfig::default(),
547            timeout: None,
548            limits: None,
549            redirect: RedirectPolicy::default(),
550            auth: None,
551            #[cfg(feature = "cookies")]
552            cookie_jar: None,
553            automatic_decompression: None,
554            max_decoded_body_size: None,
555            max_decompression_ratio: None,
556            #[cfg(feature = "proxy")]
557            proxy: None,
558            #[cfg(feature = "proxy")]
559            environment_proxies: Vec::new(),
560            tls_config: None,
561            retry: None,
562            http_version_policy: HttpVersionPolicy::default(),
563            direct_connector_config: None,
564            uds_path: None,
565        }
566    }
567
568    /// Add a default header to all requests made by this client.
569    ///
570    /// # Errors
571    ///
572    /// Returns an error if `name` or `value` is not a valid header field.
573    pub fn default_header(mut self, name: &str, value: &str) -> Result<Self> {
574        self.default_headers.insert(name, value)?;
575        Ok(self)
576    }
577
578    /// Set the default headers for all requests made by this client.
579    ///
580    /// This preserves valid header values containing HTTP `obs-text` bytes.
581    #[must_use]
582    pub fn default_headers(mut self, headers: Headers) -> Self {
583        self.default_headers = headers;
584        self
585    }
586
587    /// Set the default user-agent header.
588    #[must_use]
589    pub fn user_agent(mut self, agent: &str) -> Self {
590        self.user_agent = Some(agent.to_owned());
591        self
592    }
593
594    /// Set the maximum number of idle (unused) connections kept per host.
595    ///
596    /// This is a convenience alias for [`max_idle_connections_per_host`]:
597    /// the transport enforces the limit on a per-host basis, so total
598    /// idle connections grow with the number of distinct origins. Use
599    /// [`max_connections`] for a global concurrency cap.
600    ///
601    /// [`max_idle_connections_per_host`]: Self::max_idle_connections_per_host
602    /// [`max_connections`]: Self::max_connections
603    #[must_use]
604    pub fn max_idle_connections(mut self, max: usize) -> Self {
605        self.pool_config.max_idle_connections = Some(max);
606        self
607    }
608
609    /// Set the maximum number of idle connections per individual host.
610    #[must_use]
611    pub fn max_idle_connections_per_host(mut self, max: usize) -> Self {
612        self.pool_config.max_idle_connections_per_host = Some(max);
613        self
614    }
615
616    /// Set the maximum total number of concurrent in-flight requests.
617    ///
618    /// Compatibility alias for [`Self::max_in_flight_requests`] kept for
619    /// the pre-1.0 line. One permit equals one logical request, not one
620    /// TCP connection (H2/H3 multiplex many requests over one
621    /// connection). Prefer `max_in_flight_requests` in new code.
622    #[must_use]
623    pub fn max_connections(mut self, max: usize) -> Self {
624        self.pool_config.max_connections = Some(max);
625        self
626    }
627
628    /// Set the maximum number of concurrent in-flight requests per origin.
629    ///
630    /// Compatibility alias for [`Self::max_in_flight_requests_per_origin`].
631    #[must_use]
632    pub fn max_connections_per_host(mut self, max: usize) -> Self {
633        self.pool_config.max_connections_per_host = Some(max);
634        self
635    }
636
637    /// Set the maximum total number of concurrent in-flight requests.
638    ///
639    /// Preferred native name. Bounds logical request concurrency (one
640    /// permit per request). Under H1 one request typically owns its
641    /// connection slot; under H2/H3 many permits multiplex over one
642    /// TCP/QUIC connection. When both this and `max_connections` are
643    /// set, this wins.
644    #[must_use]
645    pub fn max_in_flight_requests(mut self, max: usize) -> Self {
646        self.pool_config.max_in_flight_requests = Some(max);
647        self
648    }
649
650    /// Set the maximum number of concurrent in-flight requests per origin.
651    ///
652    /// Preferred native name. When both this and
653    /// `max_connections_per_host` are set, this wins.
654    #[must_use]
655    pub fn max_in_flight_requests_per_origin(mut self, max: usize) -> Self {
656        self.pool_config.max_in_flight_requests_per_origin = Some(max);
657        self
658    }
659
660    /// Set the duration after which idle connections are closed.
661    #[must_use]
662    pub fn idle_timeout(mut self, timeout: Duration) -> Self {
663        self.pool_config.idle_timeout = Some(timeout);
664        self
665    }
666
667    /// Set the default timeout for all requests made by this client.
668    #[must_use]
669    pub fn timeout(mut self, timeout: Timeout) -> Self {
670        self.timeout = Some(timeout);
671        self
672    }
673
674    /// Merge a partial timeout configuration into the currently configured
675    /// timeout.
676    ///
677    /// Unlike [`timeout`](Self::timeout), which replaces the entire
678    /// configuration, each phase set in `timeout` overrides only that
679    /// phase; unset phases keep any previously configured value (or
680    /// remain unset when no timeout was configured yet).
681    #[must_use]
682    pub fn merge_timeout(mut self, timeout: Timeout) -> Self {
683        let merged = match self.timeout {
684            Some(existing) => existing.merge(Some(timeout)),
685            None => timeout,
686        };
687        self.timeout = Some(merged);
688        self
689    }
690
691    /// Set resource limits for the connection pool.
692    ///
693    /// Limits control logical request concurrency (pool permits) and
694    /// physical connection behavior (idle connection caps and expiry).
695    /// When set, the limits are applied to the pool configuration.
696    #[must_use]
697    pub fn limits(mut self, limits: Limits) -> Self {
698        self.limits = Some(limits);
699        self
700    }
701
702    /// Set the redirect policy for this client.
703    #[must_use]
704    pub fn follow_redirects(mut self, follow: bool) -> Self {
705        self.redirect.follow = follow;
706        self
707    }
708
709    /// Set the maximum number of redirects to follow.
710    #[must_use]
711    pub fn max_redirects(mut self, max: usize) -> Self {
712        self.redirect.max_redirects = max;
713        self
714    }
715
716    /// Set the full redirect policy.
717    #[must_use]
718    pub fn redirect_policy(mut self, policy: RedirectPolicy) -> Self {
719        self.redirect = policy;
720        self
721    }
722
723    /// Set a shared cookie jar for this client.
724    ///
725    /// When set, the client will automatically inject matching cookies
726    /// into requests and update the jar from `Set-Cookie` response headers.
727    ///
728    /// Only available when the `cookies` feature is enabled.
729    #[cfg(feature = "cookies")]
730    #[must_use]
731    pub fn cookie_jar(mut self, jar: CookieJar) -> Self {
732        self.cookie_jar = Some(jar);
733        self
734    }
735
736    /// Set default authentication for all requests made by this client.
737    ///
738    /// The configured auth is applied to every request unless overridden
739    /// or disabled at the request level. Auth is recomputed per redirect
740    /// hop; cross-origin redirects never carry client auth.
741    #[must_use]
742    pub fn auth(mut self, auth: impl Into<crate::auth::AuthScheme>) -> Self {
743        self.auth = Some(auth.into());
744        self
745    }
746
747    /// Set the default proxy for all requests made by this client.
748    ///
749    /// When set, all matching requests are routed through the specified
750    /// proxy. Can be overridden or disabled per-request.
751    #[cfg(feature = "proxy")]
752    #[must_use]
753    pub fn proxy(mut self, proxy: Proxy) -> Self {
754        self.proxy = Some(proxy);
755        self
756    }
757
758    /// Add a scheme-specific proxy used when no explicit proxy is configured.
759    #[cfg(feature = "proxy")]
760    #[must_use]
761    pub fn environment_proxy(mut self, proxy: Proxy) -> Self {
762        self.environment_proxies.push(proxy);
763        self
764    }
765
766    /// Set `NO_PROXY` bypass rules for the default proxy.
767    ///
768    /// When set, URLs matching any bypass rule are sent directly
769    /// without going through the proxy.
770    #[cfg(feature = "proxy")]
771    #[must_use]
772    pub fn no_proxy(mut self, no_proxy: crate::proxy::NoProxy) -> Self {
773        if let Some(proxy) = self.proxy.take() {
774            self.proxy = Some(proxy.no_proxy(no_proxy));
775        }
776        self
777    }
778
779    /// Set a custom TLS configuration for this client.
780    ///
781    /// When set, the client uses the provided [`crate::tls::TlsConfig`] for all
782    /// TLS connections instead of the default native-root-with-webpki-fallback
783    /// strategy.
784    #[must_use]
785    pub fn tls_config(mut self, config: crate::tls::TlsConfig) -> Self {
786        self.tls_config = Some(config);
787        self
788    }
789
790    /// Enable or disable insecure TLS verification while retaining other
791    /// TLS configuration already applied to this builder.
792    #[must_use]
793    pub fn danger_accept_invalid_certs(mut self, accept: bool) -> Self {
794        let config = self.tls_config.take().unwrap_or_default();
795        self.tls_config = Some(config.danger_accept_invalid_certs(accept));
796        self
797    }
798
799    /// Enable or disable automatic response decompression.
800    ///
801    /// When enabled (the default), the client sends an
802    /// `Accept-Encoding` header and transparently decompresses
803    /// response bodies. Decoded `Content-Encoding` and
804    /// `Content-Length` headers are removed from the response.
805    ///
806    /// Can be overridden per-request via
807    /// [`RequestBuilder::decompress`].
808    #[must_use]
809    pub fn automatic_decompression(mut self, enabled: bool) -> Self {
810        self.automatic_decompression = Some(enabled);
811        self
812    }
813
814    /// Set the maximum decoded response body size in bytes.
815    /// When set, responses whose decompressed body exceeds this limit
816    /// produce an error instead of buffering the full content.
817    #[must_use]
818    pub fn max_decoded_body_size(mut self, max: usize) -> Self {
819        self.max_decoded_body_size = Some(max);
820        self
821    }
822
823    /// Set the maximum decompression ratio (decoded bytes / compressed bytes).
824    /// When set, responses whose expansion ratio exceeds this limit produce
825    /// an error. This guards against zip-bomb style attacks.
826    ///
827    /// # Panics
828    ///
829    /// Panics if `ratio` is not finite or not positive.
830    #[must_use]
831    pub fn max_decompression_ratio(mut self, ratio: f64) -> Self {
832        assert!(
833            ratio.is_finite() && ratio > 0.0,
834            "max_decompression_ratio must be finite and positive, got {ratio}"
835        );
836        self.max_decompression_ratio = Some(ratio);
837        self
838    }
839
840    /// Set the retry policy for this client.
841    ///
842    /// When set, failed requests that match the policy (safe methods,
843    /// retryable statuses/errors, replayable bodies) are automatically
844    /// retried with exponential backoff.
845    #[must_use]
846    pub fn retry(mut self, policy: RetryPolicy) -> Self {
847        self.retry = Some(policy);
848        self
849    }
850
851    /// Set the HTTP version policy for this client.
852    ///
853    /// Controls which HTTP protocol versions the client may negotiate.
854    /// The default is [`HttpVersionPolicy::Auto`], which allows HTTP/2
855    /// negotiation via ALPN when the `http2` feature is enabled.
856    ///
857    /// When the `http2` feature is not compiled in, `Http2Only` and `Auto`
858    /// are silently downgraded to `Http1Only`.
859    #[must_use]
860    pub fn http_version_policy(mut self, policy: HttpVersionPolicy) -> Self {
861        self.http_version_policy = policy;
862        self
863    }
864
865    /// Set a local address to bind outbound sockets to before connecting.
866    ///
867    /// When set, all direct (non-proxy, non-UDS) connections will bind
868    /// to the specified local address before connecting to the remote.
869    /// This uses a custom connector path instead of the standard
870    /// hyper-rustls connector.
871    #[must_use]
872    pub fn local_address(mut self, addr: std::net::SocketAddr) -> Self {
873        let config = self.direct_connector_config.get_or_insert_with(|| {
874            crate::transport::direct_connector::DirectConnectorConfig {
875                local_address: None,
876                socket_options: Vec::new(),
877            }
878        });
879        config.local_address = Some(addr);
880        self
881    }
882
883    /// Set socket options to apply to outbound TCP connections.
884    ///
885    /// Options are applied to the socket before the connect operation.
886    /// Recognized options are applied via `tokio::net::TcpSocket` setters;
887    /// unrecognized options produce a connection error (never silently
888    /// ignored, per the plan's Track 2.4 requirement).
889    #[must_use]
890    pub fn socket_options(
891        mut self,
892        options: Vec<crate::transport::direct_connector::SocketOption>,
893    ) -> Self {
894        let config = self.direct_connector_config.get_or_insert_with(|| {
895            crate::transport::direct_connector::DirectConnectorConfig {
896                local_address: None,
897                socket_options: Vec::new(),
898            }
899        });
900        config.socket_options = options;
901        self
902    }
903
904    /// Set a Unix domain socket path for all connections.
905    ///
906    /// When set, all requests are routed through the specified UDS path
907    /// instead of making TCP connections. The URL in the request still
908    /// provides HTTP scheme/authority/path semantics.
909    ///
910    /// Only supported on Unix platforms. On non-Unix platforms, this
911    /// option is accepted but will produce an error at request time.
912    #[must_use]
913    pub fn uds_path(mut self, path: String) -> Self {
914        self.uds_path = Some(path);
915        self
916    }
917
918    /// Build the client.
919    ///
920    /// Native system roots are preferred. If the platform root store is
921    /// unavailable, the client falls back to the packaged Mozilla root set
922    /// while retaining certificate and hostname verification.
923    #[must_use]
924    #[allow(clippy::too_many_lines)]
925    pub fn build(self) -> Client {
926        use crate::http_version::HttpVersionPolicyEnabler;
927        let enabler = HttpVersionPolicyEnabler::from_policy(self.http_version_policy);
928        let transport_metrics = Arc::new(crate::transport::metrics::TransportMetrics::new());
929
930        let mut pool_config = self.pool_config;
931        if let Some(limits) = self.limits {
932            let limits_config: PoolConfig = limits.into();
933            if limits_config.max_connections.is_some() {
934                pool_config.max_connections = limits_config.max_connections;
935            }
936            if limits_config.max_connections_per_host.is_some() {
937                pool_config.max_connections_per_host = limits_config.max_connections_per_host;
938            }
939            if limits_config.max_in_flight_requests.is_some() {
940                pool_config.max_in_flight_requests = limits_config.max_in_flight_requests;
941            }
942            if limits_config.max_in_flight_requests_per_origin.is_some() {
943                pool_config.max_in_flight_requests_per_origin =
944                    limits_config.max_in_flight_requests_per_origin;
945            }
946            if limits_config.max_idle_connections.is_some() {
947                pool_config.max_idle_connections = limits_config.max_idle_connections;
948            }
949            if limits_config.max_idle_connections_per_host.is_some() {
950                pool_config.max_idle_connections_per_host =
951                    limits_config.max_idle_connections_per_host;
952            }
953            if limits_config.idle_timeout.is_some() {
954                pool_config.idle_timeout = limits_config.idle_timeout;
955            }
956        }
957
958        #[cfg(feature = "cookies")]
959        let cookie_jar = self.cookie_jar.unwrap_or_default();
960
961        let automatic_decompression = self.automatic_decompression.unwrap_or(true);
962        let tls_config_result = self
963            .tls_config
964            .as_ref()
965            .map(crate::tls::TlsConfig::build_rustls_config);
966        let tls_config_error = tls_config_result.as_ref().and_then(|result| {
967            result
968                .as_ref()
969                .err()
970                .map(|error| format!("failed to build TLS config: {error}"))
971        });
972
973        // `Http3Only` is strict direct-QUIC and needs no Hyper client.
974        // `Auto { allow_http3: true }` needs both: H1/H2 for discovery and
975        // safe fallback plus QUIC for discovered routes. All other policies
976        // need Hyper only.
977        let hyper_client = if matches!(
978            self.http_version_policy,
979            crate::HttpVersionPolicy::Http3Only
980        ) || tls_config_error.is_some()
981        {
982            None
983        } else {
984            let https = match tls_config_result {
985                Some(Ok(mut rc)) => {
986                    // hyper-rustls requires empty ALPN; it rebuilds based
987                    // on enable_http1/enable_http2 calls.
988                    rc.alpn_protocols.clear();
989                    let builder = hyper_rustls::HttpsConnectorBuilder::new()
990                        .with_tls_config(rc)
991                        .https_or_http();
992                    #[cfg(feature = "http2")]
993                    {
994                        match (enabler.enable_http1(), enabler.enable_http2()) {
995                            (true, true) => builder.enable_http1().enable_http2().build(),
996                            (true | false, false) => builder.enable_http1().build(),
997                            (false, true) => builder.enable_http2().build(),
998                        }
999                    }
1000                    #[cfg(not(feature = "http2"))]
1001                    {
1002                        let _ = enabler;
1003                        builder.enable_http1().build()
1004                    }
1005                }
1006                Some(Err(_)) | None => build_fallback_connector(enabler),
1007            };
1008
1009            // Wrap the connector with connect-phase timeout if configured.
1010            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1011            let https =
1012                crate::transport::connect_timeout::ConnectTimeout::new(https, connect_timeout);
1013
1014            let mut builder = hyper_util::client::legacy::Client::builder(TokioExecutor::new());
1015            // When HTTP/1 is disabled and HTTP/2 is enabled, mark the legacy
1016            // client as HTTP/2-only. This is what enforces the protocol
1017            // contract: hyper-util will attempt an HTTP/2 handshake on every
1018            // socket (including cleartext, where it falls through to HTTP/2
1019            // prior knowledge). When ALPN does not negotiate `h2`, the
1020            // HTTP/2 handshake fails with a `Connect` error rather than
1021            // silently downgrading to HTTP/1.1.
1022            #[cfg(feature = "http2")]
1023            if !enabler.enable_http1() && enabler.enable_http2() {
1024                builder.http2_only(true);
1025            }
1026            if let Some(timeout) = pool_config.idle_timeout {
1027                builder.pool_idle_timeout(timeout);
1028            }
1029            if let Some(max_idle) = pool_config
1030                .max_idle_connections_per_host
1031                .or(pool_config.max_idle_connections)
1032            {
1033                builder.pool_max_idle_per_host(max_idle);
1034            }
1035            Some(builder.build(https))
1036        };
1037
1038        #[cfg(feature = "http3")]
1039        let h3_connector = if enabler.use_http3() {
1040            crate::transport::http3::H3Connector::with_metrics(
1041                self.tls_config.clone(),
1042                &pool_config,
1043                Some(transport_metrics.clone()),
1044            )
1045            .ok()
1046        } else {
1047            None
1048        };
1049
1050        // Build the direct connector client for advanced socket options / local
1051        // address binding. This uses a custom connector path instead of the
1052        // standard hyper-rustls connector.
1053        let stored_direct_config = self.direct_connector_config.clone();
1054        let direct_client = if let Some(dc_config) = self.direct_connector_config {
1055            let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
1056
1057            // Build a TLS connector for HTTPS through the direct path.
1058            let tls_connector = match self.tls_config.as_ref() {
1059                Some(tls_config) => match tls_config.build_rustls_config() {
1060                    Ok(rc) => Some(tokio_rustls::TlsConnector::from(Arc::new(
1061                        configure_tls_alpn(
1062                            rc,
1063                            crate::http_version::HttpVersionPolicyEnabler::from_policy(
1064                                self.http_version_policy,
1065                            ),
1066                        ),
1067                    ))),
1068                    Err(_) => None,
1069                },
1070                None => None,
1071            };
1072
1073            let direct_connector =
1074                crate::transport::direct_connector::DirectConnector::with_metrics(
1075                    dc_config,
1076                    tls_connector,
1077                    transport_metrics.clone(),
1078                );
1079            let direct_connector = crate::transport::connect_timeout::ConnectTimeout::new(
1080                direct_connector,
1081                connect_timeout,
1082            );
1083
1084            let mut builder = hyper_util::client::legacy::Client::builder(TokioExecutor::new());
1085            // Match the standard hyper-rustls path: when H2-only, force
1086            // http2_only on the legacy client so HTTP/2 handshake runs even
1087            // when the connector does not advertise ALPN h2. The
1088            // DirectConnector itself signals ALPN h2 via `Connected::negotiated_h2`
1089            // when TLS selected it.
1090            #[cfg(feature = "http2")]
1091            if !enabler.enable_http1() && enabler.enable_http2() {
1092                builder.http2_only(true);
1093            }
1094            if let Some(timeout) = pool_config.idle_timeout {
1095                builder.pool_idle_timeout(timeout);
1096            }
1097            if let Some(max_idle) = pool_config
1098                .max_idle_connections_per_host
1099                .or(pool_config.max_idle_connections)
1100            {
1101                builder.pool_max_idle_per_host(max_idle);
1102            }
1103            Some(builder.build(direct_connector))
1104        } else {
1105            None
1106        };
1107
1108        // The UDS path is accepted on all platforms (see `uds_path`) but
1109        // only consumed on Unix; without this the field is never read on
1110        // non-Unix targets.
1111        #[cfg(not(unix))]
1112        let _ = &self.uds_path;
1113
1114        #[cfg(unix)]
1115        let uds_client = self.uds_path.map(|path| {
1116            let tls_connector = self.tls_config.as_ref().and_then(|config| {
1117                config.build_rustls_config().ok().map(|rc| {
1118                    tokio_rustls::TlsConnector::from(Arc::new(configure_tls_alpn(
1119                        rc,
1120                        crate::http_version::HttpVersionPolicyEnabler::from_policy(
1121                            self.http_version_policy,
1122                        ),
1123                    )))
1124                })
1125            });
1126            let connector = crate::transport::uds::UdsConnector::with_metrics(
1127                path,
1128                tls_connector,
1129                transport_metrics.clone(),
1130            );
1131            let connector = crate::transport::connect_timeout::ConnectTimeout::new(
1132                connector,
1133                self.timeout.as_ref().and_then(|timeout| timeout.connect),
1134            );
1135            let mut builder = hyper_util::client::legacy::Client::builder(TokioExecutor::new());
1136            // Mirror the standard and direct paths: when H2-only, force
1137            // http2_only on the legacy client. The UDS connector signals ALPN
1138            // h2 via `Connected::negotiated_h2` when TLS selected it.
1139            #[cfg(feature = "http2")]
1140            if !enabler.enable_http1() && enabler.enable_http2() {
1141                builder.http2_only(true);
1142            }
1143            if let Some(timeout) = pool_config.idle_timeout {
1144                builder.pool_idle_timeout(timeout);
1145            }
1146            if let Some(max_idle) = pool_config
1147                .max_idle_connections_per_host
1148                .or(pool_config.max_idle_connections)
1149            {
1150                builder.pool_max_idle_per_host(max_idle);
1151            }
1152            builder.build(connector)
1153        });
1154
1155        let config = ClientConfig {
1156            default_headers: self.default_headers,
1157            user_agent: self.user_agent,
1158            timeout: self.timeout,
1159            redirect: self.redirect,
1160            auth: self.auth,
1161            #[cfg(feature = "cookies")]
1162            cookie_jar,
1163            automatic_decompression,
1164            max_decoded_body_size: self.max_decoded_body_size,
1165            max_decompression_ratio: self.max_decompression_ratio,
1166            #[cfg(feature = "proxy")]
1167            proxy: self.proxy,
1168            #[cfg(feature = "proxy")]
1169            environment_proxies: self.environment_proxies,
1170            #[cfg(any(feature = "proxy", feature = "http3"))]
1171            tls_config: self.tls_config,
1172            retry: self.retry,
1173            http_version_policy: self.http_version_policy,
1174        };
1175
1176        let pool = Pool::new(pool_config);
1177
1178        Client {
1179            inner: Arc::new(ClientInner {
1180                hyper_client,
1181                tls_config_error,
1182                direct_client,
1183                direct_connector_config: stored_direct_config,
1184                sni_clients: Mutex::new(HashMap::new()),
1185                #[cfg(unix)]
1186                uds_client,
1187                #[cfg(feature = "proxy")]
1188                socks_clients: Mutex::new(HashMap::new()),
1189                config,
1190                pool,
1191                transport_metrics,
1192                #[cfg(feature = "http3")]
1193                h3_connector,
1194                #[cfg(feature = "http3")]
1195                alt_svc_state: Arc::new(crate::transport::alt_svc::AltSvcState::new()),
1196            }),
1197        }
1198    }
1199}
1200
1201/// Build a connector with fallback root stores.
1202///
1203/// Uses native roots when available, otherwise falls back to the packaged
1204/// Mozilla root set. Protocol versions are determined by the enabler.
1205fn build_fallback_connector(enabler: crate::http_version::HttpVersionPolicyEnabler) -> Connector {
1206    let builder = match hyper_rustls::HttpsConnectorBuilder::new().with_native_roots() {
1207        Ok(b) => b,
1208        Err(_) => hyper_rustls::HttpsConnectorBuilder::new().with_webpki_roots(),
1209    };
1210    #[cfg(feature = "http2")]
1211    {
1212        match (enabler.enable_http1(), enabler.enable_http2()) {
1213            (true, true) => builder
1214                .https_or_http()
1215                .enable_http1()
1216                .enable_http2()
1217                .build(),
1218            (true | false, false) => builder.https_or_http().enable_http1().build(),
1219            (false, true) => builder.https_or_http().enable_http2().build(),
1220        }
1221    }
1222    #[cfg(not(feature = "http2"))]
1223    {
1224        let _ = enabler;
1225        builder.https_or_http().enable_http1().build()
1226    }
1227}
1228
1229impl Default for ClientBuilder {
1230    fn default() -> Self {
1231        Self::new()
1232    }
1233}
1234
1235fn parse_url(url_str: &str) -> Result<url::Url> {
1236    // Deliberately do not echo `url_str` into the error: parsing has
1237    // failed, so `redact_url_string` would fall back to the raw input
1238    // (potentially containing credentials). `url::ParseError` renders
1239    // only a static description and never embeds the input.
1240    let url = url::Url::parse(url_str).map_err(|e| Error::InvalidUrl(e.to_string()))?;
1241    if !url.username().is_empty() || url.password().is_some() {
1242        // URL userinfo is both easy to leak through diagnostics and
1243        // surprising for an HTTP client with explicit auth APIs.
1244        return Err(Error::InvalidUrl(
1245            "URL userinfo is not supported; configure authentication explicitly".into(),
1246        ));
1247    }
1248    match url.scheme() {
1249        "http" | "https" => Ok(url),
1250        other => Err(Error::Unsupported(format!(
1251            "URL scheme '{other}' is not supported; use http or https"
1252        ))),
1253    }
1254}
1255
1256#[cfg(test)]
1257mod tests {
1258    use super::*;
1259    #[cfg(feature = "proxy")]
1260    use crate::proxy::ProxyAuth;
1261    use bytes::Bytes;
1262
1263    #[test]
1264    fn client_constructs() {
1265        let _client = Client::new();
1266    }
1267
1268    #[test]
1269    fn client_config_debug_redacts_secrets() {
1270        let mut config = ClientConfig::default();
1271        config
1272            .default_headers
1273            .insert("authorization", "Bearer header-secret-token")
1274            .unwrap();
1275        #[cfg(feature = "cookies")]
1276        config
1277            .cookie_jar
1278            .set_default_cookie("session".to_owned(), "jar-secret-token".to_owned())
1279            .expect("valid test cookie");
1280        let debug = format!("{config:?}");
1281        assert!(
1282            !debug.contains("header-secret-token"),
1283            "ClientConfig Debug must not leak header secrets: {debug}"
1284        );
1285        #[cfg(feature = "cookies")]
1286        assert!(
1287            !debug.contains("jar-secret-token"),
1288            "ClientConfig Debug must not leak jar secrets: {debug}"
1289        );
1290    }
1291
1292    #[test]
1293    fn client_default() {
1294        let _client = Client::default();
1295    }
1296
1297    #[test]
1298    fn client_builder() {
1299        let _client = Client::builder().user_agent("test-agent").build();
1300    }
1301
1302    #[test]
1303    fn client_builder_merge_timeout_preserves_other_phases() {
1304        // Phase-specific setters must merge into any existing timeout
1305        // configuration instead of replacing it wholesale.
1306        let client = Client::builder()
1307            .timeout(Timeout::from_secs(30))
1308            .merge_timeout(
1309                Timeout::builder()
1310                    .connect(std::time::Duration::from_secs(5))
1311                    .build(),
1312            )
1313            .merge_timeout(
1314                Timeout::builder()
1315                    .read(std::time::Duration::from_secs(10))
1316                    .build(),
1317            )
1318            .build();
1319
1320        let timeout = client.inner.config.timeout.expect("timeout configured");
1321        let d = |secs: u64| std::time::Duration::from_secs(secs);
1322        assert_eq!(timeout.connect, Some(d(5)), "last connect wins");
1323        assert_eq!(timeout.read, Some(d(10)), "last read wins");
1324        assert_eq!(
1325            timeout.write,
1326            Some(d(30)),
1327            "unset phases keep earlier values"
1328        );
1329        assert_eq!(timeout.pool, Some(d(30)));
1330    }
1331
1332    #[test]
1333    fn client_builder_merge_timeout_without_prior_config() {
1334        let client = Client::builder()
1335            .merge_timeout(
1336                Timeout::builder()
1337                    .connect(std::time::Duration::from_secs(5))
1338                    .build(),
1339            )
1340            .build();
1341
1342        let timeout = client.inner.config.timeout.expect("timeout configured");
1343        assert_eq!(timeout.connect, Some(std::time::Duration::from_secs(5)));
1344        assert_eq!(timeout.read, None);
1345    }
1346
1347    #[cfg(any(feature = "proxy", feature = "http3"))]
1348    #[test]
1349    fn client_builder_danger_accept_invalid_certs_preserves_tls_config() {
1350        let client = Client::builder()
1351            .tls_config(crate::tls::TlsConfig::builder().sni(false).build())
1352            .danger_accept_invalid_certs(true)
1353            .build();
1354        let tls = client
1355            .inner
1356            .config
1357            .tls_config
1358            .as_ref()
1359            .expect("TLS config should be retained");
1360        assert!(!tls.sni_enabled());
1361        assert!(!tls.verify_certificate());
1362        assert!(!tls.verify_hostname());
1363    }
1364
1365    #[test]
1366    fn tls_root_store_paths_construct() {
1367        // Native roots are environment-dependent, but when available the
1368        // production path must build the same verified connector shape.
1369        if let Ok(builder) = hyper_rustls::HttpsConnectorBuilder::new().with_native_roots() {
1370            let _ = builder.https_or_http().enable_http1().build();
1371        }
1372        let enabler =
1373            crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
1374                allow_http3: false,
1375            });
1376        let _ = build_fallback_connector(enabler);
1377    }
1378
1379    #[test]
1380    fn client_builder_http1_only() {
1381        let client = Client::builder()
1382            .http_version_policy(HttpVersionPolicy::Http1Only)
1383            .build();
1384        assert_eq!(
1385            client.inner.config.http_version_policy,
1386            HttpVersionPolicy::Http1Only
1387        );
1388    }
1389
1390    #[test]
1391    fn client_builder_http2_auto() {
1392        let client = Client::builder()
1393            .http_version_policy(HttpVersionPolicy::Auto { allow_http3: false })
1394            .build();
1395        assert_eq!(
1396            client.inner.config.http_version_policy,
1397            HttpVersionPolicy::Auto { allow_http3: false }
1398        );
1399    }
1400
1401    #[test]
1402    #[cfg(feature = "http2")]
1403    fn client_builder_http2_only() {
1404        let client = Client::builder()
1405            .http_version_policy(HttpVersionPolicy::Http2Only)
1406            .build();
1407        assert_eq!(
1408            client.inner.config.http_version_policy,
1409            HttpVersionPolicy::Http2Only
1410        );
1411    }
1412
1413    #[test]
1414    fn connector_builds_for_all_policies() {
1415        for policy in [
1416            HttpVersionPolicy::Http1Only,
1417            HttpVersionPolicy::Auto { allow_http3: false },
1418            #[cfg(feature = "http2")]
1419            HttpVersionPolicy::Http2Only,
1420            #[cfg(feature = "http3")]
1421            HttpVersionPolicy::Http3Only,
1422        ] {
1423            let enabler = crate::http_version::HttpVersionPolicyEnabler::from_policy(policy);
1424            if !enabler.use_http3() {
1425                let _ = build_fallback_connector(enabler);
1426            }
1427        }
1428    }
1429
1430    #[cfg(feature = "http2")]
1431    #[test]
1432    fn custom_connector_alpn_matches_http_version_policy() {
1433        let config = rustls::ClientConfig::builder()
1434            .with_root_certificates(rustls::RootCertStore::empty())
1435            .with_no_client_auth();
1436        let h2_only = configure_tls_alpn(
1437            config.clone(),
1438            crate::http_version::HttpVersionPolicyEnabler::from_policy(
1439                HttpVersionPolicy::Http2Only,
1440            ),
1441        );
1442        assert_eq!(h2_only.alpn_protocols, vec![b"h2".to_vec()]);
1443
1444        let auto = configure_tls_alpn(
1445            config,
1446            crate::http_version::HttpVersionPolicyEnabler::from_policy(HttpVersionPolicy::Auto {
1447                allow_http3: false,
1448            }),
1449        );
1450        assert_eq!(
1451            auto.alpn_protocols,
1452            vec![b"h2".to_vec(), b"http/1.1".to_vec()]
1453        );
1454    }
1455
1456    #[test]
1457    fn parse_valid_urls() {
1458        assert!(parse_url("https://example.com").is_ok());
1459        assert!(parse_url("http://localhost:8080").is_ok());
1460    }
1461
1462    #[test]
1463    fn parse_invalid_schemes() {
1464        assert!(parse_url("ftp://example.com").is_err());
1465        assert!(parse_url("file:///tmp/test").is_err());
1466    }
1467
1468    #[test]
1469    fn parse_invalid_urls() {
1470        assert!(parse_url("not a url").is_err());
1471    }
1472
1473    #[test]
1474    fn get_request_builder() {
1475        let client = Client::new();
1476        let builder = client.get("https://example.com").unwrap();
1477        let req = builder.build().unwrap();
1478        assert_eq!(*req.method(), Method::GET);
1479    }
1480
1481    #[test]
1482    fn apply_content_length_empty_body() {
1483        let headers = Headers::new();
1484        let body = crate::body::RequestBody::Empty;
1485        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1486        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "0");
1487    }
1488
1489    #[test]
1490    fn apply_content_length_bytes_body() {
1491        let headers = Headers::new();
1492        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1493        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1494        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
1495    }
1496
1497    #[test]
1498    fn apply_content_length_stream_known() {
1499        let headers = Headers::new();
1500        let stream = futures_util::stream::empty::<Result<Bytes>>();
1501        let body = crate::body::RequestBody::from_stream(stream, Some(7));
1502        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1503        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "7");
1504    }
1505
1506    #[test]
1507    fn apply_content_length_stream_unknown() {
1508        let headers = Headers::new();
1509        let stream = futures_util::stream::empty::<Result<Bytes>>();
1510        let body = crate::body::RequestBody::from_stream(stream, None);
1511        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1512        assert!(out.get("content-length").is_none());
1513    }
1514
1515    #[test]
1516    fn apply_content_length_user_matches() {
1517        let mut headers = Headers::new();
1518        headers.insert("content-length", "5").unwrap();
1519        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1520        let out = crate::pipeline::apply_content_length(headers, &body).unwrap();
1521        assert_eq!(out.get("content-length").unwrap().to_str().unwrap(), "5");
1522    }
1523
1524    #[test]
1525    fn apply_content_length_user_mismatch_errors() {
1526        let mut headers = Headers::new();
1527        headers.insert("content-length", "10").unwrap();
1528        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1529        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1530        assert_eq!(err.kind(), "request_build");
1531    }
1532
1533    #[test]
1534    fn apply_content_length_rejects_invalid_value() {
1535        let mut headers = Headers::new();
1536        headers.insert("content-length", "not-a-number").unwrap();
1537        let body = crate::body::RequestBody::from(Bytes::from("hello"));
1538        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1539        assert_eq!(err.kind(), "invalid_header_value");
1540    }
1541
1542    #[test]
1543    fn apply_content_length_rejects_unknown_stream_override() {
1544        let mut headers = Headers::new();
1545        headers.insert("content-length", "5").unwrap();
1546        let stream = futures_util::stream::empty::<Result<Bytes>>();
1547        let body = crate::body::RequestBody::from_stream(stream, None);
1548        let err = crate::pipeline::apply_content_length(headers, &body).unwrap_err();
1549        assert_eq!(err.kind(), "request_build");
1550    }
1551
1552    #[test]
1553    fn parse_url_rejects_userinfo_without_echoing_credentials() {
1554        let err = parse_url("https://user:secret@example.com").unwrap_err();
1555        assert_eq!(err.kind(), "invalid_url");
1556        assert!(!err.to_string().contains("secret"));
1557    }
1558
1559    #[cfg(feature = "proxy")]
1560    #[tokio::test]
1561    async fn proxy_auth_conflict_with_header() {
1562        let proxy = Proxy::all("http://proxy.example:8080")
1563            .unwrap()
1564            .auth(ProxyAuth::basic("user", "pass").unwrap());
1565        let client = Client::builder().proxy(proxy).build();
1566        let request = client
1567            .get("http://destination.example")
1568            .unwrap()
1569            .header("proxy-authorization", "Basic dXNlcjpwYXNz")
1570            .build()
1571            .unwrap();
1572        let err = client.send(request).await.unwrap_err();
1573        assert_eq!(err.kind(), "conflicting_auth");
1574        assert!(err.to_string().contains("Proxy-Authorization"));
1575    }
1576
1577    #[cfg(feature = "proxy")]
1578    #[tokio::test]
1579    async fn proxy_auth_no_conflict_without_header() {
1580        let proxy = Proxy::all("http://proxy.example:8080")
1581            .unwrap()
1582            .auth(ProxyAuth::basic("user", "pass").unwrap());
1583        let client = Client::builder().proxy(proxy).build();
1584        let request = client
1585            .get("http://destination.example")
1586            .unwrap()
1587            .build()
1588            .unwrap();
1589        let err = client.send(request).await.unwrap_err();
1590        assert_ne!(err.kind(), "conflicting_auth");
1591    }
1592
1593    #[cfg(feature = "proxy")]
1594    #[tokio::test]
1595    async fn proxy_auth_no_conflict_with_header_only() {
1596        let proxy = Proxy::all("http://proxy.example:8080").unwrap();
1597        let client = Client::builder().proxy(proxy).build();
1598        let request = client
1599            .get("http://destination.example")
1600            .unwrap()
1601            .header("proxy-authorization", "Basic dXNlcjpwYXNz")
1602            .build()
1603            .unwrap();
1604        let err = client.send(request).await.unwrap_err();
1605        assert_ne!(err.kind(), "conflicting_auth");
1606    }
1607}