Skip to main content

vortex_io/runtime/
handle.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5use std::panic::AssertUnwindSafe;
6use std::pin::Pin;
7use std::sync::Arc;
8use std::sync::Weak;
9use std::sync::atomic::AtomicBool;
10use std::sync::atomic::Ordering;
11use std::task::Context;
12use std::task::Poll;
13use std::task::ready;
14
15use futures::FutureExt;
16use futures::channel::oneshot;
17use tracing::Instrument;
18use vortex_error::vortex_panic;
19
20use crate::runtime::AbortHandle;
21use crate::runtime::AbortHandleRef;
22use crate::runtime::Executor;
23use crate::runtime::platform;
24
25/// A handle to an active Vortex runtime.
26///
27/// Users should obtain a handle from one of the Vortex runtime's and use it to spawn new async
28/// tasks, blocking I/O tasks, CPU-heavy tasks, or to open files for reading or writing.
29///
30/// Note that a [`Handle`] is a weak reference to the underlying runtime. If the associated
31/// runtime has been dropped, then any requests to spawn new tasks will panic.
32#[derive(Clone)]
33pub struct Handle {
34    runtime: Weak<dyn Executor>,
35}
36
37impl Handle {
38    pub fn new(runtime: Weak<dyn Executor>) -> Self {
39        Self { runtime }
40    }
41
42    fn runtime(&self) -> Arc<dyn Executor> {
43        self.runtime.upgrade().unwrap_or_else(|| {
44            vortex_panic!("Attempted to use a Handle after its runtime was dropped")
45        })
46    }
47
48    /// Returns a handle to the current runtime, if such a reasonable choice exists.
49    ///
50    /// For example, if called from within a Tokio context this will return a
51    /// `TokioRuntime` handle. On browser WebAssembly with the `wasm-bindgen` feature this returns
52    /// the global `WasmRuntime` handle; without it there is no event loop to schedule onto, and
53    /// callers must drive a `SingleThreadRuntime` and install its handle themselves.
54    pub fn find() -> Option<Self> {
55        #[cfg(feature = "tokio")]
56        {
57            use tokio::runtime::Handle as TokioHandle;
58
59            use crate::runtime::tokio::TokioRuntime;
60            if TokioHandle::try_current().is_ok() {
61                return Some(TokioRuntime::current());
62            }
63        }
64
65        platform::default_handle()
66    }
67
68    /// Spawn a new future onto the runtime.
69    ///
70    /// These futures are expected to not perform expensive CPU work and instead simply schedule
71    /// either CPU tasks or I/O tasks. See [`Handle::spawn_cpu`] for spawning CPU-bound work.
72    ///
73    /// See [`Task`] for details on cancelling or detaching the spawned task.
74    pub fn spawn<Fut, R>(&self, f: Fut) -> Task<R>
75    where
76        Fut: Future<Output = R> + Send + 'static,
77        R: Send + 'static,
78    {
79        let (send, recv) = oneshot::channel();
80        // Instrument with a dedicated, named span on its own target rather than
81        // re-entering `Span::current()`. `Instrumented::poll` enters and exits the
82        // span on every poll, so re-entering the caller's span makes its cost scale
83        // with poll count. A distinct target lets subscribers opt these spans in or
84        // out via filtering; when filtered out the span is disabled and enter/exit
85        // are no-ops, which keeps frequently-polled spawned futures cheap.
86        let span = tracing::trace_span!(target: "vortex_io::spawn", "spawn");
87        let abort_handle = self.runtime().spawn(
88            async move {
89                // Catch a panic so it can be re-raised on the joining side (see `Task::poll`)
90                // rather than being lost, matching `tokio::JoinError` / `smol::Task` semantics.
91                let output = AssertUnwindSafe(f).catch_unwind().await;
92                // Task::detach allows the receiver to be dropped, so we ignore send errors.
93                drop(send.send(output));
94            }
95            .instrument(span)
96            .boxed(),
97        );
98        Task {
99            recv,
100            abort_handle: Some(abort_handle),
101        }
102    }
103
104    /// A helper function to avoid manually cloning the handle when spawning nested tasks.
105    pub fn spawn_nested<F, Fut, R>(&self, f: F) -> Task<R>
106    where
107        F: FnOnce(Handle) -> Fut,
108        Fut: Future<Output = R> + Send + 'static,
109        R: Send + 'static,
110    {
111        self.spawn(f(Handle::new(Weak::clone(&self.runtime))))
112    }
113
114    /// Spawn a new I/O future onto the runtime.
115    ///
116    /// See [`Executor::spawn_io`] for more details about how this future is expected to run.
117    // See [`Task`] for details on cancelling or detaching the spawned task.
118    pub fn spawn_io<Fut, R>(&self, f: Fut) -> Task<R>
119    where
120        Fut: Future<Output = R> + Send + 'static,
121        R: Send + 'static,
122    {
123        let (send, recv) = oneshot::channel();
124        // See `spawn` above: a dedicated target rather than `Span::current()` so
125        // subscribers can filter these spans in or out. I/O futures are polled
126        // frequently, so disabling the span (the default for an unconfigured
127        // target) avoids per-poll enter/exit cost.
128        let span = tracing::trace_span!(target: "vortex_io::spawn_io", "spawn_io");
129        let abort_handle = self.runtime().spawn_io(
130            async move {
131                // See `spawn`: catch a panic so it re-raises on the joining side.
132                let output = AssertUnwindSafe(f).catch_unwind().await;
133                // Task::detach allows the receiver to be dropped, so we ignore send errors.
134                drop(send.send(output));
135            }
136            .instrument(span)
137            .boxed(),
138        );
139        Task {
140            recv,
141            abort_handle: Some(abort_handle),
142        }
143    }
144
145    /// Spawn a CPU-bound task for execution on the runtime.
146    ///
147    /// Note that many runtimes will interleave this work on the same async runtime. See the
148    /// documentation for each runtime implementation for details.
149    ///
150    /// See [`Task`] for details on cancelling or detaching the spawned work, although note that
151    /// once started, CPU work cannot be cancelled.
152    pub fn spawn_cpu<F, R>(&self, f: F) -> Task<R>
153    where
154        // Unlike scheduling futures, the CPU task should have a static lifetime because it
155        // doesn't need to access to handle to spawn more work.
156        F: FnOnce() -> R + Send + 'static,
157        R: Send + 'static,
158    {
159        let (send, recv) = oneshot::channel();
160        let aborted = Arc::new(AtomicBool::new(false));
161        let task_aborted = Arc::clone(&aborted);
162        let span = tracing::Span::current();
163        let abort_handle = self.runtime().spawn_cpu(Box::new(move || {
164            let _guard = span.enter();
165            // Skip queued work only if the task was explicitly aborted (dropped without detach).
166            if !task_aborted.load(Ordering::Acquire) {
167                // Catch a panic so it re-raises on the joining side (see `Task::poll`).
168                let output = std::panic::catch_unwind(AssertUnwindSafe(f));
169                // Task::detach allows the receiver to be dropped, so we ignore send errors.
170                drop(send.send(output));
171            }
172        }));
173        Task {
174            recv,
175            abort_handle: Some(Box::new(SyncTaskAbortHandle {
176                aborted,
177                inner: abort_handle,
178            })),
179        }
180    }
181
182    /// Spawn a blocking I/O task for execution on the runtime.
183    pub fn spawn_blocking<F, R>(&self, f: F) -> Task<R>
184    where
185        F: FnOnce() -> R + Send + 'static,
186        R: Send + 'static,
187    {
188        let (send, recv) = oneshot::channel();
189        let aborted = Arc::new(AtomicBool::new(false));
190        let task_aborted = Arc::clone(&aborted);
191        let span = tracing::Span::current();
192        let abort_handle = self.runtime().spawn_blocking_io(Box::new(move || {
193            let _guard = span.enter();
194            // Skip queued work only if the task was explicitly aborted (dropped without detach).
195            if !task_aborted.load(Ordering::Acquire) {
196                // Catch a panic so it re-raises on the joining side (see `Task::poll`).
197                let output = std::panic::catch_unwind(AssertUnwindSafe(f));
198                // Task::detach allows the receiver to be dropped, so we ignore send errors.
199                drop(send.send(output));
200            }
201        }));
202        Task {
203            recv,
204            abort_handle: Some(Box::new(SyncTaskAbortHandle {
205                aborted,
206                inner: abort_handle,
207            })),
208        }
209    }
210}
211
212/// Abort handle for synchronous (`spawn_cpu` / `spawn_blocking`) tasks.
213///
214/// Sets an explicit pre-dispatch cancellation flag only on [`AbortHandle::abort`] (ordinary
215/// [`Task`] drop), leaving detached tasks free to run even after their result receiver is dropped.
216struct SyncTaskAbortHandle {
217    aborted: Arc<AtomicBool>,
218    inner: AbortHandleRef,
219}
220
221impl AbortHandle for SyncTaskAbortHandle {
222    fn abort(self: Box<Self>) {
223        self.aborted.store(true, Ordering::Release);
224        self.inner.abort();
225    }
226}
227
228/// The value carried from a spawned task back to its [`Task`] handle: either the task's output,
229/// or the panic payload if the task panicked, so it can be re-raised on the joining side.
230type TaskOutput<T> = Result<T, Box<dyn Any + Send>>;
231
232/// The terminal outcome of joining a spawned [`Task`] with [`Task::poll_join`], without
233/// re-raising a panic.
234pub enum JoinOutcome<T> {
235    /// The task ran to completion and produced this value.
236    Completed(T),
237    /// The task panicked. Carries the original panic payload, ready to be re-raised with
238    /// [`std::panic::resume_unwind`].
239    Panicked(Box<dyn Any + Send>),
240    /// The runtime dropped the task's future before it completed, for example because the task
241    /// was aborted or the runtime shut down. No value or panic payload is available.
242    Aborted,
243}
244
245/// A handle to a spawned Task.
246///
247/// If this handle is dropped, the task is cancelled where possible. In order to allow the task to
248/// continue running in the background, call [`Task::detach`].
249#[must_use = "When a Task is dropped without being awaited, it is cancelled"]
250pub struct Task<T> {
251    recv: oneshot::Receiver<TaskOutput<T>>,
252    abort_handle: Option<AbortHandleRef>,
253}
254
255impl<T> Task<T> {
256    /// Detach the task, allowing it to continue running in the background after being dropped.
257    /// This is only possible if the underlying runtime has a 'static lifetime.
258    pub fn detach(mut self) {
259        drop(self.abort_handle.take());
260    }
261
262    /// Poll the task to completion, reporting the terminal state as a [`JoinOutcome`] instead of
263    /// re-raising a panic or panicking on abort.
264    ///
265    /// This lets a caller distinguish a task panic (which it may re-raise via
266    /// [`std::panic::resume_unwind`]) from the runtime dropping the task before it completed — for
267    /// example a runtime shutting down while work is in flight — which is benign. The [`Future`]
268    /// implementation, by contrast, re-raises a panic and itself panics on abort.
269    pub fn poll_join(&mut self, cx: &mut Context<'_>) -> Poll<JoinOutcome<T>> {
270        match ready!(self.recv.poll_unpin(cx)) {
271            Ok(Ok(output)) => Poll::Ready(JoinOutcome::Completed(output)),
272            Ok(Err(panic)) => Poll::Ready(JoinOutcome::Panicked(panic)),
273            // The result channel closed without delivering a value: the runtime dropped the task's
274            // future before it completed (for example the task was aborted or the runtime shut
275            // down).
276            Err(_recv_err) => Poll::Ready(JoinOutcome::Aborted),
277        }
278    }
279}
280
281impl<T> Future for Task<T> {
282    type Output = T;
283
284    #[expect(clippy::panic)]
285    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
286        match ready!(self.get_mut().poll_join(cx)) {
287            JoinOutcome::Completed(output) => Poll::Ready(output),
288            // The task panicked: re-raise the original panic on the joining side, preserving its
289            // message and payload rather than collapsing it into a generic error.
290            JoinOutcome::Panicked(panic) => std::panic::resume_unwind(panic),
291            JoinOutcome::Aborted => {
292                // The runtime dropped the task's future before it completed. If the caller aborted
293                // this task by dropping it, they wouldn't be able to poll it anymore, so we
294                // consider a closed channel a runtime programming error and panic.
295
296                // NOTE(ngates): we don't use vortex_panic to avoid printing a useless backtrace.
297                panic!("Runtime dropped task without completing it")
298            }
299        }
300    }
301}
302
303impl<T> Drop for Task<T> {
304    fn drop(&mut self) {
305        // Optimistically abort the task if it's still running.
306        if let Some(handle) = self.abort_handle.take() {
307            handle.abort();
308        }
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use std::sync::atomic::AtomicUsize;
315    use std::sync::atomic::Ordering;
316
317    use futures::future::BoxFuture;
318    use futures::task::noop_waker;
319    use parking_lot::Mutex;
320
321    use super::*;
322    use crate::runtime::AbortHandle;
323
324    struct GatedAbortHandle {
325        abort_calls: Arc<AtomicUsize>,
326    }
327
328    impl AbortHandle for GatedAbortHandle {
329        fn abort(self: Box<Self>) {
330            self.abort_calls.fetch_add(1, Ordering::SeqCst);
331        }
332    }
333
334    struct GatedExecutor {
335        queue: Mutex<Vec<Box<dyn FnOnce() + Send + 'static>>>,
336        abort_calls: Arc<AtomicUsize>,
337    }
338
339    impl GatedExecutor {
340        fn new() -> Arc<Self> {
341            Arc::new(Self {
342                queue: Mutex::new(Vec::new()),
343                abort_calls: Arc::new(AtomicUsize::new(0)),
344            })
345        }
346
347        fn enqueue(&self, work: Box<dyn FnOnce() + Send + 'static>) -> AbortHandleRef {
348            self.queue.lock().push(work);
349            Box::new(GatedAbortHandle {
350                abort_calls: Arc::clone(&self.abort_calls),
351            })
352        }
353
354        fn drain(&self) {
355            for job in std::mem::take(&mut *self.queue.lock()) {
356                job();
357            }
358        }
359    }
360
361    impl Executor for GatedExecutor {
362        fn spawn(&self, _fut: BoxFuture<'static, ()>) -> AbortHandleRef {
363            panic!("async spawn not used in gated sync tests")
364        }
365
366        fn spawn_cpu(&self, cpu: Box<dyn FnOnce() + Send + 'static>) -> AbortHandleRef {
367            self.enqueue(cpu)
368        }
369
370        fn spawn_blocking_io(&self, task: Box<dyn FnOnce() + Send + 'static>) -> AbortHandleRef {
371            self.enqueue(task)
372        }
373    }
374
375    #[test]
376    fn detached_cpu_and_blocking_tasks_run_queued_work() {
377        let executor = GatedExecutor::new();
378        let dyn_exec: Arc<dyn Executor> = Arc::clone(&executor) as Arc<dyn Executor>;
379        let handle = Handle::new(Arc::downgrade(&dyn_exec));
380
381        let cpu_runs = Arc::new(AtomicUsize::new(0));
382        let blocking_runs = Arc::new(AtomicUsize::new(0));
383
384        let cpu_runs_clone = Arc::clone(&cpu_runs);
385        let cpu_task = handle.spawn_cpu(move || {
386            cpu_runs_clone.fetch_add(1, Ordering::SeqCst);
387            1usize
388        });
389
390        let blocking_runs_clone = Arc::clone(&blocking_runs);
391        let blocking_task = handle.spawn_blocking(move || {
392            blocking_runs_clone.fetch_add(1, Ordering::SeqCst);
393            2usize
394        });
395
396        cpu_task.detach();
397        blocking_task.detach();
398
399        executor.drain();
400
401        assert_eq!(cpu_runs.load(Ordering::SeqCst), 1);
402        assert_eq!(blocking_runs.load(Ordering::SeqCst), 1);
403        assert_eq!(executor.abort_calls.load(Ordering::SeqCst), 0);
404    }
405
406    #[test]
407    fn dropped_cpu_and_blocking_tasks_skip_queued_work() {
408        let executor = GatedExecutor::new();
409        let dyn_exec: Arc<dyn Executor> = Arc::clone(&executor) as Arc<dyn Executor>;
410        let handle = Handle::new(Arc::downgrade(&dyn_exec));
411
412        let cpu_runs = Arc::new(AtomicUsize::new(0));
413        let blocking_runs = Arc::new(AtomicUsize::new(0));
414
415        let cpu_runs_clone = Arc::clone(&cpu_runs);
416        let cpu_task = handle.spawn_cpu(move || {
417            cpu_runs_clone.fetch_add(1, Ordering::SeqCst);
418        });
419
420        let blocking_runs_clone = Arc::clone(&blocking_runs);
421        let blocking_task = handle.spawn_blocking(move || {
422            blocking_runs_clone.fetch_add(1, Ordering::SeqCst);
423        });
424
425        drop(cpu_task);
426        drop(blocking_task);
427
428        executor.drain();
429
430        assert_eq!(cpu_runs.load(Ordering::SeqCst), 0);
431        assert_eq!(blocking_runs.load(Ordering::SeqCst), 0);
432        assert_eq!(executor.abort_calls.load(Ordering::SeqCst), 2);
433    }
434
435    // A task whose result channel closed without a value — the runtime dropped its future before
436    // it sent a result — must report `Aborted`, so callers can treat a benign teardown as a
437    // recoverable stop rather than a propagated panic.
438    #[test]
439    fn poll_join_reports_aborted_when_channel_closed_without_value() {
440        let (send, recv) = oneshot::channel::<TaskOutput<()>>();
441        // Simulate the runtime dropping the task's future before it sent a result.
442        drop(send);
443
444        let mut task = Task::<()> {
445            recv,
446            abort_handle: None,
447        };
448
449        let waker = noop_waker();
450        let mut cx = Context::from_waker(&waker);
451        assert!(matches!(
452            task.poll_join(&mut cx),
453            Poll::Ready(JoinOutcome::Aborted)
454        ));
455    }
456
457    // A completed task reports its value through `poll_join` rather than re-raising or panicking.
458    #[test]
459    fn poll_join_reports_completed_value() {
460        let (send, recv) = oneshot::channel::<TaskOutput<u32>>();
461        // Ignore the send result: the payload type is not `Debug`, and the receiver is alive.
462        drop(send.send(Ok(7)));
463
464        let mut task = Task::<u32> {
465            recv,
466            abort_handle: None,
467        };
468
469        let waker = noop_waker();
470        let mut cx = Context::from_waker(&waker);
471        assert!(matches!(
472            task.poll_join(&mut cx),
473            Poll::Ready(JoinOutcome::Completed(7))
474        ));
475    }
476}