libasync_dispatcher/
task.rs1use 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#[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 if let Err(err) = state.queue() {
62 drop(state.future.lock().take());
64 state.result_sender.try_send(Err(err)).unwrap();
67 }
68
69 future
70 }
71}
72
73impl<T> Task<T> {
74 pub fn detach(self) {
78 drop(self.detach_on_drop());
79 }
80
81 pub fn detach_on_drop(mut self) -> JoinHandle<T> {
87 self.detached = true;
88 JoinHandle(self)
89 }
90
91 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#[derive(Debug)]
129pub struct JoinHandle<T>(Task<T>);
130
131impl<T> JoinHandle<T> {
132 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 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 fn send_result(&self, res: Result<T, Status>) {
176 self.result_sender.try_send(res).ok();
180 self.future_state.waker.wake();
181 }
182
183 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 status != Status::from_raw(ZX_OK) {
195 drop(future_slot.take());
196 arc_self.send_result(Err(status));
197 return;
198 }
199
200 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}