use std::{
future::Future,
pin::Pin,
task::{Context, Poll, ready},
time::Duration,
};
use http::Response;
use pin_project_lite::pin_project;
use wreq_proto::rt::Sleep;
use super::body::TimeoutBody;
use crate::{
error::{BoxError, Error, TimedOut},
rt::Timer,
};
pin_project! {
pub struct ResponseFuture<Fut> {
#[pin]
pub(super) fut: Fut,
pub(super) timer: Timer,
pub(super) read_timeout: Option<Duration>,
pub(super) read_timeout_fut: Option<Pin<Box<dyn Sleep>>>,
pub(super) total_timeout_fut: Option<Pin<Box<dyn Sleep>>>,
}
}
impl<Fut, ResBody, E> Future for ResponseFuture<Fut>
where
Fut: Future<Output = Result<Response<ResBody>, E>>,
E: Into<BoxError>,
{
type Output = Result<Response<TimeoutBody<ResBody>>, BoxError>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
if let Some(timeout) = this.total_timeout_fut.as_mut()
&& timeout.as_mut().poll(cx).is_ready()
{
return Poll::Ready(Err(Error::request(TimedOut).into()));
}
if let Some(timeout) = this.read_timeout_fut.as_mut()
&& timeout.as_mut().poll(cx).is_ready()
{
return Poll::Ready(Err(Error::request(TimedOut).into()));
}
let response = ready!(this.fut.poll(cx)).map_err(Into::into)?;
Poll::Ready(Ok(response.map(|body| {
TimeoutBody::new(
body,
this.timer.clone(),
*this.read_timeout,
this.total_timeout_fut.take(),
)
})))
}
}