Skip to main content

toolkit_http/
builder.rs

1use crate::config::{
2    ClientAuthConfig, HttpClientConfig, OutboundProxy, RateLimitConfig, RedirectConfig,
3    RetryConfig, TlsConfig, TlsRootConfig, TlsVersion, TransportSecurity,
4};
5use crate::connector::{self, ConnectTimeout, ProxyConnector};
6use crate::error::HttpError;
7use crate::layers::{OtelLayer, RetryLayer, SecureRedirectPolicy, UserAgentLayer};
8use crate::response::ResponseBody;
9use crate::tls;
10use bytes::Bytes;
11use http::Response;
12use http_body_util::{BodyExt, Full};
13use hyper_rustls::HttpsConnector;
14use hyper_util::client::legacy::Client;
15use hyper_util::client::legacy::connect::HttpConnector;
16use hyper_util::client::proxy::matcher::Matcher;
17use hyper_util::rt::{TokioExecutor, TokioTimer};
18use rustls_pki_types::CertificateDer;
19use std::sync::Arc;
20use std::time::Duration;
21use tower::buffer::Buffer;
22use tower::limit::ConcurrencyLimitLayer;
23use tower::load_shed::LoadShedLayer;
24use tower::timeout::TimeoutLayer;
25use tower::util::BoxCloneService;
26use tower::{ServiceBuilder, ServiceExt};
27use tower_http::decompression::DecompressionLayer;
28use tower_http::follow_redirect::FollowRedirectLayer;
29
30/// Type-erased inner service between layer composition steps in [`HttpClientBuilder::build`].
31type InnerService =
32    BoxCloneService<http::Request<Full<Bytes>>, http::Response<ResponseBody>, HttpError>;
33
34/// Builder for constructing an [`HttpClient`] with a layered tower middleware stack.
35pub struct HttpClientBuilder {
36    config: HttpClientConfig,
37    auth_layer: Option<Box<dyn FnOnce(InnerService) -> InnerService + Send>>,
38    attempt_layer: Option<Box<dyn FnOnce(InnerService) -> InnerService + Send>>,
39    metrics_layer: Option<Box<dyn FnOnce(InnerService) -> InnerService + Send>>,
40}
41
42impl HttpClientBuilder {
43    /// Create a new builder with default configuration
44    #[must_use]
45    pub fn new() -> Self {
46        Self {
47            config: HttpClientConfig::default(),
48            auth_layer: None,
49            attempt_layer: None,
50            metrics_layer: None,
51        }
52    }
53
54    /// Create a builder with a specific configuration
55    #[must_use]
56    pub fn with_config(config: HttpClientConfig) -> Self {
57        Self {
58            config,
59            auth_layer: None,
60            attempt_layer: None,
61            metrics_layer: None,
62        }
63    }
64
65    /// Set the per-request timeout
66    ///
67    /// This timeout applies to each individual HTTP request/attempt.
68    /// If retries are enabled, each retry attempt gets its own timeout.
69    #[must_use]
70    pub fn timeout(mut self, timeout: Duration) -> Self {
71        self.config.request_timeout = timeout;
72        self
73    }
74
75    /// Set the total timeout spanning all retry attempts
76    ///
77    /// When set, the entire operation (including all retries and backoff delays)
78    /// must complete within this duration. If the deadline is exceeded,
79    /// the request fails with `HttpError::DeadlineExceeded(total_timeout)`.
80    #[must_use]
81    pub fn total_timeout(mut self, timeout: Duration) -> Self {
82        self.config.total_timeout = Some(timeout);
83        self
84    }
85
86    /// Set the user agent string
87    #[must_use]
88    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
89        self.config.user_agent = user_agent.into();
90        self
91    }
92
93    /// Set the retry configuration
94    #[must_use]
95    pub fn retry(mut self, retry: Option<RetryConfig>) -> Self {
96        self.config.retry = retry;
97        self
98    }
99
100    /// Set the maximum response body size
101    #[must_use]
102    pub fn max_body_size(mut self, size: usize) -> Self {
103        self.config.max_body_size = size;
104        self
105    }
106
107    /// Set the concurrency-limit configuration.
108    ///
109    /// This installs a *concurrency* cap (max in-flight requests), not a
110    /// requests-per-second rate limit. `None` disables the limiter entirely.
111    /// `Some(cfg)` installs a load-shedding
112    /// [`ConcurrencyLimitLayer`](tower::limit::ConcurrencyLimitLayer) capped at
113    /// `cfg.max_concurrent_requests`; requests beyond the cap fail fast with
114    /// [`HttpError::Overloaded`](crate::error::HttpError::Overloaded) rather
115    /// than queueing. A `max_concurrent_requests` of `usize::MAX` is treated as
116    /// unlimited (the layer is skipped); `0` is clamped to `1` at
117    /// [`build`](Self::build) time so the client can never wedge shedding every
118    /// request.
119    #[must_use]
120    pub fn concurrency_limit(mut self, rate_limit: Option<RateLimitConfig>) -> Self {
121        self.config.rate_limit = rate_limit;
122        self
123    }
124
125    /// Set transport security mode
126    ///
127    /// Use `TransportSecurity::TlsOnly` to enforce HTTPS for all connections.
128    #[must_use]
129    pub fn transport(mut self, transport: TransportSecurity) -> Self {
130        self.config.transport = transport;
131        self
132    }
133
134    /// Deny insecure HTTP connections, enforcing TLS for all traffic
135    ///
136    /// Equivalent to `.transport(TransportSecurity::TlsOnly)`.
137    ///
138    /// Use this when TLS enforcement is required (e.g., production environments).
139    #[must_use]
140    pub fn deny_insecure_http(mut self) -> Self {
141        tracing::debug!(
142            target: "toolkit_http::security",
143            "deny_insecure_http() called - enforcing TLS for all connections"
144        );
145        self.config.transport = TransportSecurity::TlsOnly;
146        self
147    }
148
149    /// Set the TLS handshake configuration (minimum protocol version and
150    /// optional mutual-TLS client identity).
151    ///
152    /// Replaces the entire [`TlsConfig`]; use [`crate::config::TlsConfig`]'s
153    /// fields to set `min_version` and `client_auth`. The root-trust strategy
154    /// is configured separately via [`tls_roots`](Self::tls_roots).
155    ///
156    /// Mutual-TLS PEM material referenced by `client_auth` is read and parsed
157    /// in [`HttpClientBuilder::build`]; IO/parse failures surface there as
158    /// [`HttpError::Tls`].
159    ///
160    /// [`HttpClientBuilder::build`]: crate::builder::HttpClientBuilder::build
161    #[must_use]
162    pub fn tls(mut self, tls: TlsConfig) -> Self {
163        self.config.tls = tls;
164        self
165    }
166
167    /// Select the root certificate store (default: [`TlsRootConfig::WebPki`]).
168    /// Extra roots from [`add_root_certificates`](Self::add_root_certificates)
169    /// are added to it.
170    #[must_use]
171    pub fn tls_roots(mut self, roots: TlsRootConfig) -> Self {
172        self.config.tls_roots = roots;
173        self
174    }
175
176    /// Set the minimum TLS protocol version, leaving the rest of the
177    /// [`TlsConfig`] (e.g. `client_auth`) untouched.
178    ///
179    /// Convenience shortcut for mutating `config.tls.min_version` without
180    /// rebuilding the whole [`TlsConfig`] via [`HttpClientBuilder::tls`].
181    ///
182    /// [`HttpClientBuilder::tls`]: crate::builder::HttpClientBuilder::tls
183    #[must_use]
184    pub fn tls_min_version(mut self, min_version: TlsVersion) -> Self {
185        self.config.tls.min_version = min_version;
186        self
187    }
188
189    /// Set the mutual-TLS client identity, leaving the rest of the
190    /// [`TlsConfig`] (e.g. `min_version`) untouched.
191    ///
192    /// Convenience shortcut for mutating `config.tls.client_auth` without
193    /// rebuilding the whole [`TlsConfig`] via [`HttpClientBuilder::tls`]. The
194    /// referenced PEM material is read and parsed in
195    /// [`HttpClientBuilder::build`]; IO/parse failures surface there as
196    /// [`HttpError::Tls`].
197    ///
198    /// [`HttpClientBuilder::tls`]: crate::builder::HttpClientBuilder::tls
199    /// [`HttpClientBuilder::build`]: crate::builder::HttpClientBuilder::build
200    #[must_use]
201    pub fn client_auth(mut self, client_auth: ClientAuthConfig) -> Self {
202        self.config.tls.client_auth = Some(client_auth);
203        self
204    }
205
206    /// Enable OpenTelemetry tracing layer
207    ///
208    /// When enabled, creates spans for outbound requests with HTTP metadata
209    /// and injects W3C trace context headers (when `otel` feature is enabled).
210    #[must_use]
211    pub fn with_otel(mut self) -> Self {
212        self.config.otel = true;
213        self
214    }
215
216    /// Insert an optional auth layer between retry and timeout in the stack.
217    ///
218    /// Stack position: `… → Retry → **this layer** → Timeout → …`
219    ///
220    /// The layer sits inside the retry loop so each attempt re-executes it
221    /// (e.g. re-reads a refreshed bearer token). Only one auth layer can be
222    /// set; a second call replaces the first.
223    #[must_use]
224    pub fn with_auth_layer(
225        mut self,
226        wrap: impl FnOnce(InnerService) -> InnerService + Send + 'static,
227    ) -> Self {
228        self.auth_layer = Some(Box::new(wrap));
229        self
230    }
231
232    /// Insert a layer that sees every attempt as it leaves for the network.
233    ///
234    /// Stack position: `… → Retry → Auth → **this layer** → ErrorMapping → Timeout → …`
235    ///
236    /// The layer runs once per attempt, after credentials are attached, and
237    /// sees the transport outcome of that attempt: a response with any status,
238    /// or a connect, TLS or timeout error. A circuit breaker belongs here.
239    /// Only one attempt layer can be set; a second call replaces the first.
240    #[must_use]
241    pub fn with_attempt_layer(
242        mut self,
243        wrap: impl FnOnce(InnerService) -> InnerService + Send + 'static,
244    ) -> Self {
245        self.attempt_layer = Some(Box::new(wrap));
246        self
247    }
248
249    /// Insert a metrics layer between the rate-limit and retry layers.
250    ///
251    /// Stack position: `… → RateLimit → **this layer** → Retry → Auth → Timeout → …`
252    ///
253    /// The layer sits outside the retry loop so it observes a single logical
254    /// request once, regardless of how many transport-level retries the retry
255    /// layer issues. If the use case is "count every attempt", the equivalent
256    /// observation can be made with [`with_otel`](Self::with_otel) (one span
257    /// per attempt) and a `tracing` → metrics bridge.
258    ///
259    /// Only one metrics layer can be set; a second call replaces the first.
260    #[must_use]
261    pub fn with_metrics_layer(
262        mut self,
263        wrap: impl FnOnce(InnerService) -> InnerService + Send + 'static,
264    ) -> Self {
265        self.metrics_layer = Some(Box::new(wrap));
266        self
267    }
268
269    /// Record OpenTelemetry client metrics using the default route classifier.
270    ///
271    /// Emits `http.client.request.duration` (a histogram, in seconds) for each
272    /// logical request. `client_type` names the instrumentation scope (the
273    /// meter), like the server-side gear name. The default classifier labels
274    /// each request `"METHOD host"` via the `http.route` attribute — a bounded
275    /// value that never contains a raw path, so metric cardinality stays
276    /// controlled. Use [`with_metrics_by`](Self::with_metrics_by)
277    /// to supply route templates.
278    ///
279    /// Like [`with_metrics_layer`](Self::with_metrics_layer), the layer sits
280    /// outside the retry loop, so it observes one logical request, not each
281    /// attempt.
282    #[cfg(feature = "otel")]
283    #[must_use]
284    pub fn with_metrics(self, client_type: impl Into<String>) -> Self {
285        self.with_metrics_by(client_type, crate::layers::default_classify)
286    }
287
288    /// Record OpenTelemetry client metrics with a custom route classifier.
289    ///
290    /// Like [`with_metrics`](Self::with_metrics) but accepts a classifier — `classify` produces the
291    /// `http.route` attribute for each request (the Rust analogue of go-appkit's
292    /// `ClassifyRequest`). It MUST return a bounded set of values (e.g.
293    /// `"GET /users/{id}"`), never raw paths, to avoid unbounded metric
294    /// cardinality.
295    #[cfg(feature = "otel")]
296    #[must_use]
297    pub fn with_metrics_by(
298        self,
299        client_type: impl Into<String>,
300        classify: impl Fn(&http::Request<Full<Bytes>>) -> std::borrow::Cow<'static, str>
301        + Send
302        + Sync
303        + 'static,
304    ) -> Self {
305        let client_type = client_type.into();
306        let classify: crate::layers::ClassifyFn = std::sync::Arc::new(classify);
307        let layer = crate::layers::MetricsLayer::new(&client_type, classify);
308        self.with_metrics_layer(move |svc| {
309            ServiceBuilder::new()
310                .layer(layer)
311                .service(svc)
312                .boxed_clone()
313        })
314    }
315
316    /// Set the buffer capacity for concurrent request handling
317    ///
318    /// The HTTP client uses an internal buffer to allow concurrent requests
319    /// without external locking. This sets the maximum number of requests
320    /// that can be queued.
321    ///
322    /// **Note**: A capacity of 0 is invalid and will be clamped to 1.
323    /// Tower's Buffer panics with capacity=0, so we enforce minimum of 1.
324    #[must_use]
325    pub fn buffer_capacity(mut self, capacity: usize) -> Self {
326        // Clamp to at least 1 - tower::Buffer panics with capacity=0
327        self.config.buffer_capacity = capacity.max(1);
328        self
329    }
330
331    /// Set the maximum number of redirects to follow
332    ///
333    /// Set to `0` to disable redirect following (3xx responses pass through as-is).
334    /// Default: 10
335    #[must_use]
336    pub fn max_redirects(mut self, max_redirects: usize) -> Self {
337        self.config.redirect.max_redirects = max_redirects;
338        self
339    }
340
341    /// Disable redirect following
342    ///
343    /// Equivalent to `.max_redirects(0)`. When disabled, 3xx responses are
344    /// returned to the caller without following the `Location` header.
345    #[must_use]
346    pub fn no_redirects(mut self) -> Self {
347        self.config.redirect = RedirectConfig::disabled();
348        self
349    }
350
351    /// Set the redirect policy configuration
352    ///
353    /// Use this to configure redirect security settings:
354    /// - `same_origin_only`: Only follow redirects to the same host
355    /// - `strip_sensitive_headers`: Remove `Authorization`/`Cookie` on cross-origin
356    /// - `allow_https_downgrade`: Allow HTTPS → HTTP redirects (not recommended)
357    ///
358    /// # Example
359    ///
360    /// ```rust,ignore
361    /// let client = HttpClient::builder()
362    ///     .redirect(RedirectConfig::permissive()) // Allow all redirects with header stripping
363    ///     .build()?;
364    /// ```
365    #[must_use]
366    pub fn redirect(mut self, config: RedirectConfig) -> Self {
367        self.config.redirect = config;
368        self
369    }
370
371    /// Set the idle connection timeout for the connection pool
372    ///
373    /// Connections that remain idle for longer than this duration will be
374    /// closed and removed from the pool. Default: 90 seconds.
375    ///
376    /// Set to `None` to disable idle timeout (connections kept indefinitely).
377    #[must_use]
378    pub fn pool_idle_timeout(mut self, timeout: Option<Duration>) -> Self {
379        self.config.pool_idle_timeout = timeout;
380        self
381    }
382
383    /// Set the maximum number of idle connections per host
384    ///
385    /// Limits how many idle connections are kept in the pool for each host.
386    /// Default: 32.
387    ///
388    /// - Setting to `0` disables connection reuse entirely
389    /// - Setting too high may waste resources on rarely-used connections
390    #[must_use]
391    pub fn pool_max_idle_per_host(mut self, max: usize) -> Self {
392        self.config.pool_max_idle_per_host = max;
393        self
394    }
395
396    /// Bound each new connection: DNS, TCP connect (to the destination or
397    /// the proxy), proxy `CONNECT` and TLS handshake together. A connect timeout
398    /// surfaces as [`HttpError::Transport`] with an `io::ErrorKind::TimedOut`
399    /// source.
400    #[must_use]
401    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
402        self.config.connect_timeout = Some(timeout);
403        self
404    }
405
406    /// Trust `certs` in addition to the roots selected by `tls_roots`.
407    ///
408    /// A certificate that is not a valid trust anchor fails
409    /// [`build`](Self::build) with [`HttpError::Tls`].
410    #[must_use]
411    pub fn add_root_certificates(
412        mut self,
413        certs: impl IntoIterator<Item = CertificateDer<'static>>,
414    ) -> Self {
415        let mut all = self.config.extra_root_certs.to_vec();
416        all.extend(certs);
417        self.config.extra_root_certs = all.into();
418        self
419    }
420
421    /// Trust every certificate in a PEM bundle in addition to the roots
422    /// selected by `tls_roots`.
423    ///
424    /// # Errors
425    ///
426    /// [`HttpError::Tls`] when the bundle is not PEM or holds no
427    /// certificate. A certificate whose DER is invalid fails
428    /// [`build`](Self::build) instead.
429    pub fn add_root_certificates_pem(self, pem: &[u8]) -> Result<Self, HttpError> {
430        let certs = tls::load_pem_bundle(pem).map_err(|e| HttpError::Tls(Box::new(e)))?;
431        Ok(self.add_root_certificates(certs))
432    }
433
434    /// Set the outbound (forward) proxy, e.g. `OutboundProxy::FromEnv` or an
435    /// [`ExplicitProxy`](crate::ExplicitProxy). See [`OutboundProxy`].
436    #[must_use]
437    pub fn outbound_proxy(mut self, proxy: impl Into<OutboundProxy>) -> Self {
438        self.config.outbound_proxy = proxy.into();
439        self
440    }
441
442    /// Build the HTTP client with all configured layers
443    ///
444    /// # Errors
445    /// Returns an error if TLS initialization fails or configuration is invalid.
446    ///
447    /// Under `--features fips`, `TransportSecurity::AllowInsecureHttp` is accepted
448    /// as an explicit opt-in (the default there is `TlsOnly`). The first such
449    /// build in the process logs a warning, because requests over `http://`
450    /// are not encrypted.
451    pub fn build(self) -> Result<crate::HttpClient, HttpError> {
452        #[cfg(feature = "fips")]
453        if self.config.transport == TransportSecurity::AllowInsecureHttp {
454            // Once per process: some callers build a client per operation.
455            static WARNED: std::sync::Once = std::sync::Once::new();
456            WARNED.call_once(|| {
457                tracing::warn!(
458                    target: "toolkit_http::security",
459                    user_agent = %self.config.user_agent,
460                    allow_https_downgrade = self.config.redirect.allow_https_downgrade,
461                    "plaintext http:// explicitly enabled (AllowInsecureHttp) in a FIPS build: \
462                     requests over http:// are not encrypted (logged once per process)"
463                );
464            });
465        }
466
467        let timeout = self.config.request_timeout;
468        let total_timeout = self.config.total_timeout;
469
470        // Build the HTTPS connector (may fail for Native roots if no valid certs)
471        let allow_http = self.config.transport == TransportSecurity::AllowInsecureHttp;
472        let proxy_matcher = connector::build_matcher(&self.config.outbound_proxy, allow_http)?;
473        let https = build_https_connector(&self.config, proxy_matcher.clone())?;
474
475        // Create the base hyper client with HTTP/2 support and connection pool settings
476        let mut client_builder = Client::builder(TokioExecutor::new());
477
478        // Configure connection pool
479        // CRITICAL: pool_timer is required for pool_idle_timeout to work!
480        client_builder
481            .pool_timer(TokioTimer::new())
482            .pool_max_idle_per_host(self.config.pool_max_idle_per_host)
483            .http2_only(false); // Allow both HTTP/1 and HTTP/2 via ALPN
484
485        // Set idle timeout (None = no timeout, connections kept indefinitely)
486        if let Some(idle_timeout) = self.config.pool_idle_timeout {
487            client_builder.pool_idle_timeout(idle_timeout);
488        }
489
490        let hyper_client = client_builder.build::<_, Full<Bytes>>(https);
491
492        // Parse user agent header (may fail)
493        let ua_layer = UserAgentLayer::try_new(&self.config.user_agent)?;
494
495        // =======================================================================
496        // Tower Layer Stack (outer to inner)
497        // =======================================================================
498        //
499        // Request flow (outer → inner):
500        //   Buffer → OtelLayer → [MetricsLayer?] → LoadShed/Concurrency →
501        //   RetryLayer → [AuthLayer?] → [AttemptLayer?] → ErrorMapping → Timeout → UserAgent →
502        //   Decompression → FollowRedirect → hyper_client
503        //
504        // AuthLayer (if set via with_auth_layer) sits inside the retry
505        // loop so each retry re-acquires credentials (e.g. refreshed
506        // bearer token).
507        //
508        // MetricsLayer (if set via with_metrics_layer) sits outside the
509        // retry loop so it observes one logical request, not per-attempt, and
510        // outside the concurrency limiter so a load-shed rejection is still
511        // counted (recorded with error.type = "overloaded").
512        //
513        // Response flow (inner → outer):
514        //   hyper_client → FollowRedirect → Decompression → UserAgent →
515        //   Timeout → ErrorMapping → [AttemptLayer?] → [AuthLayer?] → RetryLayer →
516        //   LoadShed/Concurrency → [MetricsLayer?] → OtelLayer → Buffer
517        //
518        // Key semantics (reqwest-like):
519        //  - send() returns Ok(Response) for ALL HTTP statuses (including 4xx/5xx)
520        //  - send() returns Err only for transport/timeout/TLS errors
521        //  - Non-2xx converted to error ONLY via error_for_status()
522        //  - RetryLayer handles both Err (transport) and Ok(Response) (status)
523        //     retries internally, draining body before retry for connection reuse
524        //  - FollowRedirect handles 3xx responses internally with security protections:
525        //     * Same-origin enforcement (default) - blocks SSRF attacks
526        //     * Sensitive header stripping on cross-origin redirects
527        //     * HTTPS downgrade protection
528        //
529        // =======================================================================
530        //
531        let redirect_policy = SecureRedirectPolicy::new(self.config.redirect.clone());
532
533        // Build the service stack with secure redirect following
534        let service = ServiceBuilder::new()
535            .layer(TimeoutLayer::new(timeout))
536            .layer(ua_layer)
537            .layer(DecompressionLayer::new())
538            .layer(FollowRedirectLayer::with_policy(redirect_policy))
539            // Inside FollowRedirect so every hop is checked against the matcher.
540            .map_request(move |req| add_forward_proxy_auth(proxy_matcher.as_deref(), req))
541            .service(hyper_client);
542
543        // Map the decompression body to our boxed ResponseBody type.
544        // This converts Response<DecompressionBody<Incoming>> to Response<ResponseBody>.
545        //
546        // The decompression body's error type is tower_http::BoxError, which we convert
547        // to our boxed error type for consistency with the ResponseBody definition.
548        let service = service.map_response(map_decompression_response);
549
550        // Map errors to HttpError with proper timeout duration
551        let service = service.map_err(move |e: tower::BoxError| map_tower_error(e, timeout));
552
553        // Box the service for type erasure
554        let mut boxed_service = service.boxed_clone();
555
556        // Attempt layer (e.g. a circuit breaker): inside auth, so a failure to
557        // obtain credentials is not taken for a backend failure.
558        if let Some(wrap) = self.attempt_layer {
559            boxed_service = wrap(boxed_service);
560        }
561
562        // Apply auth layer (between timeout and retry).
563        // Inside retry so each retry attempt re-acquires the token.
564        if let Some(wrap) = self.auth_layer {
565            boxed_service = wrap(boxed_service);
566        }
567
568        // Conditionally wrap with RetryLayer
569        //
570        // RetryLayer handles retries for both:
571        // - Err(HttpError::Transport/Timeout) - transport-level failures
572        // - Ok(Response) with retryable status codes (429, 5xx for GET, etc.)
573        //
574        // When retrying on status codes, RetryLayer drains the response body
575        // (up to configured limit) to allow connection reuse.
576        //
577        // If total_timeout is set, the entire operation (including all retries)
578        // must complete within that duration.
579        if let Some(ref retry_config) = self.config.retry {
580            let retry_layer = RetryLayer::with_total_timeout(retry_config.clone(), total_timeout);
581            let retry_service = ServiceBuilder::new()
582                .layer(retry_layer)
583                .service(boxed_service);
584            boxed_service = retry_service.boxed_clone();
585        }
586
587        // Conditionally wrap with concurrency limit + load shedding.
588        // LoadShedLayer returns error immediately when ConcurrencyLimitLayer is
589        // saturated instead of waiting indefinitely (Poll::Pending).
590        //
591        // Applied BEFORE the metrics layer (i.e. inner to it) on purpose: a shed
592        // request then propagates back out through MetricsLayer and is recorded
593        // in `http.client.request.duration` with `error.type = "overloaded"`,
594        // rather than being rejected outside metrics and left invisible.
595        if let Some(rate_limit) = self.config.rate_limit
596            && rate_limit.max_concurrent_requests < usize::MAX
597        {
598            let limited_service = ServiceBuilder::new()
599                .layer(LoadShedLayer::new())
600                // `.max(1)`: a cap of 0 never grants a permit (sheds everything);
601                // mirrors the `buffer_capacity` clamp below.
602                .layer(ConcurrencyLimitLayer::new(
603                    rate_limit.max_concurrent_requests.max(1),
604                ))
605                .service(boxed_service);
606            // Map load shed errors to HttpError::Overloaded
607            let limited_service = limited_service.map_err(map_load_shed_error);
608            boxed_service = limited_service.boxed_clone();
609        }
610
611        // Apply metrics layer (outside both retry and the concurrency limiter).
612        // Outside retry: observes one logical request, not per-attempt. Outside
613        // the limiter: so load-shed rejections are counted (see above).
614        if let Some(wrap) = self.metrics_layer {
615            boxed_service = wrap(boxed_service);
616        }
617
618        // Conditionally wrap with OTEL tracing layer (outermost layer before buffer)
619        // Applied last so it sees the final request after UserAgent and other modifications.
620        // Creates spans, records status, and injects trace context headers.
621        if self.config.otel {
622            let otel_service = ServiceBuilder::new()
623                .layer(OtelLayer::new())
624                .service(boxed_service);
625            boxed_service = otel_service.boxed_clone();
626        }
627
628        // Wrap in Buffer as the final step for true concurrent access
629        // Buffer spawns a background task that processes requests from a channel,
630        // providing Clone + Send + Sync without any mutex serialization.
631        let buffer_capacity = self.config.buffer_capacity.max(1);
632        let buffered_service: crate::client::BufferedService =
633            Buffer::new(boxed_service, buffer_capacity);
634
635        Ok(crate::HttpClient {
636            service: buffered_service,
637            max_body_size: self.config.max_body_size,
638            transport_security: self.config.transport,
639        })
640    }
641}
642
643#[cfg(test)]
644impl HttpClientBuilder {
645    /// Build an `HttpClient` with a custom inner service replacing the
646    /// hyper connector. The full middleware stack (Retry, Concurrency,
647    /// Buffer, etc.) is applied on top.
648    ///
649    /// The inner service must handle `Request<Full<Bytes>>` and return
650    /// `Response<ResponseBody>`. Use this to inject a fake slow service
651    /// for cancellation testing without needing a real HTTP server.
652    fn build_with_inner_service(self, inner: InnerService) -> crate::HttpClient {
653        let mut boxed_service = inner;
654
655        if let Some(ref retry_config) = self.config.retry {
656            let retry_layer =
657                RetryLayer::with_total_timeout(retry_config.clone(), self.config.total_timeout);
658            let retry_service = ServiceBuilder::new()
659                .layer(retry_layer)
660                .service(boxed_service);
661            boxed_service = retry_service.boxed_clone();
662        }
663
664        if let Some(rate_limit) = self.config.rate_limit
665            && rate_limit.max_concurrent_requests < usize::MAX
666        {
667            let limited_service = ServiceBuilder::new()
668                .layer(LoadShedLayer::new())
669                .layer(ConcurrencyLimitLayer::new(
670                    rate_limit.max_concurrent_requests.max(1),
671                ))
672                .service(boxed_service);
673            let limited_service = limited_service.map_err(map_load_shed_error);
674            boxed_service = limited_service.boxed_clone();
675        }
676
677        let buffer_capacity = self.config.buffer_capacity.max(1);
678        let buffered_service: crate::client::BufferedService =
679            Buffer::new(boxed_service, buffer_capacity);
680
681        crate::HttpClient {
682            service: buffered_service,
683            max_body_size: self.config.max_body_size,
684            transport_security: self.config.transport,
685        }
686    }
687}
688
689impl Default for HttpClientBuilder {
690    fn default() -> Self {
691        Self::new()
692    }
693}
694
695/// Map tower errors to `HttpError` with actual timeout duration
696///
697/// Attempts to extract existing `HttpError` from the boxed error before
698/// wrapping as `Transport`. This preserves typed errors like `Overloaded`
699/// and `ServiceClosed` that may have been boxed by tower middleware.
700fn map_tower_error(err: tower::BoxError, timeout: Duration) -> HttpError {
701    if err.is::<tower::timeout::error::Elapsed>() {
702        return HttpError::Timeout(timeout);
703    }
704
705    // Try to extract existing HttpError before wrapping as Transport
706    match err.downcast::<HttpError>() {
707        Ok(http_err) => *http_err,
708        Err(other) => find_proxy_error(&*other).unwrap_or(HttpError::Transport(other)),
709    }
710}
711
712/// Lift a proxy failure raised by the connector out of hyper's connect error,
713/// so it is typed; whether it is retried then depends on its `ProxyErrorKind`.
714fn find_proxy_error(err: &(dyn std::error::Error + 'static)) -> Option<HttpError> {
715    let mut source = Some(err);
716    while let Some(e) = source {
717        if let Some(HttpError::Proxy { kind, proxy }) = e.downcast_ref::<HttpError>() {
718            return Some(HttpError::Proxy {
719                kind: *kind,
720                proxy: proxy.clone(),
721            });
722        }
723        source = e.source();
724    }
725    None
726}
727
728/// Map load shed errors to `HttpError::Overloaded`.
729///
730/// A shed request is observable via metrics: the concurrency limiter is inner to
731/// [`MetricsLayer`](crate::layers::metrics), so the rejection is recorded in
732/// `http.client.request.duration` with `error.type = "overloaded"`.
733fn map_load_shed_error(err: tower::BoxError) -> HttpError {
734    if err.is::<tower::load_shed::error::Overloaded>() {
735        HttpError::Overloaded
736    } else {
737        // Pass through other HttpError types (from inner service)
738        match err.downcast::<HttpError>() {
739            Ok(http_err) => *http_err,
740            Err(err) => HttpError::Transport(err),
741        }
742    }
743}
744
745/// Map the decompression response to our boxed response body type.
746///
747/// This converts `Response<DecompressionBody<Incoming>>` to `Response<ResponseBody>`
748/// by boxing the body with appropriate error type mapping.
749fn map_decompression_response<B>(response: Response<B>) -> Response<ResponseBody>
750where
751    B: hyper::body::Body<Data = Bytes> + Send + Sync + 'static,
752    B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
753{
754    let (parts, body) = response.into_parts();
755    // Convert the decompression body errors to our boxed error type.
756    // tower-http's DecompressionBody uses tower_http::BoxError which is
757    // compatible with our Box<dyn Error + Send + Sync> via Into.
758    let boxed_body: ResponseBody = body.map_err(Into::into).boxed();
759    Response::from_parts(parts, boxed_body)
760}
761
762/// Add `Proxy-Authorization` to a plain-HTTP request that goes through a
763/// forwarding proxy with credentials. A caller-set header is kept.
764fn add_forward_proxy_auth(
765    matcher: Option<&Matcher>,
766    mut req: http::Request<Full<Bytes>>,
767) -> http::Request<Full<Bytes>> {
768    if let Some(auth) = matcher.and_then(|m| connector::forward_proxy_auth(m, req.uri())) {
769        req.headers_mut()
770            .entry(http::header::PROXY_AUTHORIZATION)
771            .or_insert(auth);
772    }
773    req
774}
775
776/// Build the HTTPS connector: TLS roots plus extra roots, connect timeout and
777/// outbound proxy routing.
778///
779/// HTTP/2 is enabled via `enable_all_versions()` which configures ALPN to
780/// advertise both h2 and http/1.1. Protocol selection happens during TLS
781/// handshake based on server support.
782///
783/// # Errors
784///
785/// Returns `HttpError::Tls` if no usable root store can be built (e.g.
786/// `TlsRootConfig::Native` with an empty OS store and no extra roots, or an
787/// invalid extra root).
788fn build_https_connector(
789    config: &HttpClientConfig,
790    proxy_matcher: Option<Arc<Matcher>>,
791) -> Result<ConnectTimeout<HttpsConnector<ProxyConnector>>, HttpError> {
792    let allow_http = config.transport == TransportSecurity::AllowInsecureHttp;
793
794    // The `ClientConfig` is built by `tls` (not `with_provider_and_webpki_roots`)
795    // so FIPS hardening applies; see `tls::build_client_config`.
796    let root_store = tls::root_store_with_extra(config.tls_roots, &config.extra_root_certs)
797        .map_err(|e| HttpError::Tls(Box::new(e)))?;
798    let client_config = tls::custom_roots_client_config(root_store.clone(), &config.tls)
799        .map_err(|e| HttpError::Tls(Box::new(e)))?;
800
801    let mut http = HttpConnector::new();
802    // The HTTPS connector on top enforces the scheme.
803    http.enforce_http(false);
804    // Split across the resolved addresses; `ConnectTimeout` below bounds the
805    // whole connect.
806    http.set_connect_timeout(config.connect_timeout);
807    let tcp = match proxy_matcher {
808        None => ProxyConnector::direct(http),
809        Some(matcher) => {
810            // Same trust and TLS floor as the destination, but no client
811            // certificate (see `ProxyConnector::with_proxy`) and HTTP/1.1 only:
812            // `CONNECT` and forwarding are HTTP/1, so ALPN must not pick h2.
813            let proxy_tls = TlsConfig {
814                min_version: config.tls.min_version,
815                client_auth: None,
816            };
817            let mut proxy_tls = tls::custom_roots_client_config(root_store, &proxy_tls)
818                .map_err(|e| HttpError::Tls(Box::new(e)))?;
819            proxy_tls.alpn_protocols = vec![b"http/1.1".to_vec()];
820            let user_agent = http::HeaderValue::from_str(&config.user_agent)?;
821            ProxyConnector::with_proxy(http, matcher, proxy_tls, user_agent)
822        }
823    };
824
825    let builder = hyper_rustls::HttpsConnectorBuilder::new().with_tls_config(client_config);
826    let connector = if allow_http {
827        builder
828            .https_or_http()
829            .enable_all_versions()
830            .wrap_connector(tcp)
831    } else {
832        builder
833            .https_only()
834            .enable_all_versions()
835            .wrap_connector(tcp)
836    };
837    Ok(ConnectTimeout::new(connector, config.connect_timeout))
838}
839
840#[cfg(test)]
841#[cfg_attr(coverage_nightly, coverage(off))]
842mod tests {
843    use super::*;
844    use crate::config::DEFAULT_USER_AGENT;
845
846    #[test]
847    fn test_builder_default() {
848        let builder = HttpClientBuilder::new();
849        assert_eq!(builder.config.request_timeout, Duration::from_secs(30));
850        assert_eq!(builder.config.user_agent, DEFAULT_USER_AGENT);
851        assert!(builder.config.retry.is_some());
852        assert_eq!(builder.config.buffer_capacity, 1024);
853    }
854
855    #[test]
856    fn test_builder_with_config() {
857        let config = HttpClientConfig::minimal();
858        let builder = HttpClientBuilder::with_config(config);
859        assert_eq!(builder.config.request_timeout, Duration::from_secs(10));
860    }
861
862    #[test]
863    fn test_builder_timeout() {
864        let builder = HttpClientBuilder::new().timeout(Duration::from_mins(1));
865        assert_eq!(builder.config.request_timeout, Duration::from_mins(1));
866    }
867
868    #[test]
869    fn test_builder_user_agent() {
870        let builder = HttpClientBuilder::new().user_agent("custom/1.0");
871        assert_eq!(builder.config.user_agent, "custom/1.0");
872    }
873
874    #[test]
875    fn test_builder_retry() {
876        let builder = HttpClientBuilder::new().retry(None);
877        assert!(builder.config.retry.is_none());
878    }
879
880    #[test]
881    fn test_builder_max_body_size() {
882        let builder = HttpClientBuilder::new().max_body_size(1024);
883        assert_eq!(builder.config.max_body_size, 1024);
884    }
885
886    #[test]
887    fn test_builder_transport_security() {
888        let builder = HttpClientBuilder::new().transport(TransportSecurity::TlsOnly);
889        assert_eq!(builder.config.transport, TransportSecurity::TlsOnly);
890
891        let builder = HttpClientBuilder::new().deny_insecure_http();
892        assert_eq!(builder.config.transport, TransportSecurity::TlsOnly);
893
894        let builder = HttpClientBuilder::new();
895        #[cfg(not(feature = "fips"))]
896        assert_eq!(
897            builder.config.transport,
898            TransportSecurity::AllowInsecureHttp
899        );
900        #[cfg(feature = "fips")]
901        assert_eq!(builder.config.transport, TransportSecurity::TlsOnly);
902    }
903
904    #[test]
905    fn test_builder_otel() {
906        let builder = HttpClientBuilder::new().with_otel();
907        assert!(builder.config.otel);
908    }
909
910    #[test]
911    fn test_builder_buffer_capacity() {
912        let builder = HttpClientBuilder::new().buffer_capacity(512);
913        assert_eq!(builder.config.buffer_capacity, 512);
914    }
915
916    /// Test that `buffer_capacity=0` is clamped to 1 to prevent panic.
917    ///
918    /// Tower's Buffer panics with capacity=0, so we enforce minimum of 1.
919    #[test]
920    fn test_builder_buffer_capacity_zero_clamped() {
921        let builder = HttpClientBuilder::new().buffer_capacity(0);
922        assert_eq!(
923            builder.config.buffer_capacity, 1,
924            "buffer_capacity=0 should be clamped to 1"
925        );
926    }
927
928    /// Test that `buffer_capacity=0` via config is clamped during `build()`.
929    #[tokio::test]
930    async fn test_builder_buffer_capacity_zero_in_config_clamped() {
931        let config = HttpClientConfig {
932            buffer_capacity: 0, // Invalid - should be clamped in build()
933            ..Default::default()
934        };
935        let result = HttpClientBuilder::with_config(config).build();
936        // Should succeed (clamped to 1), not panic
937        assert!(
938            result.is_ok(),
939            "build() should succeed with capacity clamped to 1"
940        );
941    }
942
943    #[test]
944    fn test_builder_concurrency_limit() {
945        let builder = HttpClientBuilder::new().concurrency_limit(Some(RateLimitConfig {
946            max_concurrent_requests: 7,
947        }));
948        let rate_limit = builder.config.rate_limit.expect("rate_limit should be set");
949        assert_eq!(rate_limit.max_concurrent_requests, 7);
950    }
951
952    #[test]
953    fn test_builder_concurrency_limit_none_disables() {
954        let builder = HttpClientBuilder::new().concurrency_limit(None);
955        assert!(
956            builder.config.rate_limit.is_none(),
957            "None should disable the limiter"
958        );
959    }
960
961    /// `max_concurrent_requests: usize::MAX` is treated as unlimited — the layer
962    /// is skipped in `build()`. Building must still succeed.
963    #[tokio::test]
964    async fn test_builder_concurrency_limit_unlimited_builds() {
965        let client = HttpClientBuilder::new()
966            .concurrency_limit(Some(RateLimitConfig::unlimited()))
967            .build();
968        assert!(client.is_ok());
969    }
970
971    /// Smoke test: building with `max_concurrent_requests: 0` must not fail or
972    /// panic. This does *not* prove the `0 → 1` clamp works (a dead 0-permit
973    /// limiter also builds fine) — that is covered behaviourally in
974    /// toolkit-contract's `concurrency_limit::cap_zero_is_clamped_and_still_serves`,
975    /// which builds a cap-0 client and asserts a request is still served.
976    #[tokio::test]
977    async fn test_builder_concurrency_limit_zero_builds() {
978        let client = HttpClientBuilder::new()
979            .concurrency_limit(Some(RateLimitConfig {
980                max_concurrent_requests: 0,
981            }))
982            .build();
983        assert!(client.is_ok(), "build() should succeed with a 0 cap");
984    }
985
986    #[tokio::test]
987    async fn test_builder_build_with_otel() {
988        let client = HttpClientBuilder::new().with_otel().build();
989        assert!(client.is_ok());
990    }
991
992    #[tokio::test]
993    async fn test_builder_with_auth_layer() {
994        let client = HttpClientBuilder::new()
995            .with_auth_layer(|svc| svc) // identity transform
996            .build();
997        assert!(client.is_ok());
998    }
999
1000    #[tokio::test]
1001    async fn test_builder_with_metrics_layer() {
1002        let client = HttpClientBuilder::new()
1003            .with_metrics_layer(|svc| svc) // identity transform
1004            .build();
1005        assert!(client.is_ok());
1006    }
1007
1008    #[tokio::test]
1009    async fn test_builder_with_metrics_layer_second_call_replaces_first() {
1010        use std::sync::Arc;
1011        use std::sync::atomic::{AtomicUsize, Ordering};
1012
1013        let call_count = Arc::new(AtomicUsize::new(0));
1014        let call_count2 = call_count.clone();
1015
1016        // Second call should replace the first; only one layer is applied.
1017        let client = HttpClientBuilder::new()
1018            .with_metrics_layer(|_svc| {
1019                // This closure should NOT be called (replaced by the second).
1020                panic!("first metrics layer should have been replaced");
1021            })
1022            .with_metrics_layer(move |svc| {
1023                call_count2.fetch_add(1, Ordering::SeqCst);
1024                svc
1025            })
1026            .build();
1027
1028        assert!(client.is_ok());
1029        assert_eq!(
1030            call_count.load(Ordering::SeqCst),
1031            1,
1032            "second metrics layer must be applied exactly once"
1033        );
1034    }
1035
1036    #[tokio::test]
1037    async fn test_builder_build() {
1038        let client = HttpClientBuilder::new().build();
1039        assert!(client.is_ok());
1040    }
1041
1042    #[tokio::test]
1043    async fn test_builder_build_with_deny_insecure_http() {
1044        let client = HttpClientBuilder::new().deny_insecure_http().build();
1045        assert!(client.is_ok());
1046    }
1047
1048    #[tokio::test]
1049    async fn test_builder_build_with_sse_config() {
1050        use crate::config::HttpClientConfig;
1051        let config = HttpClientConfig::sse();
1052        let client = HttpClientBuilder::with_config(config).build();
1053        assert!(client.is_ok(), "SSE config should build successfully");
1054    }
1055
1056    #[tokio::test]
1057    async fn test_builder_build_invalid_user_agent() {
1058        let client = HttpClientBuilder::new()
1059            .user_agent("invalid\x00agent")
1060            .build();
1061        assert!(client.is_err());
1062    }
1063
1064    #[tokio::test]
1065    async fn test_builder_default_uses_webpki_roots() {
1066        let builder = HttpClientBuilder::new();
1067        assert_eq!(builder.config.tls_roots, TlsRootConfig::WebPki);
1068        // Build should succeed without OS native roots
1069        let client = builder.build();
1070        assert!(client.is_ok());
1071    }
1072
1073    #[tokio::test]
1074    async fn test_builder_native_roots() {
1075        let config = HttpClientConfig {
1076            tls_roots: TlsRootConfig::Native,
1077            ..Default::default()
1078        };
1079        let result = HttpClientBuilder::with_config(config).build();
1080
1081        // Native roots may succeed or fail depending on OS certificate availability.
1082        // On systems with certs: Ok(_)
1083        // On minimal containers without certs: Err(HttpError::Tls(_))
1084        match &result {
1085            Ok(_) => {
1086                // Success on systems with native certs
1087            }
1088            Err(HttpError::Tls(err)) => {
1089                // Expected failure on systems without native certs
1090                let msg = err.to_string();
1091                assert!(
1092                    msg.contains("native root") || msg.contains("certificate"),
1093                    "TLS error should mention certificates: {msg}"
1094                );
1095            }
1096            Err(other) => {
1097                panic!("Unexpected error type: {other:?}");
1098            }
1099        }
1100    }
1101
1102    #[tokio::test]
1103    async fn test_builder_webpki_roots_https_only() {
1104        let config = HttpClientConfig {
1105            tls_roots: TlsRootConfig::WebPki,
1106            transport: TransportSecurity::TlsOnly,
1107            ..Default::default()
1108        };
1109        let client = HttpClientBuilder::with_config(config).build();
1110        assert!(client.is_ok());
1111    }
1112
1113    /// Verify HTTP/2 is enabled for all TLS root configurations.
1114    ///
1115    /// HTTP/2 support is configured via `enable_all_versions()` on the connector,
1116    /// which sets up ALPN to negotiate h2 or http/1.1 during TLS handshake.
1117    /// The hyper client uses `http2_only(false)` to allow both protocols.
1118    ///
1119    #[tokio::test]
1120    async fn test_http2_enabled_for_all_configurations() {
1121        // Test WebPki with default transport (AllowInsecureHttp without fips, TlsOnly under fips)
1122        let client = HttpClientBuilder::new().build();
1123        assert!(
1124            client.is_ok(),
1125            "WebPki + default transport should build with HTTP/2 enabled"
1126        );
1127
1128        // Test WebPki with TlsOnly (HTTPS only)
1129        let client = HttpClientBuilder::new()
1130            .transport(TransportSecurity::TlsOnly)
1131            .build();
1132        assert!(
1133            client.is_ok(),
1134            "WebPki + TlsOnly should build with HTTP/2 enabled"
1135        );
1136
1137        // Test Native roots with AllowInsecureHttp
1138        let config = HttpClientConfig {
1139            tls_roots: TlsRootConfig::Native,
1140            transport: TransportSecurity::AllowInsecureHttp,
1141            ..Default::default()
1142        };
1143        let client = HttpClientBuilder::with_config(config).build();
1144        assert!(
1145            client.is_ok(),
1146            "Native + AllowInsecureHttp should build with HTTP/2 enabled"
1147        );
1148
1149        // Test Native roots with TlsOnly (HTTPS only)
1150        let config = HttpClientConfig {
1151            tls_roots: TlsRootConfig::Native,
1152            transport: TransportSecurity::TlsOnly,
1153            ..Default::default()
1154        };
1155        let client = HttpClientBuilder::with_config(config).build();
1156        assert!(
1157            client.is_ok(),
1158            "Native + TlsOnly should build with HTTP/2 enabled"
1159        );
1160    }
1161
1162    /// Test that concurrency limit uses fail-fast behavior (C2).
1163    ///
1164    /// `LoadShedLayer` + `ConcurrencyLimitLayer` combination returns Overloaded error
1165    /// immediately when capacity is exhausted, instead of blocking indefinitely.
1166    #[tokio::test]
1167    async fn test_load_shedding_returns_overloaded_error() {
1168        use bytes::Bytes;
1169        use http::{Request, Response};
1170        use http_body_util::Full;
1171        use std::future::Future;
1172        use std::pin::Pin;
1173        use std::sync::Arc;
1174        use std::sync::atomic::{AtomicUsize, Ordering};
1175        use std::task::{Context, Poll};
1176        use tower::Service;
1177        use tower::ServiceExt;
1178
1179        // A service that holds a slot forever once called
1180        #[derive(Clone)]
1181        struct SlotHoldingService {
1182            active: Arc<AtomicUsize>,
1183        }
1184
1185        impl Service<Request<Full<Bytes>>> for SlotHoldingService {
1186            type Response = Response<Full<Bytes>>;
1187            type Error = HttpError;
1188            type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
1189
1190            fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1191                Poll::Ready(Ok(()))
1192            }
1193
1194            fn call(&mut self, _: Request<Full<Bytes>>) -> Self::Future {
1195                self.active.fetch_add(1, Ordering::SeqCst);
1196                // Never complete - holds the slot
1197                Box::pin(std::future::pending())
1198            }
1199        }
1200
1201        let active = Arc::new(AtomicUsize::new(0));
1202
1203        // Build a service with load shedding and concurrency limit of 1
1204        let service = tower::ServiceBuilder::new()
1205            .layer(LoadShedLayer::new())
1206            .layer(ConcurrencyLimitLayer::new(1))
1207            .service(SlotHoldingService {
1208                active: active.clone(),
1209            });
1210
1211        let service = service.map_err(map_load_shed_error);
1212
1213        // First request: will occupy the single slot
1214        let req1 = Request::builder()
1215            .uri("http://test")
1216            .body(Full::new(Bytes::new()))
1217            .unwrap();
1218        let mut svc1 = service.clone();
1219
1220        let svc1_ready = svc1.ready().await.unwrap();
1221        let _pending_fut = svc1_ready.call(req1);
1222
1223        // Wait for the slot to be occupied
1224        tokio::time::sleep(Duration::from_millis(10)).await;
1225        assert_eq!(
1226            active.load(Ordering::SeqCst),
1227            1,
1228            "First request should be active"
1229        );
1230
1231        // Second request: LoadShedLayer should reject because ConcurrencyLimit is at capacity
1232        let req2 = Request::builder()
1233            .uri("http://test")
1234            .body(Full::new(Bytes::new()))
1235            .unwrap();
1236
1237        let mut svc2 = service.clone();
1238
1239        // LoadShedLayer checks poll_ready and returns Overloaded if inner service is not ready
1240        let result = tokio::time::timeout(Duration::from_millis(100), async {
1241            // poll_ready should return quickly with error (not block)
1242            match svc2.ready().await {
1243                Ok(ready_svc) => ready_svc.call(req2).await,
1244                Err(e) => Err(e),
1245            }
1246        })
1247        .await;
1248
1249        // Should complete within timeout (not hang) and return Overloaded
1250        assert!(result.is_ok(), "Request should not hang");
1251        let err = result.unwrap().unwrap_err();
1252        assert!(
1253            matches!(err, HttpError::Overloaded),
1254            "Expected Overloaded error, got: {err:?}"
1255        );
1256    }
1257
1258    // ==========================================================================
1259    // map_tower_error Tests
1260    // ==========================================================================
1261
1262    /// Test that `map_tower_error` preserves `HttpError::Overloaded` when wrapped in `BoxError`
1263    #[test]
1264    fn test_map_tower_error_preserves_overloaded() {
1265        let http_err = HttpError::Overloaded;
1266        let boxed: tower::BoxError = Box::new(http_err);
1267        let result = map_tower_error(boxed, Duration::from_secs(30));
1268
1269        assert!(
1270            matches!(result, HttpError::Overloaded),
1271            "Should preserve HttpError::Overloaded, got: {result:?}"
1272        );
1273    }
1274
1275    /// Test that `map_tower_error` preserves `HttpError::ServiceClosed` when wrapped in `BoxError`
1276    #[test]
1277    fn test_map_tower_error_preserves_service_closed() {
1278        let http_err = HttpError::ServiceClosed;
1279        let boxed: tower::BoxError = Box::new(http_err);
1280        let result = map_tower_error(boxed, Duration::from_secs(30));
1281
1282        assert!(
1283            matches!(result, HttpError::ServiceClosed),
1284            "Should preserve HttpError::ServiceClosed, got: {result:?}"
1285        );
1286    }
1287
1288    /// Test that `map_tower_error` preserves `HttpError::Timeout` with original duration
1289    #[test]
1290    fn test_map_tower_error_preserves_timeout_attempt() {
1291        let original_duration = Duration::from_secs(5);
1292        let http_err = HttpError::Timeout(original_duration);
1293        let boxed: tower::BoxError = Box::new(http_err);
1294        // Pass a different timeout to verify original is preserved
1295        let result = map_tower_error(boxed, Duration::from_secs(30));
1296
1297        match result {
1298            HttpError::Timeout(d) => {
1299                assert_eq!(
1300                    d, original_duration,
1301                    "Should preserve original timeout duration"
1302                );
1303            }
1304            other => panic!("Should preserve HttpError::Timeout, got: {other:?}"),
1305        }
1306    }
1307
1308    /// Test that `map_tower_error` wraps unknown errors as Transport
1309    #[test]
1310    fn test_map_tower_error_wraps_unknown_as_transport() {
1311        let other_err: tower::BoxError = Box::new(std::io::Error::new(
1312            std::io::ErrorKind::ConnectionRefused,
1313            "connection refused",
1314        ));
1315        let result = map_tower_error(other_err, Duration::from_secs(30));
1316
1317        assert!(
1318            matches!(result, HttpError::Transport(_)),
1319            "Should wrap unknown errors as Transport, got: {result:?}"
1320        );
1321    }
1322
1323    // ==========================================================================
1324    // Cancellation chain test
1325    //
1326    // Proves that dropping the response future from HttpClient cancels the
1327    // inner service future through the toolkit-http middleware stack
1328    // (Buffer → Concurrency → inner service). Retry is disabled to
1329    // isolate the cancellation path.
1330    //
1331    // Uses build_with_inner_service() to inject a fake slow service at the
1332    // bottom of the real tower stack - no HTTP server needed.
1333    // ==========================================================================
1334
1335    /// Dropping the `HttpClient::send()` future must cancel the inner
1336    /// service future through the full middleware stack.
1337    ///
1338    /// Injects a fake service via `build_with_inner_service()` that
1339    /// blocks on a `Notify` (never completes) and signals a second
1340    /// `Notify` from its `Drop` impl. No sleeps - purely notification-based.
1341    #[tokio::test]
1342    async fn test_cancellation_propagates_through_full_stack() {
1343        use crate::response::ResponseBody;
1344        use std::future::Future;
1345        use std::pin::Pin;
1346        use std::sync::Arc;
1347        use std::sync::atomic::{AtomicBool, Ordering};
1348        use std::task::{Context, Poll};
1349        use tower::Service;
1350
1351        #[derive(Clone)]
1352        struct PendingService {
1353            completed: Arc<AtomicBool>,
1354            drop_notifier: Arc<tokio::sync::Notify>,
1355            started_notifier: Arc<tokio::sync::Notify>,
1356        }
1357
1358        struct FutureGuard {
1359            completed: Arc<AtomicBool>,
1360            drop_notifier: Arc<tokio::sync::Notify>,
1361        }
1362
1363        impl Drop for FutureGuard {
1364            fn drop(&mut self) {
1365                if !self.completed.load(Ordering::SeqCst) {
1366                    self.drop_notifier.notify_one();
1367                }
1368            }
1369        }
1370
1371        impl Service<http::Request<Full<Bytes>>> for PendingService {
1372            type Response = http::Response<ResponseBody>;
1373            type Error = HttpError;
1374            type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
1375
1376            fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
1377                Poll::Ready(Ok(()))
1378            }
1379
1380            fn call(&mut self, _: http::Request<Full<Bytes>>) -> Self::Future {
1381                let completed = self.completed.clone();
1382                let drop_notifier = self.drop_notifier.clone();
1383                let started_notifier = self.started_notifier.clone();
1384                Box::pin(async move {
1385                    let _guard = FutureGuard {
1386                        completed: completed.clone(),
1387                        drop_notifier,
1388                    };
1389                    // Signal that the request reached the inner service
1390                    started_notifier.notify_one();
1391                    // Block forever - only completes via drop
1392                    std::future::pending::<()>().await;
1393                    completed.store(true, Ordering::SeqCst);
1394                    unreachable!()
1395                })
1396            }
1397        }
1398
1399        let inner_completed = Arc::new(AtomicBool::new(false));
1400        let drop_notifier = Arc::new(tokio::sync::Notify::new());
1401        let started_notifier = Arc::new(tokio::sync::Notify::new());
1402
1403        let inner = PendingService {
1404            completed: inner_completed.clone(),
1405            drop_notifier: drop_notifier.clone(),
1406            started_notifier: started_notifier.clone(),
1407        };
1408
1409        // Build the real HttpClient stack with our fake service at the bottom.
1410        // Retry disabled to isolate cancellation. Tests: Buffer → Concurrency → PendingService
1411        let client = HttpClientBuilder::new()
1412            .timeout(Duration::from_secs(30))
1413            .retry(None)
1414            .build_with_inner_service(inner.boxed_clone());
1415
1416        // Spawn the request so we can drop it explicitly.
1417        // URL uses https:// so the scheme validation in RequestBuilder passes
1418        // under both the non-fips default (AllowInsecureHttp) and the fips
1419        // default (TlsOnly); the connector here is the injected PendingService,
1420        // so no real TLS handshake happens.
1421        let send_handle = tokio::spawn({
1422            let client = client.clone();
1423            async move { client.get("https://fake/slow").send().await }
1424        });
1425
1426        // Wait for the request to reach the inner service
1427        started_notifier.notified().await;
1428
1429        // Drop the in-flight request by aborting the task
1430        send_handle.abort();
1431
1432        // Wait for the drop notification - no sleep, pure notification
1433        tokio::time::timeout(Duration::from_secs(5), drop_notifier.notified())
1434            .await
1435            .expect(
1436                "Inner service future should have been dropped within 5s - \
1437                 the full toolkit-http stack must propagate cancellation",
1438            );
1439
1440        assert!(
1441            !inner_completed.load(Ordering::SeqCst),
1442            "Inner service future should NOT have completed"
1443        );
1444    }
1445}