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 crate::rt::async_support::BoxFuture;
7use futures::stream::{FuturesUnordered, StreamExt};
8use std::boxed::Box;
9use std::future::Future;
10use std::task::{Context, Poll};
11use std::vec::Vec;
12
13/// Any newly-deferred work queued by calls to the `spawn` function while
14/// polling the current task.
15static mut SPAWNED: Vec<BoxFuture> = Vec::new();
16
17#[derive(Default)]
18pub struct Tasks<'a> {
19    tasks: FuturesUnordered<BoxFuture<'a>>,
20}
21
22impl<'a> Tasks<'a> {
23    pub fn new(root: BoxFuture<'a>) -> Tasks<'a> {
24        Tasks {
25            tasks: [root].into_iter().collect(),
26        }
27    }
28
29    pub fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<()>> {
30        unsafe {
31            let ret = self.tasks.poll_next_unpin(cx);
32            if !SPAWNED.is_empty() {
33                self.tasks.extend(SPAWNED.drain(..));
34            }
35            ret
36        }
37    }
38
39    pub fn is_empty(&self) -> bool {
40        self.tasks.is_empty()
41    }
42}
43
44/// Spawn the provided `future` to get executed concurrently with the
45/// currently-running async computation.
46///
47/// This API is somewhat similar to `tokio::task::spawn` for example but has a
48/// number of limitations to be aware of. If possible it's recommended to avoid
49/// this, but it can be convenient if these limitations do not apply to you:
50///
51/// * Spawned tasks do not work when the version of the `wit-bindgen` crate
52///   managing the export bindings is different from the version of this crate.
53///   To work correctly the `spawn` function and export executor must be at
54///   exactly the same version. Given the major-version-breaking nature of
55///   `wit-bindgen` this is not always easy to rely on. This is tracked in
56///   [#1305].
57///
58/// * Spawned tasks do not outlive the scope of the async computation they are
59///   spawned within. For example with an async export function spawned tasks
60///   will be polled within the context of that component-model async task. For
61///   computations executing within a [`block_on`] call, however, the spawned
62///   tasks will be executed within that scope. This notably means that for
63///   [`block_on`] spawned tasks will prevent the [`block_on`] function from
64///   returning, even if a value is available to return.
65///
66/// * There is no handle returned to the spawned task meaning that it cannot be
67///   cancelled or monitored.
68///
69/// * The task spawned here is executed *concurrently*, not in *parallel*. This
70///   means that while one future is being polled no other future can be polled
71///   at the same time. This is similar to a single-thread executor in Tokio.
72///
73/// With these restrictions in mind this can be used to express
74/// execution-after-returning in the component model. For example once an
75/// exported async function has produced a value this can be used to continue to
76/// execute some more code before the component model async task exits.
77///
78/// [`block_on`]: crate::block_on
79/// [#1305]: https://github.com/bytecodealliance/wit-bindgen/issues/1305
80pub fn spawn(future: impl Future<Output = ()> + 'static) {
81    unsafe { SPAWNED.push(Box::pin(future)) }
82}