use std::any::Any;
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use crate::error::{FailureReason, Limit, Permanent};
use crate::redact::{Redacted, SecretRegistry, redact, redact_panic};
use crate::timer::{Cut, Refused, Resolved, RuntimeShutDown, Timer, timeout, timeout_at};
#[derive(Clone, Copy, Debug)]
pub(crate) struct Cap {
pub(crate) at: Instant,
pub(crate) after: Duration,
}
impl Cap {
pub(crate) fn expired(&self, timer: &dyn Timer) -> bool {
timer.now() >= self.at
}
}
pub(crate) enum Outcome<T> {
Done(T),
Panicked(Redacted),
TimedOut { after: Duration, limit: Limit },
Refused(Refused),
}
pub(crate) fn shut_down(secrets: &SecretRegistry, refused: Refused) -> FailureReason {
FailureReason::Errored(redact(secrets, Box::new(Permanent::new(RuntimeShutDown::new(refused)))))
}
pub(crate) async fn run<F: Future>(
timer: Option<&dyn Timer>,
bound: Resolved,
cap: Option<Cap>,
secrets: &SecretRegistry,
fut: F,
) -> Outcome<F::Output> {
let item = CatchUnwind::new(fut);
let capped = async {
match (timer, cap) {
(Some(t), Some(c)) => timeout_at(t, c.at, item).await.map_err(|cut| (cut, c.after, Limit::ShutdownCap)),
_ => Ok(item.await),
}
};
let ended = match (timer, bound) {
(Some(t), Resolved::After { after, limit }) => timeout(t, after, capped).await.unwrap_or_else(|cut| Err((cut, after, limit))),
_ => capped.await,
};
match ended {
Ok(Ok(value)) => Outcome::Done(value),
Ok(Err(payload)) => Outcome::Panicked(redact_panic(secrets, payload)),
Err((Cut::Expired, after, limit)) => Outcome::TimedOut { after, limit },
Err((Cut::Refused(refused), ..)) => Outcome::Refused(refused),
}
}
pub(crate) struct CatchUnwind<F: ?Sized> {
inner: Pin<Box<F>>,
}
impl<F> CatchUnwind<F> {
pub(crate) fn new(inner: F) -> Self {
CatchUnwind { inner: Box::pin(inner) }
}
}
impl<F: ?Sized> CatchUnwind<F> {
pub(crate) fn boxed(inner: Pin<Box<F>>) -> Self {
CatchUnwind { inner }
}
}
impl<F: Future + ?Sized> Future for CatchUnwind<F> {
type Output = Result<F::Output, Box<dyn Any + Send>>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
match catch_unwind(AssertUnwindSafe(|| this.inner.as_mut().poll(cx))) {
Ok(Poll::Ready(value)) => Poll::Ready(Ok(value)),
Ok(Poll::Pending) => Poll::Pending,
Err(payload) => Poll::Ready(Err(payload)),
}
}
}
#[cfg(test)]
mod tests {
use std::future::poll_fn;
use std::pin::pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::task::Waker;
use super::*;
use crate::timer::BoxFuture;
#[derive(Clone)]
struct Scripted(Arc<Mutex<Instant>>);
impl Scripted {
fn new() -> Scripted {
Scripted(Arc::new(Mutex::new(Instant::now())))
}
fn advance(&self, by: Duration) {
*self.0.lock().unwrap() += by;
}
}
impl Timer for Scripted {
fn sleep(&self, d: Duration) -> BoxFuture<'static, ()> {
let clock = Arc::clone(&self.0);
let until = *clock.lock().unwrap() + d;
Box::pin(poll_fn(move |_| if *clock.lock().unwrap() >= until { Poll::Ready(()) } else { Poll::Pending }))
}
fn now(&self) -> Instant {
*self.0.lock().unwrap()
}
fn try_sleep(&self, d: Duration) -> crate::BoxFuture<'static, Result<(), crate::Refused>> {
let sleep = crate::Timer::sleep(self, d);
Box::pin(async move {
sleep.await;
Ok(())
})
}
}
const OWN: Duration = Duration::from_secs(2);
const CAP: Duration = Duration::from_secs(9);
fn poll<F: Future>(fut: Pin<&mut F>) -> Poll<F::Output> {
fut.poll(&mut Context::from_waker(Waker::noop()))
}
fn coinciding(clock: &Scripted) -> (Resolved, Option<Cap>) {
(Resolved::After { after: OWN, limit: Limit::Item }, Some(Cap { at: clock.now() + OWN, after: CAP }))
}
#[test]
fn a_cap_and_an_own_bound_ending_on_one_poll_report_the_cap() {
let clock = Scripted::new();
let (bound, cap) = coinciding(&clock);
let secrets = SecretRegistry::default();
let mut running = pin!(run(Some(&clock), bound, cap, &secrets, std::future::pending::<()>()));
assert!(poll(running.as_mut()).is_pending(), "a limit fired before the clock moved");
clock.advance(OWN);
match poll(running.as_mut()) {
Poll::Ready(Outcome::TimedOut { after, limit }) => {
assert_eq!((after, limit), (CAP, Limit::ShutdownCap), "the cap, wrapped inside the item's own bound, is polled first");
}
Poll::Ready(Outcome::Done(())) => panic!("a pending item was reported done"),
Poll::Ready(Outcome::Panicked(_)) => panic!("a pending item was reported panicked"),
Poll::Ready(Outcome::Refused(_)) => panic!("a clock that keeps time was reported refusing"),
Poll::Pending => panic!("neither limit fired once both had passed"),
}
}
#[test]
fn an_item_ready_on_the_poll_both_limits_end_counts_as_done() {
let clock = Scripted::new();
let (bound, cap) = coinciding(&clock);
let secrets = SecretRegistry::default();
let finished = AtomicBool::new(false);
let item = poll_fn(|_| if finished.load(Ordering::SeqCst) { Poll::Ready(7) } else { Poll::Pending });
let mut running = pin!(run(Some(&clock), bound, cap, &secrets, item));
assert!(poll(running.as_mut()).is_pending(), "the item finished before it was let");
finished.store(true, Ordering::SeqCst);
clock.advance(OWN);
match poll(running.as_mut()) {
Poll::Ready(Outcome::Done(value)) => assert_eq!(value, 7),
Poll::Ready(Outcome::TimedOut { after, limit }) => panic!("a limit polled before the item: {limit:?} after {after:?}"),
Poll::Ready(Outcome::Panicked(_)) => panic!("the item was reported panicked"),
Poll::Ready(Outcome::Refused(_)) => panic!("a clock that keeps time was reported refusing"),
Poll::Pending => panic!("the item was ready and not taken"),
}
}
}