use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::task::{Context, Poll};
use axum::body::Body;
use bytes::Bytes;
use http_body::Frame;
#[derive(Debug)]
pub(crate) struct Capture {
data: Mutex<Vec<u8>>,
limit: usize,
overflow: AtomicBool,
}
impl Capture {
pub(crate) fn new(limit: usize) -> Arc<Self> {
Arc::new(Self {
data: Mutex::new(Vec::new()),
limit,
overflow: AtomicBool::new(false),
})
}
pub(crate) fn push(&self, chunk: &[u8]) {
if self.overflow.load(Ordering::Relaxed) {
return;
}
let mut data = lock(&self.data);
if data.len().saturating_add(chunk.len()) > self.limit {
self.overflow.store(true, Ordering::Release);
*data = Vec::new();
return;
}
data.extend_from_slice(chunk);
}
pub(crate) fn take(&self) -> Option<Bytes> {
if self.overflow.load(Ordering::Acquire) {
return None;
}
Some(Bytes::from(std::mem::take(&mut *lock(&self.data))))
}
}
pub(crate) struct TeeBody {
inner: Body,
capture: Arc<Capture>,
}
impl TeeBody {
pub(crate) fn new(inner: Body, capture: Arc<Capture>) -> Self {
Self { inner, capture }
}
}
impl http_body::Body for TeeBody {
type Data = Bytes;
type Error = axum::Error;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
let this = self.get_mut();
match Pin::new(&mut this.inner).poll_frame(cx) {
Poll::Ready(Some(Ok(frame))) => {
if let Some(data) = frame.data_ref() {
this.capture.push(data);
}
Poll::Ready(Some(Ok(frame)))
}
other => other,
}
}
fn is_end_stream(&self) -> bool {
self.inner.is_end_stream()
}
fn size_hint(&self) -> http_body::SizeHint {
self.inner.size_hint()
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[cfg(test)]
mod tests {
use super::Capture;
#[test]
fn frames_are_collected_in_order() {
let capture = Capture::new(8);
capture.push(b"abc");
capture.push(b"de");
assert_eq!(
capture.take(),
Some(bytes::Bytes::from_static(b"abcde")),
"the body is collected"
);
}
#[test]
fn a_body_over_the_limit_is_dropped() {
let capture = Capture::new(4);
capture.push(b"abc");
capture.push(b"de");
assert_eq!(capture.take(), None);
capture.push(b"more");
assert_eq!(capture.take(), None, "the capture stays broken");
}
}