Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/guest-rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -913,7 +913,7 @@ pub use rt::async_support::{
FutureWriteError, FutureWriter, RawFutureRead, RawFutureReader, RawFutureWrite,
RawFutureWriter, RawStreamRead, RawStreamReader, RawStreamWrite, RawStreamWriter, StreamOps,
StreamRead, StreamReader, StreamResult, StreamWrite, StreamWriter, backpressure_dec,
backpressure_inc, block_on, yield_async, yield_blocking,
backpressure_inc, block_on, block_on_detached, yield_async, yield_blocking,
};
#[cfg(feature = "async-spawn")]
pub use rt::async_support::{JoinHandle, spawn_local};
47 changes: 37 additions & 10 deletions crates/guest-rust/src/rt/async_support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,9 @@ struct SharedTaskState {
// Note the `TryLock` is the same as `waitables` above, it's serving the
// purpose of interior mutability.
waitable_set: TryLock<Option<WaitableSet>>,

/// Tasks spawned onto this task through the `rust_spawn` hook.
spawned: spawn::Spawned,
}

/// An entry of `SharedTaskState::waitables` which is added through the C ABI.
Expand All @@ -159,8 +162,11 @@ struct CabiWaitable {
unsafe impl Send for CabiWaitable {}

impl<'a> TaskState<'a> {
fn new(future: impl Future<Output = ()> + 'a) -> TaskState<'a> {
let shared = Arc::new(SharedTaskState::default());
fn new(future: impl Future<Output = ()> + 'a, spawned: spawn::Spawned) -> TaskState<'a> {
let shared = Arc::new(SharedTaskState {
spawned,
..Default::default()
});
TaskState {
waker: shared.clone().into(),
shared,
Expand Down Expand Up @@ -230,7 +236,7 @@ impl<'a> TaskState<'a> {
.store(SLEEP_STATE_POLLING, Ordering::Relaxed);

// Poll our future, seeing if it was able to make progress.
let poll = me.tasks.poll_next(&mut context);
let poll = me.tasks.poll_next(&mut context, &me.shared.spawned);

match poll {
// The task list is empty, but there might be remaining work
Expand Down Expand Up @@ -360,10 +366,12 @@ impl Drop for TaskState<'_> {
// execute arbitrary code. This arbitrary code might require the p3 APIs
// for managing waitables, notably around removing them. In this
// situation we ensure that the p3 task is set while futures are being
// destroyed.
// destroyed. The same applies to tasks that these destructors spawn
// onto this task.
if !self.tasks.is_empty() {
self.with_p3_task_set(|me| {
me.tasks = Default::default();
me.shared.spawned.take();
})
}
}
Expand Down Expand Up @@ -450,8 +458,9 @@ impl SharedTaskState {
}

#[cfg(feature = "async-spawn")]
unsafe fn cabi_rust_spawn(_ptr: *mut c_void, task: Box<dyn Future<Output = ()>>) {
spawn::push(Pin::from(task))
unsafe fn cabi_rust_spawn(ptr: *mut c_void, task: Box<dyn Future<Output = ()>>) {
let me = unsafe { Self::cabi_to_self(ptr) };
me.spawned.push(task)
}
}

Expand Down Expand Up @@ -609,7 +618,7 @@ mod task_state {
pub fn start_task(task: impl Future<Output = ()> + 'static) -> i32 {
// Allocate a new `TaskState` which will track all state necessary for
// our exported task.
let state = Box::into_raw(Box::new(TaskState::new(task)));
let state = Box::into_raw(Box::new(TaskState::new(task, Default::default())));

// Store our `TaskState` into our context-local-storage slot and then
// pretend we got EVENT_NONE to kick off everything.
Expand Down Expand Up @@ -662,10 +671,28 @@ pub unsafe fn callback(event0: u32, event1: u32, event2: u32) -> u32 {
/// This uses `waitable-set.wait` to poll for progress on any in-progress calls
/// to async-lowered imports as necessary.
pub fn block_on<T>(future: impl Future<Output = T>) -> T {
block_on_with(future, Default::default())
}

/// Like [`block_on`], but tasks spawned with `spawn_local` during the call are
/// spawned onto the task that encloses the call, and that task's executor runs
/// them after this returns.
///
/// `spawn_local` panics if no task encloses the call, or if that task's
/// executor can't spawn tasks. If `future` awaits the `JoinHandle` of a task
/// spawned during the call, this call never returns.
pub fn block_on_detached<T>(future: impl Future<Output = T>) -> T {
block_on_with(future, spawn::Spawned::detached())
}

fn block_on_with<T>(future: impl Future<Output = T>, spawned: spawn::Spawned) -> T {
let mut result = None;
let mut state = TaskState::new(async {
result = Some(future.await);
});
let mut state = TaskState::new(
async {
result = Some(future.await);
},
spawned,
);
let mut event = (EVENT_NONE, 0, 0);
loop {
match state.callback(event.0, event.1, event.2) {
Expand Down
123 changes: 90 additions & 33 deletions crates/guest-rust/src/rt/async_support/spawn.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,71 @@
// TODO: Switch to interior mutability (e.g. use Mutexes or thread-local
// RefCells) and remove this, since even in single-threaded mode `static mut`
// references can be a hazard due to recursive access.
#![allow(static_mut_refs)]

use super::cabi;
use super::try_lock::TryLock;
use crate::rt::async_support::BoxFuture;
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::future::Future;
use core::mem;
use core::pin::Pin;
use core::ptr;
use core::task::{Context, Poll};
use futures::channel::oneshot;
use futures::future::{AbortHandle, Abortable, Aborted};
use futures::stream::{FuturesUnordered, StreamExt};

/// Any newly-deferred work queued by calls to the `spawn` function while
/// polling the current task.
static mut SPAWNED: Vec<BoxFuture> = Vec::new();
/// Futures spawned with `spawn_local` while a task was the current task, which
/// that task's executor hasn't added to its `Tasks` yet.
#[derive(Default)]
pub struct Spawned {
queue: TryLock<Vec<BoxFuture<'static>>>,
/// The task that `push` spawns tasks onto instead of queueing them, if
/// set. Null if no task enclosed the `block_on_detached` call.
forward_to: Option<*mut cabi::wasip3_task>,
}

// Note: the queued futures are `!Send`, and `forward_to` is a raw pointer.
// Component model threads never run in parallel, and only switch inside
// built-ins such as `waitable-set.wait`, none of which are called while `queue`
// is locked. Futures are only pushed and polled, and `forward_to` is only
// used, on the thread that polls the task.
unsafe impl Send for Spawned {}
unsafe impl Sync for Spawned {}

impl Spawned {
/// Returns a `Spawned` for a `block_on_detached` call, which spawns tasks
/// onto the current task.
///
/// The current task must outlive the `block_on_detached` call.
pub fn detached() -> Spawned {
let current = unsafe {
let task = cabi::wasip3_task_set(ptr::null_mut());
cabi::wasip3_task_set(task);
task
};
Spawned {
queue: Default::default(),
forward_to: Some(current),
}
}

pub fn push(&self, task: Box<dyn Future<Output = ()>>) {
let Some(parent) = self.forward_to else {
self.queue.try_lock().unwrap().push(Pin::from(task));
return;
};
assert!(
!parent.is_null(),
"`spawn_local` was called in a `block_on_detached` call that no \
task encloses"
);
if !unsafe { spawn_onto(parent, task) } {
spawn_unsupported();
}
}

pub fn take(&self) -> Vec<BoxFuture<'static>> {
mem::take(&mut *self.queue.try_lock().unwrap())
}
}

#[derive(Default)]
pub struct Tasks<'a> {
Expand All @@ -43,17 +91,18 @@ impl<'a> Tasks<'a> {
}
}

pub fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<()> {
pub fn poll_next(&mut self, cx: &mut Context<'_>, spawned: &Spawned) -> Poll<()> {
loop {
// Perform some work by seeing what's next in this
// `FuturesUnordered`. Afterwards check the set of spawned tasks
// and, if any, add them to our set of tasks being done.
let poll = self.tasks.poll_next_unpin(cx);
let spawned = unsafe {
if SPAWNED.is_empty() {
let spawned = {
let spawned = spawned.take();
if spawned.is_empty() {
false
} else {
self.tasks.extend(SPAWNED.drain(..));
self.tasks.extend(spawned);
true
}
};
Expand Down Expand Up @@ -91,12 +140,6 @@ impl<'a> Tasks<'a> {
}
}

pub(super) fn push(task: BoxFuture<'static>) {
unsafe {
SPAWNED.push(task);
}
}

/// Spawn the provided `future` to get executed concurrently with the
/// currently-running async computation.
///
Expand All @@ -117,7 +160,8 @@ pub(super) fn push(task: BoxFuture<'static>) {
/// computations executing within a [`block_on`] call, however, the spawned
/// tasks will be executed within that scope. This notably means that for
/// [`block_on`] spawned tasks will prevent the [`block_on`] function from
/// returning, even if a value is available to return. If `spawn_local` is
/// returning, even if a value is available to return. [`block_on_detached`]
/// spawns them onto the enclosing task instead. If `spawn_local` is
/// called within a component-model async task which is then terminated (e.g.
/// by the host) before the future resolves, awating the `JoinHandle` will return
/// `None`.
Expand All @@ -138,6 +182,7 @@ pub(super) fn push(task: BoxFuture<'static>) {
/// [`JoinHandle::cancel`].
///
/// [`block_on`]: crate::block_on
/// [`block_on_detached`]: crate::block_on_detached
/// [#1305]: https://github.com/bytecodealliance/wit-bindgen/issues/1305
pub fn spawn_local<T: 'static>(future: impl Future<Output = T> + 'static) -> JoinHandle<T> {
let (sender, receiver) = oneshot::channel();
Expand Down Expand Up @@ -177,9 +222,24 @@ pub fn spawn_local<T: 'static>(future: impl Future<Output = T> + 'static) -> Joi
let ok = unsafe {
let task = cabi::wasip3_task_set(ptr::null_mut());
assert!(!task.is_null());
let ok = spawn_onto(task, future);
cabi::wasip3_task_set(task);
ok
};

if !ok {
spawn_unsupported();
}
JoinHandle { receiver, abort }
}

/// Spawns `future` onto `task` through its `rust_spawn` hook. Returns `false`
/// if `task` has no `rust_spawn` hook.
unsafe fn spawn_onto(task: *mut cabi::wasip3_task, future: Box<dyn Future<Output = ()>>) -> bool {
unsafe {
assert!((*task).version >= cabi::WASIP3_TASK_V1);

let ok = if (*task).version >= cabi::WASIP3_TASK_V3 {
if (*task).version >= cabi::WASIP3_TASK_V3 {
let task = task.cast::<cabi::wasip3_task_v3>();
match (*task).vtable.rust_spawn {
Some(f) => {
Expand All @@ -190,20 +250,17 @@ pub fn spawn_local<T: 'static>(future: impl Future<Output = T> + 'static) -> Joi
}
} else {
false
};
cabi::wasip3_task_set(task);
ok
};

if !ok {
panic!(
"failed to `spawn_local` because there's a different version of \
the `wit-bindgen` crate running the export than this \
`wit-bindgen` crate and that one is either too old \
or has the `async-spawn` feature disabled"
);
}
}
JoinHandle { receiver, abort }
}

fn spawn_unsupported() -> ! {
panic!(
"failed to `spawn_local` because there's a different version of \
the `wit-bindgen` crate running the export than this \
`wit-bindgen` crate and that one is either too old \
or has the `async-spawn` feature disabled"
);
}

/// A handle to a spawned task which can be awaited for its result.
Expand Down
13 changes: 12 additions & 1 deletion crates/guest-rust/src/rt/async_support/spawn_disabled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,17 @@ use alloc::boxed::Box;
use core::future::Future;
use core::task::{Context, Poll};

#[derive(Default)]
pub struct Spawned;

impl Spawned {
pub fn detached() -> Spawned {
Spawned
}

pub fn take(&self) {}
}

#[derive(Default)]
pub struct Tasks<'a> {
future: Option<BoxFuture<'a>>,
Expand All @@ -19,7 +30,7 @@ impl<'a> Tasks<'a> {
self.future = None;
}

pub fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<()> {
pub fn poll_next(&mut self, cx: &mut Context<'_>, _spawned: &Spawned) -> Poll<()> {
if let Some(future) = self.future.as_mut() {
if future.as_mut().poll(cx).is_ready() {
self.future = None;
Expand Down
4 changes: 2 additions & 2 deletions crates/guest-rust/src/rt/async_support/try_lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use core::sync::atomic::{
/// Small helper type to wrap `T` in a lock-like primitive which only supports
/// the `try_lock` operation.
///
/// This is useful on wasm right now where threads aren't actually a thing so
/// there shouldn't ever be contention, but the Rust type system still requires
/// This is useful on wasm, where threads never run in parallel and there
/// shouldn't ever be contention, but the Rust type system still requires
/// Send/Sync.
#[derive(Default)]
pub struct TryLock<T> {
Expand Down
40 changes: 40 additions & 0 deletions tests/runtime/rust/block-on-spawn/runner.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
include!(env!("BINDINGS"));

use std::cell::Cell;
use std::rc::Rc;
use wit_bindgen::{block_on, block_on_detached, spawn_local};

struct Component;

export!(Component);

impl Guest for Component {
async fn run() {
let ran = Rc::new(Cell::new(0));
let count = || {
let ran = ran.clone();
async move { ran.set(ran.get() + 1) }
};

let before = spawn_local(count());
let nested = block_on(async {
foo::hi().await;
spawn_local(async { 7 }).await
});
assert_eq!(nested, Some(7));
assert_eq!(ran.get(), 0, "`block_on` ran a task spawned outside of it");

before.await;
assert_eq!(ran.get(), 1);

let during = block_on_detached(async {
let during = spawn_local(count());
foo::hi().await;
during
});
assert_eq!(ran.get(), 1, "`block_on_detached` ran a task spawned in it");

during.await;
assert_eq!(ran.get(), 2);
}
}
11 changes: 11 additions & 0 deletions tests/runtime/rust/block-on-spawn/test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
include!(env!("BINDINGS"));

struct Test;

export!(Test);

impl exports::foo::Guest for Test {
async fn hi() {
wit_bindgen::yield_async().await;
}
}
Loading
Loading