Skip to content
Merged
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
14 changes: 10 additions & 4 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 Down Expand Up @@ -230,7 +233,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 +363,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 +455,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(Pin::from(task))
}
}

Expand Down
48 changes: 30 additions & 18 deletions crates/guest-rust/src/rt/async_support/spawn.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,40 @@
// 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>>>,
}

// Note: the queued futures are `!Send`. 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 on the thread that polls the task.
unsafe impl Send for Spawned {}
unsafe impl Sync for Spawned {}

impl Spawned {
pub fn push(&self, task: BoxFuture<'static>) {
self.queue.try_lock().unwrap().push(task);
}

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 +60,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 +109,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 Down
9 changes: 8 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,13 @@ use alloc::boxed::Box;
use core::future::Future;
use core::task::{Context, Poll};

#[derive(Default)]
pub struct Spawned;

impl Spawned {
pub fn take(&self) {}
}

#[derive(Default)]
pub struct Tasks<'a> {
future: Option<BoxFuture<'a>>,
Expand All @@ -19,7 +26,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
30 changes: 30 additions & 0 deletions tests/runtime/rust/block-on-spawn/runner.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
include!(env!("BINDINGS"));

use std::cell::Cell;
use std::rc::Rc;
use wit_bindgen::{block_on, 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);
}
}
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;
}
}
15 changes: 15 additions & 0 deletions tests/runtime/rust/block-on-spawn/test.wit
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package my:test;

world runner {
import foo: interface {
hi: async func();
}

export run: async func();
}

world test {
export foo: interface {
hi: async func();
}
}
Loading