| 1 |
/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 |
* License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 |
|
| 5 |
use std::{future::Future, sync::Arc}; |
| 6 |
|
| 7 |
mod future; |
| 8 |
mod scheduler; |
| 9 |
use future::*; |
| 10 |
use scheduler::*; |
| 11 |
|
| 12 |
#[cfg(test)] |
| 13 |
mod tests; |
| 14 |
|
| 15 |
use crate::{derive_ffi_traits, Handle, HandleAlloc, LiftArgsError, LowerReturn, RustCallStatus}; |
| 16 |
|
| 17 |
/// Result code for [rust_future_poll]. This is passed to the continuation function. |
| 18 |
#[repr(i8)] |
| 19 |
#[derive(Debug, PartialEq, Eq)] |
| 20 |
pub enum RustFuturePoll { |
| 21 |
/// The future is ready and is waiting for [rust_future_complete] to be called |
| 22 |
Ready = 0, |
| 23 |
/// The future might be ready and [rust_future_poll] should be called again |
| 24 |
MaybeReady = 1, |
| 25 |
} |
| 26 |
|
| 27 |
/// Foreign callback that's passed to [rust_future_poll] |
| 28 |
/// |
| 29 |
/// The Rust side of things calls this when the foreign side should call [rust_future_poll] again |
| 30 |
/// to continue progress on the future. |
| 31 |
pub type RustFutureContinuationCallback = extern "C" fn(callback_data: u64, RustFuturePoll); |
| 32 |
|
| 33 |
/// This marker trait allows us to put different bounds on the `Future`s we |
| 34 |
/// support, based on `#[cfg(..)]` configuration. |
| 35 |
/// |
| 36 |
/// It should not be considered as a part of the public API, and as such as |
| 37 |
/// an implementation detail and subject to change. |
| 38 |
/// |
| 39 |
/// It is _not_ intended to be implemented by libray users or bindings |
| 40 |
/// implementors. |
| 41 |
#[doc(hidden)] |
| 42 |
pub trait UniffiCompatibleFuture<T>: Future<Output = T> {} |
| 43 |
|
| 44 |
#[doc(hidden)] |
| 45 |
pub trait FutureLowerReturn<UT>: LowerReturn<UT> {} |
| 46 |
|
| 47 |
/// The `Send` bound is required because the Foreign code may call the |
| 48 |
/// `rust_future_*` methods from different threads. |
| 49 |
#[cfg(not(target_arch = "wasm32"))] |
| 50 |
impl<T, F> UniffiCompatibleFuture<T> for F where F: Future<Output = T> + Send {} |
| 51 |
#[cfg(not(all(target_arch = "wasm32", feature = "wasm-unstable-single-threaded")))] |
| 52 |
impl<UT, LR> FutureLowerReturn<UT> for LR where LR: LowerReturn<UT> + Send {} |
| 53 |
|
| 54 |
/// `Future`'s on WASM32 are not `Send` because it's a single threaded environment. |
| 55 |
/// |
| 56 |
/// # Safety: |
| 57 |
/// |
| 58 |
/// WASM32 is a single threaded environment. However, in a browser there do |
| 59 |
/// exist [`WebWorker`][webworker]s which do not share memory or event-loop |
| 60 |
/// with the main browser context. |
| 61 |
/// |
| 62 |
/// Communication between contexts is only possible by message passing, |
| 63 |
/// using a small number of ['transferable' object types][transferable]. |
| 64 |
/// |
| 65 |
/// The most common source of asynchrony in Rust compiled to WASM is |
| 66 |
/// [wasm-bindgen's `JsFuture`][jsfuture]. It is not `Send` because: |
| 67 |
/// |
| 68 |
/// 1. `T` and `E` are both `JsValue` |
| 69 |
/// 2. `JsValue` may contain `JsFunction`s, either as a function themselves or |
| 70 |
/// an object containing functions. |
| 71 |
/// 3. Functions cannot be [serialized and sent][transferable] to `WebWorker`s. |
| 72 |
/// |
| 73 |
/// Implementors of binding generators should be able to enumerate the |
| 74 |
/// combinations of Rust or JS communicating across different contexts (here |
| 75 |
/// using: <->), and in the same context (+) to account for why it is safe |
| 76 |
/// for UniFFI to support `Future`s that are not `Send`: |
| 77 |
/// |
| 78 |
/// 1. JS + Rust in the same contexts: polling and waking happens in the same |
| 79 |
/// thread, no `Send` is needed. |
| 80 |
/// 2. Rust <-> Rust in different contexts: Futures cannot be sent between JS |
| 81 |
/// contexts within the same Rust crate (because they are not `Send`). |
| 82 |
/// 3. JS <-> Rust in different contexts: the `Promise` are [not transferable |
| 83 |
/// between contexts][transferable], so this is impossible. |
| 84 |
/// 4. JS <-> JS + Rust, this is possible, but safe since the Future is being |
| 85 |
/// driven by JS in the same thread. If a Promise metaphor is desired, then |
| 86 |
/// this must be built with JS talking to JS, because 3. |
| 87 |
/// |
| 88 |
/// [webworker]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers |
| 89 |
/// [jsfuture]: https://github.com/rustwasm/wasm-bindgen/blob/main/crates/futures/src/lib.rs |
| 90 |
/// [transferable]: (https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Transferable_objects |
| 91 |
#[cfg(target_arch = "wasm32")] |
| 92 |
impl<T, F> UniffiCompatibleFuture<T> for F where F: Future<Output = T> {} |
| 93 |
#[cfg(all(target_arch = "wasm32", feature = "wasm-unstable-single-threaded"))] |
| 94 |
impl<UT, LR> FutureLowerReturn<UT> for LR where LR: LowerReturn<UT> {} |
| 95 |
|
| 96 |
// === Public FFI API === |
| 97 |
|
| 98 |
/// Create a new [Handle] for a Rust future |
| 99 |
/// |
| 100 |
/// For each exported async function, UniFFI will create a scaffolding function that uses this to |
| 101 |
/// create the [Handle] to pass to the foreign code. |
| 102 |
// Need to allow let_and_return, or clippy complains when the `ffi-trace` feature is disabled. |
| 103 |
#[allow(clippy::let_and_return)] |
| 104 |
pub fn rust_future_new<F, T, UT>(future: F, tag: UT) -> Handle |
| 105 |
where |
| 106 |
// F is the future type returned by the exported async function. It needs to be Send + `static |
| 107 |
// since it will move between threads for an indeterminate amount of time as the foreign |
| 108 |
// executor calls polls it and the Rust executor wakes it. It does not need to by `Sync`, |
| 109 |
// since we synchronize all access to the values. |
| 110 |
F: UniffiCompatibleFuture<Result<T, LiftArgsError>> + 'static, |
| 111 |
// T is the output of the Future. It needs to implement [LowerReturn]. Also it must be Send + |
| 112 |
// 'static for the same reason as F. |
| 113 |
T: FutureLowerReturn<UT> + 'static, |
| 114 |
// The UniFfiTag ZST. The Send + 'static bound is to keep rustc happy. |
| 115 |
UT: Send + 'static, |
| 116 |
// Needed to allocate a handle |
| 117 |
dyn RustFutureFfi<T::ReturnType>: HandleAlloc<UT>, |
| 118 |
{ |
| 119 |
let handle = HandleAlloc::new_handle( |
| 120 |
RustFuture::new(Box::pin(future), tag) as Arc<dyn RustFutureFfi<T::ReturnType>> |
| 121 |
); |
| 122 |
trace!("rust_future_new: {handle:?}"); |
| 123 |
handle |
| 124 |
} |
| 125 |
|
| 126 |
/// Poll a Rust future |
| 127 |
/// |
| 128 |
/// When the future is ready to progress the continuation will be called with the `data` value and |
| 129 |
/// a [RustFuturePoll] value. For each [rust_future_poll] call the continuation will be called |
| 130 |
/// exactly once. |
| 131 |
/// |
| 132 |
/// # Safety |
| 133 |
/// |
| 134 |
/// The [Handle] must not previously have been passed to [rust_future_free] |
| 135 |
pub unsafe fn rust_future_poll<ReturnType, UT>( |
| 136 |
handle: Handle, |
| 137 |
callback: RustFutureContinuationCallback, |
| 138 |
data: u64, |
| 139 |
) where |
| 140 |
dyn RustFutureFfi<ReturnType>: HandleAlloc<UT>, |
| 141 |
{ |
| 142 |
trace!("rust_future_poll: {handle:?}"); |
| 143 |
<dyn RustFutureFfi<ReturnType> as HandleAlloc<UT>>::get_arc(handle).ffi_poll(callback, data) |
| 144 |
} |
| 145 |
|
| 146 |
/// Cancel a Rust future |
| 147 |
/// |
| 148 |
/// Any current and future continuations will be immediately called with RustFuturePoll::Ready. |
| 149 |
/// |
| 150 |
/// This is needed for languages like Swift, which continuation to wait for the continuation to be |
| 151 |
/// called when tasks are cancelled. |
| 152 |
/// |
| 153 |
/// # Safety |
| 154 |
/// |
| 155 |
/// The [Handle] must not previously have been passed to [rust_future_free] |
| 156 |
pub unsafe fn rust_future_cancel<ReturnType, UT>(handle: Handle) |
| 157 |
where |
| 158 |
dyn RustFutureFfi<ReturnType>: HandleAlloc<UT>, |
| 159 |
{ |
| 160 |
trace!("rust_future_cancel: {handle:?}"); |
| 161 |
<dyn RustFutureFfi<ReturnType> as HandleAlloc<UT>>::get_arc(handle).ffi_cancel() |
| 162 |
} |
| 163 |
|
| 164 |
/// Complete a Rust future |
| 165 |
/// |
| 166 |
/// Note: the actually extern "C" scaffolding functions can't be generic, so we generate one for |
| 167 |
/// each supported FFI type. |
| 168 |
/// |
| 169 |
/// # Safety |
| 170 |
/// |
| 171 |
/// - The [Handle] must not previously have been passed to [rust_future_free] |
| 172 |
/// - The `T` param must correctly correspond to the [rust_future_new] call. It must |
| 173 |
/// be `<Output as LowerReturn<UT>>::ReturnType` |
| 174 |
pub unsafe fn rust_future_complete<ReturnType, UT>( |
| 175 |
handle: Handle, |
| 176 |
out_status: &mut RustCallStatus, |
| 177 |
) -> ReturnType |
| 178 |
where |
| 179 |
dyn RustFutureFfi<ReturnType>: HandleAlloc<UT>, |
| 180 |
{ |
| 181 |
trace!("rust_future_complete: {handle:?}"); |
| 182 |
<dyn RustFutureFfi<ReturnType> as HandleAlloc<UT>>::get_arc(handle).ffi_complete(out_status) |
| 183 |
} |
| 184 |
|
| 185 |
/// Free a Rust future, dropping the strong reference and releasing all references held by the |
| 186 |
/// future. |
| 187 |
/// |
| 188 |
/// # Safety |
| 189 |
/// |
| 190 |
/// The [Handle] must not previously have been passed to [rust_future_free] |
| 191 |
pub unsafe fn rust_future_free<ReturnType, UT>(handle: Handle) |
| 192 |
where |
| 193 |
dyn RustFutureFfi<ReturnType>: HandleAlloc<UT>, |
| 194 |
{ |
| 195 |
trace!("rust_future_free: {handle:?}"); |
| 196 |
<dyn RustFutureFfi<ReturnType> as HandleAlloc<UT>>::consume_handle(handle).ffi_free() |
| 197 |
} |
| 198 |
|
| 199 |
// Derive HandleAlloc for dyn RustFutureFfi<T> for all FFI return types |
| 200 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<u8>); |
| 201 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<i8>); |
| 202 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<u16>); |
| 203 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<i16>); |
| 204 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<u32>); |
| 205 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<i32>); |
| 206 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<u64>); |
| 207 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<i64>); |
| 208 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<f32>); |
| 209 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<f64>); |
| 210 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<*const std::ffi::c_void>); |
| 211 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<crate::RustBuffer>); |
| 212 |
derive_ffi_traits!(impl<UT> HandleAlloc<UT> for dyn RustFutureFfi<()>); |