use std::error::Error;
use std::future::{Future, poll_fn};
use std::pin::{Pin, pin};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use crate::error::Limit;
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub type BoxError = Box<dyn Error + Send + Sync + 'static>;
pub trait Timer: Send + Sync + 'static {
fn sleep(&self, d: Duration) -> BoxFuture<'static, ()>;
fn now(&self) -> Instant;
fn try_sleep(&self, d: Duration) -> BoxFuture<'static, Result<(), Refused>>;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Refused;
impl std::fmt::Display for Refused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("the runtime has shut down")
}
}
impl Error for Refused {}
pub const RUNTIME_SHUT_DOWN: &str = "runtime_shut_down";
#[derive(Debug)]
pub struct RuntimeShutDown {
source: BoxError,
}
impl RuntimeShutDown {
pub fn new(refused: Refused) -> RuntimeShutDown {
RuntimeShutDown { source: Box::new(refused) }
}
pub fn after(last: impl Into<BoxError>) -> RuntimeShutDown {
RuntimeShutDown { source: last.into() }
}
pub fn reason(&self) -> &'static str {
RUNTIME_SHUT_DOWN
}
}
impl std::fmt::Display for RuntimeShutDown {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("the runtime has shut down")
}
}
impl Error for RuntimeShutDown {
fn source(&self) -> Option<&(dyn Error + 'static)> {
Some(&*self.source)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Bound {
#[default]
Default,
After(Duration),
Unbounded,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum BoundKind {
Hook,
Construction,
ReadinessAttempt,
ReadinessWhole,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Resolved {
After { after: Duration, limit: Limit },
Unbounded,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct Defaults {
pub(crate) hook_timeout: Duration,
pub(crate) construct_timeout: Duration,
}
pub(crate) fn resolve_bound(bound: Bound, kind: BoundKind, defaults: Option<&Defaults>) -> Resolved {
let Some(defaults) = defaults else {
return Resolved::Unbounded;
};
match bound {
Bound::Unbounded => Resolved::Unbounded,
Bound::After(after) => {
let limit = match kind {
BoundKind::ReadinessAttempt => Limit::Attempt,
BoundKind::Hook | BoundKind::Construction | BoundKind::ReadinessWhole => Limit::Item,
};
Resolved::After { after, limit }
}
Bound::Default => match kind {
BoundKind::Hook => Resolved::After { after: defaults.hook_timeout, limit: Limit::Default },
BoundKind::Construction | BoundKind::ReadinessAttempt => {
Resolved::After { after: defaults.construct_timeout, limit: Limit::Default }
}
BoundKind::ReadinessWhole => Resolved::Unbounded,
},
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Cut {
Expired,
Refused(Refused),
}
pub struct Expiry<'t> {
timer: &'t dyn Timer,
until: Option<Instant>,
sleep: Option<BoxFuture<'static, Result<(), Refused>>>,
refused: Option<Refused>,
}
impl<'t> Expiry<'t> {
pub fn at(timer: &'t dyn Timer, until: Instant) -> Expiry<'t> {
let left = until.saturating_duration_since(timer.now());
let sleep = (!left.is_zero()).then(|| timer.try_sleep(left));
Expiry { timer, until: Some(until), sleep, refused: None }
}
pub fn after(timer: &'t dyn Timer, d: Duration) -> Expiry<'t> {
let until = timer.now().checked_add(d);
let sleep = (!d.is_zero()).then(|| timer.try_sleep(d));
Expiry { timer, until, sleep, refused: None }
}
pub fn passed(&self) -> bool {
self.until.is_some_and(|until| self.timer.now() >= until)
}
}
impl Future for Expiry<'_> {
type Output = Cut;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Cut> {
let this = self.get_mut();
if let Some(refused) = this.refused {
return Poll::Ready(Cut::Refused(refused));
}
let Some(sleep) = &mut this.sleep else {
return Poll::Ready(Cut::Expired);
};
match sleep.as_mut().poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(Ok(())) => Poll::Ready(Cut::Expired),
Poll::Ready(Err(_)) if this.passed() => Poll::Ready(Cut::Expired),
Poll::Ready(Err(refused)) => {
this.refused = Some(refused);
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
}
pub async fn timeout<F: Future>(timer: &dyn Timer, d: Duration, fut: F) -> Result<F::Output, Cut> {
race(Expiry::after(timer, d), fut).await
}
pub async fn timeout_at<F: Future>(timer: &dyn Timer, until: Instant, fut: F) -> Result<F::Output, Cut> {
race(Expiry::at(timer, until), fut).await
}
async fn race<F: Future>(mut expiry: Expiry<'_>, fut: F) -> Result<F::Output, Cut> {
let mut fut = pin!(fut);
let mut first = true;
let mut early = None;
poll_fn(|cx| {
let polled = std::mem::take(&mut first);
if polled {
if let Poll::Ready(cut) = Pin::new(&mut expiry).poll(cx) {
early = Some(cut);
}
}
if let Poll::Ready(output) = fut.as_mut().poll(cx) {
return Poll::Ready(Ok(output));
}
match early {
Some(cut) => Poll::Ready(Err(cut)),
None if polled => Poll::Pending,
None => Pin::new(&mut expiry).poll(cx).map(Err),
}
})
.await
}
#[cfg(test)]
mod tests {
use std::task::{Context, Waker};
use std::time::Instant;
use super::*;
const HOOK: Duration = Duration::from_secs(10);
const CONSTRUCT: Duration = Duration::from_secs(30);
const SET: Duration = Duration::from_secs(3);
const KINDS: [BoundKind; 4] =
[BoundKind::Hook, BoundKind::Construction, BoundKind::ReadinessAttempt, BoundKind::ReadinessWhole];
fn defaults() -> Defaults {
Defaults { hook_timeout: HOOK, construct_timeout: CONSTRUCT }
}
#[test]
fn a_bound_is_default_until_written() {
assert_eq!(Bound::default(), Bound::Default);
}
#[test]
fn without_a_timer_every_bound_runs_unbounded() {
for kind in KINDS {
for bound in [Bound::Default, Bound::After(SET), Bound::Unbounded] {
assert_eq!(resolve_bound(bound, kind, None), Resolved::Unbounded, "{bound:?} on {kind:?}");
}
}
}
#[test]
fn unbounded_stays_unbounded_with_a_timer() {
for kind in KINDS {
assert_eq!(resolve_bound(Bound::Unbounded, kind, Some(&defaults())), Resolved::Unbounded, "{kind:?}");
}
}
#[test]
fn an_explicit_bound_is_the_items_own_limit_and_a_readiness_attempts_is_the_attempt_limit() {
let defaults = defaults();
for kind in [BoundKind::Hook, BoundKind::Construction, BoundKind::ReadinessWhole] {
assert_eq!(
resolve_bound(Bound::After(SET), kind, Some(&defaults)),
Resolved::After { after: SET, limit: Limit::Item },
"{kind:?}"
);
}
assert_eq!(
resolve_bound(Bound::After(SET), BoundKind::ReadinessAttempt, Some(&defaults)),
Resolved::After { after: SET, limit: Limit::Attempt }
);
}
#[test]
fn default_takes_the_app_default_for_the_kind_of_item() {
let defaults = defaults();
let default = |after| Resolved::After { after, limit: Limit::Default };
assert_eq!(resolve_bound(Bound::Default, BoundKind::Hook, Some(&defaults)), default(HOOK));
assert_eq!(resolve_bound(Bound::Default, BoundKind::Construction, Some(&defaults)), default(CONSTRUCT));
assert_eq!(resolve_bound(Bound::Default, BoundKind::ReadinessAttempt, Some(&defaults)), default(CONSTRUCT));
assert_eq!(resolve_bound(Bound::Default, BoundKind::ReadinessWhole, Some(&defaults)), Resolved::Unbounded);
}
struct Clock {
ready: bool,
refuses: bool,
passes: Duration,
at: std::sync::Mutex<Instant>,
asked: std::sync::Mutex<Option<Duration>>,
}
impl Clock {
fn new(ready: bool) -> Clock {
Clock { ready, refuses: false, passes: Duration::ZERO, at: std::sync::Mutex::new(Instant::now()), asked: Default::default() }
}
fn refusing(passes: Duration) -> Clock {
Clock { refuses: true, passes, ..Clock::new(false) }
}
}
impl Timer for Clock {
fn sleep(&self, d: Duration) -> BoxFuture<'static, ()> {
*self.asked.lock().unwrap() = Some(d);
if self.ready || self.refuses { Box::pin(std::future::ready(())) } else { Box::pin(std::future::pending()) }
}
fn now(&self) -> Instant {
*self.at.lock().unwrap()
}
fn try_sleep(&self, d: Duration) -> crate::BoxFuture<'static, Result<(), crate::Refused>> {
if self.refuses {
*self.asked.lock().unwrap() = Some(d);
*self.at.lock().unwrap() += self.passes;
return Box::pin(std::future::ready(Err(Refused)));
}
let sleep = crate::Timer::sleep(self, d);
Box::pin(async move {
sleep.await;
Ok(())
})
}
}
fn block_on<F: Future>(fut: F) -> F::Output {
let mut fut = pin!(fut);
let mut cx = Context::from_waker(Waker::noop());
for _ in 0..100 {
if let Poll::Ready(output) = fut.as_mut().poll(&mut cx) {
return output;
}
}
panic!("the future did not complete in 100 polls");
}
fn ready_after(polls: usize) -> impl Future<Output = u8> {
let mut left = polls;
poll_fn(move |cx| {
if left == 0 {
return Poll::Ready(7);
}
left -= 1;
cx.waker().wake_by_ref();
Poll::Pending
})
}
#[test]
fn the_future_that_finishes_first_wins() {
let clock = Clock::new(false);
let out = block_on(timeout(&clock, SET, async { 7 }));
assert_eq!(out, Ok(7));
}
#[test]
fn the_sleep_is_asked_for_the_bound() {
let clock = Clock::new(false);
let mut running = pin!(timeout(&clock, SET, std::future::pending::<u8>()));
assert!(running.as_mut().poll(&mut Context::from_waker(Waker::noop())).is_pending());
assert_eq!(*clock.asked.lock().unwrap(), Some(SET), "the sleep is asked for the bound");
}
#[test]
fn the_sleep_wins_when_the_future_never_finishes() {
let clock = Clock::new(true);
let out = block_on(timeout(&clock, SET, std::future::pending::<u8>()));
assert_eq!(out, Err(Cut::Expired));
}
#[test]
fn work_that_completes_in_the_poll_the_sleep_fires_in_counts_as_done() {
let clock = Clock::new(true);
let out = block_on(timeout(&clock, SET, async { 7 }));
assert_eq!(out, Ok(7));
}
#[test]
fn a_refused_bound_that_did_not_pass_is_reported_as_refused() {
let clock = Clock::refusing(Duration::ZERO);
let out = block_on(timeout(&clock, SET, std::future::pending::<u8>()));
assert_eq!(out, Err(Cut::Refused(Refused)));
}
#[test]
fn an_answer_ready_in_the_poll_after_the_refusal_outranks_it() {
let clock = Clock::refusing(Duration::ZERO);
let out = block_on(timeout(&clock, SET, ready_after(1)));
assert_eq!(out, Ok(7));
}
#[test]
fn work_pending_past_the_poll_after_the_refusal_ends_on_it() {
let clock = Clock::refusing(Duration::ZERO);
let out = block_on(timeout(&clock, SET, ready_after(2)));
assert_eq!(out, Err(Cut::Refused(Refused)));
}
#[test]
fn a_refusal_after_the_bound_passed_reports_the_expiry() {
let clock = Clock::refusing(SET);
let out = block_on(timeout(&clock, SET, std::future::pending::<u8>()));
assert_eq!(out, Err(Cut::Expired));
}
#[test]
fn a_bound_already_passed_when_made_expires_without_a_sleep() {
let clock = Clock::refusing(Duration::ZERO);
let until = clock.now();
let out = block_on(timeout_at(&clock, until, std::future::pending::<u8>()));
assert_eq!(out, Err(Cut::Expired));
assert_eq!(*clock.asked.lock().unwrap(), None, "a sleep was asked for a bound already passed");
}
#[test]
fn a_bound_past_the_clocks_range_is_refused_and_never_expired() {
let clock = Clock::refusing(Duration::from_secs(10 * 365 * 86_400));
let out = block_on(timeout(&clock, Duration::MAX, std::future::pending::<u8>()));
assert_eq!(out, Err(Cut::Refused(Refused)));
}
}