use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
time::{Duration, Instant},
};
use crate::{Error, Result};
use super::{Sleep, Timer};
#[derive(Clone, Debug)]
pub(crate) struct Deadline {
instant: Option<Instant>,
timer: Timer,
}
impl Deadline {
pub(crate) fn after(timeout: Option<Duration>, timer: Timer) -> Result<Self> {
let instant = timeout
.map(|duration| {
Instant::now()
.checked_add(duration)
.ok_or_else(Error::timeout)
})
.transpose()?;
Ok(Self { instant, timer })
}
#[cfg(test)]
fn at(instant: Option<Instant>) -> Self {
Self {
instant,
timer: Timer::default(),
}
}
pub(crate) const fn instant(&self) -> Option<Instant> {
self.instant
}
pub(crate) fn remaining(&self) -> Result<Option<Duration>> {
self.instant
.map(|deadline| {
deadline
.checked_duration_since(Instant::now())
.filter(|remaining| !remaining.is_zero())
.ok_or_else(Error::timeout)
})
.transpose()
}
pub(crate) fn within(&self, timeout: Option<Duration>) -> Result<Self> {
let Some(timeout) = timeout else {
return Ok(self.clone());
};
let requested = Instant::now()
.checked_add(timeout)
.ok_or_else(Error::timeout)?;
Ok(Self {
instant: Some(
self.instant
.map_or(requested, |current| current.min(requested)),
),
timer: self.timer.clone(),
})
}
pub(crate) fn timer(&self) -> &Timer {
&self.timer
}
pub(crate) async fn run<T>(&self, future: impl Future<Output = Result<T>>) -> Result<T> {
let Some(deadline) = self.instant else {
return future.await;
};
if Instant::now() >= deadline {
return Err(Error::timeout());
}
futures_util::pin_mut!(future);
let mut timer = None;
std::future::poll_fn(|context| {
if let Poll::Ready(result) = future.as_mut().poll(context) {
return Poll::Ready(result);
}
let timer = timer.get_or_insert_with(|| self.timer.until(deadline));
if timer.as_mut().poll(context).is_ready() {
Poll::Ready(Err(Error::timeout()))
} else {
Poll::Pending
}
})
.await
}
}
pub(crate) struct DeadlineBody<B> {
body: B,
timer: Timer,
deadline: Option<Instant>,
total: Option<Sleep>,
read: Option<Sleep>,
read_timeout: Option<Duration>,
expired: bool,
}
impl<B> DeadlineBody<B> {
pub(crate) fn new(body: B, deadline: Deadline, read_timeout: Option<Duration>) -> Self {
Self {
body,
timer: deadline.timer.clone(),
deadline: deadline.instant(),
total: None,
read: None,
read_timeout,
expired: false,
}
}
}
impl<B> http_body::Body for DeadlineBody<B>
where
B: http_body::Body + Unpin,
B::Error: Into<Error>,
{
type Data = B::Data;
type Error = Error;
fn poll_frame(
mut self: Pin<&mut Self>,
context: &mut Context<'_>,
) -> Poll<Option<Result<http_body::Frame<Self::Data>>>> {
if self.expired {
return Poll::Ready(None);
}
if self
.deadline
.is_some_and(|deadline| Instant::now() >= deadline)
{
self.expired = true;
return Poll::Ready(Some(Err(Error::timeout())));
}
match Pin::new(&mut self.body).poll_frame(context) {
Poll::Ready(frame) => {
self.read = None;
Poll::Ready(frame.map(|frame| frame.map_err(Into::into)))
}
Poll::Pending => {
if self.total.is_none()
&& let Some(deadline) = self.deadline
{
self.total = Some(self.timer.until(deadline));
}
if let Some(timer) = &mut self.total
&& timer.as_mut().poll(context).is_ready()
{
self.expired = true;
return Poll::Ready(Some(Err(Error::timeout())));
}
let Some(timeout) = self.read_timeout else {
return Poll::Pending;
};
let factory = self.timer.clone();
let timer = self.read.get_or_insert_with(|| factory.after(timeout));
if timer.as_mut().poll(context).is_ready() {
self.expired = true;
Poll::Ready(Some(Err(Error::timeout())))
} else {
Poll::Pending
}
}
}
}
fn is_end_stream(&self) -> bool {
self.expired || self.body.is_end_stream()
}
fn size_hint(&self) -> http_body::SizeHint {
self.body.size_hint()
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicBool, Ordering};
use super::*;
#[test]
fn expired_deadlines_fail_before_work_starts() {
let expired = Instant::now()
.checked_sub(Duration::from_millis(1))
.expect("one millisecond fits before the current instant");
let deadline = Deadline::at(Some(expired));
assert!(deadline.remaining().unwrap_err().is_timeout());
}
#[test]
fn expired_deadlines_do_not_poll_the_operation() {
let expired = Instant::now()
.checked_sub(Duration::from_millis(1))
.expect("one millisecond fits before the current instant");
let deadline = Deadline::at(Some(expired));
let polled = AtomicBool::new(false);
let error = futures_lite::future::block_on(deadline.run(async {
polled.store(true, Ordering::Relaxed);
Ok(())
}))
.unwrap_err();
assert!(error.is_timeout());
assert!(!polled.load(Ordering::Relaxed));
}
#[test]
fn missing_deadlines_are_unbounded() {
assert_eq!(
Deadline::after(None, Timer::default())
.unwrap()
.remaining()
.unwrap(),
None
);
}
#[test]
fn overflowing_deadlines_do_not_become_unbounded() {
assert!(
Deadline::after(Some(Duration::MAX), Timer::default())
.unwrap_err()
.is_timeout()
);
}
}