use crate::task::BoxError;
use axum::body::{Body, Bytes};
use http_body::{Body as HttpBody, Frame, SizeHint};
use std::{
future::Future,
io,
pin::Pin,
task::{Context, Poll},
time::Duration,
};
use tokio::time::{Instant, Sleep, sleep};
pub(super) struct IdleBody {
inner: Body,
outcome: Option<crate::telemetry::OutcomeToken>,
idle: Duration,
timer: Option<Pin<Box<Sleep>>>,
}
impl IdleBody {
pub(super) fn new(inner: Body, idle: Duration) -> Self {
Self {
timer: Some(Box::pin(sleep(idle))),
..Self::on_first_poll(inner, idle)
}
}
pub(super) fn on_first_poll(inner: Body, idle: Duration) -> Self {
Self {
inner,
outcome: None,
idle,
timer: None,
}
}
pub(super) fn observe(mut self, outcome: Option<crate::telemetry::OutcomeToken>) -> Self {
self.outcome = outcome;
self
}
}
impl HttpBody for IdleBody {
type Data = Bytes;
type Error = BoxError;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Frame<Bytes>, BoxError>>> {
let this = self.get_mut();
let timer = this.timer.get_or_insert_with(|| Box::pin(sleep(this.idle)));
if timer.as_mut().poll(cx).is_ready() {
if let Some(outcome) = &this.outcome {
outcome.mark(crate::telemetry::Outcome::TimedOut);
}
return Poll::Ready(Some(Err(io::Error::new(
io::ErrorKind::TimedOut,
"body idle timeout",
)
.into())));
}
match Pin::new(&mut this.inner).poll_frame(cx) {
Poll::Ready(frame) => {
timer.as_mut().reset(Instant::now() + this.idle);
Poll::Ready(frame.map(|frame| frame.map_err(Into::into)))
}
Poll::Pending => Poll::Pending,
}
}
fn is_end_stream(&self) -> bool {
self.inner.is_end_stream()
}
fn size_hint(&self) -> SizeHint {
self.inner.size_hint()
}
}