use std::error::Error;
use std::future::{Future, poll_fn};
use std::pin::{Pin, pin};
use std::task::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;
}
#[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,
},
}
}
pub(crate) async fn timeout<F: Future>(timer: &dyn Timer, d: Duration, fut: F) -> Result<F::Output, ()> {
let mut fut = pin!(fut);
let mut sleep = timer.sleep(d);
poll_fn(|cx| {
if let Poll::Ready(output) = fut.as_mut().poll(cx) {
return Poll::Ready(Ok(output));
}
match sleep.as_mut().poll(cx) {
Poll::Ready(()) => Poll::Ready(Err(())),
Poll::Pending => Poll::Pending,
}
})
.await
}