use std::any::Any;
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::pin::Pin;
use std::sync::{Arc, Mutex, PoisonError};
use std::task::{Context, Poll, ready};
use std::time::{Duration, Instant};
use crate::lifecycle::run::CatchUnwind;
use crate::redact::{Redacted, Redactor, SecretRegistry, redact_panic};
use crate::timer::{BoxFuture, Refused, Timer};
pub trait Spawn: Send + Sync + 'static {
fn spawn(&self, fut: BoxFuture<'static, ()>) -> TaskHandle;
fn try_spawn(&self, fut: BoxFuture<'static, ()>) -> Result<TaskHandle, Refused>;
fn name(&self) -> &'static str {
"unknown"
}
}
pub trait Runtime: Timer + Spawn {}
impl<R: Timer + Spawn + ?Sized> Runtime for R {}
pub(crate) struct Clocked {
spawner: Arc<dyn Runtime>,
timer: Arc<dyn Timer>,
redactor: Redactor,
}
impl Clocked {
pub(crate) fn new(spawner: Arc<dyn Runtime>, timer: Arc<dyn Timer>, redactor: Redactor) -> Clocked {
Clocked { spawner, timer, redactor }
}
}
impl Timer for Clocked {
fn sleep(&self, d: Duration) -> BoxFuture<'static, ()> {
self.timer.sleep(d)
}
fn now(&self) -> Instant {
self.timer.now()
}
fn try_sleep(&self, d: Duration) -> BoxFuture<'static, Result<(), Refused>> {
self.timer.try_sleep(d)
}
}
impl Spawn for Clocked {
fn spawn(&self, fut: BoxFuture<'static, ()>) -> TaskHandle {
let (launched, recorded) = Launched::new(fut, Some(self.redactor.clone()));
self.spawner.spawn(Box::pin(launched)).reading(recorded)
}
fn try_spawn(&self, fut: BoxFuture<'static, ()>) -> Result<TaskHandle, Refused> {
let (launched, recorded) = Launched::new(fut, Some(self.redactor.clone()));
Ok(self.spawner.try_spawn(Box::pin(launched))?.reading(recorded))
}
fn name(&self) -> &'static str {
self.spawner.name()
}
}
#[derive(Clone, Debug)]
pub enum TaskEnd {
Finished,
Aborted,
Panicked(Arc<Redacted>),
}
impl TaskEnd {
pub fn is_finished(&self) -> bool {
matches!(self, TaskEnd::Finished)
}
pub fn is_aborted(&self) -> bool {
matches!(self, TaskEnd::Aborted)
}
pub fn is_panicked(&self) -> bool {
matches!(self, TaskEnd::Panicked(_))
}
}
pub trait RuntimeTask: Send + 'static {
fn abort(&mut self);
fn poll_ended(&mut self, cx: &mut Context<'_>) -> Poll<()>;
fn detach(self: Box<Self>);
}
enum Recorded {
Finished,
Panicked(Redacted),
}
pub struct TaskHandle {
task: Mutex<Option<Box<dyn RuntimeTask>>>,
recorded: Arc<Mutex<Option<Recorded>>>,
end: Option<TaskEnd>,
}
impl TaskHandle {
pub fn launch<T, S>(fut: BoxFuture<'static, ()>, start: S) -> TaskHandle
where
T: RuntimeTask,
S: FnOnce(BoxFuture<'static, ()>) -> T,
{
let (launched, recorded) = Launched::new(fut, None);
let task = start(Box::pin(launched));
TaskHandle { task: Mutex::new(Some(Box::new(task))), recorded, end: None }
}
fn reading(mut self, recorded: Arc<Mutex<Option<Recorded>>>) -> TaskHandle {
self.recorded = recorded;
self
}
pub fn abort(&self) {
if self.end.is_some() {
return;
}
if let Some(task) = self.task.lock().unwrap_or_else(PoisonError::into_inner).as_mut() {
task.abort();
}
}
}
impl Future for TaskHandle {
type Output = TaskEnd;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<TaskEnd> {
let this = self.get_mut();
if let Some(end) = &this.end {
return Poll::Ready(end.clone());
}
let task = this.task.get_mut().unwrap_or_else(PoisonError::into_inner);
if let Some(task) = task.as_mut() {
ready!(task.poll_ended(cx));
}
let end = match this.recorded.lock().unwrap_or_else(PoisonError::into_inner).take() {
Some(Recorded::Finished) => TaskEnd::Finished,
Some(Recorded::Panicked(message)) => TaskEnd::Panicked(Arc::new(message)),
None => TaskEnd::Aborted,
};
Poll::Ready(this.end.insert(end).clone())
}
}
struct Launched {
fut: Option<CatchUnwind<dyn Future<Output = ()> + Send>>,
record: Arc<Mutex<Option<Recorded>>>,
redactor: Option<Redactor>,
}
impl Launched {
fn new(fut: BoxFuture<'static, ()>, redactor: Option<Redactor>) -> (Launched, Arc<Mutex<Option<Recorded>>>) {
let recorded = Arc::new(Mutex::new(None));
(Launched { fut: Some(CatchUnwind::boxed(fut)), record: Arc::clone(&recorded), redactor }, recorded)
}
}
fn redacted(redactor: Option<&Redactor>, payload: Box<dyn Any + Send>) -> Redacted {
match redactor {
Some(redactor) => redactor.panic(payload),
None => redact_panic(&SecretRegistry::default(), payload),
}
}
impl Future for Launched {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
let this = self.get_mut();
let Some(fut) = this.fut.as_mut() else {
return Poll::Ready(());
};
let end = match ready!(Pin::new(fut).poll(cx)) {
Ok(()) => Recorded::Finished,
Err(payload) => Recorded::Panicked(redacted(this.redactor.as_ref(), payload)),
};
drop_caught(this.fut.take(), this.redactor.as_ref(), "after it ended");
*this.record.lock().unwrap_or_else(PoisonError::into_inner) = Some(end);
Poll::Ready(())
}
}
impl Drop for Launched {
fn drop(&mut self) {
drop_caught(self.fut.take(), self.redactor.as_ref(), "unfinished, so the task ends `Aborted`");
}
}
fn drop_caught(fut: Option<CatchUnwind<dyn Future<Output = ()> + Send>>, redactor: Option<&Redactor>, when: &str) {
if let Some(fut) = fut
&& let Err(payload) = catch_unwind(AssertUnwindSafe(move || drop(fut)))
{
let message = redacted(redactor, payload);
tracing::warn!(%message, "a task's future panicked while it was dropped {when}");
}
}
impl Drop for TaskHandle {
fn drop(&mut self) {
if let Some(task) = self.task.get_mut().unwrap_or_else(PoisonError::into_inner).take() {
task.detach();
}
}
}
pub fn spawn_with<T, F, R>(runtime: &R, fut: F) -> ValueHandle<T>
where
T: Send + 'static,
F: Future<Output = T> + Send + 'static,
R: Spawn + ?Sized,
{
let slot = Arc::new(Mutex::new(None));
let fill = Arc::clone(&slot);
let task = runtime.spawn(Box::pin(async move {
let value = fut.await;
*fill.lock().unwrap_or_else(PoisonError::into_inner) = Some(value);
}));
ValueHandle { task, slot }
}
pub struct ValueHandle<T> {
task: TaskHandle,
slot: Arc<Mutex<Option<T>>>,
}
impl<T> ValueHandle<T> {
pub fn abort(&self) {
self.task.abort();
}
}
impl<T> Future for ValueHandle<T> {
type Output = Result<T, TaskEnd>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
let end = ready!(Pin::new(&mut this.task).poll(cx));
let value = this.slot.lock().unwrap_or_else(PoisonError::into_inner).take();
Poll::Ready(match (end, value) {
(TaskEnd::Finished, Some(value)) => Ok(value),
(end, _) => Err(end),
})
}
}
#[cfg(test)]
mod tests {
use std::task::Waker;
use super::*;
struct ShutDown;
impl Timer for ShutDown {
fn sleep(&self, _d: Duration) -> BoxFuture<'static, ()> {
Box::pin(std::future::ready(()))
}
fn now(&self) -> Instant {
Instant::now()
}
fn try_sleep(&self, _d: Duration) -> BoxFuture<'static, Result<(), Refused>> {
Box::pin(std::future::ready(Err(Refused)))
}
}
impl Spawn for ShutDown {
fn spawn(&self, _fut: BoxFuture<'static, ()>) -> TaskHandle {
panic!("the app's runtime answered `try_spawn` through the wrapped runtime's `spawn`, dropping its refusal")
}
fn try_spawn(&self, _fut: BoxFuture<'static, ()>) -> Result<TaskHandle, Refused> {
Err(Refused)
}
}
fn refused_sleep(timer: &dyn Timer) -> Poll<Result<(), Refused>> {
timer.try_sleep(Duration::from_secs(3600)).as_mut().poll(&mut Context::from_waker(Waker::noop()))
}
#[test]
fn the_app_s_runtime_forwards_the_refusals_of_the_runtime_it_wraps() {
let runtime: Arc<dyn Runtime> = Arc::new(ShutDown);
let clocked = Clocked::new(Arc::clone(&runtime), Arc::clone(&runtime) as Arc<dyn Timer>, Redactor::default());
assert!(clocked.try_spawn(Box::pin(async {})).is_err(), "the app's runtime answered a refused `try_spawn` with a handle");
assert_eq!(refused_sleep(&clocked), Poll::Ready(Err(Refused)), "the app's runtime answered a refused `try_sleep` otherwise");
}
}