1use 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
51pub type BoxFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
53
54pub trait Spawner: Send + Sync + 'static {
59 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#[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
87pub fn set_spawner(spawner: impl Spawner) -> Result<(), SpawnerAlreadySet> {
99 SPAWNER
100 .set(Box::new(spawner))
101 .map_err(|_| SpawnerAlreadySet)
102}
103
104#[derive(Debug, Clone, PartialEq, Eq)]
106pub enum SpawnError {
107 Failed(String),
109 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
125pub 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 drop(fut);
207 return Err(SpawnError::Suspended);
208 }
209 }
210}
211
212pub 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
248struct Completion<C> {
251 state: Mutex<CompletionState<C>>,
252}
253
254struct CompletionState<C> {
255 complete: Option<C>,
256 launching: bool,
258 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
268struct 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
302pub 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
365pub 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 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
404pub struct CatchUnwind<F> {
412 inner: Option<Pin<Box<F>>>,
413}
414
415impl<F: Future> CatchUnwind<F> {
416 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 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}