1use 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#[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 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 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 let span = tracing::trace_span!(target: "vortex_io::spawn", "spawn");
87 let abort_handle = self.runtime().spawn(
88 async move {
89 let output = AssertUnwindSafe(f).catch_unwind().await;
92 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 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 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 let span = tracing::trace_span!(target: "vortex_io::spawn_io", "spawn_io");
129 let abort_handle = self.runtime().spawn_io(
130 async move {
131 let output = AssertUnwindSafe(f).catch_unwind().await;
133 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 pub fn spawn_cpu<F, R>(&self, f: F) -> Task<R>
153 where
154 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 if !task_aborted.load(Ordering::Acquire) {
167 let output = std::panic::catch_unwind(AssertUnwindSafe(f));
169 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 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 if !task_aborted.load(Ordering::Acquire) {
196 let output = std::panic::catch_unwind(AssertUnwindSafe(f));
198 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
212struct 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
228type TaskOutput<T> = Result<T, Box<dyn Any + Send>>;
231
232pub enum JoinOutcome<T> {
235 Completed(T),
237 Panicked(Box<dyn Any + Send>),
240 Aborted,
243}
244
245#[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 pub fn detach(mut self) {
259 drop(self.abort_handle.take());
260 }
261
262 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 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 JoinOutcome::Panicked(panic) => std::panic::resume_unwind(panic),
291 JoinOutcome::Aborted => {
292 panic!("Runtime dropped task without completing it")
298 }
299 }
300 }
301}
302
303impl<T> Drop for Task<T> {
304 fn drop(&mut self) {
305 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 #[test]
439 fn poll_join_reports_aborted_when_channel_closed_without_value() {
440 let (send, recv) = oneshot::channel::<TaskOutput<()>>();
441 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 #[test]
459 fn poll_join_reports_completed_value() {
460 let (send, recv) = oneshot::channel::<TaskOutput<u32>>();
461 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}