1use 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#[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.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 let accounting = BodyMemoryAccounting::default();
92 accounting.hold(guard);
93 let retained_accounting = accounting.clone();
98 let (mut parts, body) = req.into_parts();
99 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 quota_exceeded_response(&retained_accounting, response)
113}
114
115fn quota_exceeded_response(accounting: &BodyMemoryAccounting, response: Response) -> Response {
121 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
133pub 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 let accounting = req
162 .extensions()
163 .get::<BodyMemoryAccounting>()
164 .cloned()
165 .unwrap_or_default();
166 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 quota_exceeded_response(&retained_accounting, response)
177}
178
179#[derive(Clone, Default)]
185pub(crate) struct BodyMemoryAccounting {
186 guards: Arc<Mutex<Vec<MemoryGuard<RequestMemoryMetrics>>>>,
187 reserved_bytes: Arc<AtomicU64>,
188 quota_exceeded: Arc<AtomicBool>,
191}
192
193impl BodyMemoryAccounting {
194 pub(crate) fn reserved_bytes(&self) -> u64 {
196 self.reserved_bytes.load(Ordering::Acquire)
197 }
198
199 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
228struct AccountedBody {
231 inner: Body,
232 limiter: ServerMemoryLimiter,
233 accounting: BodyMemoryAccounting,
234 streamed: u64,
236 incrementally_charged: u64,
238 pre_charged: u64,
240 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 fn uncharged(&self) -> u64 {
267 self.streamed
268 .saturating_sub(self.pre_charged)
269 .saturating_sub(self.incrementally_charged)
270 }
271
272 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 drop(external);
690 tokio::time::sleep(Duration::from_millis(300)).await;
691 tx.send(Ok(Bytes::from(vec![b'b'; 8192]))).await.unwrap();
692 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 let limiter = ServerMemoryLimiter::new(16 * 1024, OnExhaustedPolicy::Fail);
720 let app = decompressing_app(limiter.clone());
721
722 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 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}