use std::borrow::Cow;
use std::pin::Pin;
use std::task::{Context, Poll, ready};
pub use bytes::Bytes;
use futures_util::{Stream, TryStream};
pub use http_body::Body as HttpBody;
use http_body::{Frame, SizeHint};
use http_body_util::combinators::UnsyncBoxBody;
use http_body_util::{BodyExt, Collected, Empty, Full, LengthLimitError, Limited};
use navree_kernel::BoxError;
use pin_project_lite::pin_project;
use crate::serve::BodyReadTimeout;
type BoxedBody = UnsyncBoxBody<Bytes, BoxError>;
#[must_use]
#[derive(Debug)]
pub struct Body(BoxedBody);
impl Body {
pub fn new<B>(body: B) -> Self
where
B: HttpBody<Data = Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
try_downcast(body).unwrap_or_else(|body| Self(boxed(body)))
}
pub fn empty() -> Self {
Self::new(Empty::new())
}
pub fn from_stream<S>(stream: S) -> Self
where
S: TryStream + Send + 'static,
S::Ok: Into<Bytes>,
S::Error: Into<BoxError>,
{
Self::new(StreamBody { stream })
}
pub fn into_data_stream(self) -> BodyDataStream {
BodyDataStream { inner: self }
}
}
fn boxed<B>(body: B) -> BoxedBody
where
B: HttpBody<Data = Bytes> + Send + 'static,
B::Error: Into<BoxError>,
{
try_downcast(body).unwrap_or_else(|body| body.map_err(Into::into).boxed_unsync())
}
pub(crate) fn try_downcast<T: 'static, K: Send + 'static>(value: K) -> Result<T, K> {
let mut value = Some(value);
match <dyn std::any::Any>::downcast_mut::<Option<T>>(&mut value).and_then(Option::take) {
Some(found) => Ok(found),
None => Err(value.expect("a value of another type stays where it was")),
}
}
impl Default for Body {
fn default() -> Self {
Self::empty()
}
}
impl From<()> for Body {
fn from((): ()) -> Self {
Self::empty()
}
}
macro_rules! body_from {
($($ty:ty),* $(,)?) => {
$(
impl From<$ty> for Body {
fn from(value: $ty) -> Self {
Self::new(Full::from(value))
}
}
)*
};
}
body_from!(
&'static [u8],
Cow<'static, [u8]>,
Vec<u8>,
&'static str,
Cow<'static, str>,
String,
Bytes,
);
impl HttpBody for Body {
type Data = Bytes;
type Error = BoxError;
#[inline]
fn poll_frame(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Bytes>, BoxError>>> {
Pin::new(&mut self.0).poll_frame(cx)
}
#[inline]
fn is_end_stream(&self) -> bool {
self.0.is_end_stream()
}
#[inline]
fn size_hint(&self) -> SizeHint {
self.0.size_hint()
}
}
#[must_use]
#[derive(Debug)]
pub struct BodyDataStream {
inner: Body,
}
impl Stream for BodyDataStream {
type Item = Result<Bytes, BoxError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
loop {
match ready!(Pin::new(&mut self.inner).poll_frame(cx)?) {
Some(frame) => {
if let Ok(data) = frame.into_data() {
return Poll::Ready(Some(Ok(data)));
}
}
None => return Poll::Ready(None),
}
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
let hint = self.inner.size_hint();
let lower = usize::try_from(hint.lower()).unwrap_or_default();
(lower, hint.upper().and_then(|upper| upper.try_into().ok()))
}
}
impl HttpBody for BodyDataStream {
type Data = Bytes;
type Error = BoxError;
fn poll_frame(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Bytes>, BoxError>>> {
Pin::new(&mut self.inner).poll_frame(cx)
}
fn is_end_stream(&self) -> bool {
self.inner.is_end_stream()
}
fn size_hint(&self) -> SizeHint {
self.inner.size_hint()
}
}
pin_project! {
struct StreamBody<S> {
#[pin]
stream: S,
}
}
impl<S> HttpBody for StreamBody<S>
where
S: TryStream,
S::Ok: Into<Bytes>,
S::Error: Into<BoxError>,
{
type Data = Bytes;
type Error = BoxError;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Bytes>, BoxError>>> {
match ready!(self.project().stream.try_poll_next(cx)) {
Some(Ok(chunk)) => Poll::Ready(Some(Ok(Frame::data(chunk.into())))),
Some(Err(error)) => Poll::Ready(Some(Err(error.into()))),
None => Poll::Ready(None),
}
}
}
pub async fn to_bytes(body: Body, limit: usize) -> Result<Bytes, BoxError> {
Limited::new(body, limit)
.collect()
.await
.map(Collected::to_bytes)
}
pub const DEFAULT_BODY_LIMIT: usize = 2 * 1024 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BodyLimit(pub usize);
impl BodyLimit {
pub fn of(extensions: &http::Extensions) -> usize {
extensions
.get::<BodyLimit>()
.map_or(DEFAULT_BODY_LIMIT, |limit| limit.0)
}
}
pub async fn read_body(body: Body, limit: usize) -> Result<Bytes, BodyError> {
match Limited::new(body, limit).collect().await {
Ok(collected) => Ok(collected.to_bytes()),
Err(error) => {
Err(body_error_in(&*error).unwrap_or_else(|| BodyError::Read(error.to_string())))
}
}
}
pub(crate) fn body_error_in(error: &(dyn std::error::Error + 'static)) -> Option<BodyError> {
let chain = || std::iter::successors(Some(error), |error| error.source());
if chain().any(|error| error.is::<LengthLimitError>()) {
Some(BodyError::TooLarge)
} else if chain().any(|error| error.is::<BodyReadTimeout>()) {
Some(BodyError::TimedOut)
} else {
None
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum BodyError {
TooLarge,
TimedOut,
Read(String),
}
impl BodyError {
pub fn status(&self) -> http::StatusCode {
match self {
BodyError::TooLarge => http::StatusCode::PAYLOAD_TOO_LARGE,
BodyError::TimedOut => http::StatusCode::REQUEST_TIMEOUT,
BodyError::Read(_) => http::StatusCode::BAD_REQUEST,
}
}
}
impl std::fmt::Display for BodyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BodyError::TooLarge => {
f.write_str("Failed to buffer the request body: length limit exceeded")
}
BodyError::TimedOut => {
f.write_str("Failed to buffer the request body: it arrived too slowly")
}
BodyError::Read(error) => write!(f, "Failed to buffer the request body: {error}"),
}
}
}
impl std::error::Error for BodyError {}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn bodies_are_read_up_to_the_limit() {
let body = read_body(Body::from("hello"), 5).await.unwrap();
assert_eq!(&body[..], b"hello");
let error = read_body(Body::from("hello!"), 5).await.unwrap_err();
assert_eq!(error, BodyError::TooLarge);
assert_eq!(error.status(), http::StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(
error.to_string(),
"Failed to buffer the request body: length limit exceeded"
);
let chunks = futures_util::stream::iter(
(0..10).map(|_| Ok::<_, std::io::Error>(Bytes::from_static(b"0123456789"))),
);
let error = read_body(Body::from_stream(chunks), 64).await.unwrap_err();
assert_eq!(error, BodyError::TooLarge);
}
#[tokio::test]
async fn a_body_the_client_sent_too_slowly_is_a_408() {
let chunks = futures_util::stream::iter([Err::<Bytes, _>(BodyReadTimeout)]);
let error = read_body(Body::from_stream(chunks), 64).await.unwrap_err();
assert_eq!(error, BodyError::TimedOut);
assert_eq!(error.status(), http::StatusCode::REQUEST_TIMEOUT);
}
#[test]
fn the_limit_comes_from_the_extensions() {
let mut extensions = http::Extensions::new();
assert_eq!(BodyLimit::of(&extensions), DEFAULT_BODY_LIMIT);
extensions.insert(BodyLimit(16));
assert_eq!(BodyLimit::of(&extensions), 16);
}
}