Skip to main content

servers/http/
memory_limit.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Middleware for limiting total memory usage of concurrent HTTP request bodies.
16//!
17//! Admission works in two stages:
18//!
19//! 1. Upfront, the request's `Content-Length` (if present) is charged to the
20//!    shared [`ServerMemoryLimiter`], preserving the configured wait/fail
21//!    policy for regular requests.
22//! 2. While the body is streamed, [`AccountedBody`] charges every byte beyond
23//!    the upfront reservation. This closes two gaps of a header-only
24//!    reservation: HTTP/1.1 chunked requests carry no `Content-Length` (and
25//!    would otherwise be admitted for free), and a client can understate the
26//!    header while sending a much larger body.
27//!
28//! Upfront and streaming permits are held by [`BodyMemoryAccounting`],
29//! which is also inserted into the request extensions so they stay alive until
30//! the whole request is finished (extractors collect the body into owned
31//! buffers that outlive the body stream itself).
32
33use std::pin::Pin;
34use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
35use std::sync::{Arc, Mutex, Weak};
36use std::task::{Context, Poll};
37
38use axum::body::Body;
39use axum::extract::{Request, State};
40use axum::middleware::Next;
41use axum::response::{IntoResponse, Response};
42use bytes::Bytes;
43use common_memory_manager::MemoryGuard;
44use http::StatusCode;
45use http_body::{Body as HttpBody, Frame};
46
47use crate::error::Result;
48use crate::request_memory_limiter::ServerMemoryLimiter;
49use crate::request_memory_metrics::RequestMemoryMetrics;
50
51/// Marker inserted by [`memory_limit_middleware`] when the request arrives
52/// with a non-identity `Content-Encoding` header. Route-local
53/// [`decoded_body_accounting_middleware`] uses it to account the decompressed
54/// body: only such requests expand during request decompression.
55#[derive(Clone, Copy)]
56pub(crate) struct ContentEncoded;
57
58pub async fn memory_limit_middleware(
59    State(limiter): State<ServerMemoryLimiter>,
60    req: Request,
61    next: Next,
62) -> Response {
63    let content_length = req
64        .headers()
65        .get(http::header::CONTENT_LENGTH)
66        .and_then(|v| v.to_str().ok())
67        .and_then(|v| v.parse::<u64>().ok())
68        .unwrap_or(0);
69
70    // A fresh request must not claim partial FIFO permits that an active
71    // request (including PostgreSQL COPY) needs to finish.
72    let guard = match limiter.admit_stream(content_length).await {
73        Ok(guard) => guard,
74        Err(e) => {
75            return (
76                StatusCode::TOO_MANY_REQUESTS,
77                format!("Request body memory limit exceeded: {}", e),
78            )
79                .into_response();
80        }
81    };
82
83    let content_encoded = req
84        .headers()
85        .get(http::header::CONTENT_ENCODING)
86        .and_then(|v| v.to_str().ok())
87        .is_some_and(|v| !v.eq_ignore_ascii_case("identity"));
88
89    // Account whatever is actually streamed beyond the upfront reservation
90    // (chunked transfer has none).
91    let accounting = BodyMemoryAccounting::default();
92    accounting.hold(guard);
93    // The middleware keeps its own handle so the acquired permits stay held
94    // for the whole request: the body wrapper and the extensions are dropped
95    // once the extractors finish collecting the body, before the handler is
96    // done with the decoded data.
97    let retained_accounting = accounting.clone();
98    let (mut parts, body) = req.into_parts();
99    // Expose the limiter to handlers that decompress request bodies on their
100    // own (e.g. the Loki protobuf push) so they can charge the decoded size.
101    parts.extensions.insert(limiter.clone());
102    parts.extensions.insert(accounting.clone());
103    if content_encoded {
104        parts.extensions.insert(ContentEncoded);
105    }
106    let accounted = AccountedBody::new(body, limiter, content_length, accounting);
107    let req = Request::from_parts(parts, Body::new(accounted));
108
109    let response = next.run(req).await;
110    // `retained_accounting` stays alive until this function returns, holding
111    // the permits across the handler's use of the collected body.
112    quota_exceeded_response(&retained_accounting, response)
113}
114
115/// Rewrites the response of a request whose body accounting hit the quota:
116/// the failure aborts the body mid-stream, so the extractors reject the
117/// request with a generic body error (mapped to 400). Quota exhaustion must
118/// surface as 429, matching the upfront admission path, so clients can tell
119/// backpressure apart from malformed input.
120fn quota_exceeded_response(accounting: &BodyMemoryAccounting, response: Response) -> Response {
121    // The flag can only be set when the body failed before the handler ran,
122    // so the response is the extractor rejection and can be replaced.
123    if accounting.take_quota_exceeded() {
124        return (
125            StatusCode::TOO_MANY_REQUESTS,
126            "Request body memory limit exceeded",
127        )
128            .into_response();
129    }
130    response
131}
132
133/// Route-local accounting for routes that install `RequestDecompressionLayer`:
134/// it must be layered *inside* the
135/// decompression layer, so the body it wraps is the **decompressed** stream.
136/// It requires the global accounting installed by [`crate::http::HttpServer`]
137/// and must use the same [`ServerMemoryLimiter`].
138///
139/// Only encoded requests marked by the global middleware are
140/// accounted; plain (uncompressed) requests are already covered by the global
141/// wire-byte accounting, and charging them here as well would double-count.
142/// For decompressed requests the `Content-Length` header has been stripped by
143/// the decompression layer, so the full decoded size is charged as it streams.
144pub async fn decoded_body_accounting_middleware(
145    State(limiter): State<ServerMemoryLimiter>,
146    req: Request,
147    next: Next,
148) -> Response {
149    if req.extensions().get::<ContentEncoded>().is_none() {
150        return next.run(req).await;
151    }
152
153    let content_length = req
154        .headers()
155        .get(http::header::CONTENT_LENGTH)
156        .and_then(|v| v.to_str().ok())
157        .and_then(|v| v.parse::<u64>().ok())
158        .unwrap_or(0);
159
160    // Share the wire-byte ledger so handlers see all permits held by this request.
161    let accounting = req
162        .extensions()
163        .get::<BodyMemoryAccounting>()
164        .cloned()
165        .unwrap_or_default();
166    // Retain the permits for the whole request, like the global middleware.
167    let retained_accounting = accounting.clone();
168    let (mut parts, body) = req.into_parts();
169    parts.extensions.insert(accounting.clone());
170    let accounted = AccountedBody::new(body, limiter, content_length, accounting);
171    let req = Request::from_parts(parts, Body::new(accounted));
172
173    let response = next.run(req).await;
174    // `retained_accounting` stays alive until this function returns, holding
175    // the permits across the handler's use of the collected body.
176    quota_exceeded_response(&retained_accounting, response)
177}
178
179/// Holds the memory guards acquired upfront and while a request body is streamed. Shared
180/// between the [`AccountedBody`] wrapper, the request extensions and the
181/// middleware itself, so the permits are only released when the request
182/// (including any collected body buffers and the handler still using them)
183/// is finished.
184#[derive(Clone, Default)]
185pub(crate) struct BodyMemoryAccounting {
186    guards: Arc<Mutex<Vec<MemoryGuard<RequestMemoryMetrics>>>>,
187    reserved_bytes: Arc<AtomicU64>,
188    /// Set when an incremental charge hit the quota, so the rejection can be
189    /// rewritten into a 429 after the middleware regains control.
190    quota_exceeded: Arc<AtomicBool>,
191}
192
193impl BodyMemoryAccounting {
194    /// Includes permit rounding and all frames collected so far.
195    pub(crate) fn reserved_bytes(&self) -> u64 {
196        self.reserved_bytes.load(Ordering::Acquire)
197    }
198
199    /// Observes subsequent body charges without extending the guards' lifetime.
200    pub(crate) fn reserved_bytes_counter(&self) -> Weak<AtomicU64> {
201        Arc::downgrade(&self.reserved_bytes)
202    }
203
204    fn hold(&self, guard: MemoryGuard<RequestMemoryMetrics>) {
205        self.reserved_bytes
206            .fetch_add(guard.granted_bytes(), Ordering::Release);
207        self.guards.lock().unwrap().push(guard);
208    }
209
210    fn mark_quota_exceeded(&self) {
211        self.quota_exceeded.store(true, Ordering::Release);
212    }
213
214    fn take_quota_exceeded(&self) -> bool {
215        self.quota_exceeded.swap(false, Ordering::AcqRel)
216    }
217}
218
219type AcquireFuture =
220    Pin<Box<dyn std::future::Future<Output = Result<MemoryGuard<RequestMemoryMetrics>>> + Send>>;
221
222enum ChargeOutcome {
223    Charged,
224    Pending,
225    Failed,
226}
227
228/// A request body wrapper that charges the shared limiter for every byte
229/// streamed beyond `pre_charged` (the upfront `Content-Length` reservation).
230struct AccountedBody {
231    inner: Body,
232    limiter: ServerMemoryLimiter,
233    accounting: BodyMemoryAccounting,
234    /// Bytes of body data streamed so far.
235    streamed: u64,
236    /// Bytes of the streamed body already covered by incremental permits.
237    incrementally_charged: u64,
238    /// Bytes covered by the upfront `Content-Length` reservation.
239    pre_charged: u64,
240    /// A data frame held back while its permit is being acquired, together
241    /// with the number of extra bytes to charge for it.
242    pending: Option<(Frame<Bytes>, u64)>,
243    pending_acquire: Option<AcquireFuture>,
244}
245
246impl AccountedBody {
247    fn new(
248        inner: Body,
249        limiter: ServerMemoryLimiter,
250        pre_charged: u64,
251        accounting: BodyMemoryAccounting,
252    ) -> Self {
253        Self {
254            inner,
255            limiter,
256            accounting,
257            streamed: 0,
258            incrementally_charged: 0,
259            pre_charged,
260            pending: None,
261            pending_acquire: None,
262        }
263    }
264
265    /// Bytes that still need an incremental permit for the body streamed so far.
266    fn uncharged(&self) -> u64 {
267        self.streamed
268            .saturating_sub(self.pre_charged)
269            .saturating_sub(self.incrementally_charged)
270    }
271
272    /// Acquires a permit for `bytes`; only one acquisition may be in flight.
273    ///
274    /// A parked acquisition always belongs to the currently buffered frame, so
275    /// it must be resolved *before* any new acquisition is tried: letting the
276    /// fast path succeed while a waiter is parked would leave the waiter alive,
277    /// and its late completion would then be credited with another frame's
278    /// byte count (under-reserving memory relative to what is marked charged).
279    fn charge(&mut self, bytes: u64, cx: &mut Context<'_>) -> ChargeOutcome {
280        debug_assert!(bytes > 0);
281        let fut = match &mut self.pending_acquire {
282            Some(fut) => fut,
283            None => {
284                if let Some(guard) = self.limiter.probe(bytes) {
285                    self.accounting.hold(guard);
286                    self.incrementally_charged += bytes;
287                    return ChargeOutcome::Charged;
288                }
289                // Without Content-Length, the first data frame is the initial
290                // admission. Consult the shared ledger: a decoded body can
291                // already hold permits from its wire representation.
292                let initial = self.accounting.reserved_bytes() == 0;
293                let limiter = self.limiter.clone();
294                self.pending_acquire.insert(Box::pin(async move {
295                    if initial {
296                        limiter.admit_stream(bytes).await
297                    } else {
298                        limiter.acquire(bytes).await
299                    }
300                }))
301            }
302        };
303        // Poll immediately so a ready result is not missed (returning
304        // `Pending` without registering progress would park the task forever).
305        match fut.as_mut().poll(cx) {
306            Poll::Ready(Ok(guard)) => {
307                self.accounting.hold(guard);
308                self.pending_acquire = None;
309                self.incrementally_charged += bytes;
310                ChargeOutcome::Charged
311            }
312            Poll::Ready(Err(_)) => {
313                self.pending_acquire = None;
314                ChargeOutcome::Failed
315            }
316            Poll::Pending => ChargeOutcome::Pending,
317        }
318    }
319
320    /// Hands out `frame` once `bytes` of it are charged, buffering the frame
321    /// while the acquisition is pending.
322    fn hand_out(
323        &mut self,
324        frame: Frame<Bytes>,
325        bytes: u64,
326        cx: &mut Context<'_>,
327    ) -> Poll<Option<Result<Frame<Bytes>, axum::Error>>> {
328        if bytes == 0 {
329            return Poll::Ready(Some(Ok(frame)));
330        }
331        match self.charge(bytes, cx) {
332            ChargeOutcome::Charged => Poll::Ready(Some(Ok(frame))),
333            ChargeOutcome::Pending => {
334                self.pending = Some((frame, bytes));
335                Poll::Pending
336            }
337            ChargeOutcome::Failed => {
338                self.accounting.mark_quota_exceeded();
339                Poll::Ready(Some(Err(limit_exceeded_error())))
340            }
341        }
342    }
343}
344
345impl HttpBody for AccountedBody {
346    type Data = Bytes;
347    type Error = axum::Error;
348
349    fn poll_frame(
350        self: Pin<&mut Self>,
351        cx: &mut Context<'_>,
352    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
353        let this = self.get_mut();
354
355        // Finish a pending acquisition for a buffered frame first.
356        if let Some((frame, bytes)) = this.pending.take() {
357            return this.hand_out(frame, bytes, cx);
358        }
359
360        match Pin::new(&mut this.inner).poll_frame(cx) {
361            Poll::Pending => Poll::Pending,
362            Poll::Ready(None) => Poll::Ready(None),
363            Poll::Ready(Some(Err(e))) => Poll::Ready(Some(Err(e))),
364            Poll::Ready(Some(Ok(frame))) => {
365                if let Some(data) = frame.data_ref() {
366                    this.streamed += data.len() as u64;
367                    let uncharged = this.uncharged();
368                    this.hand_out(frame, uncharged, cx)
369                } else {
370                    // Trailers pass through uncharged.
371                    Poll::Ready(Some(Ok(frame)))
372                }
373            }
374        }
375    }
376
377    fn is_end_stream(&self) -> bool {
378        self.pending.is_none() && self.inner.is_end_stream()
379    }
380
381    fn size_hint(&self) -> http_body::SizeHint {
382        self.inner.size_hint()
383    }
384}
385
386fn limit_exceeded_error() -> axum::Error {
387    axum::Error::new(std::io::Error::other(
388        "request body exceeded the aggregate memory limit",
389    ))
390}
391
392#[cfg(test)]
393mod tests {
394    use axum::body::{Body, Bytes};
395    use axum::http::{Request, StatusCode, header};
396    use axum::routing::post;
397    use axum::{Router, middleware};
398    use common_memory_manager::OnExhaustedPolicy;
399    use tower::ServiceExt;
400
401    use super::memory_limit_middleware;
402    use crate::request_memory_limiter::ServerMemoryLimiter;
403
404    /// Streams `body` in `chunk_size` frames without a Content-Length header
405    /// (like HTTP/1.1 chunked transfer).
406    fn chunked_request(uri: &str, body: Vec<u8>, chunk_size: usize) -> Request<Body> {
407        let stream = futures_util::stream::iter(
408            body.chunks(chunk_size)
409                .map(|c| Ok::<_, std::io::Error>(Bytes::copy_from_slice(c)))
410                .collect::<Vec<_>>(),
411        );
412        Request::builder()
413            .uri(uri)
414            .method("POST")
415            .body(Body::from_stream(stream))
416            .unwrap()
417    }
418
419    fn counted_body_app(limiter: ServerMemoryLimiter) -> Router {
420        Router::new()
421            .route(
422                "/echo",
423                post(|body: Bytes| async move { (StatusCode::OK, body.len().to_string()) }),
424            )
425            .layer(middleware::from_fn_with_state(
426                limiter,
427                memory_limit_middleware,
428            ))
429    }
430
431    #[tokio::test]
432    async fn test_chunked_body_larger_than_quota_is_rejected() {
433        // The quota cannot cover a fully streamed 64 KiB chunked body.
434        let limiter = ServerMemoryLimiter::new(8 * 1024, OnExhaustedPolicy::Fail);
435        let app = counted_body_app(limiter.clone());
436
437        let res = app
438            .oneshot(chunked_request("/echo", vec![b'x'; 64 * 1024], 1024))
439            .await
440            .unwrap();
441        assert_eq!(
442            res.status(),
443            StatusCode::TOO_MANY_REQUESTS,
444            "a chunked body larger than the quota must be rejected with 429, not 400"
445        );
446        assert_eq!(0, limiter.used_bytes(), "guards must be released");
447    }
448
449    #[tokio::test]
450    async fn test_small_chunked_body_fits() {
451        let limiter = ServerMemoryLimiter::new(8 * 1024, OnExhaustedPolicy::Fail);
452        let app = counted_body_app(limiter.clone());
453
454        let res = app
455            .oneshot(chunked_request("/echo", vec![b'x'; 1024], 512))
456            .await
457            .unwrap();
458        assert_eq!(res.status(), StatusCode::OK);
459        let body = axum::body::to_bytes(res.into_body(), 1024).await.unwrap();
460        assert_eq!(&body[..], b"1024");
461        assert_eq!(0, limiter.used_bytes(), "guards must be released");
462    }
463
464    #[tokio::test]
465    async fn test_content_length_still_admitted_upfront() {
466        // A Content-Length larger than the quota is rejected before the body
467        // is read (429), unchanged from the previous behavior.
468        let limiter = ServerMemoryLimiter::new(1024, OnExhaustedPolicy::Fail);
469        let app = counted_body_app(limiter);
470
471        let req = Request::builder()
472            .uri("/echo")
473            .method("POST")
474            .header(header::CONTENT_LENGTH, "4096")
475            .body(Body::from(vec![b'x'; 4096]))
476            .unwrap();
477        let res = app.oneshot(req).await.unwrap();
478        assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
479    }
480
481    #[tokio::test]
482    async fn test_understated_content_length_is_charged_the_difference() {
483        // Claim 1 KiB in Content-Length but stream 16 KiB: the extra 15 KiB
484        // must be charged while streaming and rejected by the small quota.
485        let limiter = ServerMemoryLimiter::new(2 * 1024, OnExhaustedPolicy::Fail);
486        let app = counted_body_app(limiter.clone());
487
488        let stream = futures_util::stream::iter(vec![Ok::<_, std::io::Error>(
489            Bytes::copy_from_slice(&vec![b'x'; 16 * 1024]),
490        )]);
491        let req = Request::builder()
492            .uri("/echo")
493            .method("POST")
494            .header(header::CONTENT_LENGTH, "1024")
495            .body(Body::from_stream(stream))
496            .unwrap();
497        let res = app.oneshot(req).await.unwrap();
498        assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS);
499        assert_eq!(0, limiter.used_bytes());
500    }
501
502    #[tokio::test]
503    async fn test_honest_content_length_is_not_double_charged() {
504        // With a quota large enough for the whole body, an accurate
505        // Content-Length must admit the request without extra charges.
506        let limiter = ServerMemoryLimiter::new(8 * 1024, OnExhaustedPolicy::Fail);
507        let app = counted_body_app(limiter.clone());
508
509        let req = Request::builder()
510            .uri("/echo")
511            .method("POST")
512            .header(header::CONTENT_LENGTH, "4096")
513            .body(Body::from(vec![b'x'; 4096]))
514            .unwrap();
515        let res = app.oneshot(req).await.unwrap();
516        assert_eq!(res.status(), StatusCode::OK);
517        assert_eq!(0, limiter.used_bytes());
518    }
519
520    /// Mirrors the route-local stack: decoded-body accounting *inside* a
521    /// request-decompression layer, like the ingestion routes in `http.rs`.
522    fn decompressing_app(limiter: ServerMemoryLimiter) -> Router {
523        use tower_http::decompression::RequestDecompressionLayer;
524
525        Router::new()
526            .route(
527                "/echo",
528                post(|body: Bytes| async move { (StatusCode::OK, body.len().to_string()) }),
529            )
530            .layer(middleware::from_fn_with_state(
531                limiter,
532                super::decoded_body_accounting_middleware,
533            ))
534            .layer(RequestDecompressionLayer::new().pass_through_unaccepted(true))
535    }
536
537    fn zstd_body(decoded: &[u8]) -> Body {
538        let compressed = zstd::stream::encode_all(decoded, 3).unwrap();
539        Body::from(compressed)
540    }
541
542    #[tokio::test]
543    async fn test_body_reservations_follow_context_without_extending_lifetime() {
544        use std::sync::{Arc, Mutex};
545
546        use axum::Extension;
547        use session::context::QueryContext;
548        use tower_http::decompression::RequestDecompressionLayer;
549
550        use crate::batcher::BatchingProtocol;
551        use crate::http::set_http_write_batching;
552
553        for limit in [0, 8 * 1024] {
554            for compressed in [false, true] {
555                let limiter = ServerMemoryLimiter::new(limit, OnExhaustedPolicy::default());
556                let captured = Arc::new(Mutex::new(None));
557                let output = captured.clone();
558                let memory = limiter.clone();
559                let app = Router::new()
560                    .route(
561                        "/echo",
562                        post(
563                            move |Extension(ctx): Extension<QueryContext>, body: Bytes| async move {
564                                assert_eq!(body.len(), 1536);
565                                assert!(ctx.batching_enabled());
566                                assert!(ctx.held_memory_bytes() >= body.len() as u64);
567                                assert_eq!(ctx.held_memory_bytes(), memory.used_bytes());
568                                *output.lock().unwrap() = Some(ctx.with_write_admission());
569                                StatusCode::OK
570                            },
571                        ),
572                    )
573                    .layer(middleware::from_fn_with_state(
574                        limiter.clone(),
575                        super::decoded_body_accounting_middleware,
576                    ))
577                    .layer(RequestDecompressionLayer::new())
578                    .layer(middleware::from_fn_with_state(
579                        BatchingProtocol::Influxdb,
580                        set_http_write_batching,
581                    ))
582                    .layer(Extension(QueryContext::with("greptime", "public")))
583                    .layer(Extension(Arc::new(vec![BatchingProtocol::Influxdb])))
584                    .layer(middleware::from_fn_with_state(
585                        limiter.clone(),
586                        memory_limit_middleware,
587                    ));
588                let body = vec![b'x'; 1536];
589                let body = if compressed {
590                    zstd::stream::encode_all(body.as_slice(), 3).unwrap()
591                } else {
592                    body
593                };
594                let mut request = chunked_request("/echo", body, 512);
595                if compressed {
596                    request
597                        .headers_mut()
598                        .insert(header::CONTENT_ENCODING, "zstd".parse().unwrap());
599                }
600                assert_eq!(app.oneshot(request).await.unwrap().status(), StatusCode::OK);
601                assert_eq!(limiter.used_bytes(), 0);
602                assert_eq!(
603                    captured
604                        .lock()
605                        .unwrap()
606                        .as_ref()
607                        .unwrap()
608                        .held_memory_bytes(),
609                    0
610                );
611            }
612        }
613    }
614
615    #[tokio::test]
616    async fn test_decompressed_body_is_charged_for_content_encoded_requests() {
617        // The decoded size (64 KiB) exceeds the 16 KiB quota: the accounting
618        // layer must see the decompressed bytes and reject mid-stream.
619        let limiter = ServerMemoryLimiter::new(16 * 1024, OnExhaustedPolicy::Fail);
620        let app = decompressing_app(limiter.clone());
621
622        let req = Request::builder()
623            .uri("/echo")
624            .method("POST")
625            .header("content-encoding", "zstd")
626            .extension(super::ContentEncoded)
627            .body(zstd_body(&vec![b'x'; 64 * 1024]))
628            .unwrap();
629        let res = app.oneshot(req).await.unwrap();
630        assert_eq!(
631            res.status(),
632            StatusCode::TOO_MANY_REQUESTS,
633            "decoded body larger than the quota must be rejected with 429"
634        );
635        assert_eq!(0, limiter.used_bytes(), "guards must be released");
636    }
637
638    #[tokio::test]
639    async fn test_small_decompressed_body_fits() {
640        let limiter = ServerMemoryLimiter::new(16 * 1024, OnExhaustedPolicy::Fail);
641        let app = decompressing_app(limiter.clone());
642
643        let req = Request::builder()
644            .uri("/echo")
645            .method("POST")
646            .header("content-encoding", "zstd")
647            .extension(super::ContentEncoded)
648            .body(zstd_body(&vec![b'x'; 1024]))
649            .unwrap();
650        let res = app.oneshot(req).await.unwrap();
651        assert_eq!(res.status(), StatusCode::OK);
652        let body = axum::body::to_bytes(res.into_body(), 1024).await.unwrap();
653        assert_eq!(&body[..], b"1024", "the handler must see the decoded body");
654        assert_eq!(0, limiter.used_bytes(), "guards must be released");
655    }
656
657    #[tokio::test]
658    async fn test_pending_acquisition_is_attributed_to_its_own_bytes() {
659        use std::time::Duration;
660
661        use tokio_stream::wrappers::ReceiverStream;
662
663        // Regression test: a parked acquisition must be resolved before any
664        // new acquisition is tried; otherwise a late waiter completion can be
665        // credited with a later frame's byte count.
666        //
667        // Scenario: quota 8 KiB fully held externally; frame A (4 KiB) parks
668        // its acquisition; the external guard is then released so A drains;
669        // frame B (8 KiB) arrives. Correct behavior: B waits for its own 8 KiB
670        // acquisition and is rejected when it times out (only 4 KiB are free).
671        // Buggy behavior: the stale waiter (4 KiB) completes and is credited
672        // with B's 8 KiB, so B is delivered although the quota cannot cover it.
673        let limiter = ServerMemoryLimiter::new(
674            8 * 1024,
675            OnExhaustedPolicy::Wait {
676                timeout: Duration::from_millis(500),
677            },
678        );
679        let app = counted_body_app(limiter.clone());
680
681        let (tx, rx) = tokio::sync::mpsc::channel::<Result<Bytes, std::io::Error>>(2);
682        let driver_limiter = limiter.clone();
683        let driver = tokio::spawn(async move {
684            // Hold the whole quota so frame A's acquisition parks.
685            let external = driver_limiter.acquire(8 * 1024).await.unwrap();
686            tx.send(Ok(Bytes::from(vec![b'a'; 4096]))).await.unwrap();
687            tokio::time::sleep(Duration::from_millis(300)).await;
688            // Free the quota: frame A's waiter drains and A is delivered.
689            drop(external);
690            tokio::time::sleep(Duration::from_millis(300)).await;
691            tx.send(Ok(Bytes::from(vec![b'b'; 8192]))).await.unwrap();
692            // Keep the channel open; frame B's own acquisition must time out.
693            tokio::time::sleep(Duration::from_millis(1500)).await;
694        });
695
696        let res = app
697            .oneshot(
698                Request::builder()
699                    .uri("/echo")
700                    .method("POST")
701                    .body(Body::from_stream(ReceiverStream::new(rx)))
702                    .unwrap(),
703            )
704            .await
705            .unwrap();
706        driver.await.unwrap();
707
708        assert_eq!(
709            res.status(),
710            StatusCode::TOO_MANY_REQUESTS,
711            "frame B must wait for its own 8 KiB and time out, not borrow A's reservation"
712        );
713    }
714
715    #[tokio::test]
716    async fn test_plain_requests_are_not_charged_by_the_decoded_layer() {
717        // Without the ContentEncoded marker the decoded layer must be a
718        // no-op: plain bodies are accounted by the global wire accounting.
719        let limiter = ServerMemoryLimiter::new(16 * 1024, OnExhaustedPolicy::Fail);
720        let app = decompressing_app(limiter.clone());
721
722        // Plain body, no marker: passes through.
723        let req = Request::builder()
724            .uri("/echo")
725            .method("POST")
726            .body(Body::from(vec![b'x'; 1024]))
727            .unwrap();
728        let res = app.clone().oneshot(req).await.unwrap();
729        assert_eq!(res.status(), StatusCode::OK);
730
731        // Compressed body WITHOUT the marker (e.g. a route that has the
732        // decompression layer but no accounting): still passes through.
733        let req = Request::builder()
734            .uri("/echo")
735            .method("POST")
736            .header("content-encoding", "zstd")
737            .body(zstd_body(&vec![b'x'; 1024]))
738            .unwrap();
739        let res = app.oneshot(req).await.unwrap();
740        assert_eq!(res.status(), StatusCode::OK);
741    }
742}