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