use std::pin::Pin;
use std::time::{Duration, Instant};
use std::task::Poll;
use futures::Future;
use tokio::time::Sleep;
use pin_project_lite::pin_project;
pin_project! {
#[must_use = "futures do nothing unless you `.await` or poll them"]
#[derive(Debug)]
pub struct StaleTimeout<T> {
#[pin]
value: T,
#[pin]
delay: Sleep,
#[pin]
duration: Duration,
}
}
impl<T> StaleTimeout<T> {
pub(crate) fn new_with_duration(value: T, duration: Duration) -> StaleTimeout<T> {
StaleTimeout { value, delay: tokio::time::sleep(duration), duration }
}
pub fn get_ref(&self) -> &T {
&self.value
}
pub fn get_mut(&mut self) -> &mut T {
&mut self.value
}
pub fn into_inner(self) -> T {
self.value
}
}
#[derive(Debug,Default)]
pub struct Stale {
}
impl std::fmt::Display for Stale {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Stale")
}
}
impl Stale {
pub fn new() -> Self {
Self {}
}
}
impl<T> Future for StaleTimeout<T>
where
T: Future,
{
type Output = Result<T::Output, Stale>;
fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
let mut me = self.project();
match me.delay.as_mut().poll(cx) {
Poll::Ready(()) => return Poll::Ready(Err(Stale::new())),
Poll::Pending => {},
}
me.delay.as_mut().reset((Instant::now() + *me.duration).into());
if let Poll::Ready(v) = me.value.poll(cx) {
return Poll::Ready(Ok(v));
}
Poll::Pending
}
}
pub fn progress<T>(request: T, duration: Duration) -> StaleTimeout<T>
where
T: Future
{
StaleTimeout::new_with_duration(request, duration)
}