wit_bindgen/rt/async_support/spawn.rs
1// TODO: Switch to interior mutability (e.g. use Mutexes or thread-local
2// RefCells) and remove this, since even in single-threaded mode `static mut`
3// references can be a hazard due to recursive access.
4#![allow(static_mut_refs)]
5
6use super::cabi;
7use crate::rt::async_support::BoxFuture;
8use alloc::boxed::Box;
9use alloc::vec::Vec;
10use core::future::Future;
11use core::pin::Pin;
12use core::ptr;
13use core::task::{Context, Poll};
14use futures::channel::oneshot;
15use futures::future::{AbortHandle, Abortable, Aborted};
16use futures::stream::{FuturesUnordered, StreamExt};
17
18/// Any newly-deferred work queued by calls to the `spawn` function while
19/// polling the current task.
20static mut SPAWNED: Vec<BoxFuture> = Vec::new();
21
22#[derive(Default)]
23pub struct Tasks<'a> {
24 tasks: FuturesUnordered<BoxFuture<'a>>,
25 root: Option<AbortHandle>,
26}
27
28impl<'a> Tasks<'a> {
29 pub fn new(root: impl Future<Output = ()> + 'a) -> Tasks<'a> {
30 let (abort, registration) = AbortHandle::new_pair();
31 let root: BoxFuture<'a> = Box::pin(async move {
32 let _ = Abortable::new(root, registration).await;
33 });
34 Tasks {
35 tasks: [root].into_iter().collect(),
36 root: Some(abort),
37 }
38 }
39
40 pub fn cancel_root(&mut self) {
41 if let Some(root) = self.root.take() {
42 root.abort();
43 }
44 }
45
46 pub fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<()> {
47 loop {
48 // Perform some work by seeing what's next in this
49 // `FuturesUnordered`. Afterwards check the set of spawned tasks
50 // and, if any, add them to our set of tasks being done.
51 let poll = self.tasks.poll_next_unpin(cx);
52 let spawned = unsafe {
53 if SPAWNED.is_empty() {
54 false
55 } else {
56 self.tasks.extend(SPAWNED.drain(..));
57 true
58 }
59 };
60 match poll {
61 // If no tasks were ready, and if we didn't spawn any work,
62 // then there's nothing left to do so return pending.
63 //
64 // If no tasks were ready, and if we spawned some work, then
65 // turn the loop again to register interest in the work and
66 // ensure that it's not forgotten about.
67 Poll::Pending => {
68 if !spawned {
69 return Poll::Pending;
70 }
71 }
72
73 // If our set of tasks is empty it shouldn't be possible to have
74 // spawned anything, and return saying that we're done.
75 Poll::Ready(None) => {
76 assert!(!spawned);
77 return Poll::Ready(());
78 }
79
80 // If a task finished, then turn the loop again to see if there
81 // are any other completed tasks. This also serves double-duty
82 // to ensure that we look at everything in our set of tasks
83 // before concluding that we're finished.
84 Poll::Ready(Some(())) => {}
85 }
86 }
87 }
88
89 pub fn is_empty(&self) -> bool {
90 self.tasks.is_empty()
91 }
92}
93
94pub(super) fn push(task: BoxFuture<'static>) {
95 unsafe {
96 SPAWNED.push(task);
97 }
98}
99
100/// Spawn the provided `future` to get executed concurrently with the
101/// currently-running async computation.
102///
103/// This API is somewhat similar to `tokio::task::spawn` for example but has a
104/// number of limitations to be aware of. If possible it's recommended to avoid
105/// this, but it can be convenient if these limitations do not apply to you:
106///
107/// * Spawned tasks do not work when the version of the `wit-bindgen` crate
108/// managing the export bindings is different from the version of this crate.
109/// To work correctly the `spawn` function and export executor must be at
110/// exactly the same version. Given the major-version-breaking nature of
111/// `wit-bindgen` this is not always easy to rely on. This is tracked in
112/// [#1305].
113///
114/// * Spawned tasks do not outlive the scope of the async computation they are
115/// spawned within. For example with an async export function spawned tasks
116/// will be polled within the context of that component-model async task. For
117/// computations executing within a [`block_on`] call, however, the spawned
118/// tasks will be executed within that scope. This notably means that for
119/// [`block_on`] spawned tasks will prevent the [`block_on`] function from
120/// returning, even if a value is available to return. If `spawn_local` is
121/// called within a component-model async task which is then terminated (e.g.
122/// by the host) before the future resolves, awating the `JoinHandle` will return
123/// `None`.
124///
125/// * The task spawned here is executed *concurrently*, not in *parallel*. This
126/// means that while one future is being polled no other future can be polled
127/// at the same time. This is similar to a single-thread executor in Tokio.
128///
129/// With these restrictions in mind this can be used to express
130/// execution-after-returning in the component model. For example once an
131/// exported async function has produced a value this can be used to continue to
132/// execute some more code before the component model async task exits.
133///
134/// # Cancellation
135///
136/// Dropping the resulting [`JoinHandle`] will detach the task and allow it to
137/// continue running in the background. It can also be explicitly cancelled with
138/// [`JoinHandle::cancel`].
139///
140/// [`block_on`]: crate::block_on
141/// [#1305]: https://github.com/bytecodealliance/wit-bindgen/issues/1305
142pub fn spawn_local<T: 'static>(future: impl Future<Output = T> + 'static) -> JoinHandle<T> {
143 let (sender, receiver) = oneshot::channel();
144 let (abort, registration) = AbortHandle::new_pair();
145 let future = Box::new(async move {
146 let _ = sender.send(Abortable::new(future, registration).await);
147 });
148
149 // This isn't quite as easy as just pushing onto the `SPAWNED` static within
150 // this file because the request for spawning a task can come from any
151 // version of the `wit-bindgen` crate but only the version that's running
152 // the exported task is actually capable of handling the request to spawn
153 // something. This means that our `SPAWNED` static may not actually be read
154 // by the export running because it might be a different version of
155 // `wit-bindgen`. To arbitrate this the `cabi` module has a hook, which is
156 // configured by exports, to receive Rust futures to spawn.
157 //
158 // This itself is a bit thorny to handle a few cases:
159 //
160 // * The hook for spawn was added after `cabi` was created, so a revision
161 // was necessary with a bumped number. Historical versions don't have a
162 // spawn hook at all.
163 //
164 // * The `async-spawn` feature is a conditional feature of this crate that
165 // may not be enabled at compile time. If it's not enabled then the
166 // `rust_spawn` hook won't be specified.
167 //
168 // For now this just panics if something can't be spawned. In both cases it
169 // means that there's some other version of `wit-bindgen` running the export
170 // that this request to spawn can't be satisfied with, and there's really
171 // not much that can be done.
172 //
173 // TODO: this is a pretty awful error to run into as a developer and a
174 // pretty awful experience. There's nothing that can be done to solve this
175 // other than "update wit-bindgen somewhere else" which is not always easy
176 // to do. Not that I've got a better idea of what to do here.
177 let ok = unsafe {
178 let task = cabi::wasip3_task_set(ptr::null_mut());
179 assert!(!task.is_null());
180 assert!((*task).version >= cabi::WASIP3_TASK_V1);
181
182 let ok = if (*task).version >= cabi::WASIP3_TASK_V3 {
183 let task = task.cast::<cabi::wasip3_task_v3>();
184 match (*task).vtable.rust_spawn {
185 Some(f) => {
186 f((*task).v1.ptr, future);
187 true
188 }
189 None => false,
190 }
191 } else {
192 false
193 };
194 cabi::wasip3_task_set(task);
195 ok
196 };
197
198 if !ok {
199 panic!(
200 "failed to `spawn_local` because there's a different version of \
201 the `wit-bindgen` crate running the export than this \
202 `wit-bindgen` crate and that one is either too old \
203 or has the `async-spawn` feature disabled"
204 );
205 }
206 JoinHandle { receiver, abort }
207}
208
209/// A handle to a spawned task which can be awaited for its result.
210///
211/// Dropping the handle allows the task to continue running in the background.
212/// Awaiting the handle returns `None` if the task was cancelled or otherwise
213/// terminated without producing a result.
214pub struct JoinHandle<T> {
215 receiver: oneshot::Receiver<Result<T, Aborted>>,
216 abort: AbortHandle,
217}
218
219impl<T> JoinHandle<T> {
220 /// Cancels the spawned task. It is possible the task resolved and produced
221 /// a result before cancelation completed and the [`JoinHandle`] can still
222 /// be awaited to check for that case.
223 pub fn cancel(&mut self) {
224 self.abort.abort();
225 }
226}
227
228impl<T> Future for JoinHandle<T> {
229 type Output = Option<T>;
230
231 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<T>> {
232 match Pin::new(&mut self.receiver).poll(cx) {
233 Poll::Ready(Ok(Ok(result))) => Poll::Ready(Some(result)),
234 Poll::Ready(Ok(Err(_)) | Err(_)) => Poll::Ready(None),
235 Poll::Pending => Poll::Pending,
236 }
237 }
238}