use std::any::Any;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Weak;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::task::Context;
use std::task::Poll;
use std::task::ready;
use futures::FutureExt;
use futures::channel::oneshot;
use tracing::Instrument;
use vortex_error::vortex_panic;
use crate::runtime::AbortHandle;
use crate::runtime::AbortHandleRef;
use crate::runtime::Executor;
use crate::runtime::platform;
#[derive(Clone)]
pub struct Handle {
runtime: Weak<dyn Executor>,
}
impl Handle {
pub fn new(runtime: Weak<dyn Executor>) -> Self {
Self { runtime }
}
fn runtime(&self) -> Arc<dyn Executor> {
self.runtime.upgrade().unwrap_or_else(|| {
vortex_panic!("Attempted to use a Handle after its runtime was dropped")
})
}
pub fn find() -> Option<Self> {
#[cfg(feature = "tokio")]
{
use tokio::runtime::Handle as TokioHandle;
use crate::runtime::tokio::TokioRuntime;
if TokioHandle::try_current().is_ok() {
return Some(TokioRuntime::current());
}
}
platform::default_handle()
}
pub fn spawn<Fut, R>(&self, f: Fut) -> Task<R>
where
Fut: Future<Output = R> + Send + 'static,
R: Send + 'static,
{
let (send, recv) = oneshot::channel();
let span = tracing::trace_span!(target: "vortex_io::spawn", "spawn");
let abort_handle = self.runtime().spawn(
async move {
let output = AssertUnwindSafe(f).catch_unwind().await;
drop(send.send(output));
}
.instrument(span)
.boxed(),
);
Task {
recv,
abort_handle: Some(abort_handle),
}
}
pub fn spawn_nested<F, Fut, R>(&self, f: F) -> Task<R>
where
F: FnOnce(Handle) -> Fut,
Fut: Future<Output = R> + Send + 'static,
R: Send + 'static,
{
self.spawn(f(Handle::new(Weak::clone(&self.runtime))))
}
pub fn spawn_io<Fut, R>(&self, f: Fut) -> Task<R>
where
Fut: Future<Output = R> + Send + 'static,
R: Send + 'static,
{
let (send, recv) = oneshot::channel();
let span = tracing::trace_span!(target: "vortex_io::spawn_io", "spawn_io");
let abort_handle = self.runtime().spawn_io(
async move {
let output = AssertUnwindSafe(f).catch_unwind().await;
drop(send.send(output));
}
.instrument(span)
.boxed(),
);
Task {
recv,
abort_handle: Some(abort_handle),
}
}
pub fn spawn_cpu<F, R>(&self, f: F) -> Task<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let (send, recv) = oneshot::channel();
let aborted = Arc::new(AtomicBool::new(false));
let task_aborted = Arc::clone(&aborted);
let span = tracing::Span::current();
let abort_handle = self.runtime().spawn_cpu(Box::new(move || {
let _guard = span.enter();
if !task_aborted.load(Ordering::Acquire) {
let output = std::panic::catch_unwind(AssertUnwindSafe(f));
drop(send.send(output));
}
}));
Task {
recv,
abort_handle: Some(Box::new(SyncTaskAbortHandle {
aborted,
inner: abort_handle,
})),
}
}
pub fn spawn_blocking<F, R>(&self, f: F) -> Task<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
let (send, recv) = oneshot::channel();
let aborted = Arc::new(AtomicBool::new(false));
let task_aborted = Arc::clone(&aborted);
let span = tracing::Span::current();
let abort_handle = self.runtime().spawn_blocking_io(Box::new(move || {
let _guard = span.enter();
if !task_aborted.load(Ordering::Acquire) {
let output = std::panic::catch_unwind(AssertUnwindSafe(f));
drop(send.send(output));
}
}));
Task {
recv,
abort_handle: Some(Box::new(SyncTaskAbortHandle {
aborted,
inner: abort_handle,
})),
}
}
}
struct SyncTaskAbortHandle {
aborted: Arc<AtomicBool>,
inner: AbortHandleRef,
}
impl AbortHandle for SyncTaskAbortHandle {
fn abort(self: Box<Self>) {
self.aborted.store(true, Ordering::Release);
self.inner.abort();
}
}
type TaskOutput<T> = Result<T, Box<dyn Any + Send>>;
pub enum JoinOutcome<T> {
Completed(T),
Panicked(Box<dyn Any + Send>),
Aborted,
}
#[must_use = "When a Task is dropped without being awaited, it is cancelled"]
pub struct Task<T> {
recv: oneshot::Receiver<TaskOutput<T>>,
abort_handle: Option<AbortHandleRef>,
}
impl<T> Task<T> {
pub fn detach(mut self) {
drop(self.abort_handle.take());
}
pub fn poll_join(&mut self, cx: &mut Context<'_>) -> Poll<JoinOutcome<T>> {
match ready!(self.recv.poll_unpin(cx)) {
Ok(Ok(output)) => Poll::Ready(JoinOutcome::Completed(output)),
Ok(Err(panic)) => Poll::Ready(JoinOutcome::Panicked(panic)),
Err(_recv_err) => Poll::Ready(JoinOutcome::Aborted),
}
}
}
impl<T> Future for Task<T> {
type Output = T;
#[expect(clippy::panic)]
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match ready!(self.get_mut().poll_join(cx)) {
JoinOutcome::Completed(output) => Poll::Ready(output),
JoinOutcome::Panicked(panic) => std::panic::resume_unwind(panic),
JoinOutcome::Aborted => {
panic!("Runtime dropped task without completing it")
}
}
}
}
impl<T> Drop for Task<T> {
fn drop(&mut self) {
if let Some(handle) = self.abort_handle.take() {
handle.abort();
}
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use futures::future::BoxFuture;
use futures::task::noop_waker;
use parking_lot::Mutex;
use super::*;
use crate::runtime::AbortHandle;
struct GatedAbortHandle {
abort_calls: Arc<AtomicUsize>,
}
impl AbortHandle for GatedAbortHandle {
fn abort(self: Box<Self>) {
self.abort_calls.fetch_add(1, Ordering::SeqCst);
}
}
struct GatedExecutor {
queue: Mutex<Vec<Box<dyn FnOnce() + Send + 'static>>>,
abort_calls: Arc<AtomicUsize>,
}
impl GatedExecutor {
fn new() -> Arc<Self> {
Arc::new(Self {
queue: Mutex::new(Vec::new()),
abort_calls: Arc::new(AtomicUsize::new(0)),
})
}
fn enqueue(&self, work: Box<dyn FnOnce() + Send + 'static>) -> AbortHandleRef {
self.queue.lock().push(work);
Box::new(GatedAbortHandle {
abort_calls: Arc::clone(&self.abort_calls),
})
}
fn drain(&self) {
for job in std::mem::take(&mut *self.queue.lock()) {
job();
}
}
}
impl Executor for GatedExecutor {
fn spawn(&self, _fut: BoxFuture<'static, ()>) -> AbortHandleRef {
panic!("async spawn not used in gated sync tests")
}
fn spawn_cpu(&self, cpu: Box<dyn FnOnce() + Send + 'static>) -> AbortHandleRef {
self.enqueue(cpu)
}
fn spawn_blocking_io(&self, task: Box<dyn FnOnce() + Send + 'static>) -> AbortHandleRef {
self.enqueue(task)
}
}
#[test]
fn detached_cpu_and_blocking_tasks_run_queued_work() {
let executor = GatedExecutor::new();
let dyn_exec: Arc<dyn Executor> = Arc::clone(&executor) as Arc<dyn Executor>;
let handle = Handle::new(Arc::downgrade(&dyn_exec));
let cpu_runs = Arc::new(AtomicUsize::new(0));
let blocking_runs = Arc::new(AtomicUsize::new(0));
let cpu_runs_clone = Arc::clone(&cpu_runs);
let cpu_task = handle.spawn_cpu(move || {
cpu_runs_clone.fetch_add(1, Ordering::SeqCst);
1usize
});
let blocking_runs_clone = Arc::clone(&blocking_runs);
let blocking_task = handle.spawn_blocking(move || {
blocking_runs_clone.fetch_add(1, Ordering::SeqCst);
2usize
});
cpu_task.detach();
blocking_task.detach();
executor.drain();
assert_eq!(cpu_runs.load(Ordering::SeqCst), 1);
assert_eq!(blocking_runs.load(Ordering::SeqCst), 1);
assert_eq!(executor.abort_calls.load(Ordering::SeqCst), 0);
}
#[test]
fn dropped_cpu_and_blocking_tasks_skip_queued_work() {
let executor = GatedExecutor::new();
let dyn_exec: Arc<dyn Executor> = Arc::clone(&executor) as Arc<dyn Executor>;
let handle = Handle::new(Arc::downgrade(&dyn_exec));
let cpu_runs = Arc::new(AtomicUsize::new(0));
let blocking_runs = Arc::new(AtomicUsize::new(0));
let cpu_runs_clone = Arc::clone(&cpu_runs);
let cpu_task = handle.spawn_cpu(move || {
cpu_runs_clone.fetch_add(1, Ordering::SeqCst);
});
let blocking_runs_clone = Arc::clone(&blocking_runs);
let blocking_task = handle.spawn_blocking(move || {
blocking_runs_clone.fetch_add(1, Ordering::SeqCst);
});
drop(cpu_task);
drop(blocking_task);
executor.drain();
assert_eq!(cpu_runs.load(Ordering::SeqCst), 0);
assert_eq!(blocking_runs.load(Ordering::SeqCst), 0);
assert_eq!(executor.abort_calls.load(Ordering::SeqCst), 2);
}
#[test]
fn poll_join_reports_aborted_when_channel_closed_without_value() {
let (send, recv) = oneshot::channel::<TaskOutput<()>>();
drop(send);
let mut task = Task::<()> {
recv,
abort_handle: None,
};
let waker = noop_waker();
let mut cx = Context::from_waker(&waker);
assert!(matches!(
task.poll_join(&mut cx),
Poll::Ready(JoinOutcome::Aborted)
));
}
#[test]
fn poll_join_reports_completed_value() {
let (send, recv) = oneshot::channel::<TaskOutput<u32>>();
drop(send.send(Ok(7)));
let mut task = Task::<u32> {
recv,
abort_handle: None,
};
let waker = noop_waker();
let mut cx = Context::from_waker(&waker);
assert!(matches!(
task.poll_join(&mut cx),
Poll::Ready(JoinOutcome::Completed(7))
));
}
}