Skip to main content

libasync_dispatcher/
task.rs

1// Copyright 2025 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Safe bindings for the C libasync async dispatcher library
6
7use zx_types::ZX_OK;
8
9use core::task::Context;
10use fuchsia_sync::Mutex;
11use std::pin::Pin;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::{Arc, mpsc};
14use std::task::{Poll, Wake, Waker};
15
16use zx_status::Status;
17
18use futures::future::{BoxFuture, FutureExt};
19use futures::task::AtomicWaker;
20
21use crate::{AsAsyncDispatcherRef, OnDispatcher};
22
23/// The future returned by [`OnDispatcher::compute`] or [`OnDispatcher::try_compute`]. If this is
24/// dropped, the task will be cancelled.
25#[must_use]
26#[derive(Debug)]
27pub struct Task<T> {
28    state: Arc<TaskFutureState>,
29    result_receiver: mpsc::Receiver<Result<T, Status>>,
30    detached: bool,
31}
32
33impl<T: Send + 'static> Task<T> {
34    fn new<D: OnDispatcher + 'static>(
35        future: impl Future<Output = T> + Send + 'static,
36        dispatcher: D,
37    ) -> (Self, Arc<TaskWakerState<T, D>>) {
38        let future_state = Arc::new(TaskFutureState {
39            waker: AtomicWaker::new(),
40            aborted: AtomicBool::new(false),
41        });
42        let (result_sender, result_receiver) = mpsc::sync_channel(1);
43        let state = Arc::new(TaskWakerState {
44            result_sender,
45            future_state: future_state.clone(),
46            future: Mutex::new(Some(future.boxed())),
47            dispatcher,
48        });
49        let future = Task { state: future_state, result_receiver, detached: false };
50        (future, state)
51    }
52
53    pub(crate) fn start<D: OnDispatcher + 'static>(
54        future: impl Future<Output = T> + Send + 'static,
55        dispatcher: D,
56    ) -> Self {
57        let (future, state) = Self::new(future, dispatcher);
58
59        // try to queue the task and if it fails short circuit the delivery of failure to the
60        // caller.
61        if let Err(err) = state.queue() {
62            // drop the future we were given
63            drop(state.future.lock().take());
64            // send the error to the result receiver. This should never fail, since
65            // we just created both ends and the task queuing failed.
66            state.result_sender.try_send(Err(err)).unwrap();
67        }
68
69        future
70    }
71}
72
73impl<T> Task<T> {
74    /// Detaches this future from the task so that it will continue executing without waiting
75    /// on the future. If this is not called, and the future is dropped, the task will be aborted
76    /// the next time it is awoken.
77    pub fn detach(self) {
78        drop(self.detach_on_drop());
79    }
80
81    /// Detaches this future from the task so that it will continue executing without waiting
82    /// on the future. If this is not called, and the future is dropped, the task will be aborted
83    /// the next time it is awoken.
84    ///
85    /// Returns a future that can be awaited on or dropped without affecting the task.
86    pub fn detach_on_drop(mut self) -> JoinHandle<T> {
87        self.detached = true;
88        JoinHandle(self)
89    }
90
91    /// Aborts the task and returns a future that can be used to wait for the task to either
92    /// complete or cancel. If the task was canceled the result of the future will be
93    /// [`Status::CANCELED`].
94    pub fn abort(&self) {
95        self.state.aborted.store(true, Ordering::Relaxed);
96    }
97}
98
99impl<T> Drop for Task<T> {
100    fn drop(&mut self) {
101        if !self.detached {
102            self.state.aborted.store(true, Ordering::Relaxed);
103        }
104    }
105}
106
107#[derive(Debug)]
108struct TaskFutureState {
109    waker: AtomicWaker,
110    aborted: AtomicBool,
111}
112
113impl<T> Future for Task<T> {
114    type Output = Result<T, Status>;
115
116    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
117        use std::sync::mpsc::TryRecvError;
118        self.state.waker.register(cx.waker());
119        match self.result_receiver.try_recv() {
120            Ok(res) => Poll::Ready(res),
121            Err(TryRecvError::Disconnected) => Poll::Ready(Err(Status::CANCELED)),
122            Err(TryRecvError::Empty) => Poll::Pending,
123        }
124    }
125}
126
127/// A handle for a task that will detach on drop. Returned by [`OnDispatcher::spawn`].
128#[derive(Debug)]
129pub struct JoinHandle<T>(Task<T>);
130
131impl<T> JoinHandle<T> {
132    /// Aborts the task and returns a future that can be used to wait for the task to either
133    /// complete or cancel. If the task was canceled the result of the future will be
134    /// [`Status::CANCELED`].
135    pub fn abort(&self) {
136        self.0.abort()
137    }
138}
139
140impl<T> Future for JoinHandle<T> {
141    type Output = Result<T, Status>;
142
143    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
144        self.0.poll_unpin(cx)
145    }
146}
147
148struct TaskWakerState<T, D> {
149    result_sender: mpsc::SyncSender<Result<T, Status>>,
150    future_state: Arc<TaskFutureState>,
151    future: Mutex<Option<BoxFuture<'static, T>>>,
152    dispatcher: D,
153}
154
155impl<T: Send + 'static, D: OnDispatcher + 'static> Wake for TaskWakerState<T, D> {
156    fn wake(self: Arc<Self>) {
157        self.wake_by_ref();
158    }
159    fn wake_by_ref(self: &Arc<Self>) {
160        match self.queue() {
161            Err(e) if e == Status::BAD_STATE => {
162                // the dispatcher is shutting down so drop the future, if there
163                // is one, to cancel it.
164                let future_slot = self.future.lock().take();
165                drop(future_slot);
166                self.send_result(Err(e));
167            }
168            res => res.expect("Unexpected error waking dispatcher task"),
169        }
170    }
171}
172
173impl<T: Send + 'static, D: OnDispatcher + 'static> TaskWakerState<T, D> {
174    /// Sends the result to the future end of this task, if it still exists.
175    fn send_result(&self, res: Result<T, Status>) {
176        // send the result and wake the waker if any has been registered.
177        // We ignore the result here because if the other end has dropped it's
178        // fine for the result to go nowhere.
179        self.result_sender.try_send(res).ok();
180        self.future_state.waker.wake();
181    }
182
183    /// Posts a task to progress the currently stored future. The task will
184    /// consume the future if the future is ready after the next poll.
185    /// Otherwise, the future is kept to be polled again after being woken.
186    pub(crate) fn queue(self: &Arc<Self>) -> Result<(), Status> {
187        let arc_self = self.clone();
188        self.dispatcher.on_maybe_dispatcher(move |dispatcher| {
189            dispatcher
190                .post_task_sync(move |status| {
191                    let mut future_slot = arc_self.future.lock();
192                    // if the executor is shutting down, drop the future we're waiting on and pass
193                    // on the error.
194                    if status != Status::from_raw(ZX_OK) {
195                        drop(future_slot.take());
196                        arc_self.send_result(Err(status));
197                        return;
198                    }
199
200                    // if the future has been dropped without being detached, drop the future and
201                    // send an Err(Status::CANCELED) if the caller is still listening.
202                    if arc_self.future_state.aborted.load(Ordering::Relaxed) {
203                        drop(future_slot.take());
204                        arc_self.send_result(Err(Status::CANCELED));
205                        return;
206                    }
207
208                    let Some(mut future) = future_slot.take() else {
209                        return;
210                    };
211                    let waker = Waker::from(arc_self.clone());
212                    let context = &mut Context::from_waker(&waker);
213                    match future.as_mut().poll(context) {
214                        Poll::Pending => *future_slot = Some(future),
215                        Poll::Ready(res) => {
216                            arc_self.send_result(Ok(res));
217                        }
218                    }
219                })
220                .map(|_| ())
221        })
222    }
223}