use std::{
fmt,
future::{Future as _, poll_fn},
panic::{AssertUnwindSafe, catch_unwind},
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use bytes::Bytes;
use http::{HeaderMap, HeaderName};
use serde::Serialize;
use tokio::{
runtime::Handle,
time::{Instant, Sleep},
};
use crate::{Error, ErrorKind, Result};
#[derive(Clone, Default, Eq, PartialEq)]
pub struct BodyChunk(Bytes);
impl BodyChunk {
#[must_use]
pub fn new(bytes: impl Into<Vec<u8>>) -> Self {
Self(Bytes::from(bytes.into()))
}
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
#[must_use]
pub fn into_bytes(self) -> Vec<u8> {
self.0.to_vec()
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub(crate) fn from_shared(bytes: Bytes) -> Self {
Self(bytes)
}
pub(crate) fn into_shared(self) -> Bytes {
self.0
}
}
impl AsRef<[u8]> for BodyChunk {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl fmt::Debug for BodyChunk {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("BodyChunk")
.field("length", &self.len())
.finish()
}
}
#[non_exhaustive]
pub enum BodyFrame {
Data(BodyChunk),
Trailers(HeaderMap),
}
impl fmt::Debug for BodyFrame {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Data(chunk) => formatter.debug_tuple("Data").field(chunk).finish(),
Self::Trailers(trailers) => formatter
.debug_struct("Trailers")
.field("field_count", &trailers.len())
.finish(),
}
}
}
pub trait BodySource: Send + 'static {
fn poll_frame(
self: Pin<&mut Self>,
context: &mut Context<'_>,
) -> Poll<Result<Option<BodyFrame>>>;
fn len(&self) -> Option<u64> {
None
}
fn is_empty(&self) -> bool {
self.len() == Some(0)
}
fn may_have_trailers(&self) -> bool {
false
}
fn trailer_names(&self) -> Vec<HeaderName> {
Vec::new()
}
fn try_clone(&self) -> Option<Box<dyn BodySource>> {
None
}
}
enum BodyInner {
Absent,
Buffered { bytes: Bytes, position: usize },
Streaming(Pin<Box<dyn BodySource>>),
Finished,
}
pub struct Body {
inner: BodyInner,
trailers: Option<HeaderMap>,
trailers_emitted: bool,
declared_remaining: Option<u64>,
finished: bool,
}
impl Default for Body {
fn default() -> Self {
Self {
inner: BodyInner::Absent,
trailers: None,
trailers_emitted: false,
declared_remaining: None,
finished: false,
}
}
}
impl Body {
#[must_use]
pub fn empty() -> Self {
Self::bytes(Vec::new())
}
#[must_use]
pub fn bytes(bytes: impl Into<Vec<u8>>) -> Self {
Self::from_shared(Bytes::from(bytes.into()), None)
}
#[must_use]
pub fn text(text: impl Into<String>) -> Self {
Self::bytes(text.into().into_bytes())
}
#[cfg(feature = "json")]
pub fn json<T>(value: &T) -> Result<Self>
where
T: Serialize + ?Sized,
{
serde_json::to_vec(value).map(Self::bytes).map_err(|_| {
Error::new(
ErrorKind::Request,
"request JSON value could not be serialized",
)
})
}
pub fn form<T>(value: &T) -> Result<Self>
where
T: Serialize + ?Sized,
{
serde_urlencoded::to_string(value)
.map(Self::text)
.map_err(Error::from)
}
#[must_use]
pub fn stream(source: impl BodySource) -> Self {
Self::from_source(source)
}
pub(crate) fn from_source(source: impl BodySource) -> Self {
let declared_remaining = source.len();
Self {
inner: BodyInner::Streaming(Box::pin(source)),
trailers: None,
trailers_emitted: false,
declared_remaining,
finished: false,
}
}
#[must_use]
pub fn is_absent(&self) -> bool {
matches!(self.inner, BodyInner::Absent)
}
#[must_use]
pub fn as_bytes(&self) -> Option<&[u8]> {
match &self.inner {
BodyInner::Buffered { bytes, position } => Some(&bytes[*position..]),
BodyInner::Absent | BodyInner::Streaming(_) | BodyInner::Finished => None,
}
}
#[must_use]
pub fn len(&self) -> Option<u64> {
match &self.inner {
BodyInner::Absent => None,
BodyInner::Buffered { bytes, position } => {
u64::try_from(bytes.len().saturating_sub(*position)).ok()
}
BodyInner::Streaming(_) => self.declared_remaining,
BodyInner::Finished => Some(0),
}
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == Some(0)
}
pub(crate) fn may_have_trailers(&self) -> bool {
self.trailers.is_some()
|| match &self.inner {
BodyInner::Streaming(source) => {
let source = source.as_ref().get_ref();
source.may_have_trailers() || !source.trailer_names().is_empty()
}
BodyInner::Absent | BodyInner::Buffered { .. } | BodyInner::Finished => false,
}
}
pub(crate) fn trailer_names(&self) -> Vec<HeaderName> {
if let Some(trailers) = &self.trailers {
return trailers.keys().cloned().collect();
}
match &self.inner {
BodyInner::Streaming(source) => source.as_ref().get_ref().trailer_names(),
BodyInner::Absent | BodyInner::Buffered { .. } | BodyInner::Finished => Vec::new(),
}
}
#[must_use]
pub fn try_clone(&self) -> Option<Self> {
let inner = match &self.inner {
BodyInner::Absent => BodyInner::Absent,
BodyInner::Buffered { bytes, position } => BodyInner::Buffered {
bytes: bytes.slice(*position..),
position: 0,
},
BodyInner::Streaming(source) => {
BodyInner::Streaming(Pin::from(source.as_ref().get_ref().try_clone()?))
}
BodyInner::Finished => BodyInner::Finished,
};
Some(Self {
inner,
trailers: self.trailers.clone(),
trailers_emitted: self.trailers_emitted,
declared_remaining: self.declared_remaining,
finished: self.finished,
})
}
pub async fn next_chunk(&mut self) -> Result<Option<BodyChunk>> {
poll_fn(|context| {
loop {
match Pin::new(&mut *self).poll_local_frame(context) {
Poll::Ready(Ok(Some(BodyFrame::Data(chunk)))) => {
return Poll::Ready(Ok(Some(chunk)));
}
Poll::Ready(Ok(Some(BodyFrame::Trailers(_)))) => {}
Poll::Ready(Ok(None)) => return Poll::Ready(Ok(None)),
Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
Poll::Pending => return Poll::Pending,
}
}
})
.await
}
#[must_use]
pub fn trailers(&self) -> Option<&HeaderMap> {
self.trailers.as_ref()
}
pub(crate) async fn collect_limited(mut self, limit: usize) -> Result<Self> {
if self.len().is_some_and(|length| length > limit as u64) {
return Err(Error::body_limit(limit));
}
let mut bytes = Vec::new();
while let Some(chunk) = self.next_chunk().await? {
let next = bytes
.len()
.checked_add(chunk.len())
.ok_or_else(|| Error::new(ErrorKind::BodyLimit, "body size overflow"))?;
if next > limit {
return Err(Error::body_limit(limit));
}
bytes.extend_from_slice(chunk.as_bytes());
}
Ok(Self::from_shared(Bytes::from(bytes), self.trailers))
}
pub(crate) async fn discard_limited(mut self, limit: usize) -> Result<()> {
let mut consumed = 0usize;
if self.len().is_some_and(|length| length > limit as u64) {
return Err(Error::body_limit(limit));
}
while let Some(chunk) = self.next_chunk().await? {
let remaining = limit.saturating_sub(consumed);
if chunk.len() > remaining {
return Err(Error::body_limit(limit));
}
consumed += chunk.len();
}
Ok(())
}
pub(crate) fn into_buffered_bytes(self) -> Option<Vec<u8>> {
self.as_bytes().map(<[u8]>::to_vec)
}
pub(crate) fn enforce_timeouts(self, deadline: Instant, read_idle: Duration) -> Self {
if !matches!(self.inner, BodyInner::Streaming(_)) {
return self;
}
Self::from_source(TimedSource::new(self, deadline, read_idle))
}
fn from_shared(bytes: Bytes, trailers: Option<HeaderMap>) -> Self {
Self {
inner: BodyInner::Buffered { bytes, position: 0 },
trailers,
trailers_emitted: false,
declared_remaining: None,
finished: false,
}
}
fn poll_local_frame(
mut self: Pin<&mut Self>,
context: &mut Context<'_>,
) -> Poll<Result<Option<BodyFrame>>> {
if self.finished {
return Poll::Ready(Ok(None));
}
let mut result = match &mut self.inner {
BodyInner::Absent => Poll::Ready(Ok(None)),
BodyInner::Buffered { bytes, position } => {
if *position == bytes.len() {
Poll::Ready(Ok(None))
} else {
let chunk = bytes.slice(*position..);
*position = bytes.len();
Poll::Ready(Ok(Some(BodyFrame::Data(BodyChunk::from_shared(chunk)))))
}
}
BodyInner::Streaming(source) => source.as_mut().poll_frame(context),
BodyInner::Finished => Poll::Ready(Ok(None)),
};
if matches!(self.inner, BodyInner::Streaming(_)) {
if self.trailers_emitted && matches!(result, Poll::Ready(Ok(Some(_)))) {
self.finish();
return Poll::Ready(Err(Error::new(
ErrorKind::BodyIo,
"body source emitted a frame after trailers",
)));
}
match &result {
Poll::Ready(Ok(Some(BodyFrame::Data(chunk)))) => {
if let Some(remaining) = self.declared_remaining {
let Ok(length) = u64::try_from(chunk.len()) else {
self.finish();
return Poll::Ready(Err(Error::new(
ErrorKind::BodyIo,
"body chunk length overflow",
)));
};
let Some(next) = remaining.checked_sub(length) else {
self.finish();
return Poll::Ready(Err(Error::new(
ErrorKind::BodyIo,
"body source exceeded its declared length",
)));
};
self.declared_remaining = Some(next);
}
}
Poll::Ready(Ok(Some(BodyFrame::Trailers(_))) | Ok(None))
if self.declared_remaining.is_some_and(|value| value != 0) =>
{
self.finish();
return Poll::Ready(Err(Error::new(
ErrorKind::BodyIo,
"body source ended before its declared length",
)));
}
_ => {}
}
}
if matches!(result, Poll::Ready(Ok(None)))
&& matches!(self.inner, BodyInner::Buffered { .. })
&& !self.trailers_emitted
&& let Some(trailers) = self.trailers.clone()
{
result = Poll::Ready(Ok(Some(BodyFrame::Trailers(trailers))));
}
match &result {
Poll::Ready(Ok(Some(BodyFrame::Trailers(trailers)))) => {
let declared = self.trailer_names();
if trailers.keys().any(is_forbidden_trailer_name)
|| (!declared.is_empty()
&& trailers.keys().any(|name| !declared.contains(name)))
{
self.finish();
return Poll::Ready(Err(Error::new(
ErrorKind::BodyIo,
"body source emitted a forbidden or undeclared trailer field",
)));
}
self.trailers = Some(trailers.clone());
self.trailers_emitted = true;
}
Poll::Ready(Ok(None) | Err(_)) => self.finish(),
Poll::Ready(Ok(Some(BodyFrame::Data(_)))) | Poll::Pending => {}
}
result
}
fn finish(&mut self) {
self.finished = true;
if matches!(self.inner, BodyInner::Streaming(_)) {
self.inner = BodyInner::Finished;
self.declared_remaining = Some(0);
}
}
}
pub(crate) fn is_forbidden_trailer_name(name: &HeaderName) -> bool {
matches!(
name.as_str(),
"authorization"
| "cache-control"
| "connection"
| "content-encoding"
| "content-length"
| "content-range"
| "content-type"
| "cookie"
| "accept"
| "accept-charset"
| "accept-encoding"
| "accept-language"
| "accept-ranges"
| "age"
| "allow"
| "authentication-info"
| "content-disposition"
| "date"
| "etag"
| "expect"
| "expires"
| "forwarded"
| "from"
| "host"
| "if-match"
| "if-modified-since"
| "if-none-match"
| "if-range"
| "if-unmodified-since"
| "keep-alive"
| "last-modified"
| "location"
| "max-forwards"
| "origin"
| "proxy-authenticate"
| "proxy-authentication-info"
| "proxy-authorization"
| "proxy-connection"
| "range"
| "referer"
| "retry-after"
| "server"
| "set-cookie"
| "te"
| "trailer"
| "transfer-encoding"
| "upgrade"
| "user-agent"
| "vary"
| "via"
| "www-authenticate"
)
}
struct TimedSource {
inner: Pin<Box<dyn BodySource>>,
runtime: Option<Handle>,
runtime_guard: Option<tokio::task::JoinHandle<()>>,
deadline_at: Instant,
idle_at: Instant,
deadline: Option<Pin<Box<Sleep>>>,
idle: Option<Pin<Box<Sleep>>>,
read_idle: Duration,
}
impl TimedSource {
fn new(body: Body, deadline: Instant, read_idle: Duration) -> Self {
let idle_deadline = Instant::now().checked_add(read_idle).unwrap_or(deadline);
let runtime = Handle::try_current().ok();
Self {
inner: Box::pin(body),
deadline: make_sleep(runtime.as_ref(), deadline),
idle: make_sleep(runtime.as_ref(), idle_deadline),
runtime_guard: make_runtime_guard(runtime.as_ref()),
runtime,
deadline_at: deadline,
idle_at: idle_deadline,
read_idle,
}
}
}
impl BodySource for TimedSource {
fn poll_frame(
mut self: Pin<&mut Self>,
context: &mut Context<'_>,
) -> Poll<Result<Option<BodyFrame>>> {
if let Err(error) = ensure_runtime_alive(&mut self.runtime_guard, context) {
return Poll::Ready(Err(error));
}
match poll_sleep(&mut self.deadline, context) {
Poll::Ready(Ok(())) => {
return Poll::Ready(Err(Error::timeout("total request deadline exceeded")));
}
Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
Poll::Pending => {}
}
match poll_sleep(&mut self.idle, context) {
Poll::Ready(Ok(())) => {
return Poll::Ready(Err(Error::timeout(
"response body read-idle timeout exceeded",
)));
}
Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
Poll::Pending => {}
}
match self.inner.as_mut().poll_frame(context) {
Poll::Ready(Ok(Some(BodyFrame::Data(chunk)))) => {
let next = Instant::now()
.checked_add(self.read_idle)
.unwrap_or(self.deadline_at);
self.idle_at = next;
if reset_sleep(&mut self.idle, next).is_err() {
return Poll::Ready(Err(runtime_timer_error()));
}
Poll::Ready(Ok(Some(BodyFrame::Data(chunk))))
}
other => other,
}
}
fn len(&self) -> Option<u64> {
self.inner.as_ref().get_ref().len()
}
fn may_have_trailers(&self) -> bool {
self.inner.as_ref().get_ref().may_have_trailers()
}
fn trailer_names(&self) -> Vec<HeaderName> {
self.inner.as_ref().get_ref().trailer_names()
}
fn try_clone(&self) -> Option<Box<dyn BodySource>> {
let inner = self.inner.as_ref().get_ref().try_clone()?;
Some(Box::new(Self {
inner: Box::into_pin(inner),
runtime: self.runtime.clone(),
runtime_guard: make_runtime_guard(self.runtime.as_ref()),
deadline_at: self.deadline_at,
idle_at: self.idle_at,
deadline: make_sleep(self.runtime.as_ref(), self.deadline_at),
idle: make_sleep(self.runtime.as_ref(), self.idle_at),
read_idle: self.read_idle,
}))
}
}
impl Drop for TimedSource {
fn drop(&mut self) {
if let Some(guard) = &self.runtime_guard {
guard.abort();
}
}
}
fn make_runtime_guard(runtime: Option<&Handle>) -> Option<tokio::task::JoinHandle<()>> {
let runtime = runtime?;
catch_unwind(AssertUnwindSafe(|| runtime.spawn(std::future::pending()))).ok()
}
fn ensure_runtime_alive(
guard: &mut Option<tokio::task::JoinHandle<()>>,
context: &mut Context<'_>,
) -> Result<()> {
let Some(guard) = guard.as_mut() else {
return Err(runtime_timer_error());
};
match Pin::new(guard).poll(context) {
Poll::Pending => Ok(()),
Poll::Ready(_) => Err(runtime_timer_error()),
}
}
fn make_sleep(runtime: Option<&Handle>, deadline: Instant) -> Option<Pin<Box<Sleep>>> {
let runtime = runtime?;
catch_unwind(AssertUnwindSafe(|| {
let _guard = runtime.enter();
Box::pin(tokio::time::sleep_until(deadline))
}))
.ok()
}
fn poll_sleep(sleep: &mut Option<Pin<Box<Sleep>>>, context: &mut Context<'_>) -> Poll<Result<()>> {
let Some(timer) = sleep.as_mut() else {
return Poll::Ready(Err(runtime_timer_error()));
};
let result = catch_unwind(AssertUnwindSafe(|| timer.as_mut().poll(context)));
match result {
Ok(Poll::Ready(())) => Poll::Ready(Ok(())),
Ok(Poll::Pending) => Poll::Pending,
Err(_) => {
*sleep = None;
Poll::Ready(Err(runtime_timer_error()))
}
}
}
fn reset_sleep(sleep: &mut Option<Pin<Box<Sleep>>>, deadline: Instant) -> Result<()> {
let Some(sleep) = sleep.as_mut() else {
return Err(runtime_timer_error());
};
catch_unwind(AssertUnwindSafe(|| sleep.as_mut().reset(deadline)))
.map_err(|_| runtime_timer_error())
}
fn runtime_timer_error() -> Error {
Error::new(
ErrorKind::Runtime,
"the asynchronous runtime timer is unavailable",
)
}
impl BodySource for Body {
fn poll_frame(
self: Pin<&mut Self>,
context: &mut Context<'_>,
) -> Poll<Result<Option<BodyFrame>>> {
self.poll_local_frame(context)
}
fn len(&self) -> Option<u64> {
Body::len(self)
}
fn try_clone(&self) -> Option<Box<dyn BodySource>> {
Body::try_clone(self).map(|body| Box::new(body) as Box<dyn BodySource>)
}
fn may_have_trailers(&self) -> bool {
Body::may_have_trailers(self)
}
fn trailer_names(&self) -> Vec<HeaderName> {
Body::trailer_names(self)
}
}
impl fmt::Debug for Body {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let kind = match self.inner {
BodyInner::Absent => "absent",
BodyInner::Buffered { .. } => "buffered",
BodyInner::Streaming(_) => "streaming",
BodyInner::Finished => "finished",
};
formatter
.debug_struct("Body")
.field("kind", &kind)
.field("len", &self.len())
.field("has_trailers", &self.trailers.is_some())
.finish()
}
}
impl From<Vec<u8>> for Body {
fn from(bytes: Vec<u8>) -> Self {
Self::bytes(bytes)
}
}
impl From<&[u8]> for Body {
fn from(bytes: &[u8]) -> Self {
Self::bytes(bytes)
}
}
impl From<String> for Body {
fn from(text: String) -> Self {
Self::text(text)
}
}
impl From<&str> for Body {
fn from(text: &str) -> Self {
Self::text(text)
}
}
#[cfg(test)]
mod describe_body {
use std::collections::VecDeque;
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use super::*;
#[derive(Clone)]
struct ReplayOnce {
chunk: Option<&'static [u8]>,
}
impl BodySource for ReplayOnce {
fn poll_frame(
mut self: Pin<&mut Self>,
_context: &mut Context<'_>,
) -> Poll<Result<Option<BodyFrame>>> {
Poll::Ready(Ok(self
.chunk
.take()
.map(|chunk| BodyFrame::Data(BodyChunk::new(chunk)))))
}
fn try_clone(&self) -> Option<Box<dyn BodySource>> {
Some(Box::new(self.clone()))
}
}
enum TerminalMode {
Eof,
Error,
Trailers(HeaderMap),
Pending,
}
struct ObservableSource {
dropped: Arc<AtomicBool>,
mode: Option<TerminalMode>,
length: Option<u64>,
trailer_names: Vec<HeaderName>,
}
impl Drop for ObservableSource {
fn drop(&mut self) {
self.dropped.store(true, Ordering::SeqCst);
}
}
impl BodySource for ObservableSource {
fn poll_frame(
mut self: Pin<&mut Self>,
_context: &mut Context<'_>,
) -> Poll<Result<Option<BodyFrame>>> {
match self.mode.take().unwrap_or(TerminalMode::Eof) {
TerminalMode::Eof => Poll::Ready(Ok(None)),
TerminalMode::Error => Poll::Ready(Err(Error::new(
ErrorKind::BodyIo,
"observable source failed",
))),
TerminalMode::Trailers(trailers) => {
Poll::Ready(Ok(Some(BodyFrame::Trailers(trailers))))
}
TerminalMode::Pending => {
self.mode = Some(TerminalMode::Pending);
Poll::Pending
}
}
}
fn len(&self) -> Option<u64> {
self.length
}
fn may_have_trailers(&self) -> bool {
!self.trailer_names.is_empty()
}
fn trailer_names(&self) -> Vec<HeaderName> {
self.trailer_names.clone()
}
}
fn observable_body(
mode: TerminalMode,
length: Option<u64>,
trailer_names: Vec<HeaderName>,
) -> (Body, Arc<AtomicBool>) {
let dropped = Arc::new(AtomicBool::new(false));
let body = Body::from_source(ObservableSource {
dropped: dropped.clone(),
mode: Some(mode),
length,
trailer_names,
});
(body, dropped)
}
#[test]
fn it_body_absence_is_distinct_from_zero_bytes() {
let absent = Body::default();
let empty = Body::empty();
assert!(absent.is_absent());
assert!(!absent.is_empty());
assert_eq!(absent.as_bytes(), None);
assert!(!empty.is_absent());
assert!(empty.is_empty());
assert_eq!(empty.as_bytes(), Some(&b""[..]));
assert_eq!(empty.len(), Some(0));
}
#[test]
fn it_body_debug_never_prints_content() {
let body = Body::text("body-secret");
let debug = format!("{body:?}");
assert!(debug.contains("buffered"));
assert!(!debug.contains("body-secret"));
let mut trailers = HeaderMap::new();
trailers.insert("x-secret", "trailer-secret".parse().unwrap());
let debug = format!("{:?}", BodyFrame::Trailers(trailers));
assert!(!debug.contains("x-secret"));
assert!(!debug.contains("trailer-secret"));
}
#[test]
fn it_buffered_bodies_are_replayable() {
let body = Body::bytes(vec![1, 2, 3]);
let clone = body.try_clone().expect("buffered body is replayable");
assert_eq!(clone.as_bytes(), Some(&[1, 2, 3][..]));
}
#[tokio::test]
async fn it_collect_accepts_exact_limit_and_rejects_one_more() {
let exact = Body::text("four").collect_limited(4).await.unwrap();
assert_eq!(exact.as_bytes(), Some(&b"four"[..]));
let error = Body::text("fives").collect_limited(4).await.unwrap_err();
assert_eq!(error.kind(), ErrorKind::BodyLimit);
}
#[cfg(feature = "json")]
#[test]
fn it_json_and_form_constructors_serialize_values() {
let json = Body::json(&serde_json::json!({ "name": "nous" })).unwrap();
let form = Body::form(&[("q", "nous labs")]).unwrap();
assert_eq!(json.as_bytes(), Some(&br#"{"name":"nous"}"#[..]));
assert_eq!(form.as_bytes(), Some(&b"q=nous+labs"[..]));
}
struct ScriptedSource {
frames: VecDeque<BodyFrame>,
}
impl BodySource for ScriptedSource {
fn poll_frame(
mut self: Pin<&mut Self>,
_context: &mut Context<'_>,
) -> Poll<Result<Option<BodyFrame>>> {
Poll::Ready(Ok(self.frames.pop_front()))
}
fn may_have_trailers(&self) -> bool {
true
}
fn trailer_names(&self) -> Vec<HeaderName> {
vec![HeaderName::from_static("x-checksum")]
}
}
#[tokio::test]
async fn it_stream_collection_limit_is_chunk_boundary_independent() {
let body = Body::stream(ScriptedSource {
frames: VecDeque::from([
BodyFrame::Data(BodyChunk::new(b"12")),
BodyFrame::Data(BodyChunk::new(b"345")),
]),
});
assert_eq!(
body.collect_limited(4).await.unwrap_err().kind(),
ErrorKind::BodyLimit
);
}
#[tokio::test]
async fn it_extreme_read_idle_timeout_does_not_overflow_after_data() {
let body = Body::stream(ScriptedSource {
frames: VecDeque::from([BodyFrame::Data(BodyChunk::new(b"data"))]),
});
let deadline = Instant::now() + Duration::from_secs(1);
let mut body = body.enforce_timeouts(deadline, Duration::MAX);
assert_eq!(
body.next_chunk().await.unwrap().unwrap().as_bytes(),
b"data"
);
assert!(body.next_chunk().await.unwrap().is_none());
}
#[tokio::test]
async fn it_timeout_wrapping_preserves_genuine_replay_capability() {
let deadline = Instant::now() + Duration::from_secs(1);
let mut body = Body::from_source(ReplayOnce {
chunk: Some(b"replay"),
})
.enforce_timeouts(deadline, Duration::from_secs(1));
let mut replay = body.try_clone().expect("timeout wrapper must replay");
assert_eq!(
body.next_chunk().await.unwrap().unwrap().as_bytes(),
b"replay"
);
assert_eq!(
replay.next_chunk().await.unwrap().unwrap().as_bytes(),
b"replay"
);
}
#[test]
fn it_timeout_wrapped_replay_crosses_runtime_boundaries() {
let origin = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.enable_time()
.build()
.unwrap();
let body = origin.block_on(async {
Body::from_source(ReplayOnce {
chunk: Some(b"cross-runtime"),
})
.enforce_timeouts(
Instant::now() + Duration::from_secs(5),
Duration::from_secs(5),
)
});
assert!(body.try_clone().is_some());
let mut replay = body.try_clone().expect("wrapped source remains replayable");
let consumer = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
consumer.block_on(async {
assert_eq!(
replay.next_chunk().await.unwrap().unwrap().as_bytes(),
b"cross-runtime"
);
assert!(replay.next_chunk().await.unwrap().is_none());
});
}
#[test]
fn it_timeout_wrapped_body_without_a_runtime_returns_runtime_error() {
let mut body = Body::from_source(ReplayOnce {
chunk: Some(b"unavailable"),
})
.enforce_timeouts(
Instant::now() + Duration::from_secs(5),
Duration::from_secs(5),
);
let mut context = Context::from_waker(std::task::Waker::noop());
let Poll::Ready(Err(error)) = Pin::new(&mut body).poll_local_frame(&mut context) else {
panic!("a missing runtime must fail immediately");
};
assert_eq!(error.kind(), ErrorKind::Runtime);
}
#[test]
fn it_timeout_wrapped_replay_without_a_live_runtime_returns_runtime_error() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.unwrap();
let body = runtime.block_on(async {
Body::from_source(ReplayOnce {
chunk: Some(b"unavailable"),
})
.enforce_timeouts(
Instant::now() + Duration::from_secs(5),
Duration::from_secs(5),
)
});
drop(runtime);
assert!(body.try_clone().is_some());
let mut replay = body.try_clone().expect("source capability is unchanged");
let mut context = Context::from_waker(std::task::Waker::noop());
let Poll::Ready(Err(error)) = Pin::new(&mut replay).poll_local_frame(&mut context) else {
panic!("a shut down timer must fail immediately");
};
assert_eq!(error.kind(), ErrorKind::Runtime);
}
#[tokio::test]
async fn it_read_idle_timeout_fires_between_body_frames() {
struct PendingAfterData(bool);
impl BodySource for PendingAfterData {
fn poll_frame(
mut self: Pin<&mut Self>,
_context: &mut Context<'_>,
) -> Poll<Result<Option<BodyFrame>>> {
if self.0 {
Poll::Pending
} else {
self.0 = true;
Poll::Ready(Ok(Some(BodyFrame::Data(BodyChunk::new(b"first")))))
}
}
}
let deadline = Instant::now() + Duration::from_secs(2);
let mut body = Body::from_source(PendingAfterData(false))
.enforce_timeouts(deadline, Duration::from_millis(50));
assert_eq!(
body.next_chunk().await.unwrap().unwrap().as_bytes(),
b"first"
);
assert_eq!(
body.next_chunk().await.unwrap_err().kind(),
ErrorKind::Timeout
);
}
#[tokio::test]
async fn it_terminal_eof_drops_stream_source_immediately() {
let (mut body, dropped) = observable_body(TerminalMode::Eof, None, Vec::new());
assert!(body.next_chunk().await.unwrap().is_none());
assert!(dropped.load(Ordering::SeqCst));
}
#[tokio::test]
async fn it_terminal_source_errors_drop_stream_source_immediately() {
let (mut body, dropped) = observable_body(TerminalMode::Error, None, Vec::new());
assert_eq!(
body.next_chunk().await.unwrap_err().kind(),
ErrorKind::BodyIo
);
assert!(dropped.load(Ordering::SeqCst));
}
#[tokio::test]
async fn it_length_and_trailer_errors_drop_stream_sources_immediately() {
let (mut short, short_dropped) = observable_body(TerminalMode::Eof, Some(1), Vec::new());
assert_eq!(
short.next_chunk().await.unwrap_err().kind(),
ErrorKind::BodyIo
);
assert!(short_dropped.load(Ordering::SeqCst));
let mut trailers = HeaderMap::new();
trailers.insert("content-length", "1".parse().unwrap());
let content_length = HeaderName::from_static("content-length");
let (mut invalid_trailer, trailer_dropped) =
observable_body(TerminalMode::Trailers(trailers), None, vec![content_length]);
assert_eq!(
invalid_trailer.next_chunk().await.unwrap_err().kind(),
ErrorKind::BodyIo
);
assert!(trailer_dropped.load(Ordering::SeqCst));
}
#[tokio::test(start_paused = true)]
async fn it_timeout_drops_stream_source_immediately() {
let (body, dropped) = observable_body(TerminalMode::Pending, None, Vec::new());
let mut body = body.enforce_timeouts(
Instant::now() + Duration::from_secs(1),
Duration::from_secs(2),
);
assert_eq!(
body.next_chunk().await.unwrap_err().kind(),
ErrorKind::Timeout
);
assert!(dropped.load(Ordering::SeqCst));
}
#[test]
fn it_rejects_known_core_trailer_categories() {
for (category, name) in [
("framing", "content-length"),
("routing", "host"),
("authentication", "www-authenticate"),
("request modifier", "if-match"),
("response control", "location"),
("content processing", "content-type"),
] {
assert!(
is_forbidden_trailer_name(&HeaderName::from_static(name)),
"{category} field {name} was accepted as a trailer"
);
}
assert!(!is_forbidden_trailer_name(&HeaderName::from_static(
"x-checksum"
)));
}
#[tokio::test]
async fn it_trailers_are_available_after_eof() {
let mut trailers = HeaderMap::new();
trailers.insert("x-checksum", "complete".parse().unwrap());
let mut body = Body::stream(ScriptedSource {
frames: VecDeque::from([
BodyFrame::Data(BodyChunk::new(b"data")),
BodyFrame::Trailers(trailers),
]),
});
assert_eq!(
body.next_chunk().await.unwrap().unwrap().as_bytes(),
b"data"
);
assert!(body.next_chunk().await.unwrap().is_none());
assert_eq!(body.trailers().unwrap()["x-checksum"], "complete");
}
#[tokio::test]
async fn it_rejects_frames_after_trailers() {
struct RepeatedTrailers(HeaderMap);
impl BodySource for RepeatedTrailers {
fn poll_frame(
self: Pin<&mut Self>,
_context: &mut Context<'_>,
) -> Poll<Result<Option<BodyFrame>>> {
Poll::Ready(Ok(Some(BodyFrame::Trailers(self.0.clone()))))
}
fn may_have_trailers(&self) -> bool {
true
}
}
let mut trailers = HeaderMap::new();
trailers.insert("x-checksum", "complete".parse().unwrap());
let mut body = Body::stream(RepeatedTrailers(trailers));
assert_eq!(
body.next_chunk().await.unwrap_err().kind(),
ErrorKind::BodyIo
);
}
#[tokio::test]
async fn it_rejects_forbidden_and_undeclared_trailer_fields_terminally() {
struct OneTrailer {
trailers: Option<HeaderMap>,
}
impl BodySource for OneTrailer {
fn poll_frame(
mut self: Pin<&mut Self>,
_context: &mut Context<'_>,
) -> Poll<Result<Option<BodyFrame>>> {
Poll::Ready(Ok(self.trailers.take().map(BodyFrame::Trailers)))
}
fn may_have_trailers(&self) -> bool {
true
}
fn trailer_names(&self) -> Vec<HeaderName> {
vec![HeaderName::from_static("x-allowed")]
}
}
for name in ["x-other", "set-cookie"] {
let mut trailers = HeaderMap::new();
trailers.insert(name, http::HeaderValue::from_static("secret"));
let mut body = Body::stream(OneTrailer {
trailers: Some(trailers),
});
assert_eq!(
body.next_chunk().await.unwrap_err().kind(),
ErrorKind::BodyIo
);
assert!(body.next_chunk().await.unwrap().is_none());
}
}
#[tokio::test]
async fn it_enforces_stream_lens() {
struct DeclaredSource {
frames: VecDeque<BodyFrame>,
length: u64,
}
impl BodySource for DeclaredSource {
fn poll_frame(
mut self: Pin<&mut Self>,
_context: &mut Context<'_>,
) -> Poll<Result<Option<BodyFrame>>> {
Poll::Ready(Ok(self.frames.pop_front()))
}
fn len(&self) -> Option<u64> {
Some(self.length)
}
}
let short = Body::stream(DeclaredSource {
frames: VecDeque::from([BodyFrame::Data(BodyChunk::new(b"one"))]),
length: 4,
});
assert_eq!(
short.collect_limited(10).await.unwrap_err().kind(),
ErrorKind::BodyIo
);
let long = Body::stream(DeclaredSource {
frames: VecDeque::from([BodyFrame::Data(BodyChunk::new(b"three"))]),
length: 4,
});
assert_eq!(
long.collect_limited(10).await.unwrap_err().kind(),
ErrorKind::BodyIo
);
}
struct DropSource(Arc<AtomicBool>);
impl Drop for DropSource {
fn drop(&mut self) {
self.0.store(true, Ordering::SeqCst);
}
}
impl BodySource for DropSource {
fn poll_frame(
self: Pin<&mut Self>,
_context: &mut Context<'_>,
) -> Poll<Result<Option<BodyFrame>>> {
let _ = self;
Poll::Pending
}
}
#[test]
fn it_dropping_a_partial_stream_cancels_its_source() {
let dropped = Arc::new(AtomicBool::new(false));
let body = Body::stream(DropSource(dropped.clone()));
drop(body);
assert!(dropped.load(Ordering::SeqCst));
}
}