Skip to main content

iroh_http_core/http/server/
stack.rs

1//! Tower stack composition shared by [`crate::http::serve`] (server) and
2//! [`crate::http::client::fetch_request`] (client).
3//!
4//! Closes Slice B of #182.
5//!
6//! Before this slice the per-connection pipeline was assembled by
7//! [`super::pipeline::build_stack`] from a hand-coded
8//! `PipelineParams` struct, while the outgoing-fetch pipeline was assembled
9//! inline in `client.rs` from a one-off `HyperClientSvc` wrapper.
10//! Compression on serve and decompression on fetch composed with different
11//! code paths to do structurally the same thing.
12//!
13//! After this slice there is exactly one composition function per direction
14//! ([`build_stack`] for inbound, [`build_client_stack`] for outbound),
15//! both consume the same typed [`StackConfig`], and every middleware is
16//! driven by a dedicated `apply_*` factory taking [`ServeService`] →
17//! [`ServeService`] (axum-style boxed-per-layer composition). Toggling
18//! a `cfg` field off produces a service whose runtime shape is identical
19//! to the layer never having been built (no-op early-return).
20//!
21//! Layer ordering (outermost first), inbound:
22//!
23//! ```text
24//! [body limit →] HandleLayerError → [load shed →] [timeout →]
25//!   [compression →] [decompression →] svc
26//! ```
27//!
28//! Layer ordering (outermost first), outbound:
29//!
30//! ```text
31//! [decompression →] hyper SendRequest
32//! ```
33//!
34//! ## Why two functions, one config
35//!
36//! Server and client use the same primitive layers from `tower-http`, but
37//! in opposite roles: a server *responds* compressed (compression layer)
38//! and *accepts* compressed requests (decompression layer); a client *sends*
39//! plain and *accepts* compressed responses (decompression layer). A single
40//! [`StackConfig`] captures the operator's intent; the direction-specific
41//! function decides which subset to apply.
42//!
43//! Slice D (#186) replaces [`build_client_stack`]'s ad-hoc hyper wrapper
44//! with a proper `Service<Request<Body>, Response<Body>, FetchError>`
45//! contract; until then, the wrapper lives here so the construction site
46//! is unified even if the inner type still spells `hyper::Error`.
47
48use std::convert::Infallible;
49use std::pin::Pin;
50use std::time::Duration;
51
52use bytes::Bytes;
53use tower::ServiceBuilder;
54
55use crate::http::body::BoxError;
56use crate::Body;
57
58// ── Public-facing config type ────────────────────────────────────────────────
59
60/// Compression options for response bodies (server) and outgoing requests
61/// (client; reserved).
62///
63/// Lives in this module because it configures the compression layer in
64/// [`build_stack`]/[`build_client_stack`]. Re-exported from the crate root
65/// so adapter callsites are unchanged.
66#[derive(Debug, Clone)]
67pub struct CompressionOptions {
68    /// Minimum body size in bytes before compression is applied.
69    /// Default: [`CompressionOptions::DEFAULT_MIN_BODY_BYTES`] (1 KiB).
70    pub min_body_bytes: usize,
71    /// Zstd compression level (1–22). `None` uses the zstd default (3).
72    pub level: Option<u32>,
73}
74
75impl CompressionOptions {
76    /// Default minimum body size before compression is applied.
77    ///
78    /// 1 KiB. Matches the documented default and the threshold most HTTP
79    /// servers tune to: below ~1 KiB the CPU cost of compression typically
80    /// outweighs the bandwidth savings on a single TCP/QUIC packet.
81    pub const DEFAULT_MIN_BODY_BYTES: usize = 1024;
82}
83
84impl Default for CompressionOptions {
85    fn default() -> Self {
86        Self {
87            min_body_bytes: Self::DEFAULT_MIN_BODY_BYTES,
88            level: None,
89        }
90    }
91}
92
93// ── Internal stack types ─────────────────────────────────────────────────────
94
95/// Server-side stack alias: type-erased `Service<Request<Body>>` returning
96/// `Response<Body>` with [`Infallible`] errors.
97///
98/// Boxing once at the construction site (in `server::serve_with_events`)
99/// means every future addition to the layer stack — `AddExtensionLayer`,
100/// `TraceLayer`, a response-signing layer, anything — is **one append**
101/// in the builder without rippling a new concrete type signature through
102/// the per-bistream code path.
103pub(crate) type ServeService =
104    tower::util::BoxCloneService<hyper::Request<Body>, hyper::Response<Body>, Infallible>;
105
106/// Client-side stack alias.
107///
108/// Carries `hyper::Error` (Slice D will replace this with a typed
109/// `FetchError`). Boxed via [`tower::util::BoxService`] rather than
110/// [`tower::util::BoxCloneService`] because hyper's `SendRequest` is not
111/// `Clone`; the boxed service is consumed by a single `oneshot` call.
112pub(crate) type ClientService =
113    tower::util::BoxService<hyper::Request<Body>, hyper::Response<Body>, hyper::Error>;
114
115/// Tower stack configuration shared by [`build_stack`] and
116/// [`build_client_stack`].
117///
118/// Each field is consumed by a dedicated `apply_*` factory in this module
119/// (see [`build_stack`]'s body). Factories are no-ops when their field is
120/// `None`/`false`, so toggling a field off produces a service whose
121/// runtime shape is identical to the layer never having been built.
122///
123/// Composition uses the axum-style boxed-per-layer pattern: every
124/// `apply_*` takes a [`ServeService`] and returns a [`ServeService`],
125/// performing its own `boxed_clone()`. This re-erases the inner
126/// `Service::Future` after each layer, so layer addition is decoupled
127/// from the type-soup of `Either<L::Service, S>` and `impl Layer<…>`
128/// return-position bound erasure (see Slice B (#184) carry-forward in
129/// Slice C (#185)).
130///
131/// Slice D (#186): made public so the pure-Rust
132/// [`crate::http::client::fetch_request`] can take `&StackConfig` directly.
133/// `#[non_exhaustive]` so adapters constructing literal `StackConfig`
134/// values (`StackConfig { timeout, decompression, ..default() }`) opt in
135/// explicitly and future fields don't break them.
136#[derive(Clone, Debug)]
137#[non_exhaustive]
138pub struct StackConfig {
139    /// Application execution timeout. `None` ⇒ no `TimeoutLayer` is applied.
140    pub timeout: Option<Duration>,
141    /// Maximum time a request body may remain pending while it is actively
142    /// being consumed. `None` disables progress-based body protection.
143    pub body_idle_timeout: Option<Duration>,
144    /// Maximum **wire** request body size before the server rejects with 413.
145    ///
146    /// This limit is applied **before** decompression, i.e. it counts compressed
147    /// bytes as they arrive from the QUIC stream. It is an effective guard
148    /// against network-level DoS (high-bandwidth senders), but it does **not**
149    /// protect against a compression bomb (a small compressed body that
150    /// decompresses to many GB). Use [`Self::max_request_body_decoded_bytes`]
151    /// for that.
152    pub max_request_body_wire_bytes: Option<usize>,
153    /// Maximum **decoded** request body size before the server rejects with 413.
154    ///
155    /// This limit is applied **after** decompression. It is the primary guard
156    /// against compression bombs: a zstd payload that is tiny on the wire but
157    /// expands to GB in memory is rejected once the decoded byte count crosses
158    /// this threshold. Transparent proxies normally leave this unset and let
159    /// the application-facing server enforce its semantic decoded size.
160    pub max_request_body_decoded_bytes: Option<usize>,
161    /// `true` ⇒ wrap with `LoadShedLayer` so saturated capacity returns 503
162    /// immediately rather than blocking the caller.
163    pub load_shed: bool,
164    /// Operator's compression configuration. `None` disables response
165    /// compression on the server side; ignored by [`build_client_stack`]
166    /// (clients do not yet compress request bodies).
167    pub compression: Option<CompressionOptions>,
168    /// `true` ⇒ apply `RequestDecompressionLayer` (server) /
169    /// `DecompressionLayer` (client). Defaults to `true` — every server
170    /// today accepts compressed requests, every client accepts compressed
171    /// responses.
172    pub decompression: bool,
173}
174
175impl Default for StackConfig {
176    fn default() -> Self {
177        Self {
178            timeout: None,
179            body_idle_timeout: None,
180            max_request_body_wire_bytes: None,
181            max_request_body_decoded_bytes: None,
182            load_shed: false,
183            compression: None,
184            decompression: true,
185        }
186    }
187}
188
189impl StackConfig {
190    /// Set [`Self::timeout`] using the builder pattern.
191    ///
192    /// Convenience constructor for external callers — `#[non_exhaustive]`
193    /// blocks struct-literal construction outside this crate, so use
194    /// `StackConfig::default().with_timeout(...)`.
195    #[must_use]
196    pub fn with_timeout(mut self, timeout: Option<Duration>) -> Self {
197        self.timeout = timeout;
198        self
199    }
200
201    /// Set [`Self::decompression`] using the builder pattern.
202    #[must_use]
203    pub fn with_decompression(mut self, decompression: bool) -> Self {
204        self.decompression = decompression;
205        self
206    }
207}
208
209// ── Server pipeline ──────────────────────────────────────────────────────────
210
211/// Compose the inbound per-connection tower stack.
212///
213/// Layer ordering (outermost first):
214///
215/// ```text
216///   body idle timeout  →  wire body limit  →  load shed
217///                      →  request timeout
218///                      →  compression (response)
219///                      →  decompression (request)
220///                      →  decoded body limit
221///                      →  svc
222/// ```
223///
224/// Built bottom-up (innermost first) by chaining `apply_*` factories,
225/// each of which takes a [`ServeService`] and returns a [`ServeService`].
226/// Adding a new layer is a single line.
227///
228/// The two body-limit layers enforce different semantic guarantees:
229/// - **wire limit** (outermost): counts compressed bytes from the QUIC
230///   stream. Guards against high-bandwidth network floods.
231/// - **decoded limit** (inside decompression): counts bytes after
232///   `RequestDecompressionLayer` expands them. Guards against zstd/gzip
233///   compression bombs (#190).
234///
235/// `HandleLayerError` is owned **by each layer that can produce a
236/// `BoxError`** (load-shed, timeout) rather than threaded as a separate
237/// outer wrap: this keeps every factory's signature uniformly
238/// `ServeService → ServeService` and the chain composable in any order.
239/// See Slice C carry-forward (#185) for the design rationale.
240pub(crate) fn build_stack(svc: ServeService, cfg: &StackConfig) -> ServeService {
241    let svc = apply_body_limit(svc, cfg.max_request_body_decoded_bytes); // inside decompression
242    let svc = apply_decompression(svc, cfg.decompression);
243    let svc = apply_compression(svc, cfg.compression.as_ref());
244    let svc = apply_timeout(svc, cfg.timeout);
245    let svc = apply_load_shed(svc, cfg.load_shed);
246    let svc = apply_body_limit(svc, cfg.max_request_body_wire_bytes);
247    apply_body_idle_timeout(svc, cfg.body_idle_timeout) // outermost: raw wire progress
248}
249
250/// Bound gaps between frames while an application is actively consuming the
251/// request body. The timer is armed only while the inner body returns Pending,
252/// so application work performed between polls is not mistaken for network
253/// idleness.
254pub(crate) fn apply_body_idle_timeout(
255    svc: ServeService,
256    timeout: Option<Duration>,
257) -> ServeService {
258    use tower::ServiceExt;
259    use tower_http::map_request_body::MapRequestBodyLayer;
260
261    let Some(timeout) = timeout else {
262        return svc;
263    };
264    ServiceBuilder::new()
265        .layer(MapRequestBodyLayer::new(move |body| {
266            Body::new(BodyIdleTimeout::new(body, timeout))
267        }))
268        .service(svc)
269        .boxed_clone()
270}
271
272pin_project_lite::pin_project! {
273    struct BodyIdleTimeout<B> {
274        #[pin]
275        inner: B,
276        timeout: Duration,
277        timer: Option<Pin<Box<tokio::time::Sleep>>>,
278        done: bool,
279    }
280}
281
282impl<B> BodyIdleTimeout<B> {
283    fn new(inner: B, timeout: Duration) -> Self {
284        Self {
285            inner,
286            timeout,
287            timer: None,
288            done: false,
289        }
290    }
291}
292
293#[derive(Debug, thiserror::Error)]
294#[error("request body made no progress before the idle timeout")]
295struct BodyIdleTimeoutError;
296
297impl<B> http_body::Body for BodyIdleTimeout<B>
298where
299    B: http_body::Body<Data = Bytes>,
300    B::Error: Into<BoxError>,
301{
302    type Data = Bytes;
303    type Error = BoxError;
304
305    fn poll_frame(
306        self: Pin<&mut Self>,
307        cx: &mut std::task::Context<'_>,
308    ) -> std::task::Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
309        use std::future::Future;
310
311        let mut this = self.project();
312        if *this.done {
313            return std::task::Poll::Ready(None);
314        }
315        match this.inner.as_mut().poll_frame(cx) {
316            std::task::Poll::Ready(Some(Ok(frame))) => {
317                *this.timer = None;
318                std::task::Poll::Ready(Some(Ok(frame)))
319            }
320            std::task::Poll::Ready(Some(Err(error))) => {
321                *this.done = true;
322                std::task::Poll::Ready(Some(Err(error.into())))
323            }
324            std::task::Poll::Ready(None) => {
325                *this.done = true;
326                std::task::Poll::Ready(None)
327            }
328            std::task::Poll::Pending => {
329                let timer = this
330                    .timer
331                    .get_or_insert_with(|| Box::pin(tokio::time::sleep(*this.timeout)));
332                if timer.as_mut().poll(cx).is_ready() {
333                    *this.done = true;
334                    std::task::Poll::Ready(Some(Err(Box::new(BodyIdleTimeoutError))))
335                } else {
336                    std::task::Poll::Pending
337                }
338            }
339        }
340    }
341
342    fn is_end_stream(&self) -> bool {
343        self.done || self.inner.is_end_stream()
344    }
345
346    fn size_hint(&self) -> http_body::SizeHint {
347        self.inner.size_hint()
348    }
349}
350
351// ── Renormalisation helper ───────────────────────────────────────────────────
352
353/// Convert any body type back to [`Body`].
354///
355/// Used as the mapping function in `MapResponseBodyLayer` / `MapRequestBodyLayer`
356/// after every layer that changes the body type. Since [`Body::new`] already
357/// short-circuits via `try_downcast` when the input is already a `Body`, the
358/// cost of using this at every seam is essentially free for pass-through layers.
359fn renormalize_body<B>(body: B) -> Body
360where
361    B: http_body::Body<Data = Bytes> + Send + 'static,
362    B::Error: Into<BoxError>,
363{
364    Body::new(body)
365}
366
367// ── Layer factories ──────────────────────────────────────────────────────────
368
369/// `RequestBodyLimitLayer` rejects oversize bodies with 413. Wrapped in
370/// matching `MapRequestBody` / `MapResponseBody` to renormalise both
371/// directions back to [`Body`] (ADR-014 D2 / #175).
372pub(crate) fn apply_body_limit(svc: ServeService, limit: Option<usize>) -> ServeService {
373    use tower::ServiceExt;
374    use tower_http::limit::RequestBodyLimitLayer;
375    use tower_http::map_request_body::MapRequestBodyLayer;
376    use tower_http::map_response_body::MapResponseBodyLayer;
377
378    let Some(limit) = limit else {
379        return svc;
380    };
381    ServiceBuilder::new()
382        .layer(MapResponseBodyLayer::new(renormalize_body))
383        .layer(RequestBodyLimitLayer::new(limit))
384        .layer(MapRequestBodyLayer::new(renormalize_body))
385        .service(svc)
386        .boxed_clone()
387}
388
389/// `LoadShedLayer` returns `Overloaded` immediately when the inner
390/// service reports `Poll::Pending` from `poll_ready`. The error is
391/// converted to a 503 response by an inner [`HandleLayerErrorLayer`] so
392/// the resulting service still has `Error = Infallible`. No-op when
393/// `enabled = false`.
394pub(crate) fn apply_load_shed(svc: ServeService, enabled: bool) -> ServeService {
395    use crate::http::server::HandleLayerErrorLayer;
396    use tower::ServiceExt;
397    if !enabled {
398        return svc;
399    }
400    ServiceBuilder::new()
401        .layer(HandleLayerErrorLayer)
402        .layer(tower::load_shed::LoadShedLayer::new())
403        .service(svc)
404        .boxed_clone()
405}
406
407/// Application execution timeout. The `Elapsed` error is converted to a 408
408/// response by an inner [`HandleLayerErrorLayer`] so the resulting
409/// service still has `Error = Infallible`. No-op when `timeout = None`.
410pub(crate) fn apply_timeout(svc: ServeService, timeout: Option<Duration>) -> ServeService {
411    use crate::http::server::HandleLayerErrorLayer;
412    use tower::ServiceExt;
413    let Some(timeout) = timeout else {
414        return svc;
415    };
416    ServiceBuilder::new()
417        .layer(HandleLayerErrorLayer)
418        .layer(tower::timeout::TimeoutLayer::new(timeout))
419        .service(svc)
420        .boxed_clone()
421}
422
423/// Response compression with project-specific predicates (see
424/// [`build_compression_layer`]). No-op when `comp = None`.
425pub(crate) fn apply_compression(
426    svc: ServeService,
427    comp: Option<&CompressionOptions>,
428) -> ServeService {
429    use tower::ServiceExt;
430    use tower_http::map_response_body::MapResponseBodyLayer;
431
432    let Some(comp) = comp else {
433        return svc;
434    };
435    ServiceBuilder::new()
436        .layer(MapResponseBodyLayer::new(renormalize_body))
437        .layer(build_compression_layer(comp))
438        .service(svc)
439        .boxed_clone()
440}
441
442/// Request decompression. Wrapped in matching `MapRequestBody` /
443/// `MapResponseBody` to renormalise both body sides back to [`Body`].
444/// No-op when `enabled = false`.
445pub(crate) fn apply_decompression(svc: ServeService, enabled: bool) -> ServeService {
446    use tower::ServiceExt;
447    use tower_http::decompression::RequestDecompressionLayer;
448    use tower_http::map_request_body::MapRequestBodyLayer;
449    use tower_http::map_response_body::MapResponseBodyLayer;
450
451    if !enabled {
452        return svc;
453    }
454    ServiceBuilder::new()
455        .layer(MapResponseBodyLayer::new(renormalize_body))
456        .layer(RequestDecompressionLayer::new())
457        .layer(MapRequestBodyLayer::new(renormalize_body))
458        .service(svc)
459        .boxed_clone()
460}
461
462/// Build the `tower-http` compression layer with the project's predicate set.
463///
464/// Two custom predicates remain because tower-http does not ship built-ins
465/// for either:
466///
467/// 1. Skip if the response already carries `Content-Encoding` (handler
468///    returned a pre-encoded body — re-compressing would double-encode).
469/// 2. Honour `Cache-Control: no-transform` per RFC 9111 §5.2.2.7.
470pub(crate) fn build_compression_layer(
471    comp: &CompressionOptions,
472) -> tower_http::compression::CompressionLayer<impl tower_http::compression::Predicate> {
473    use http::{Extensions, HeaderMap, StatusCode, Version};
474    use tower_http::compression::{
475        predicate::{NotForContentType, Predicate, SizeAbove},
476        CompressionLayer, CompressionLevel,
477    };
478
479    let mut layer = CompressionLayer::new().zstd(true);
480    if let Some(level) = comp.level {
481        layer = layer.quality(CompressionLevel::Precise(level as i32));
482    }
483
484    let not_pre_compressed = |_: StatusCode, _: Version, h: &HeaderMap, _: &Extensions| {
485        !h.contains_key(http::header::CONTENT_ENCODING)
486    };
487    let not_no_transform = |_: StatusCode, _: Version, h: &HeaderMap, _: &Extensions| {
488        h.get(http::header::CACHE_CONTROL)
489            .and_then(|v| v.to_str().ok())
490            .map(|v| {
491                !v.split(',')
492                    .any(|d| d.trim().eq_ignore_ascii_case("no-transform"))
493            })
494            .unwrap_or(true)
495    };
496
497    let predicate = SizeAbove::new(comp.min_body_bytes as u64)
498        .and(NotForContentType::IMAGES)
499        .and(NotForContentType::SSE)
500        .and(NotForContentType::const_new("audio/"))
501        .and(NotForContentType::const_new("video/"))
502        .and(NotForContentType::const_new("application/zstd"))
503        .and(NotForContentType::const_new("application/octet-stream"))
504        .and(not_pre_compressed)
505        .and(not_no_transform);
506
507    layer.compress_when(predicate)
508}
509
510// ── Client pipeline ──────────────────────────────────────────────────────────
511
512/// Compose the outbound per-request tower stack.
513///
514/// ```text
515///   [timeout →] decompression → incoming→Body → hyper SendRequest
516/// ```
517///
518/// Returns a [`ClientService`] — boxed once so the caller
519/// ([`crate::http::client::fetch_request`]) does not have to spell the inner
520/// type. Honours `cfg.decompression`. `cfg.timeout` is **not** wired into
521/// this stack — enforcing it as a tower layer would change the service
522/// error type away from `hyper::Error`. The pure-Rust caller
523/// [`crate::http::client::fetch_request`] applies `cfg.timeout` with an
524/// outer `tokio::time::timeout` instead. Per Slice D
525/// (#186) the inner `SendRequest` wrapper that used to be a named
526/// `HyperClientSvc` lives inline below.
527pub(crate) fn build_client_stack(
528    sender: hyper::client::conn::http1::SendRequest<Body>,
529    cfg: &StackConfig,
530) -> ClientService {
531    use tower::ServiceExt;
532    use tower_http::map_response_body::MapResponseBodyLayer;
533
534    // Inline `SendRequest<Body> as tower::Service` adapter. Lives inside
535    // `build_client_stack` so the wrapper has no name outside this
536    // function (Slice D acceptance #3).
537    struct SendRequestSvc(hyper::client::conn::http1::SendRequest<Body>);
538
539    impl tower::Service<hyper::Request<Body>> for SendRequestSvc {
540        type Response = hyper::Response<hyper::body::Incoming>;
541        type Error = hyper::Error;
542        type Future = std::pin::Pin<
543            Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
544        >;
545
546        fn poll_ready(
547            &mut self,
548            cx: &mut std::task::Context<'_>,
549        ) -> std::task::Poll<Result<(), Self::Error>> {
550            self.0.poll_ready(cx)
551        }
552
553        fn call(&mut self, req: hyper::Request<Body>) -> Self::Future {
554            Box::pin(self.0.send_request(req))
555        }
556    }
557
558    // Step 1: normalise hyper's `Incoming` to `Body` so subsequent layers
559    // operate on the canonical body type.
560    let svc = ServiceBuilder::new()
561        .layer(MapResponseBodyLayer::new(renormalize_body))
562        .service(SendRequestSvc(sender))
563        .boxed();
564
565    // Step 2: optional response decompression (always-on by default).
566    apply_client_decompression(svc, cfg.decompression)
567    // Per-request timeout is enforced by the caller in
568    // [`crate::http::client::fetch_request`] via `tokio::time::timeout` rather
569    // than a `TimeoutLayer` here, so the `ClientService` error type can
570    // stay `hyper::Error` and the timeout maps cleanly to
571    // `FetchError::Timeout` without going through `BoxError` downcasts.
572}
573
574/// Client-side equivalent of [`apply_decompression`]. No-op when
575/// `enabled = false`.
576pub(crate) fn apply_client_decompression(svc: ClientService, enabled: bool) -> ClientService {
577    use tower::ServiceExt;
578    use tower_http::decompression::DecompressionLayer;
579    use tower_http::map_response_body::MapResponseBodyLayer;
580
581    if !enabled {
582        return svc;
583    }
584    ServiceBuilder::new()
585        .layer(MapResponseBodyLayer::new(renormalize_body))
586        .layer(DecompressionLayer::new())
587        .service(svc)
588        .boxed()
589}
590
591#[cfg(test)]
592mod tests {
593    //! ADR-014 D2 / #175 + Slice B (#184) guardrail.
594    //!
595    //! Exercises the *real* per-bistream chain ([`build_stack`]) to prove
596    //! the structural property the issue was filed for: every layer in the
597    //! production pipeline composes uniformly into [`ServeService`], and a
598    //! request still flows through to a `Response<Body>`. If a future
599    //! change to the inner service's body or error type breaks uniformity,
600    //! `build_stack` itself stops compiling — the failure surfaces here,
601    //! not later in an integration test over the network.
602    //!
603    //! No hyper / no Iroh / no networking: feeds requests directly into
604    //! the boxed [`ServeService`] with `tower::ServiceExt::oneshot`.
605
606    use super::*;
607    use bytes::Bytes;
608    use http_body_util::BodyExt;
609    use std::convert::Infallible;
610    use tower::ServiceExt;
611
612    /// Stand-in for `IrohHttpService` shaped exactly like the real one
613    /// (`Service<Request<Body>, Response = Response<Body>, Error = Infallible>`).
614    /// Echoes the request body back in the response.
615    #[derive(Clone)]
616    struct EchoService;
617
618    impl tower::Service<hyper::Request<Body>> for EchoService {
619        type Response = hyper::Response<Body>;
620        type Error = Infallible;
621        type Future = std::pin::Pin<
622            Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
623        >;
624
625        fn poll_ready(
626            &mut self,
627            _cx: &mut std::task::Context<'_>,
628        ) -> std::task::Poll<Result<(), Self::Error>> {
629            std::task::Poll::Ready(Ok(()))
630        }
631
632        fn call(&mut self, req: hyper::Request<Body>) -> Self::Future {
633            Box::pin(async move {
634                let bytes = req
635                    .into_body()
636                    .collect()
637                    .await
638                    .map(|c| c.to_bytes())
639                    .unwrap_or_default();
640                Ok(hyper::Response::new(Body::full(bytes)))
641            })
642        }
643    }
644
645    fn default_cfg() -> StackConfig {
646        StackConfig {
647            timeout: None,
648            body_idle_timeout: None,
649            max_request_body_wire_bytes: Some(1024 * 1024),
650            max_request_body_decoded_bytes: Some(1024 * 1024),
651            load_shed: true,
652            compression: None,
653            decompression: true,
654        }
655    }
656
657    #[tokio::test]
658    async fn body_idle_timeout_fails_a_stalled_stream() {
659        let inner = http_body_util::StreamBody::new(futures::stream::pending::<
660            Result<http_body::Frame<Bytes>, Infallible>,
661        >());
662        let body = BodyIdleTimeout::new(inner, Duration::from_millis(10));
663        let error = Body::new(body)
664            .collect()
665            .await
666            .expect_err("stalled body must time out");
667        assert!(error.to_string().contains("made no progress"));
668    }
669
670    fn boxed_echo() -> ServeService {
671        ServiceBuilder::new().service(EchoService).boxed_clone()
672    }
673
674    /// Drives the *production* `build_stack`. Body limit, load-shed and
675    /// decompression are all in-circuit. If any of them stops composing
676    /// into `ServeService`, this fails to compile — that is the structural
677    /// guardrail.
678    #[tokio::test]
679    async fn real_chain_round_trips_a_request() {
680        let stack = build_stack(boxed_echo(), &default_cfg());
681
682        let req = hyper::Request::builder()
683            .uri("/")
684            .body(Body::full("ping"))
685            .unwrap();
686        let resp = stack.oneshot(req).await.expect("service infallible");
687        assert_eq!(resp.status(), hyper::StatusCode::OK);
688        let body = resp
689            .into_body()
690            .collect()
691            .await
692            .expect("body collect")
693            .to_bytes();
694        assert_eq!(body, Bytes::from_static(b"ping"));
695    }
696
697    /// Same chain, with response-side compression enabled. Proves the
698    /// `option_layer(comp_layer)` arm composes and produces the same
699    /// `ServeService` shape.
700    #[tokio::test]
701    async fn real_chain_with_compression_enabled_still_round_trips() {
702        let mut cfg = default_cfg();
703        cfg.compression = Some(CompressionOptions {
704            level: None,
705            min_body_bytes: 0,
706        });
707        let stack = build_stack(boxed_echo(), &cfg);
708
709        let req = hyper::Request::builder()
710            .uri("/")
711            .header("accept-encoding", "zstd")
712            .body(Body::full("ping"))
713            .unwrap();
714        let resp = stack.oneshot(req).await.expect("service infallible");
715        assert_eq!(resp.status(), hyper::StatusCode::OK);
716        // Body is opaque (may be zstd-encoded). We only assert structural
717        // success; wire-format coverage lives in the dedicated compression
718        // integration tests.
719        let _ = resp.into_body().collect().await;
720    }
721
722    /// #184 acceptance criterion 5 — extensibility regression test.
723    ///
724    /// Wraps the production `build_stack` output with one additional
725    /// `MapRequestBodyLayer::new(identity)` and asserts the request still
726    /// flows. Demonstrates ADR-014 D2's structural payoff at runtime: a
727    /// new layer is one append, no signature change anywhere downstream
728    /// because both `build_stack`'s input and output are
729    /// [`ServeService`]. If a future layer addition breaks the
730    /// "uniformly composes into `ServeService`" property this test fails
731    /// to compile.
732    #[tokio::test]
733    async fn build_stack_accepts_additional_outer_layer() {
734        use tower_http::map_request_body::MapRequestBodyLayer;
735
736        let inner = build_stack(boxed_echo(), &default_cfg());
737        let stack = ServiceBuilder::new()
738            .layer(MapRequestBodyLayer::new(|b: Body| b))
739            .service(inner);
740
741        let req = hyper::Request::builder()
742            .uri("/")
743            .body(Body::full("ping"))
744            .unwrap();
745        let resp = stack.oneshot(req).await.expect("service infallible");
746        assert_eq!(resp.status(), hyper::StatusCode::OK);
747        let body = resp
748            .into_body()
749            .collect()
750            .await
751            .expect("body collect")
752            .to_bytes();
753        assert_eq!(body, Bytes::from_static(b"ping"));
754    }
755}