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.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 let accounting = BodyMemoryAccounting::default();
90 accounting.hold(guard);
91 let retained_accounting = accounting.clone();
96 let (mut parts, body) = req.into_parts();
97 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 quota_exceeded_response(&retained_accounting, response)
111}
112
113fn quota_exceeded_response(accounting: &BodyMemoryAccounting, response: Response) -> Response {
119 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
131pub 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 let accounting = req
160 .extensions()
161 .get::<BodyMemoryAccounting>()
162 .cloned()
163 .unwrap_or_default();
164 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 quota_exceeded_response(&retained_accounting, response)
175}
176
177#[derive(Clone, Default)]
183pub(crate) struct BodyMemoryAccounting {
184 guards: Arc<Mutex<Vec<MemoryGuard<RequestMemoryMetrics>>>>,
185 reserved_bytes: Arc<AtomicU64>,
186 quota_exceeded: Arc<AtomicBool>,
189}
190
191impl BodyMemoryAccounting {
192 pub(crate) fn reserved_bytes(&self) -> u64 {
194 self.reserved_bytes.load(Ordering::Acquire)
195 }
196
197 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
226struct AccountedBody {
229 inner: Body,
230 limiter: ServerMemoryLimiter,
231 accounting: BodyMemoryAccounting,
232 streamed: u64,
234 incrementally_charged: u64,
236 pre_charged: u64,
238 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 fn uncharged(&self) -> u64 {
265 self.streamed
266 .saturating_sub(self.pre_charged)
267 .saturating_sub(self.incrementally_charged)
268 }
269
270 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 drop(external);
688 tokio::time::sleep(Duration::from_millis(300)).await;
689 tx.send(Ok(Bytes::from(vec![b'b'; 8192]))).await.unwrap();
690 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 let limiter = ServerMemoryLimiter::new(16 * 1024, OnExhaustedPolicy::Fail);
718 let app = decompressing_app(limiter.clone());
719
720 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 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}