use std::{
io,
pin::Pin,
task::{Context, Poll},
};
use axum::body::{Body, Bytes};
use http_body::{Body as HttpBody, Frame, SizeHint};
use tokio::{
sync::OwnedSemaphorePermit,
time::{Instant, Sleep, sleep_until},
};
use crate::task::BoxError;
pub(super) struct ExchangeBody {
inner: Body,
permit: Option<OwnedSemaphorePermit>,
deadline: Pin<Box<Sleep>>,
finished: bool,
}
impl ExchangeBody {
pub(super) fn new(inner: Body, permit: OwnedSemaphorePermit, deadline: Instant) -> Self {
Self {
inner,
permit: Some(permit),
deadline: Box::pin(sleep_until(deadline)),
finished: false,
}
}
}
impl HttpBody for ExchangeBody {
type Data = Bytes;
type Error = BoxError;
fn poll_frame(
self: Pin<&mut Self>,
context: &mut Context<'_>,
) -> Poll<Option<std::result::Result<Frame<Bytes>, BoxError>>> {
let body = self.get_mut();
if body.finished {
return Poll::Ready(None);
}
if std::future::Future::poll(body.deadline.as_mut(), context).is_ready() {
body.finished = true;
body.permit.take();
return Poll::Ready(Some(Err(Box::new(io::Error::new(
io::ErrorKind::TimedOut,
"response body deadline exceeded",
)))));
}
match Pin::new(&mut body.inner).poll_frame(context) {
Poll::Ready(None) => {
body.finished = true;
body.permit.take();
Poll::Ready(None)
}
Poll::Ready(Some(Err(error))) => {
body.finished = true;
body.permit.take();
Poll::Ready(Some(Err(Box::new(error))))
}
Poll::Ready(Some(Ok(frame))) => Poll::Ready(Some(Ok(frame))),
Poll::Pending => Poll::Pending,
}
}
fn is_end_stream(&self) -> bool {
self.finished || self.inner.is_end_stream()
}
fn size_hint(&self) -> SizeHint {
self.inner.size_hint()
}
}
#[cfg(test)]
#[path = "body_test.rs"]
mod body_test;