use std::any::Any;
use std::future::{Future, poll_fn};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::pin::{Pin, pin};
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
use crate::error::{FailureReason, Limit};
use crate::redact::{Redacted, SecretRegistry, redact_panic};
use crate::timer::{BoxFuture, Resolved, Timer};
#[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 },
}
impl<T> Outcome<T> {
pub(crate) fn into_failure(self) -> Result<T, FailureReason> {
match self {
Outcome::Done(v) => Ok(v),
Outcome::Panicked(p) => Err(FailureReason::Panicked(p)),
Outcome::TimedOut { after, limit } => Err(FailureReason::TimedOut { after, limit }),
}
}
}
pub(crate) async fn run<F: Future>(
timer: Option<&dyn Timer>,
bound: Resolved,
cap: Option<Cap>,
secrets: &SecretRegistry,
fut: F,
) -> Outcome<F::Output> {
let mut item = pin!(CatchUnwind::new(fut));
let mut own: Option<(BoxFuture<'static, ()>, Duration, Limit)> = match (timer, bound) {
(Some(t), Resolved::After { after, limit }) => Some((t.sleep(after), after, limit)),
_ => None,
};
let mut capped: Option<(BoxFuture<'static, ()>, Duration)> = match (timer, cap) {
(Some(t), Some(c)) => Some((t.sleep(c.at.saturating_duration_since(t.now())), c.after)),
_ => None,
};
let ended = poll_fn(|cx| {
if let Poll::Ready(out) = item.as_mut().poll(cx) {
return Poll::Ready(Ok(out));
}
if let Some((sleep, after)) = capped.as_mut() {
if sleep.as_mut().poll(cx).is_ready() {
return Poll::Ready(Err((*after, Limit::ShutdownCap)));
}
}
if let Some((sleep, after, limit)) = own.as_mut() {
if sleep.as_mut().poll(cx).is_ready() {
return Poll::Ready(Err((*after, *limit)));
}
}
Poll::Pending
})
.await;
match ended {
Ok(Ok(value)) => Outcome::Done(value),
Ok(Err(payload)) => Outcome::Panicked(redact_panic(secrets, payload)),
Err((after, limit)) => Outcome::TimedOut { after, limit },
}
}
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)),
}
}
}
pub(crate) async fn select<A: Future, B: Future>(a: A, b: B) -> Either<A::Output, B::Output> {
let mut a = pin!(a);
let mut b = pin!(b);
poll_fn(|cx| {
if let Poll::Ready(v) = a.as_mut().poll(cx) {
return Poll::Ready(Either::Left(v));
}
if let Poll::Ready(v) = b.as_mut().poll(cx) {
return Poll::Ready(Either::Right(v));
}
Poll::Pending
})
.await
}
pub(crate) enum Either<A, B> {
Left(A),
Right(B),
}