Skip to main content

weaveffi/rt/
spawn.rs

1//! The pluggable executor async exports run on, and the launcher driver that
2//! keeps the completion promise.
3//!
4//! An exported `async fn` lowers to a launcher that returns immediately and a
5//! completion callback that fires when the future resolves. Something has to
6//! drive the future in between:
7//!
8//! * By default (the `tokio` feature, on by default), a Tokio runtime: the
9//!   current one when the launcher is called from inside a runtime,
10//!   otherwise a multi-thread runtime the library creates on first use
11//!   (its threads are named `weaveffi-async`).
12//! * Without the `tokio` feature (`default-features = false`), each call
13//!   runs on a thread of its own, named `weaveffi-async`, which drives the
14//!   future with [`block_on`] and exits when it completes. There's no
15//!   reactor, so a future that awaits Tokio's I/O or timers never wakes;
16//!   a future woken from another thread resumes on its own thread.
17//! * On `wasm32`, which has no threads, the future is polled inline before
18//!   the launcher returns. A future still pending once nothing wakes it
19//!   completes with [`GENERIC_ERROR_CODE`]
20//!   ("async function suspended with no executor on wasm32") instead of
21//!   spinning.
22//!
23//! A producer installs its own [`Spawner`] once at startup with
24//! [`set_spawner`], which overrides every default:
25//!
26//! ```
27//! # fn spawn_on_my_runtime(_f: weaveffi::BoxFuture) {}
28//! // e.g. `|fut| { tokio_handle.spawn(fut); }`
29//! let _ = weaveffi::set_spawner(|fut| spawn_on_my_runtime(fut));
30//! ```
31//!
32//! Generated launchers call [`launch_async`], which runs the launcher's own
33//! work (lifting the inputs) under `catch_unwind` and hands the producer's
34//! future to [`run_async`]. Every future handed to a spawner is
35//! `Send + 'static` and already wrapped so a panic inside it is caught and
36//! reported through the completion callback; a spawner never observes an
37//! unwinding future. A spawner may also drop a future without finishing it
38//! (a runtime shutting down, say): the completion still fires, with
39//! [`CANCELLED_ERROR_CODE`](crate::rt::CANCELLED_ERROR_CODE). A spawner that
40//! panics, or a default executor that can't start, completes the call with
41//! [`GENERIC_ERROR_CODE`].
42
43use std::future::Future;
44use std::pin::Pin;
45use std::sync::{Arc, Mutex, OnceLock, PoisonError};
46use std::task::{Context, Poll, Wake, Waker};
47
48use crate::rt::cancel::{CancelToken, Cancellable};
49use crate::rt::error::{FfiError, GENERIC_ERROR_CODE};
50
51/// The type-erased future a [`Spawner`] receives.
52pub type BoxFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
53
54/// An executor hook that drives the futures produced by async exports.
55///
56/// Implemented for any `Fn(BoxFuture) + Send + Sync + 'static`, so a closure
57/// that forwards to a runtime handle is enough.
58pub trait Spawner: Send + Sync + 'static {
59    /// Schedule `fut` to run to completion. Must not block the caller: the
60    /// launcher that invokes it is on the consumer's thread.
61    fn spawn(&self, fut: BoxFuture);
62}
63
64impl<F> Spawner for F
65where
66    F: Fn(BoxFuture) + Send + Sync + 'static,
67{
68    fn spawn(&self, fut: BoxFuture) {
69        self(fut);
70    }
71}
72
73static SPAWNER: OnceLock<Box<dyn Spawner>> = OnceLock::new();
74
75/// The error returned when [`set_spawner`] is called a second time.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub struct SpawnerAlreadySet;
78
79impl std::fmt::Display for SpawnerAlreadySet {
80    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81        f.write_str("a WeaveFFI spawner has already been installed")
82    }
83}
84
85impl std::error::Error for SpawnerAlreadySet {}
86
87/// Install the process-wide spawner async exports run on.
88///
89/// Call once, before the first async export is launched (an initialization
90/// export or a library constructor is the natural place). Until it's called,
91/// and forever after if it never is, the default executor is used (see the
92/// [module docs](self)).
93///
94/// # Errors
95///
96/// Returns [`SpawnerAlreadySet`] if a spawner was installed already; the
97/// first one wins.
98pub fn set_spawner(spawner: impl Spawner) -> Result<(), SpawnerAlreadySet> {
99    SPAWNER
100        .set(Box::new(spawner))
101        .map_err(|_| SpawnerAlreadySet)
102}
103
104/// Why the executor didn't take a future.
105#[derive(Debug, Clone, PartialEq, Eq)]
106pub enum SpawnError {
107    /// The spawner panicked, or the default executor couldn't start.
108    Failed(String),
109    /// `wasm32` only: the future was still pending after nothing was left
110    /// to wake it.
111    Suspended,
112}
113
114impl std::fmt::Display for SpawnError {
115    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116        match self {
117            Self::Failed(why) => write!(f, "could not start the async call: {why}"),
118            Self::Suspended => f.write_str("async function suspended with no executor on wasm32"),
119        }
120    }
121}
122
123impl std::error::Error for SpawnError {}
124
125/// Run `fut` on the installed spawner, or on the default executor.
126///
127/// # Errors
128///
129/// Returns [`SpawnError`] when the spawner panics (the future is dropped),
130/// when the default executor can't start, or (on `wasm32`) when the future
131/// is still pending once nothing wakes it.
132pub fn spawn(fut: impl Future<Output = ()> + Send + 'static) -> Result<(), SpawnError> {
133    let fut: BoxFuture = Box::pin(fut);
134    match SPAWNER.get() {
135        Some(spawner) => std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
136            spawner.spawn(fut);
137        }))
138        .map_err(|payload| {
139            SpawnError::Failed(format!(
140                "the spawner panicked: {}",
141                crate::rt::error::panic_message(&*payload)
142            ))
143        }),
144        None => default_spawn(fut),
145    }
146}
147
148#[cfg(all(not(target_arch = "wasm32"), not(feature = "tokio")))]
149fn default_spawn(fut: BoxFuture) -> Result<(), SpawnError> {
150    std::thread::Builder::new()
151        .name("weaveffi-async".to_string())
152        .spawn(move || block_on(fut))
153        .map(drop)
154        .map_err(|e| SpawnError::Failed(format!("could not start a thread: {e}")))
155}
156
157#[cfg(all(not(target_arch = "wasm32"), feature = "tokio"))]
158fn default_spawn(fut: BoxFuture) -> Result<(), SpawnError> {
159    if let Ok(handle) = tokio::runtime::Handle::try_current() {
160        drop(handle.spawn(fut));
161        return Ok(());
162    }
163    static RUNTIME: OnceLock<Result<tokio::runtime::Runtime, String>> = OnceLock::new();
164    match RUNTIME.get_or_init(|| {
165        tokio::runtime::Builder::new_multi_thread()
166            .thread_name("weaveffi-async")
167            .enable_all()
168            .build()
169            .map_err(|e| e.to_string())
170    }) {
171        Ok(rt) => {
172            drop(rt.spawn(fut));
173            Ok(())
174        }
175        Err(why) => Err(SpawnError::Failed(format!(
176            "could not start the Tokio runtime: {why}"
177        ))),
178    }
179}
180
181#[cfg(target_arch = "wasm32")]
182fn default_spawn(mut fut: BoxFuture) -> Result<(), SpawnError> {
183    use std::sync::atomic::{AtomicBool, Ordering};
184
185    struct Woken(AtomicBool);
186    impl Wake for Woken {
187        fn wake(self: Arc<Self>) {
188            self.0.store(true, Ordering::SeqCst);
189        }
190        fn wake_by_ref(self: &Arc<Self>) {
191            self.0.store(true, Ordering::SeqCst);
192        }
193    }
194
195    let woken = Arc::new(Woken(AtomicBool::new(false)));
196    let waker = Waker::from(Arc::clone(&woken));
197    let mut cx = Context::from_waker(&waker);
198    loop {
199        woken.0.store(false, Ordering::SeqCst);
200        if fut.as_mut().poll(&mut cx).is_ready() {
201            return Ok(());
202        }
203        if !woken.0.load(Ordering::SeqCst) {
204            // Nothing can wake it on a thread-less target: dropping it fires
205            // the completion through `run_async`'s guard.
206            drop(fut);
207            return Err(SpawnError::Suspended);
208        }
209    }
210}
211
212/// Drive a future to completion on the current thread, blocking until it
213/// resolves.
214///
215/// This is a minimal, dependency-free executor for tests and examples. It
216/// parks the thread between polls and wakes on `Waker::wake`, so a future
217/// that yields (for example, one awaiting a channel woken from another
218/// thread) makes progress without busy-spinning.
219///
220/// # Examples
221///
222/// ```
223/// let n = weaveffi::__rt::spawn::block_on(async { 1 + 2 });
224/// assert_eq!(n, 3);
225/// ```
226pub fn block_on<F: Future>(fut: F) -> F::Output {
227    struct ThreadWaker(std::thread::Thread);
228    impl Wake for ThreadWaker {
229        fn wake(self: Arc<Self>) {
230            self.0.unpark();
231        }
232        fn wake_by_ref(self: &Arc<Self>) {
233            self.0.unpark();
234        }
235    }
236
237    let mut fut = std::pin::pin!(fut);
238    let waker = Waker::from(Arc::new(ThreadWaker(std::thread::current())));
239    let mut cx = Context::from_waker(&waker);
240    loop {
241        match fut.as_mut().poll(&mut cx) {
242            Poll::Ready(out) => return out,
243            Poll::Pending => std::thread::park(),
244        }
245    }
246}
247
248/// The completion an async call owes, shared between the launcher and the
249/// spawned task so it fires exactly once whichever side finishes the call.
250struct Completion<C> {
251    state: Mutex<CompletionState<C>>,
252}
253
254struct CompletionState<C> {
255    complete: Option<C>,
256    /// The launcher is still inside the spawner.
257    launching: bool,
258    /// The task was dropped unfinished while launching.
259    dropped: bool,
260}
261
262impl<C> Completion<C> {
263    fn lock(&self) -> std::sync::MutexGuard<'_, CompletionState<C>> {
264        self.state.lock().unwrap_or_else(PoisonError::into_inner)
265    }
266}
267
268/// The task's handle on its [`Completion`]: fires it with the result, or
269/// (when dropped unfinished) with the cancelled code, unless the launcher is
270/// still inside the spawner, in which case the launcher decides.
271struct Guard<T, C: FnOnce(Result<T, FfiError>)> {
272    shared: Arc<Completion<C>>,
273    _result: std::marker::PhantomData<fn(T)>,
274}
275
276impl<T, C: FnOnce(Result<T, FfiError>)> Guard<T, C> {
277    fn complete(self, result: Result<T, FfiError>) {
278        let complete = self.shared.lock().complete.take();
279        if let Some(c) = complete {
280            c(result);
281        }
282    }
283}
284
285impl<T, C: FnOnce(Result<T, FfiError>)> Drop for Guard<T, C> {
286    fn drop(&mut self) {
287        let complete = {
288            let mut state = self.shared.lock();
289            if state.launching {
290                state.dropped = true;
291                None
292            } else {
293                state.complete.take()
294            }
295        };
296        if let Some(c) = complete {
297            c(Err(FfiError::cancelled()));
298        }
299    }
300}
301
302/// Run an async export to completion and deliver its result exactly once.
303///
304/// `fut` is the producer's work, already mapped to `Result<T, FfiError>` (a
305/// domain error becomes its [`FfiError`]); `complete` lowers the outcome
306/// into the C completion callback's slots and invokes it. The runtime calls
307/// `complete` exactly once:
308///
309/// * with `fut`'s result when it resolves;
310/// * with a [`PANIC_ERROR_CODE`](crate::rt::PANIC_ERROR_CODE) error when
311///   polling it panics;
312/// * with [`CANCELLED_ERROR_CODE`](crate::rt::CANCELLED_ERROR_CODE) as soon
313///   as `cancel` fires, after dropping `fut`, or when the executor drops the
314///   task before it resolves;
315/// * with [`GENERIC_ERROR_CODE`] when the executor can't take the task (see
316///   [`spawn`]).
317pub fn run_async<T, Fut, C>(fut: Fut, cancel: Option<CancelToken>, complete: C)
318where
319    T: 'static,
320    Fut: Future<Output = Result<T, FfiError>> + Send + 'static,
321    C: FnOnce(Result<T, FfiError>) + Send + 'static,
322{
323    let shared = Arc::new(Completion {
324        state: Mutex::new(CompletionState {
325            complete: Some(complete),
326            launching: true,
327            dropped: false,
328        }),
329    });
330    let guard = Guard {
331        shared: Arc::clone(&shared),
332        _result: std::marker::PhantomData,
333    };
334    let task = async move {
335        let guard = guard;
336        let caught = CatchUnwind::new(fut);
337        let outcome = match cancel {
338            Some(token) => Cancellable::new(caught, token).await,
339            None => Some(caught.await),
340        };
341        guard.complete(match outcome {
342            None => Err(FfiError::cancelled()),
343            Some(Ok(result)) => result,
344            Some(Err(payload)) => Err(FfiError::from_panic(&*payload)),
345        });
346    };
347    let spawned = spawn(task);
348    let (complete, error) = {
349        let mut state = shared.lock();
350        state.launching = false;
351        match spawned {
352            Err(e) => (
353                state.complete.take(),
354                FfiError::new(GENERIC_ERROR_CODE, &e.to_string()),
355            ),
356            Ok(()) if state.dropped => (state.complete.take(), FfiError::cancelled()),
357            Ok(()) => (None, FfiError::default()),
358        }
359    };
360    if let Some(c) = complete {
361        c(Err(error));
362    }
363}
364
365/// The body of every generated async launcher.
366///
367/// `prepare` runs on the caller's thread under `catch_unwind`: it lifts the
368/// launcher's inputs into owned values and returns the producer's future
369/// (with the call's cancel token, for a `cancellable` function), or the
370/// first input that failed to lift. `lower` turns the producer's value into
371/// the completion callback's result slots, and `deliver` invokes the
372/// callback with a heap-boxed error (or null) and those slots; on any
373/// failure the slots are `zero`. `deliver` runs exactly once, from any
374/// thread, possibly before this returns.
375pub fn launch_async<T, S, Fut>(
376    prepare: impl FnOnce() -> Result<(Fut, Option<CancelToken>), FfiError>,
377    lower: impl FnOnce(T) -> Result<S, FfiError> + Send + 'static,
378    deliver: impl FnOnce(*mut FfiError, S) + Send + 'static,
379    zero: S,
380) where
381    T: 'static,
382    S: Copy + Send + 'static,
383    Fut: Future<Output = Result<T, FfiError>> + Send + 'static,
384{
385    let finish = move |result: Result<T, FfiError>| {
386        let lowered = result.and_then(|value| {
387            // Lowering can panic (an oversized buffer, say) and must not
388            // unwind past the exactly-once promise.
389            std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| lower(value)))
390                .unwrap_or_else(|payload| Err(FfiError::from_panic(&*payload)))
391        });
392        match lowered {
393            Ok(slots) => deliver(std::ptr::null_mut(), slots),
394            Err(e) => deliver(crate::rt::error::boxed_error(e), zero),
395        }
396    };
397    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(prepare)) {
398        Ok(Ok((fut, cancel))) => run_async(fut, cancel, finish),
399        Ok(Err(e)) => finish(Err(e)),
400        Err(payload) => finish(Err(FfiError::from_panic(&*payload))),
401    }
402}
403
404/// A future adapter that catches a panic from the inner future's `poll` and
405/// resolves to `Err(payload)` instead of unwinding into the executor.
406///
407/// This is how [`run_async`] keeps the "callback fires exactly once" promise
408/// even when the producer's future panics: it awaits
409/// `CatchUnwind::new(user_future)` and reports an `Err` through the
410/// completion callback with the reserved panic code.
411pub struct CatchUnwind<F> {
412    inner: Option<Pin<Box<F>>>,
413}
414
415impl<F: Future> CatchUnwind<F> {
416    /// Wrap `fut`.
417    pub fn new(fut: F) -> Self {
418        Self {
419            inner: Some(Box::pin(fut)),
420        }
421    }
422}
423
424impl<F: Future> Future for CatchUnwind<F> {
425    type Output = Result<F::Output, Box<dyn std::any::Any + Send + 'static>>;
426
427    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
428        let this = &mut *self;
429        let Some(inner) = this.inner.as_mut() else {
430            // Polled after completion; a well-behaved executor never does
431            // this, and there is nothing left to drive.
432            return Poll::Pending;
433        };
434        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| inner.as_mut().poll(cx))) {
435            Ok(Poll::Pending) => Poll::Pending,
436            Ok(Poll::Ready(out)) => {
437                this.inner = None;
438                Poll::Ready(Ok(out))
439            }
440            Err(payload) => {
441                this.inner = None;
442                Poll::Ready(Err(payload))
443            }
444        }
445    }
446}
447
448#[cfg(test)]
449mod tests {
450    use super::*;
451    use std::sync::mpsc;
452
453    #[test]
454    fn default_spawner_runs_the_future() {
455        let (tx, rx) = mpsc::channel();
456        spawn(async move {
457            tx.send(7).unwrap();
458        })
459        .unwrap();
460        assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(30)), Ok(7));
461    }
462
463    #[test]
464    fn catch_unwind_reports_panics_and_values() {
465        let ok = block_on(CatchUnwind::new(async { 5 }));
466        assert_eq!(ok.unwrap(), 5);
467        let err = block_on(CatchUnwind::new(async {
468            if true {
469                panic!("boom");
470            }
471            1
472        }));
473        let payload = err.unwrap_err();
474        assert_eq!(crate::rt::error::panic_message(&*payload), "boom");
475    }
476
477    fn run(
478        fut: impl Future<Output = Result<i32, FfiError>> + Send + 'static,
479        cancel: Option<CancelToken>,
480    ) -> mpsc::Receiver<Result<i32, i32>> {
481        let (tx, rx) = mpsc::channel();
482        run_async(fut, cancel, move |r: Result<i32, FfiError>| {
483            tx.send(r.map_err(|e| e.code)).unwrap();
484        });
485        rx
486    }
487
488    const WAIT: std::time::Duration = std::time::Duration::from_secs(30);
489
490    #[test]
491    fn run_async_delivers_values_errors_and_panics() {
492        assert_eq!(run(async { Ok(4) }, None).recv_timeout(WAIT), Ok(Ok(4)));
493        let rx = run(async { Err(FfiError::new(9, "domain")) }, None);
494        assert_eq!(rx.recv_timeout(WAIT), Ok(Err(9)));
495        let rx = run(
496            async {
497                if true {
498                    panic!("bug");
499                }
500                Ok(0)
501            },
502            None,
503        );
504        assert_eq!(rx.recv_timeout(WAIT), Ok(Err(crate::rt::PANIC_ERROR_CODE)));
505    }
506
507    #[test]
508    fn run_async_completes_cancelled_when_the_token_fires() {
509        let raw = crate::rt::cancel_token_create();
510        let token = unsafe { CancelToken::from_raw(raw) };
511        let rx = run(
512            async {
513                std::future::pending::<()>().await;
514                Ok(1)
515            },
516            Some(token),
517        );
518        unsafe { crate::rt::cancel_token_cancel(raw) };
519        unsafe { crate::rt::cancel_token_destroy(raw) };
520        assert_eq!(
521            rx.recv_timeout(WAIT),
522            Ok(Err(crate::rt::CANCELLED_ERROR_CODE))
523        );
524        assert!(rx
525            .recv_timeout(std::time::Duration::from_millis(50))
526            .is_err());
527    }
528
529    #[test]
530    fn a_dropped_guard_completes_cancelled_once() {
531        let (tx, rx) = mpsc::channel();
532        let shared = Arc::new(Completion {
533            state: Mutex::new(CompletionState {
534                complete: Some(move |r: Result<(), FfiError>| {
535                    tx.send(r.map_err(|e| e.code)).unwrap();
536                }),
537                launching: false,
538                dropped: false,
539            }),
540        });
541        drop(Guard {
542            shared,
543            _result: std::marker::PhantomData,
544        });
545        assert_eq!(rx.recv(), Ok(Err(crate::rt::CANCELLED_ERROR_CODE)));
546        assert!(rx.recv().is_err());
547    }
548
549    type Prepared = Result<
550        (
551            std::future::Ready<Result<i32, FfiError>>,
552            Option<CancelToken>,
553        ),
554        FfiError,
555    >;
556
557    #[test]
558    fn a_panicking_prepare_completes_with_the_panic_code() {
559        let (tx, rx) = mpsc::channel();
560        launch_async(
561            || -> Prepared { panic!("lifting blew up") },
562            |v: i32| Ok(v),
563            move |err, v| {
564                let code = unsafe { err.as_ref() }.map_or(0, |e| e.code);
565                unsafe { crate::rt::error_free(err) };
566                tx.send((code, v)).unwrap();
567            },
568            0,
569        );
570        assert_eq!(rx.recv_timeout(WAIT), Ok((crate::rt::PANIC_ERROR_CODE, 0)));
571    }
572}