diff --git a/CHANGELOG.md b/CHANGELOG.md index 57da3a5..66f1d93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ #### v0.10.0+v0.31.2 ---- +- Tests: Expand coverage of the upstream async API client example - Core: Update bindgen to UniFFI v0.31.2 - Core: Objects are passed across the FFI as `uint64_t` handles instead of raw pointers - Core: Trait interfaces distinguish Rust- and C++-implemented objects when lifting and lowering, and implement the new `uniffi_clone` vtable entry @@ -10,7 +11,7 @@ - Core: Support `#[uniffi(default)]` without a literal using C++ value initialization (`{}`) - Core: Fix optional enum default values rendering with the wrong type - Core: Fix duplicate type definitions when a record or enum references the same type more than once -- Core: Async functions, constructors and methods are omitted with a warning instead of aborting generation; async callback interfaces are still unsupported +- Core: Support async functions, constructors, methods, and callback interfaces with C++17 futures, cancellation, continuations, and one shared control executor #### v0.9.0+v0.29.4 diff --git a/Cargo.lock b/Cargo.lock index 019bf5c..8ce3602 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -96,7 +96,7 @@ dependencies = [ "rustc-hash", "serde", "serde_derive", - "syn", + "syn 2.0.106", ] [[package]] @@ -113,7 +113,7 @@ dependencies = [ "rustc-hash", "serde", "serde_derive", - "syn", + "syn 2.0.106", ] [[package]] @@ -153,6 +153,17 @@ dependencies = [ "tokio", ] +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "autocfg" version = "1.1.0" @@ -258,7 +269,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -313,24 +324,100 @@ dependencies = [ "autocfg", ] +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + [[package]] name = "futures-io" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + [[package]] name = "futures-timer" version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + [[package]] name = "glob" version = "0.3.1" @@ -533,7 +620,7 @@ checksum = "7f81c2fde025af7e69b1d1420531c8a8811ca898919db177141a85313b1cb932" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -572,7 +659,7 @@ checksum = "8db53ae22f34573731bafa1db20f04027b2d25e02d8205921b569171699cdb33" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -603,6 +690,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ee5873ec9cce0195efcb7a4e9507a04cd49aec9c83d0389df45b1ef7ba2e649" +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + [[package]] name = "smawk" version = "0.3.2" @@ -632,6 +725,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "tempfile" version = "3.10.1" @@ -681,7 +785,7 @@ checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -692,7 +796,7 @@ checksum = "6c5e1be1c48b9172ee610da68fd9cd2770e7a4056cb3fc98710ee6906f0c7960" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -803,7 +907,9 @@ version = "0.31.2" source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.2#05b45b110f652d58d94c653992aeb3adc3a094f4" dependencies = [ "anyhow", + "camino", "cargo_metadata", + "clap", "uniffi_bindgen", "uniffi_build", "uniffi_core", @@ -815,6 +921,7 @@ dependencies = [ name = "uniffi-async-calls" version = "0.21.0" dependencies = [ + "async-trait", "futures-timer", "thiserror 1.0.50", "tokio", @@ -849,6 +956,7 @@ dependencies = [ "uniffi-enum-style-test", "uniffi-error-types-builtin", "uniffi-example-arithmetic", + "uniffi-example-async-api-client", "uniffi-example-callbacks", "uniffi-example-custom-types", "uniffi-example-geometry", @@ -861,6 +969,7 @@ dependencies = [ "uniffi-fixture-callbacks", "uniffi-fixture-coverall", "uniffi-fixture-docstring", + "uniffi-fixture-futures", "uniffi-fixture-time", "uniffi-fixture-trait-methods", "uniffi-reserved-field-name", @@ -909,6 +1018,18 @@ dependencies = [ "uniffi", ] +[[package]] +name = "uniffi-example-async-api-client" +version = "0.26.1" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.2#05b45b110f652d58d94c653992aeb3adc3a094f4" +dependencies = [ + "async-trait", + "serde", + "serde_json", + "thiserror 2.0.16", + "uniffi", +] + [[package]] name = "uniffi-example-callbacks" version = "0.22.0" @@ -1015,6 +1136,19 @@ dependencies = [ "uniffi", ] +[[package]] +name = "uniffi-fixture-futures" +version = "0.21.0" +source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.2#05b45b110f652d58d94c653992aeb3adc3a094f4" +dependencies = [ + "async-trait", + "futures", + "once_cell", + "thiserror 2.0.16", + "tokio", + "uniffi", +] + [[package]] name = "uniffi-fixture-time" version = "0.22.0" @@ -1105,7 +1239,7 @@ dependencies = [ "indexmap", "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -1119,7 +1253,7 @@ dependencies = [ "proc-macro2", "quote", "serde", - "syn", + "syn 2.0.106", "toml", "uniffi_meta", ] diff --git a/README.md b/README.md index 5409f69..262eb57 100644 --- a/README.md +++ b/README.md @@ -44,11 +44,87 @@ Regardless of the generation method, these files are produced: To integrate the bindings into your projects, simply add the generated bindings files to your project. C++17 or newer is required to compile the bindings. -# Unsupported features +# Async functions + +UniFFI expects the foreign bindings to provide the scheduler for Rust futures. C++17 provides +futures for waiting on results, so the generated bindings supply scheduling through `AsyncExecutor`. +See [why C++ needs an executor](docs/ASYNC_RUNTIME.md#overview). + +Rust async functions, constructors, and methods return a move-only `uniffi::Future`. +The future supports `get()`, `wait()`, `wait_for()`, `cancel()`, and a consuming `then()` operation. +Destroying an incomplete future requests cancellation. Cancellation races are resolved by the +`RustCallStatus` returned by UniFFI completion, so a result that won the race is not discarded. +Keep the `FutureContinuation` returned by `then()` alive until the callback runs. Destroying it +requests cancellation. Access each `Future` or `FutureContinuation` from one thread at a time. +For cross-thread cancellation, take a copyable `FutureCancelHandle` with `future.cancel_handle()` +before calling `get()` or `then()`. The handle's `cancel()` can run while `get()` is blocked, and +has no effect after completion. + +One shared control executor drives all generated components linked into the same C++ library or +executable. It owns one lazily started, joinable worker thread. Pending calls own state, not threads. +Rust's waker schedules work only when a future can make progress; there is no polling timer or +blocking waiter per future. Each future's poll/cancel/complete/free operations are serialized. +The first poll normally blocks the caller until Rust yields or completes, including any +synchronous C++ callbacks it invokes, while the worker delivers `then()` continuations and starts +async C++ callbacks. + +Continuations use that same executor: + +```cpp +auto subscription = std::move(service.fetch()).then([](uniffi::FutureResult result) { + try { + consume(std::move(result).get()); + } catch (const std::exception &error) { + report(error); + } +}); +``` + +Keep continuations and foreign callback startup/cancellation actions short and nonblocking. Delegate +blocking application work to an existing application worker pool or async I/O service. Waiting on an +incomplete generated future from the control executor throws `std::logic_error` instead of deadlocking. + +Stop application producers, then call `uniffi::shutdown_async_executor()` from an application +thread before unloading the bindings or the Rust library. Shutdown keeps admission open while +caller-thread first polls finish, queuing new calls on the worker during that wait, then closes +admission, cancels active calls, drains queued cleanup and continuations, and joins the worker. +New calls to async Rust exports receive `uniffi::AsyncExecutorError` until an application thread +calls `uniffi::start_async_executor()`. Starting an already running executor is harmless. A +nonreturning first poll or application callback can prevent shutdown from completing. On the +worker or inside a caller-thread first poll, shutdown throws `std::logic_error` and start returns +immediately. + +The shared executor has process lifetime. At process exit, pending work and its Rust handles are +left to process teardown. Python, Kotlin, and TypeScript UniFFI bindings likewise rely on their +host runtimes for process exit. Use explicit shutdown when you need to drain outstanding work. + +Async callback-interface methods return `uniffi::ForeignFuture` from their C++ implementation. +The start function arranges application work, invokes exactly one supplied completion callback, and +returns a cancellation action: + +```cpp +uniffi::ForeignFuture fetch(Request request) override { + return uniffi::ForeignFuture( + [request = std::move(request)](auto success, auto failure) { + return http_pool.start(std::move(request), std::move(success), std::move(failure)); + } + ); +} +``` + +Callback startup, cancellation, result delivery and continuations use the shared control executor. +The C++ implementation can invoke the supplied success or failure callback from any thread. While +the executor is running, the bridge queues delivery to Rust. +The generated bridge arbitrates success, failure, and Rust-side drop exactly once. A dropped Rust +future invokes the returned cancellation action and closes the UniFFI completion channel. -The following uniffi features are unsupported. +When shutdown cancels or rejects a C++ callback that a Rust-owned task is still awaiting, UniFFI +treats the result as an unexpected callback error. A trait method returning `Result` can +receive it as `Err` if `E` implements `From`. UniFFI panics +when the conversion is unavailable. -* Async functions +See the [async runtime design](docs/ASYNC_RUNTIME.md#rust-owned-tasks-during-shutdown) for callback +shutdown, handle ownership, and scheduling. # Configuration options diff --git a/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs b/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs index 3b0cd0c..d8b8d36 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs @@ -158,7 +158,12 @@ impl CppCodeOracle { let class_name = self.class_name(obj.name()); if obj.has_callback_interface() { let impl_name = format!("{class_name}Impl"); - (class_name, impl_name) + let interface_name = if obj.has_async_method() { + format!("{class_name}Foreign") + } else { + class_name + }; + (interface_name, impl_name) } else { (format!("I{class_name}"), class_name) } @@ -359,6 +364,14 @@ pub(crate) fn ffi_type_name(ffi_type: &FfiType) -> Result { }) } +pub(crate) fn ffi_field_type_name(ffi_type: &FfiType) -> Result { + if matches!(ffi_type, FfiType::RustCallStatus) { + Ok("RustCallStatus".into()) + } else { + ffi_type_name(ffi_type) + } +} + pub(crate) fn class_name(nm: &str) -> Result { Ok(CppCodeOracle.class_name(nm)) } diff --git a/bindgen/src/bindings/cpp/gen_cpp/mod.rs b/bindgen/src/bindings/cpp/gen_cpp/mod.rs index 66aeb0f..2729691 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/mod.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/mod.rs @@ -120,6 +120,19 @@ impl<'a> ScaffoldingHeader<'a> { .map(Into::into) .chain(self.ci.iter_ffi_function_definitions().map(Into::into)) } + + pub fn foreign_future_struct_definitions(&self) -> impl Iterator + '_ { + self.ci + .ffi_definitions() + .filter_map(|definition| match definition { + FfiDefinition::Struct(ffi_struct) + if ffi_struct.name().starts_with("ForeignFuture") => + { + Some(ffi_struct) + } + _ => None, + }) + } } #[derive(Template)] diff --git a/bindgen/src/bindings/cpp/mod.rs b/bindgen/src/bindings/cpp/mod.rs index ec0ffad..1602a55 100644 --- a/bindgen/src/bindings/cpp/mod.rs +++ b/bindgen/src/bindings/cpp/mod.rs @@ -93,13 +93,6 @@ impl BindingGenerator for CppBindingGenerator { components: &[uniffi_bindgen::Component], ) -> Result<()> { for Component { ci, config, .. } in components { - if ci.has_async_callback_interface_definition() { - unimplemented!( - "Cpp bindgen does not support async callback interfaces! Namespace: {}", - ci.namespace() - ); - } - if self.scaffolding_mode { unimplemented!("Cpp scaffolding is not supported yet!"); } else { diff --git a/bindgen/src/bindings/cpp/templates/async.cpp b/bindgen/src/bindings/cpp/templates/async.cpp index 7f83d4a..d2bee40 100644 --- a/bindgen/src/bindings/cpp/templates/async.cpp +++ b/bindgen/src/bindings/cpp/templates/async.cpp @@ -1,6 +1,117 @@ constexpr int8_t UNIFFI_RUST_FUTURE_POLL_READY = 0; constexpr int8_t UNIFFI_RUST_FUTURE_POLL_WAKE = 1; +// Coordinates completion and Rust-driven cancellation for a C++ implementation of an async +// callback-interface method. Dropping the Rust future wins the completion race, invokes the +// operation's cancel action, and sends a cancelled result exactly once. +class ForeignFutureTaskState { + public: + void enqueue_or_cancel(::uniffi::AsyncTask task) noexcept { + if (!::uniffi::detail::enqueue_async(std::move(task))) { + cancel(); + } + } + + void start(const std::shared_ptr &self) { + std::lock_guard guard(mutex_); + auto weak = std::weak_ptr(self); + operation_id_ = ::uniffi::detail::async_executor().track([weak] { + if (auto state = weak.lock()) { + state->enqueue_or_cancel([state] { state->cancel(); }); + } + }); + } + + bool can_start() { + std::lock_guard guard(mutex_); + return operation_id_ != 0 && !finished_; + } + + bool finish() noexcept { + std::function cancel; + std::function complete_cancelled; + { + std::lock_guard guard(mutex_); + if (finished_) { + return false; + } + finished_ = true; + cancel = std::move(cancel_); + complete_cancelled = std::move(complete_cancelled_); + } + ::uniffi::detail::async_executor().untrack(operation_id_); + // Releasing captures can destroy application objects; do it outside the state mutex. + return true; + } + + void set_cancel(std::function cancel) noexcept { + std::function cancel_now; + { + std::lock_guard guard(mutex_); + if (cancel_requested_) { + cancel_now = std::move(cancel); + } else if (!finished_) { + cancel_ = std::move(cancel); + } + } + if (cancel_now) { + try { + cancel_now(); + } catch (...) { + } + } + } + + void set_cancel_completion(std::function complete_cancelled) { + std::lock_guard guard(mutex_); + complete_cancelled_ = std::move(complete_cancelled); + } + + void cancel() noexcept { + std::function cancel; + std::function complete_cancelled; + { + std::lock_guard guard(mutex_); + if (finished_) { + return; + } + finished_ = true; + cancel_requested_ = true; + cancel = std::move(cancel_); + complete_cancelled = std::move(complete_cancelled_); + } + if (cancel) { + try { + cancel(); + } catch (...) { + } + } + if (complete_cancelled) { + complete_cancelled(); + } + ::uniffi::detail::async_executor().untrack(operation_id_); + } + + private: + std::mutex mutex_; + uint64_t operation_id_ = 0; + bool finished_ = false; + bool cancel_requested_ = false; + std::function cancel_; + std::function complete_cancelled_; +}; + +inline uint64_t foreign_future_handle(const std::shared_ptr &state) { + return reinterpret_cast(new std::shared_ptr(state)); +} + +inline void foreign_future_drop(uint64_t handle) noexcept { + auto state = std::unique_ptr>( + reinterpret_cast *>(handle)); + auto task_state = *state; + task_state->enqueue_or_cancel([task_state] { task_state->cancel(); }); +} + using RustFutureHandleFn = void (*)(uint64_t); class RustFutureHandleGuard { diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp index c8e113c..417ddc0 100644 --- a/bindgen/src/bindings/cpp/templates/async.hpp +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -222,6 +222,14 @@ inline void check_blocking_wait(bool ready) { } } +template struct ForeignFutureSuccess { + using Type = std::function; +}; + +template <> struct ForeignFutureSuccess { + using Type = std::function; +}; + } // namespace detail // Joins the shared worker after waiting for first polls, cancelling calls, and draining cleanup. @@ -233,6 +241,36 @@ inline void shutdown_async_executor() { detail::async_executor().shutdown(); } // Calls from the worker or inside a caller-thread first poll return immediately. inline void start_async_executor() { detail::async_executor().start(); } +// A deferred C++ callback result that Rust can await. The bridge calls start() on the worker. +// The supplied success and failure callbacks may be called from any thread. +template class ForeignFuture { + public: + using Cancel = std::function; + using Success = typename detail::ForeignFutureSuccess::Type; + using Failure = std::function; + using Start = std::function; + + ForeignFuture() = default; + explicit ForeignFuture(Start start) : start_(std::move(start)) {} + + ForeignFuture(const ForeignFuture &) = delete; + ForeignFuture &operator=(const ForeignFuture &) = delete; + ForeignFuture(ForeignFuture &&) noexcept = default; + ForeignFuture &operator=(ForeignFuture &&) noexcept = default; + + // Invoke the stored start function once and return its optional cancellation action. + Cancel start(Success success, Failure failure) && { + if (!start_) { + throw std::logic_error("UniFFI foreign future is invalid or has already been started"); + } + auto start = std::move(start_); + return start(std::move(success), std::move(failure)); + } + + private: + Start start_; +}; + // Carries the lifted value or exception delivered when an async call completes. template class FutureResult { public: diff --git a/bindgen/src/bindings/cpp/templates/callback.hpp b/bindgen/src/bindings/cpp/templates/callback.hpp index 2ecfbc1..f6d1e93 100644 --- a/bindgen/src/bindings/cpp/templates/callback.hpp +++ b/bindgen/src/bindings/cpp/templates/callback.hpp @@ -3,13 +3,13 @@ {%- let trait_impl = canonical_type_name|callback_interface_name %} {% call macros::docstring_value(interface_docstring, 0) %} -struct {{ interface_name }} { +struct {{ interface_name }}{% if !interface_base_name.is_empty() %} : public {{ interface_base_name }}{% endif %} { virtual ~{{ interface_name }}() {} {%- for method in methods.iter() %} {%- call macros::docstring(method, 4) %} virtual - {% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch %} + {% if method.is_async() %}::uniffi::ForeignFuture<{% endif %}{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }}{% else %}void{% endmatch %}{% if method.is_async() %}>{% endif %}{{ " " }} {{- method.name()|fn_name }}({% call macros::param_list(method) %}) = 0; {%- endfor %} }; @@ -17,7 +17,7 @@ struct {{ interface_name }} { namespace uniffi { struct {{ trait_impl }} { {%- for (ffi_callback, method) in vtable_methods.iter() %} - static {% call macros::ffi_return_type(ffi_callback) %} {{ method.name()|var_name }}({% call macros::arg_list_ffi_decl_xx(ffi_callback) %}); + static {% call macros::ffi_return_type(ffi_callback) %} {{ method.name()|var_name }}({% call macros::arg_list_ffi_decl_xx(ffi_callback) %}) noexcept; {%- endfor %} static void uniffi_free(uint64_t uniffi_handle); diff --git a/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp b/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp index 4ef44a3..04639b7 100644 --- a/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp +++ b/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp @@ -4,7 +4,141 @@ {%- let trait_impl = canonical_type_name|callback_interface_name %} {%- for (ffi_callback, method) in vtable_methods.iter() %} - {% call macros::ffi_return_type(ffi_callback) %} {{ trait_impl}}::{{ method.name()|var_name }}({% call macros::arg_list_ffi_decl_xx(ffi_callback) %}) { + {% call macros::ffi_return_type(ffi_callback) %} {{ trait_impl}}::{{ method.name()|var_name }}({% call macros::arg_list_ffi_decl_xx(ffi_callback) %}) noexcept { + {%- if method.is_async() %} + {%- let result_struct = method.foreign_future_ffi_result_struct() %} + using Result = {{ result_struct.name()|ffi_struct_name }}; + using Complete = void (*)(uint64_t, Result); + auto complete = reinterpret_cast(uniffi_future_callback); + auto state = std::make_shared(); + + state->set_cancel_completion([complete, uniffi_callback_data] { + Result result{}; + result.call_status.code = 3; + complete(uniffi_callback_data, result); + }); + state->start(state); + uniffi_out_dropped_callback.handle = foreign_future_handle(state); + uniffi_out_dropped_callback.free = reinterpret_cast(&foreign_future_drop); + + auto deliver_failure = [state, complete, uniffi_callback_data](std::exception_ptr error) { + if (!state->finish()) { + return; + } + + Result result{}; + try { + if (error) { + std::rethrow_exception(error); + } + throw std::runtime_error("UniFFI foreign future failed without an exception"); + } + {%- match method.throws_type() %} + {%- when Some(error) %} + catch ({{ error|canonical_name }} &e) { + result.call_status.code = 1; + result.call_status.error_buf = {{ error|lower_fn }}(e); + } + {%- when None %} + {%- endmatch %} + catch (std::exception &e) { + result.call_status.code = 2; + result.call_status.error_buf = {{ Type::String.borrow()|lower_fn }}(e.what()); + } catch (...) { + result.call_status.code = 2; + result.call_status.error_buf = {{ Type::String.borrow()|lower_fn }}("Unknown C++ exception"); + } + complete(uniffi_callback_data, result); + }; + + {% match method.return_type() %} + {% when Some(t) %} + auto deliver_success = [state, complete, uniffi_callback_data](const {{ t|type_name(ci) }} &value) { + if (!state->finish()) { + return; + } + + Result result{}; + try { + result.return_value = {{ t|lower_fn }}(value); + } catch (std::exception &e) { + result.call_status.code = 2; + result.call_status.error_buf = {{ Type::String.borrow()|lower_fn }}(e.what()); + } catch (...) { + result.call_status.code = 2; + result.call_status.error_buf = {{ Type::String.borrow()|lower_fn }}("Unknown C++ exception"); + } + complete(uniffi_callback_data, result); + }; + {% when None %} + auto deliver_success = [state, complete, uniffi_callback_data]() { + if (!state->finish()) { + return; + } + complete(uniffi_callback_data, Result{}); + }; + {% endmatch %} + + auto complete_failure = [state, deliver_failure](std::exception_ptr error) { + state->enqueue_or_cancel([deliver_failure, error] { + deliver_failure(error); + }); + }; + {% match method.return_type() %} + {% when Some(t) %} + auto complete_success = [state, deliver_success, complete_failure]({{ t|type_name(ci) }} &&value) { + try { + state->enqueue_or_cancel([deliver_success, value = std::move(value)] { + deliver_success(value); + }); + } catch (...) { + complete_failure(std::current_exception()); + } + }; + {% when None %} + auto complete_success = [state, deliver_success]() { + state->enqueue_or_cancel([deliver_success] { deliver_success(); }); + }; + {% endmatch %} + + try { + auto obj = std::dynamic_pointer_cast<{{ foreign_interface_name }}>( + {{ ffi_converter_name }}::handle_map.at(uniffi_handle) + ); + if (!obj) { + throw std::runtime_error("UniFFI callback handle has the wrong implementation type"); + } + {%- for arg in method.arguments() %} + auto arg{{ loop.index0 }} = {{- arg|lift_fn }}({{ arg.name()|var_name }}); + {%- endfor %} + state->enqueue_or_cancel([ + state, obj, complete_success, complete_failure + {%- for arg in method.arguments() %}, arg{{ loop.index0 }} = std::move(arg{{ loop.index0 }}){% endfor %} + ]() mutable { + if (!::uniffi::detail::begin_async_call() || !state->can_start()) { + state->cancel(); + return; + } + try { + auto future = obj->{{ method.name()|var_name }}( + {%- for arg in method.arguments() %} + arg{{ loop.index0 }}{%- if !loop.last %}, {% endif %} + {%- endfor %} + ); + auto cancel = std::move(future).start(complete_success, complete_failure); + state->set_cancel([obj, cancel = std::move(cancel)] { + if (cancel) { + cancel(); + } + }); + } catch (...) { + complete_failure(std::current_exception()); + } + }); + } catch (...) { + complete_failure(std::current_exception()); + } + {%- else %} auto obj = {{ ffi_converter_name }}::handle_map.at(uniffi_handle); auto make_call = [&]() {% match method.return_type() %}{% when Some(t) %}-> {{ t|type_name(ci) }}{% when None %}{% endmatch %} { @@ -26,6 +160,7 @@ uniffi_out_return = {{ t|lower_fn }}(v); }; {% when None %} + (void)uniffi_out_return; auto write_value = [](){}; {% endmatch %} @@ -35,6 +170,7 @@ {% when None %} rust_call_trait_interface(out_status, make_call, write_value); {% endmatch %} + {%- endif %} } {%- endfor %} diff --git a/bindgen/src/bindings/cpp/templates/obj.cpp b/bindgen/src/bindings/cpp/templates/obj.cpp index 98658a1..3975c2b 100644 --- a/bindgen/src/bindings/cpp/templates/obj.cpp +++ b/bindgen/src/bindings/cpp/templates/obj.cpp @@ -1,5 +1,6 @@ {%- let obj = ci.get_object_definition(name).unwrap() %} {%- let (interface_name, impl_class_name) = obj|object_names %} +{%- let foreign_interface_name = interface_name %} {%- let class_name = type_name|class_name %} {%- let ffi_converter_name = typ|ffi_converter_name %} {%- let canonical_type_name = typ|canonical_name %} diff --git a/bindgen/src/bindings/cpp/templates/obj.hpp b/bindgen/src/bindings/cpp/templates/obj.hpp index 7647861..9a3f3f4 100644 --- a/bindgen/src/bindings/cpp/templates/obj.hpp +++ b/bindgen/src/bindings/cpp/templates/obj.hpp @@ -4,12 +4,23 @@ {%- let ffi_converter_name = typ|ffi_converter_name %} {%- let canonical_type_name = typ|canonical_name %} {%- if obj.has_callback_interface() %} +{%- if obj.has_async_method() %} +struct {{ canonical_type_name }} { + virtual ~{{ canonical_type_name }}() = default; +}; +{%- endif %} {%- let vtable = obj.vtable().expect("trait interface should have a vtable") %} {%- let vtable_methods = obj.vtable_methods() %} {%- let methods = obj.methods() %} {%- let ffi_init_callback = obj.ffi_init_callback() %} {%- let interface_docstring = obj.docstring() %} +{%- if obj.has_async_method() %} +{%- let interface_base_name = canonical_type_name %} {% include "callback.hpp" %} +{%- else %} +{%- let interface_base_name = "" %} +{% include "callback.hpp" %} +{%- endif %} {%- endif %} namespace uniffi { @@ -22,7 +33,7 @@ struct {{ impl_class_name }} Since an interface being a callback interface or an error is mutually exclusive, we don't need to complex branching for multiple inheritance #} -{% if obj.has_callback_interface() %} : public {{ interface_name }} {% endif %} +{% if obj.has_callback_interface() %} : public {% if obj.has_async_method() %}{{ canonical_type_name }}{% else %}{{ interface_name }}{% endif %} {% endif %} {% if ci.is_name_used_as_error(name) %} : public std::exception {% endif %} { friend uniffi::{{ ffi_converter_name|class_name }}; diff --git a/bindgen/src/bindings/cpp/templates/scaffolding.hpp b/bindgen/src/bindings/cpp/templates/scaffolding.hpp index d33b54c..7cf2c45 100644 --- a/bindgen/src/bindings/cpp/templates/scaffolding.hpp +++ b/bindgen/src/bindings/cpp/templates/scaffolding.hpp @@ -28,6 +28,14 @@ struct RustCallStatus { typedef void (*RustFutureContinuationCallback)(uint64_t callback_data, int8_t poll_result); +{%- for ffi_struct in self.foreign_future_struct_definitions() %} +struct {{ ffi_struct.name()|ffi_struct_name }} { + {%- for field in ffi_struct.fields() %} + {{ field.type_().borrow()|ffi_field_type_name }} {{ field.name()|var_name }}; + {%- endfor %} +}; +{%- endfor %} + #endif {%- for def in self.scaffolding_definitions() %} @@ -39,7 +47,7 @@ typedef void (*RustFutureContinuationCallback)(uint64_t callback_data, int8_t po {%- when FfiDefinition::Struct(ffi_struct) %} struct {{ ffi_struct.name()|ffi_struct_name }} { {%- for field in ffi_struct.fields() %} - {{ field.type_().borrow()|ffi_type_name }} {{ field.name()|var_name }}; + {{ field.type_().borrow()|ffi_field_type_name }} {{ field.name()|var_name }}; {%- endfor %} }; {%- when FfiDefinition::Function(func) %} diff --git a/bindgen/src/bindings/cpp/templates/types.cpp b/bindgen/src/bindings/cpp/templates/types.cpp index a486253..6110c6b 100644 --- a/bindgen/src/bindings/cpp/templates/types.cpp +++ b/bindgen/src/bindings/cpp/templates/types.cpp @@ -61,6 +61,7 @@ namespace uniffi { {%- let cbi = ci.get_callback_interface_definition(name).unwrap() %} {%- let ffi_init_callback = cbi.ffi_init_callback() %} {%- let interface_name = name %} +{%- let foreign_interface_name = interface_name %} {%- let methods = cbi.methods() %} {%- let vtable = cbi.vtable() %} {%- let vtable_methods = cbi.vtable_methods() %} diff --git a/bindgen/src/bindings/cpp/templates/wrapper.hpp b/bindgen/src/bindings/cpp/templates/wrapper.hpp index b6aafef..2c9c46f 100644 --- a/bindgen/src/bindings/cpp/templates/wrapper.hpp +++ b/bindgen/src/bindings/cpp/templates/wrapper.hpp @@ -110,6 +110,7 @@ typedef {{ type_name }} {{ name }}; {%- let vtable = cbi.vtable() %} {%- let vtable_methods = cbi.vtable_methods() %} {%- let interface_docstring = cbi.docstring() %} +{%- let interface_base_name = "" %} {% include "callback.hpp" %} {%- when Type::Object { module_path, name, imp } %} {% include "obj.hpp" %} diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index 154521b..22527bf 100644 --- a/cpp-tests/CMakeLists.txt +++ b/cpp-tests/CMakeLists.txt @@ -106,7 +106,11 @@ test_case(error_types_builtin) test_case(reserved_field_name) test_case(type_flattening) list(APPEND BINDING_FILES ${BINDINGS_SRC_DIR}/async_calls.cpp) -test_case(async_executor tests/async_executor/ffi_lifecycle.cpp) +test_case(futures) +target_sources(futures-test PRIVATE ${BINDINGS_SRC_DIR}/async_calls.cpp) +test_case(async_api_client) +test_case(async_executor tests/async_executor/ffi_lifecycle.cpp tests/async_executor/peer.cpp + ${BINDINGS_SRC_DIR}/futures.cpp) test_case(async_pending_at_exit ${BINDINGS_SRC_DIR}/async_calls.cpp) add_executable(ext_types_import-test @@ -149,9 +153,10 @@ add_custom_target(bindings ALL COMMENT "Generating bindings" ) -set_tests_properties(async_executor-test PROPERTIES TIMEOUT 45) +set_tests_properties(futures-test async_api_client-test async_executor-test PROPERTIES TIMEOUT 45) set_tests_properties(async_pending_at_exit-test PROPERTIES TIMEOUT 15) if(VALGRIND) - set_tests_properties(async_executor-test-test-memcheck PROPERTIES TIMEOUT 90) + set_tests_properties(futures-test-test-memcheck async_api_client-test-test-memcheck + async_executor-test-test-memcheck PROPERTIES TIMEOUT 90) set_tests_properties(async_pending_at_exit-test-test-memcheck PROPERTIES TIMEOUT 30) endif() diff --git a/cpp-tests/include/async_api_client_test.hpp b/cpp-tests/include/async_api_client_test.hpp new file mode 100644 index 0000000..d26ee79 --- /dev/null +++ b/cpp-tests/include/async_api_client_test.hpp @@ -0,0 +1,166 @@ +// Copyright 2026 LiveKit, Inc. +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#include + +namespace async_api_client_test { +namespace api = async_api_client; + +// Application workers for potentially blocking RustTask::execute, not runtime control workers. +class WorkerPool { + public: + explicit WorkerPool(size_t count = 1) : capacity_(1024) { + for (size_t i = 0; i < count; ++i) { + workers_.emplace_back([this] { run(); }); + } + } + ~WorkerPool() { shutdown(); } + + bool enqueue(uniffi::AsyncTask task) { + { + std::lock_guard lock(mutex_); + if (!accepting_ || tasks_.size() >= capacity_) { + return false; + } + tasks_.push_back(std::move(task)); + } + ready_.notify_one(); + return true; + } + + size_t queued() { + std::lock_guard lock(mutex_); + return tasks_.size(); + } + + bool wait_idle(std::chrono::seconds timeout = std::chrono::seconds(10)) { + std::unique_lock lock(mutex_); + return idle_.wait_for(lock, timeout, [this] { return tasks_.empty() && running_ == 0; }); + } + + void shutdown() { + { + std::lock_guard lock(mutex_); + accepting_ = false; + } + ready_.notify_all(); + for (auto &worker : workers_) { + if (worker.joinable()) { + worker.join(); + } + } + } + + std::atomic ran_on_control{false}; + + private: + void run() { + for (;;) { + uniffi::AsyncTask task; + { + std::unique_lock lock(mutex_); + ready_.wait(lock, [this] { return !accepting_ || !tasks_.empty(); }); + if (tasks_.empty()) { + return; + } + task = std::move(tasks_.front()); + tasks_.pop_front(); + ++running_; + } + if (uniffi::detail::async_executor().is_worker()) { + ran_on_control = true; + } + task(); + task = {}; + { + std::lock_guard lock(mutex_); + --running_; + } + idle_.notify_all(); + } + } + std::mutex mutex_; + std::condition_variable ready_, idle_; + std::deque tasks_; + std::vector workers_; + const size_t capacity_; + size_t running_ = 0; + bool accepting_ = true; +}; + +class TestHttpClient final : public api::HttpClientForeign { + public: + explicit TestHttpClient(std::shared_ptr workers, + std::string response = api::test_response_data()) + : workers_(std::move(workers)), + response_(std::make_shared(std::move(response))) {} + + uniffi::ForeignFuture fetch(const std::string &url, + const std::string &credentials) override { + return uniffi::ForeignFuture([workers = workers_, response = response_, url, + credentials](auto success, auto failure) { + auto cancelled = std::make_shared>(false); + if (!workers->enqueue([response, url, credentials, success, failure, cancelled] { + if (cancelled->load()) { + return; + } + if (credentials != "username:password" || + url != "https://api.github.com/repos/mozilla/uniffi-rs/issues/2017") { + api::api_error::Http error; + error.reason = credentials != "username:password" ? "Unauthorized" + : "Wrong URL: " + url; + failure(std::make_exception_ptr(error)); + } else { + success(*response); + } + })) { + failure(std::make_exception_ptr(std::runtime_error("HTTP worker rejected work"))); + } + return [cancelled] { cancelled->store(true); }; + }); + } + + private: + std::shared_ptr workers_; + std::shared_ptr response_; +}; + +class TestTaskRunner final : public api::TaskRunnerForeign { + public: + explicit TestTaskRunner(std::shared_ptr workers) : workers_(std::move(workers)) {} + uniffi::ForeignFuture run_task(const std::shared_ptr &task) override { + return uniffi::ForeignFuture([counters = counters_, workers = workers_, + task](auto success, auto failure) { + auto cancelled = std::make_shared>(false); + if (!workers->enqueue([counters, task, success, failure, cancelled] { + if (cancelled->load()) { + return; + } + try { + task->execute(); + ++counters->executed; + success(); + } catch (...) { + failure(std::current_exception()); + } + })) { + failure(std::make_exception_ptr(std::runtime_error("task worker rejected work"))); + } + return [counters, cancelled] { + cancelled->store(true); + ++counters->cancellations; + }; + }); + } + size_t executed() const { return counters_->executed.load(); } + size_t cancellations() const { return counters_->cancellations.load(); } + + private: + struct Counters { + std::atomic executed{0}, cancellations{0}; + }; + std::shared_ptr counters_ = std::make_shared(); + std::shared_ptr workers_; +}; +} // namespace async_api_client_test diff --git a/cpp-tests/tests/async_api_client/main.cpp b/cpp-tests/tests/async_api_client/main.cpp new file mode 100644 index 0000000..fd92c4c --- /dev/null +++ b/cpp-tests/tests/async_api_client/main.cpp @@ -0,0 +1,75 @@ +#include +#include + +using namespace std::chrono_literals; +namespace api = async_api_client; +using namespace async_api_client_test; + +template void eventually(Predicate predicate) { + const auto deadline = std::chrono::steady_clock::now() + 5s; + while (!predicate()) { + ASSERT_TRUE(std::chrono::steady_clock::now() < deadline); + std::this_thread::yield(); + } +} + +int main() { + auto workers = std::make_shared(); + auto runner = std::make_shared(workers); + auto client = api::ApiClient::init(std::make_shared(workers), runner); + + // The upstream success case, with credentials executed on application workers. + auto issue = client->get_issue("mozilla", "uniffi-rs", 2017).get(); + ASSERT_EQ("Foreign-implemented async traits", issue.title); + ASSERT_EQ(api::IssueState::kOpen, issue.state); + ASSERT_EQ("https://api.github.com/repos/mozilla/uniffi-rs/issues/2017", issue.url); + ASSERT_EQ(1, runner->executed()); + ASSERT_FALSE(workers->ran_on_control.load()); + + // A declared foreign HTTP error must survive C++ -> Rust -> C++ as the same variant and fields. + try { + client->get_issue("wrong", "repository", 2017).get(); + ASSERT_TRUE(false); + } catch (const api::api_error::Http &error) { + ASSERT_EQ("Wrong URL: https://api.github.com/repos/wrong/repository/issues/2017", + error.reason); + } + auto invalid = + api::ApiClient::init(std::make_shared(workers, "invalid JSON"), runner); + EXPECT_EXCEPTION(invalid->get_issue("mozilla", "uniffi-rs", 2017).get(), api::api_error::Json); + invalid.reset(); + + std::vector> calls; + for (int i = 0; i < 32; ++i) { + calls.push_back(client->get_issue("mozilla", "uniffi-rs", 2017)); + } + for (auto &call : calls) { + ASSERT_EQ("Foreign-implemented async traits", call.get().title); + } + ASSERT_TRUE(workers->wait_idle()); + + // Hold the sole application worker so a queued RustTask can be deterministically cancelled. + auto entered = std::make_shared>(); + auto release = std::make_shared>(); + auto released = release->get_future().share(); + ASSERT_TRUE(workers->enqueue([entered, released] { + entered->set_value(); + released.wait(); + })); + ASSERT_EQ(std::future_status::ready, entered->get_future().wait_for(5s)); + const auto before = runner->executed(); + const auto cancelled_before = runner->cancellations(); + auto cancelled = client->get_issue("mozilla", "uniffi-rs", 2017); + eventually([&] { return workers->queued() != 0; }); + cancelled.cancel(); + EXPECT_EXCEPTION(cancelled.get(), uniffi::AsyncCancelledError); + eventually([&] { return runner->cancellations() > cancelled_before; }); + release->set_value(); + ASSERT_TRUE(workers->wait_idle()); + ASSERT_EQ(before, runner->executed()); + ASSERT_FALSE(workers->ran_on_control.load()); + + client.reset(); + uniffi::shutdown_async_executor(); + workers->shutdown(); +} diff --git a/cpp-tests/tests/async_executor/ffi_lifecycle.cpp b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp index 100f351..e3f3a2c 100644 --- a/cpp-tests/tests/async_executor/ffi_lifecycle.cpp +++ b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp @@ -321,6 +321,149 @@ void test_continuation_move_failure() { probe.expect_steps({Step::Start, Step::Poll, Step::Complete, Step::Free}); } +class RejectedParser final : public async_calls::TestParserForeign { + public: + uniffi::ForeignFuture stringify(std::int32_t) override { return {}; } + uniffi::ForeignFuture parse(const std::string &) override { return {}; } + uniffi::ForeignFuture wait() override { + assert(false && "a rejected callback started"); + return {}; + } +}; + +class DeferredParser final : public async_calls::TestParserForeign { + public: + uniffi::ForeignFuture stringify(std::int32_t) override { return {}; } + uniffi::ForeignFuture parse(const std::string &) override { return {}; } + uniffi::ForeignFuture wait() override { + return uniffi::ForeignFuture([this](auto success, auto) { + completing.set_value(std::move(success)); + return [this] { ++cancellations; }; + }); + } + + std::promise::Success> completing; + unsigned cancellations = 0; +}; + +// A success queued while Rust's drop is being processed cannot complete the callback a second time. +void test_completion_after_foreign_drop() { + auto &executor = uniffi::detail::async_executor(); + struct CompletionRecord { + unsigned calls = 0; + std::int8_t status = -1; + } record; + auto complete = +[](std::uint64_t data, UniffiForeignFutureResultVoid result) { + auto &received = *reinterpret_cast(data); + ++received.calls; + received.status = result.call_status.code; + }; + + auto parser = std::make_shared(); + auto completing = parser->completing.get_future(); + using Trampoline = async_calls::uniffi::UniffiCallbackInterfaceTestParser; + const auto handle = async_calls::uniffi::FfiConverterTestParser::lower(parser); + UniffiForeignFutureDroppedCallbackStruct drop{}; + Trampoline::wait(handle, reinterpret_cast(complete), + reinterpret_cast(&record), drop); + auto success = wait_for_future(completing); + + PausedTask worker; + ASSERT_TRUE(executor.enqueue([&] { worker.pause(); })); + worker.wait_until_paused(); + ASSERT_NE(drop.free, nullptr); + reinterpret_cast(drop.free)(drop.handle); + success(); + + std::promise drained; + auto barrier = drained.get_future(); + ASSERT_TRUE(executor.enqueue([&] { drained.set_value(); })); + worker.resume(); + wait_for_future(barrier); + ASSERT_EQ(record.calls, 1u); + ASSERT_EQ(record.status, cancelled); + ASSERT_EQ(parser->cancellations, 1u); + Trampoline::uniffi_free(handle); +} + +// Shutdown cancels a pending Rust call before it can consume a rejected C++ callback result. +void test_shutdown_cancels_before_repoll() { + auto &executor = uniffi::detail::async_executor(); + PausedTask before_callback_start; + PausedTask before_call_cancellation; + + // Register first to pause shutdown after it closes admission and before it cancels the call. + const auto blocker = executor.track([&] { before_call_cancellation.pause(); }); + ASSERT_NE(blocker, 0u); + + ASSERT_TRUE(executor.enqueue([&] { before_callback_start.pause(); })); + before_callback_start.wait_until_paused(); + auto future = async_calls::wait_using_parser(std::make_shared()); + + auto stopping = std::async(std::launch::async, [] { uniffi::shutdown_async_executor(); }); + before_call_cancellation.wait_until_paused(); + ASSERT_FALSE(executor.accepting()); + before_callback_start.resume(); + EXPECT_EXCEPTION(wait_for_future(future), uniffi::AsyncCancelledError); + + executor.untrack(blocker); + before_call_cancellation.resume(); + wait_for_future(stopping); + uniffi::start_async_executor(); +} + +class ImmediateParser final : public async_calls::TestParserForeign { + public: + uniffi::ForeignFuture stringify(std::int32_t) override { return {}; } + uniffi::ForeignFuture parse(const std::string &) override { return {}; } + uniffi::ForeignFuture wait() override { + return uniffi::ForeignFuture([](auto success, auto) { + success(); + return nullptr; + }); + } +}; + +// Shutdown waits for an in-flight caller-thread poll before it closes admission, so a callback +// that starts during that poll is not rejected. It then cancels the call and frees the handle. +void test_shutdown_during_first_poll() { + auto &executor = uniffi::detail::async_executor(); + PausedTask first_poll; + RustFutureProbe probe({PollReply::Park}, &first_poll); + auto call = std::async(std::launch::async, [&] { return probe.start(); }); + first_poll.wait_until_paused(); + + auto stopping = std::async(std::launch::async, [] { uniffi::shutdown_async_executor(); }); + wait_for_deferred_first_poll(executor); + ASSERT_TRUE(executor.accepting()); + ASSERT_EQ(stopping.wait_for(std::chrono::seconds(0)), std::future_status::timeout); + + const std::int8_t call_succeeded = 0; + std::promise completed; + auto completion = completed.get_future(); + auto complete = +[](std::uint64_t data, UniffiForeignFutureResultVoid result) { + reinterpret_cast *>(data)->set_value(result.call_status.code); + }; + using Trampoline = async_calls::uniffi::UniffiCallbackInterfaceTestParser; + const auto handle = + async_calls::uniffi::FfiConverterTestParser::lower(std::make_shared()); + UniffiForeignFutureDroppedCallbackStruct drop{}; + Trampoline::wait(handle, reinterpret_cast(complete), + reinterpret_cast(&completed), drop); + ASSERT_EQ(wait_for_future(completion), call_succeeded); + ASSERT_NE(drop.free, nullptr); + reinterpret_cast(drop.free)(drop.handle); + probe.expect_steps({Step::Start, Step::Poll}); + + first_poll.resume(); + auto future = wait_for_future(call); + EXPECT_EXCEPTION(wait_for_future(future), uniffi::AsyncCancelledError); + wait_for_future(stopping); + probe.expect_steps({Step::Start, Step::Poll, Step::Cancel, Step::Complete, Step::Free}); + Trampoline::uniffi_free(handle); + uniffi::start_async_executor(); +} + } // namespace void test_rust_future_lifecycle() { @@ -335,6 +478,12 @@ void test_rust_future_lifecycle() { test_continuation_move_failure(); } +void test_foreign_callback_lifecycle() { + test_completion_after_foreign_drop(); + test_shutdown_cancels_before_repoll(); + test_shutdown_during_first_poll(); +} + // Close admission after the start check while the caller still owns the new Rust handle. void test_shutdown_during_handle_creation() { unsigned frees = 0; @@ -357,4 +506,45 @@ void test_shutdown_during_handle_creation() { ASSERT_EQ(frees, 1u); } +// The trampoline must complete once even when it cannot start the application callback. +void test_foreign_callback_after_shutdown() { + struct CompletionRecord { + unsigned calls = 0; + std::int8_t status = -1; + } record; + auto complete = +[](std::uint64_t data, UniffiForeignFutureResultVoid result) { + auto &received = *reinterpret_cast(data); + ++received.calls; + received.status = result.call_status.code; + }; + using Trampoline = async_calls::uniffi::UniffiCallbackInterfaceTestParser; + const auto handle = async_calls::uniffi::FfiConverterTestParser::lower(std::make_shared()); + UniffiForeignFutureDroppedCallbackStruct drop{}; + Trampoline::wait(handle, reinterpret_cast(complete), reinterpret_cast(&record), drop); + ASSERT_EQ(record.calls, 1u); + ASSERT_EQ(record.status, cancelled); + ASSERT_NE(drop.free, nullptr); + reinterpret_cast(drop.free)(drop.handle); + ASSERT_EQ(record.calls, 1u); + Trampoline::uniffi_free(handle); +} + +// A delayed callback startup stays rejected if its state was rejected or cancelled before restart. +void test_foreign_states_across_restart() { + using State = async_calls::uniffi::ForeignFutureTaskState; + auto rejected = std::make_shared(); + rejected->start(rejected); + uniffi::start_async_executor(); + ASSERT_FALSE(rejected->can_start()); + + auto previous = std::make_shared(); + previous->start(previous); + ASSERT_TRUE(previous->can_start()); + uniffi::shutdown_async_executor(); + uniffi::start_async_executor(); + ASSERT_FALSE(previous->can_start()); + ASSERT_FALSE(previous->finish()); + uniffi::shutdown_async_executor(); +} + } // namespace executor_tests diff --git a/cpp-tests/tests/async_executor/main.cpp b/cpp-tests/tests/async_executor/main.cpp index 2f9cecc..7043187 100644 --- a/cpp-tests/tests/async_executor/main.cpp +++ b/cpp-tests/tests/async_executor/main.cpp @@ -16,6 +16,33 @@ void wait_for_queued_work(AsyncExecutor &executor) { wait_for_future(barrier); } +// Generated components share the singleton and deliver ready continuations on its worker. +void test_singleton_across_components() { + auto &executor = async_executor(); + ASSERT_EQ(&executor, &executor_from_peer()); + + auto worker_id = std::make_shared>(); + auto observed_worker = worker_id->get_future(); + ASSERT_TRUE(executor_from_peer().enqueue([worker_id] { + ASSERT_TRUE(async_executor().is_worker()); + worker_id->set_value(std::this_thread::get_id()); + })); + const auto worker = wait_for_future(observed_worker); + ASSERT_NE(worker, std::this_thread::get_id()); + + // Exercise then() both after a result is ready and while a result is pending (below). + auto future = futures::always_ready(); + ASSERT_EQ(future.wait_for(test_timeout), std::future_status::ready); + auto delivered = std::make_shared>(); + auto result = delivered->get_future(); + auto continuation = std::move(future).then([worker, delivered](auto completed) { + ASSERT_EQ(std::this_thread::get_id(), worker); + ASSERT_TRUE(std::move(completed).get()); + delivered->set_value(); + }); + wait_for_future(result); +} + // Two Rust streams receive independently, with bounded buffering and clean end-of-stream. void test_interleaved_stream_reads() { const auto first = wait_for_future(async_calls::SampleStream::open()); @@ -215,12 +242,37 @@ void test_singleton_shutdown() { uniffi::shutdown_async_executor(); } +class RestartParser final : public async_calls::TestParserForeign { + public: + uniffi::ForeignFuture stringify(std::int32_t value) override { + return uniffi::ForeignFuture([value](auto success, auto) { + success(std::to_string(value)); + return nullptr; + }); + } + uniffi::ForeignFuture parse(const std::string &) override { return {}; } + uniffi::ForeignFuture wait() override { return {}; } +}; + +// After explicit restart, the singleton can poll Rust and deliver an async C++ callback. +void test_singleton_restart() { + uniffi::start_async_executor(); + uniffi::start_async_executor(); + ASSERT_TRUE(wait_for_future(futures::always_ready())); + ASSERT_EQ(wait_for_future(async_calls::stringify_using_parser(std::make_shared(), 42)), + "42"); + uniffi::shutdown_async_executor(); + EXPECT_EXCEPTION(wait_for_future(futures::always_ready()), uniffi::AsyncExecutorError); +} + } // namespace } // namespace executor_tests int main() { using namespace executor_tests; + test_singleton_across_components(); test_rust_future_lifecycle(); + test_foreign_callback_lifecycle(); test_pending_future(); test_interleaved_stream_reads(); test_cancel_pending_read(); @@ -230,4 +282,7 @@ int main() { test_detached_continuation(); test_future_move_assignment(); test_singleton_shutdown(); + test_foreign_callback_after_shutdown(); + test_foreign_states_across_restart(); + test_singleton_restart(); } diff --git a/cpp-tests/tests/async_executor/peer.cpp b/cpp-tests/tests/async_executor/peer.cpp new file mode 100644 index 0000000..ce7b547 --- /dev/null +++ b/cpp-tests/tests/async_executor/peer.cpp @@ -0,0 +1,9 @@ +#include "futures.hpp" + +namespace executor_tests { + +uniffi::detail::AsyncExecutor &executor_from_peer() { + return uniffi::detail::async_executor(); +} + +} // namespace executor_tests diff --git a/cpp-tests/tests/async_executor/test_support.hpp b/cpp-tests/tests/async_executor/test_support.hpp index 24d781a..2267778 100644 --- a/cpp-tests/tests/async_executor/test_support.hpp +++ b/cpp-tests/tests/async_executor/test_support.hpp @@ -1,11 +1,17 @@ #pragma once #include "async_calls.hpp" +#include "futures.hpp" #include "async_test_support.hpp" namespace executor_tests { +uniffi::detail::AsyncExecutor &executor_from_peer(); void test_rust_future_lifecycle(); void test_shutdown_during_handle_creation(); +void test_foreign_callback_lifecycle(); +void test_foreign_callback_after_shutdown(); +void test_foreign_states_across_restart(); + } // namespace executor_tests diff --git a/cpp-tests/tests/futures/main.cpp b/cpp-tests/tests/futures/main.cpp new file mode 100644 index 0000000..8a07dc0 --- /dev/null +++ b/cpp-tests/tests/futures/main.cpp @@ -0,0 +1,322 @@ +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__APPLE__) +#include +#elif defined(__linux__) +#include +#endif + +// Measure actual process threads as well as checking which thread executes callbacks. +std::optional thread_count() { +#if defined(__APPLE__) + thread_act_array_t threads; + mach_msg_type_number_t count; + if (task_threads(mach_task_self(), &threads, &count) != KERN_SUCCESS) { + return {}; + } + for (mach_msg_type_number_t i = 0; i < count; ++i) { + mach_port_deallocate(mach_task_self(), threads[i]); + } + vm_deallocate(mach_task_self(), reinterpret_cast(threads), + count * sizeof(thread_t)); + return count; +#elif defined(__linux__) + size_t count = 0; + for (const auto &entry : std::filesystem::directory_iterator("/proc/self/task")) { + static_cast(entry); + ++count; + } + return count; +#else + return {}; +#endif +} + +using namespace std::chrono_literals; +using executor_tests::wait_for_future; + +template void eventually(Predicate predicate) { + const auto deadline = std::chrono::steady_clock::now() + 10s; + while (!predicate()) { + ASSERT_TRUE(std::chrono::steady_clock::now() < deadline); + std::this_thread::sleep_for(1ms); + } +} + +class TestAsyncParser final : public async_calls::TestParserForeign { + public: + TestAsyncParser(std::shared_ptr> started_count, + std::shared_ptr> cancellation_count, + std::shared_ptr> destruction_count) + : started_count_(std::move(started_count)), + cancellation_count_(std::move(cancellation_count)), + destruction_count_(std::move(destruction_count)) {} + + ~TestAsyncParser() override { destruction_count_->fetch_add(1); } + + uniffi::ForeignFuture stringify(int32_t value) override { + ASSERT_TRUE(::uniffi::detail::async_executor().is_worker()); + return uniffi::ForeignFuture([value](auto success, auto failure) { + success(std::to_string(value)); + // Only the first completion should reach Rust. + success("duplicate"); + failure(std::make_exception_ptr(std::runtime_error("duplicate failure"))); + return [] {}; + }); + } + + uniffi::ForeignFuture parse(const std::string &value) override { + if (value == "throw") { + throw std::runtime_error("C++ callback method threw"); + } + if (value == "empty") { + return {}; + } + return uniffi::ForeignFuture([value](auto success, auto failure) { + if (value == "unexpected") { + failure(std::make_exception_ptr(std::runtime_error("C++ callback failed"))); + } else { + try { + success(std::stoi(value)); + } catch (...) { + failure(std::make_exception_ptr( + async_calls::async_parser_error::InvalidInteger("invalid integer"))); + } + } + return [] {}; + }); + } + + uniffi::ForeignFuture wait() override { + auto started_count = started_count_; + auto cancellation_count = cancellation_count_; + return uniffi::ForeignFuture([started_count, cancellation_count](auto, auto) { + started_count->fetch_add(1); + return [cancellation_count] { cancellation_count->fetch_add(1); }; + }); + } + + private: + std::shared_ptr> started_count_; + std::shared_ptr> cancellation_count_; + std::shared_ptr> destruction_count_; +}; + +class TestGreeter final : public async_calls::AsyncGreeter { + public: + uniffi::ForeignFuture greeting() override { + return uniffi::ForeignFuture([](auto success, auto) { + success("Hello from a C++ callback!"); + return nullptr; + }); + } +}; + +int main() { + ASSERT_EQ("Hello, C++", futures::greet("C++")); + ASSERT_TRUE(futures::always_ready().get()); + futures::void_().get(); + ASSERT_EQ("Hello, Future!", futures::say().get()); + ASSERT_EQ("Hello, Future!", futures::say_after(1, "Future").get()); + ASSERT_TRUE(futures::sleep(1).get()); + futures::sleep_no_return(1).get(); + + auto waitable = futures::say_after(1, "Wait"); + waitable.wait(); + ASSERT_EQ("Hello, Wait!", waitable.get()); + + for (auto i = 0; i < 100; ++i) { + auto racing = futures::say_after(1, "Race"); + if (i % 2 == 0) { + std::this_thread::sleep_for(1ms); + } + racing.cancel(); + try { + ASSERT_EQ("Hello, Race!", racing.get()); + } catch (const uniffi::AsyncCancelledError &) { + } + } + + ASSERT_EQ(42, futures::fallible_me(false).get()); + EXPECT_EXCEPTION(futures::fallible_me(true).get(), futures::my_error::Foo); + + auto megaphone = futures::new_megaphone(); + ASSERT_EQ("HELLO, WORLD!", megaphone->say_after(1, "World").get()); + ASSERT_EQ("", megaphone->silence().get()); + ASSERT_EQ(42, megaphone->fallible_me(false).get()); + EXPECT_EXCEPTION(megaphone->fallible_me(true).get(), futures::my_error::Foo); + + ASSERT_TRUE(futures::fallible_struct(false).get() != nullptr); + EXPECT_EXCEPTION(futures::fallible_struct(true).get(), futures::my_error::Foo); + ASSERT_TRUE(futures::async_new_megaphone().get() != nullptr); + ASSERT_TRUE(futures::async_maybe_new_megaphone(true).get() != nullptr); + ASSERT_TRUE(futures::async_maybe_new_megaphone(false).get() == nullptr); + ASSERT_EQ("HELLO, FRIEND!", futures::say_after_with_megaphone(megaphone, 1, "Friend").get()); + + ASSERT_TRUE(futures::Megaphone::init().get() != nullptr); + ASSERT_TRUE(futures::Megaphone::secondary().get() != nullptr); + EXPECT_EXCEPTION(futures::FallibleMegaphone::init().get(), futures::my_error::Foo); + + auto udl_megaphone = futures::UdlMegaphone::init().get(); + ASSERT_EQ("HELLO, UDL!", udl_megaphone->say_after(1, "Udl").get()); + ASSERT_TRUE(futures::UdlMegaphone::secondary().get() != nullptr); + + auto record = futures::new_my_record("value", 42).get(); + ASSERT_EQ("value", record.a); + ASSERT_EQ(42, record.b); + + for (const auto &trait : futures::get_say_after_traits()) { + ASSERT_EQ(trait->say_after(1, "Trait").get(), "Hello, Trait!"); + } + for (const auto &trait : futures::get_say_after_udl_traits()) { + ASSERT_EQ(trait->say_after(1, "UDL trait").get(), "Hello, UDL trait!"); + } + + auto holding = futures::use_shared_resource({2000, 4000}); + EXPECT_EXCEPTION(futures::use_shared_resource({0, 250}).get(), futures::async_error::Timeout); + holding.get(); + + auto started_count = std::make_shared>(0); + auto cancellation_count = std::make_shared>(0); + auto destruction_count = std::make_shared>(0); + auto parser = + std::make_shared(started_count, cancellation_count, destruction_count); + ASSERT_EQ("42", async_calls::stringify_using_parser(parser, 42).get()); + ASSERT_EQ("43", async_calls::stringify_on_tokio(parser, 43).get()); + const auto rust_parser = + std::dynamic_pointer_cast(async_calls::rust_async_parser()); + ASSERT_TRUE(rust_parser); + ASSERT_EQ(rust_parser->stringify(44).get(), "44"); + ASSERT_EQ(rust_parser->parse("45").get(), 45); + EXPECT_EXCEPTION(rust_parser->parse("bad input").get(), + async_calls::async_parser_error::InvalidInteger); + ASSERT_EQ(42, async_calls::parse_using_parser(parser, "42").get()); + EXPECT_EXCEPTION(async_calls::parse_using_parser(parser, "not an integer").get(), + async_calls::async_parser_error::InvalidInteger); + for (const auto *input : {"unexpected", "throw", "empty"}) { + EXPECT_EXCEPTION(async_calls::parse_using_parser(parser, input).get(), + async_calls::async_parser_error::Unexpected); + } + ASSERT_EQ(async_calls::greet_with(std::make_shared()).get(), + "Hello from a C++ callback!"); + + { + auto waiting = async_calls::wait_using_parser(parser); + eventually([&] { return started_count->load() != 0; }); + ASSERT_EQ(1, started_count->load()); + parser.reset(); + ASSERT_EQ(0, destruction_count->load()); + waiting.cancel(); + EXPECT_EXCEPTION(waiting.get(), uniffi::AsyncCancelledError); + } + eventually([&] { return cancellation_count->load() != 0 && destruction_count->load() != 0; }); + ASSERT_EQ(1, cancellation_count->load()); + ASSERT_EQ(1, destruction_count->load()); + + auto continuation_result = std::make_shared>(); + auto continuation = std::move(futures::say_after(1, "Continuation")) + .then([continuation_result](uniffi::FutureResult result) { + try { + continuation_result->set_value(std::move(result).get()); + } catch (...) { + continuation_result->set_exception(std::current_exception()); + } + }); + ASSERT_EQ("Hello, Continuation!", wait_for_future(continuation_result->get_future())); + // Thousands of parked Rust futures must not consume thousands of C++ threads. + const auto threads_before = thread_count(); + std::vector> parked; + for (int i = 0; i < 2000; ++i) { + parked.push_back(async_calls::pending()); + } + const auto parked_deadline = std::chrono::steady_clock::now() + 5s; + while (async_calls::pending_count() != 2000) { + ASSERT_TRUE(std::chrono::steady_clock::now() < parked_deadline); + std::this_thread::yield(); + } + if (auto threads_parked = thread_count(); threads_before && threads_parked) { + ASSERT_TRUE(*threads_parked <= *threads_before + 1); + } + for (auto &future : parked) { + future.cancel(); + } + for (auto &future : parked) { + EXPECT_EXCEPTION(future.get(), uniffi::AsyncCancelledError); + } + ASSERT_EQ(0, async_calls::pending_count()); + + // A continuation runs on the shared executor and cannot block it waiting on another call. + auto callback_done = std::make_shared>(); + auto nested = std::move(futures::always_ready()).then([callback_done](auto result) { + ASSERT_TRUE(uniffi::detail::async_executor().is_worker()); + ASSERT_TRUE(std::move(result).get()); + auto inner = async_calls::pending(); + EXPECT_EXCEPTION(inner.get(), std::logic_error); + EXPECT_EXCEPTION(inner.wait(), std::logic_error); + EXPECT_EXCEPTION(inner.wait_for(1ms), std::logic_error); + ASSERT_EQ(inner.wait_for(0ms), std::future_status::timeout); + EXPECT_EXCEPTION(uniffi::shutdown_async_executor(), std::logic_error); + callback_done->set_value(); + }); + ASSERT_EQ(std::future_status::ready, callback_done->get_future().wait_for(5s)); + + // Bound the producer work. The executor tests gate individual shutdown orderings. + std::atomic stop_producers{false}; + std::atomic produced{0}; + std::vector producers; + for (int i = 0; i < 4; ++i) { + producers.emplace_back([&] { + for (int call = 0; call < 16 && !stop_producers.load(); ++call) { + try { + ASSERT_TRUE(futures::always_ready().get()); + ++produced; + } catch (const uniffi::AsyncExecutorError &) { + return; + } catch (const uniffi::AsyncCancelledError &) { + // Shutdown also cancels calls accepted immediately before it. + } + std::this_thread::sleep_for(1ms); + } + }); + } + const auto producers_deadline = std::chrono::steady_clock::now() + 5s; + while (produced.load() < 20) { + ASSERT_TRUE(std::chrono::steady_clock::now() < producers_deadline); + std::this_thread::sleep_for(1ms); + } + auto late_continuation = futures::always_ready(); + late_continuation.wait(); + auto shutdown_pending = async_calls::pending(); + const auto callbacks_started = started_count->load(); + const auto callbacks_cancelled = cancellation_count->load(); + auto shutdown_foreign = async_calls::wait_using_parser( + std::make_shared(started_count, cancellation_count, destruction_count)); + eventually([&] { return started_count->load() > callbacks_started; }); + uniffi::shutdown_async_executor(); + stop_producers.store(true); + for (auto &producer : producers) { + producer.join(); + } + EXPECT_EXCEPTION(static_cast(std::move(late_continuation).then([](auto) {})), + uniffi::AsyncExecutorError); + ASSERT_TRUE(late_continuation.get()); + uniffi::shutdown_async_executor(); // Idempotent. + EXPECT_EXCEPTION(wait_for_future(shutdown_pending), uniffi::AsyncCancelledError); + EXPECT_EXCEPTION(wait_for_future(shutdown_foreign), uniffi::AsyncCancelledError); + ASSERT_EQ(cancellation_count->load(), callbacks_cancelled + 1); + EXPECT_EXCEPTION(futures::always_ready().get(), uniffi::AsyncExecutorError); + + return 0; +} diff --git a/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md new file mode 100644 index 0000000..c0c80be --- /dev/null +++ b/docs/ASYNC_RUNTIME.md @@ -0,0 +1,310 @@ +# Async Runtime + +## Overview + +UniFFI uses the foreign bindings' runtime to schedule Rust future polls and completions. C++ has +no default async runtime for this work. The generated bindings provide a shared +[`AsyncExecutor`](../bindgen/src/bindings/cpp/templates/async.hpp) for async Rust exports and +C++ callback methods that Rust awaits. + +- **One worker thread.** Generated components in each linked executable or shared library share a + worker and a FIFO queue. [Executor][executor] +- **UniFFI Rust future calls.** The wrapper obtains the future handle and normally calls + `rust_future_poll` on the calling thread. If that poll reports `READY`, the wrapper calls + `rust_future_complete` and `rust_future_free` there before returning `Future`. The worker + polls deferred calls, repolls on `WAKE`, calls `rust_future_cancel` to cancel, and completes and + frees the remaining handles. [First poll][state-start] · [UniFFI handle rules][rust-handle-rules] +- **Pending calls and continuations.** The worker can run other tasks while a future waits for a + wake. C++ continuations run on the worker, so keep them short and do blocking waits on + application threads. [Continuation delivery][completion] · [Wait guard][wait-guard] +- **Async C++ callbacks.** When Rust awaits a C++ `ForeignFuture`, the worker starts the + callback and delivers its result or handles cancellation. [Callback bridge][callback-results] +- **Shutdown and restart.** Call `shutdown_async_executor()` from an application thread to wait + for caller-thread first polls, close admission, cancel outstanding work, drain the queue, and + join the worker. Call `start_async_executor()` to reopen admission. + [Shutdown][shutdown] · [Restart][restart] + +The sequence adapts the [UniFFI Async Overview][upstream-sequence] to the C++ executor. + +```mermaid +sequenceDiagram + participant C as C++ caller + participant B as Generated C++ binding + participant E as AsyncExecutor + participant R as Rust scaffolding + + C->>B: call async function + B->>R: call scaffolding function + R-->>B: return RustFuture handle + B->>B: Register RustFutureState with the executor + alt Caller-thread first poll admitted + B->>R: rust_future_poll(handle, continuation, state) + alt READY on the first poll + R->>B: continuation(state, READY) + R-->>B: Return from poll + B->>R: rust_future_complete(handle, &status) + R-->>B: Lowered result and RustCallStatus + B->>B: Check status and lift value + B->>R: rust_future_free(handle) + B->>B: Publish result and untrack the call + else Pending on the first poll + Note over B,R: WAKE may arrive during or after the poll + R-->>B: Return from poll + end + else Shutdown is waiting for caller-thread polls + B->>E: Queue the first poll + end + B-->>C: Return Future + + opt Call is pending or its first poll was queued + opt Pending after a caller-thread poll + R->>B: continuation(state, WAKE) + B->>E: Schedule the driver after the first poll returns + end + loop One outstanding poll until READY + E->>R: rust_future_poll(handle, continuation, state) + alt WAKE + Note over E: The worker can run other tasks while the future waits + R->>B: continuation(state, WAKE) + B->>E: Request another poll + else READY + R->>B: continuation(state, READY) + B->>B: Record readiness + end + end + E->>R: rust_future_complete(handle, &status) + R-->>E: Lowered result and RustCallStatus + E->>E: Check status and lift value + E->>R: rust_future_free(handle) + E->>B: Publish to FutureCompletionState + E->>E: Untrack the call + end + Note over C,E: get() reads the result or throws
then() delivers on the worker +``` + +## Execution model + +The `async_executor()` singleton creates a joinable worker on first use. The worker takes short +tasks from a FIFO queue and sleeps on a condition variable when the queue is empty. The caller +normally runs the first poll before the wrapper returns. Rust code through its first suspension +or completion, including synchronous C++ callbacks it invokes, blocks the calling thread. +Pending Rust futures retain their state and wake callback. Each worker turn runs at most 64 +driver actions before yielding to the queue. [Executor][executor] · [First poll][state-start] · +[Driver][drive] + +```mermaid +flowchart LR + A[Application thread] -->|First poll, complete and free if ready| R[Rust scaffolding] + A -->|Publish ready result| F[C++ future] + A -->|Queue first poll during shutdown wait| Q[Control queue] + Q --> W[One C++ worker] + W -->|Poll, cancel or finish| R + R -->|Wake callback| Q + W -->|Publish result| F + W -->|Deliver| T[C++ continuation] +``` + +A move-only `Future` supports `wait()`, `wait_for()`, `get()`, `cancel()`, and a consuming +`then()`. `get()` returns the lifted value or rethrows the stored exception. `then()` transfers +cancellation ownership to its return value, a `FutureContinuation`, and delivers the result on +the worker. Hold that token until delivery or cancel it to request cancellation. Only application +threads may block on an incomplete call. The worker can inspect readiness or consume a ready result. +[Future API][future] · [Completion state][completion] · [Worker wait guard][wait-guard] + +Access each `Future` or `FutureContinuation` from one thread at a time. Before calling `get()` +or `then()`, use `cancel_handle()` to obtain a copyable `FutureCancelHandle` for a different thread. +The handle can request cancellation while `get()` waits or after `then()` takes ownership. Its +weak reference keeps cancellation harmless after completion. [Cancel handle][cancel-handle] · +[Rust cancellation state][state-start] + +## C++ calls an async Rust export + +The generator uses the same driver for free functions, primary and secondary constructors, and +methods on objects, records, and enums. The wrapper checks the Rust contract version and checksums, +lowers the arguments, and calls the start symbol to obtain a `uint64_t` Rust future handle. The +generator selects poll, cancel, complete, and free symbols from UniFFI metadata for the lowered +result type. It also selects the value and error conversions, including the `void` case. An admitted +object method passes a cloned receiver handle. A record or enum method lowers its receiver by value +inside the start call. Rust owns the lifted receiver across polls and writes `RustCallStatus` through +an out pointer on completion. [Function template][function] · [Object template][object] · +[Value methods][value-methods] · [Flat enum methods][flat-enum-methods] · +[Async call macros][macros] · [Initialization][init] · [Rust scaffolding][tokio] + +- **Create a handle and poll with a callback and opaque data.** `rust_call_async` gives the acquired + handle to a scope guard. `start()` registers shared ownership of `RustFutureState` with the + executor. `run_inline()` normally calls `poll_first_turn()` before the wrapper returns + `Future`. While shutdown waits for caller-thread polls, `start()` queues the first poll on + the worker. The poll passes the state's address as callback data, and the callback takes a + strong reference to the state on entry. + [Handle guard][handle-guard] · [Start and callback lifetime][state-start] · [Poll][poll] +- **Poll again on `WAKE` and complete on `READY`.** The callback clears `poll_outstanding_` and + records `poll_requested_` for `WAKE` (`1`) or `ready_` for `READY` (`0`) under the state mutex. + `start()` sets `poll_outstanding_` for a caller-thread poll. `next_action()` sets it for worker + polls and admits another poll only after the callback. Rust guarantees one callback per poll, + which can arrive from another thread. + [C++ state transitions][continuation] · [Rust poll guarantee][rust-poll] +- **Complete once and stop polling.** `poll_first_turn()` and `next_action()` give `READY` priority + and set `terminal_` before completion. That flag closes the driver, callback, and cancellation + paths. Completion checks `RustCallStatus` and lifts the value on success. A ready first poll + completes on the caller. The worker completes pending and deferred calls. + [First poll][state-start] · [Action selection][next-action] · [Result conversion][finish] · + [Status handling][status] +- **Free the handle as the last FFI operation.** The driver frees the handle, publishes the result, + then removes the registry entry. Status, lifting, and result-transfer failures are stored as + exceptions for the caller. The scope guard owns the handle until registration succeeds. It + frees the handle if registration fails, including when admission closes during handle creation. + The wrapper arms `Future` cancellation after successful registration. + [Completion and free][finish] · [Guard and handoff][call-async] · [Admission race][state-start] +- **Serialize optional cancellation with the rest of the lifecycle.** `cancel()` and token + destruction request work on the driver. It sends at most one `rust_future_cancel`. After the + driver sets `terminal_`, only completion and free can touch the handle. + [Action selection][next-action] · [Cancellation FFI call][cancel] · + [Rust handle rules][rust-handle-rules] + +Wake-ups also work when Rust invokes the callback inline during `poll`. `scheduled_` and `driving_` +coalesce driver requests. The driver rechecks the flags under the mutex before parking, covering a +callback that arrives as the driver is about to yield. FFI calls run with the state mutex released, +so inline callbacks can acquire it and return. [Driver scheduling and parking][drive] + +Cancellation with a poll outstanding produces `READY` from the Rust scheduler. If cancellation +arrives before a callback is installed, the worker polls the cancelled handle to get `READY`. +`complete` consumes any result already produced by Rust. If Rust has no result, it reports +`Cancelled` and drops the pending future. The C++ wrapper maps that status to `AsyncCancelledError` +and runs the same cleanup path. This preserves results that win the cancellation race. +[C++ cancel path][cancel] · [Rust scheduler][rust-scheduler] · [Rust completion][rust-complete] + +## Rust awaits an async C++ callback + +A generated async callback method returns a move-only `ForeignFuture` on the C++ side. Its start +function accepts success and failure callbacks and returns an optional cancellation action. In the +FFI vtable, the method returns `void` and accepts a completion function, its original `uint64_t` +context, and an output slot for the drop callback. The trampoline fills the drop slot, lifts the +arguments, and queues startup. Application code can arrange blocking work on an application +worker and invoke the supplied success or failure callback from any thread. +[C++ callback surface][callback-api] · +[Vtable trampoline][callback-entry] · [Upstream async API client][api-client] + +```mermaid +sequenceDiagram + participant R as Rust future + participant B as C++ callback bridge + participant E as Control worker + participant A as C++ implementation + R->>B: Call vtable with completion and context + B-->>R: Write drop callback and task handle + B->>E: Queue startup + E->>A: Start ForeignFuture + A-->>E: Return cancellation action + alt Application resolves or fails + A->>E: Queue completion + else Rust drops the future + R->>B: Invoke drop callback + B->>E: Release handle and queue cancellation + end + E->>R: Complete once with original context and status +``` + +The `finished_` gate in `ForeignFutureTaskState` is shared by success, error, and cancellation. +The first terminal action takes that gate. Success lowers a value into the metadata-defined result +structure. Failure sends a declared UniFFI error or an unexpected exception message, including +exceptions from moving a value into the queue or lowering it. A `void` completion carries just the +status. The completion function consumes Rust's one-shot sender using the original context. These +paths run on the control worker for an active executor, even when an application worker supplies +the result. [Completion lowering and queueing][callback-results] · +[Terminal gate][foreign-state] · [Rust receiver and completion callback][rust-foreign] + +The drop slot owns a separate handle to the C++ task state. The state retains the callback object +through the registered cancel action, and moves that action out of its mutex before running or +releasing it. If cancellation takes the terminal gate, the drop path requests application +cancellation and sends a cancelled completion to release Rust's sender. If completion took the +gate, a later drop just releases the C++ handle. +[Startup and retained callback object][callback-results] · +[Drop callback and cancellation][foreign-drop] · [UniFFI foreign handle contract][foreign-rules] + +## Shutdown + +Stop producers before calling `shutdown_async_executor()` from an application thread. The executor +first waits for caller-thread first polls to finish with admission open. Calls that start during +that wait queue their first poll on the worker. A blocked first poll delays shutdown. After the +caller-thread polls finish, the executor closes admission, requests cancellation for registered +calls, drains the queue and in-flight work, and joins the worker. Continuation delivery retains its +own registration until its callback is released. Keep control callbacks short so other calls and +shutdown can make progress. +[Drain and join][shutdown] · [Continuation registration][registration] + +Once admission closes, the driver sends cancellation before polling a pending Rust future. +This covers a C++ callback that reports shutdown before the executor reaches the outer Rust +call's registered cancellation. The driver still completes a future that has already signaled +`READY`. [Action selection][next-action] + +New C++ calls to async Rust exports receive `AsyncExecutorError` until an application thread calls +`start_async_executor()`. Start waits for any concurrent shutdown to finish joining the worker, +then opens admission. Calling start on a running executor is harmless. Operation IDs continue +increasing across restarts. The callback trampoline checks admission and its own state before it +starts work, so rejected or retired callbacks stay inactive after restart. [Restart][restart] · +[Callback bridge][callback-results] + +On the worker or inside a caller-thread first poll, `shutdown_async_executor()` throws +`std::logic_error` and `start_async_executor()` returns immediately. +[Shutdown guard][shutdown] · [Start guard][restart] + +The singleton has process lifetime. Returning from `main` or calling `std::exit` leaves pending +work and its Rust handles to process teardown. Python, Kotlin, and TypeScript UniFFI bindings +likewise rely on their host runtimes for process exit. Use explicit shutdown before unloading +the generated bindings or the Rust library. [Singleton lifetime][executor] + +### Rust-owned tasks during shutdown + +A task driven by a Rust runtime can still be awaiting a C++ callback when shutdown cancels it or +rejects its startup. A callback that Rust invokes while the executor is stopped is rejected the +same way. The bridge completes the callback with status code 3 and an empty error buffer. +UniFFI lifts that status through the same branch as code 2, creating an +`UnexpectedUniFFICallbackError`. [Callback cancellation status][callback-entry] · +[UniFFI status handling][rust-foreign-return] + +To receive this as an `Err` in Rust, declare the trait method with a `Result` return and +implement `From` for `E`. UniFFI panics for an infallible +method or when conversion to the declared error type fails. [Result handling][rust-foreign-result] · +[Error conversion][rust-callback-conversion] + +[upstream-sequence]: https://mozilla.github.io/uniffi-rs/latest/internals/async-overview.html#rust-async-functions +[rust-handle-rules]: https://mozilla.github.io/uniffi-rs/latest/internals/async-ffi.html#managing-the-rustfuture-handle +[foreign-rules]: https://mozilla.github.io/uniffi-rs/latest/internals/async-ffi.html#managing-the-foreignfuture-handle +[api-client]: https://github.com/mozilla/uniffi-rs/tree/05b45b110f652d58d94c653992aeb3adc3a094f4/examples/async-api-client +[tokio]: https://github.com/mozilla/uniffi-rs/blob/05b45b110f652d58d94c653992aeb3adc3a094f4/uniffi_macros/src/export/scaffolding.rs#L271-L299 +[rust-poll]: https://github.com/mozilla/uniffi-rs/blob/05b45b110f652d58d94c653992aeb3adc3a094f4/uniffi_core/src/ffi/rustfuture/mod.rs#L119-L149 +[rust-scheduler]: https://github.com/mozilla/uniffi-rs/blob/05b45b110f652d58d94c653992aeb3adc3a094f4/uniffi_core/src/ffi/rustfuture/scheduler.rs#L80-L84 +[rust-complete]: https://github.com/mozilla/uniffi-rs/blob/05b45b110f652d58d94c653992aeb3adc3a094f4/uniffi_core/src/ffi/rustfuture/future.rs#L162-L179 +[rust-foreign]: https://github.com/mozilla/uniffi-rs/blob/05b45b110f652d58d94c653992aeb3adc3a094f4/uniffi_core/src/ffi/foreignfuture.rs#L67-L99 +[rust-foreign-return]: https://github.com/mozilla/uniffi-rs/blob/05b45b110f652d58d94c653992aeb3adc3a094f4/uniffi_core/src/ffi_converter_traits.rs#L357-L395 +[rust-foreign-result]: https://github.com/mozilla/uniffi-rs/blob/05b45b110f652d58d94c653992aeb3adc3a094f4/uniffi_core/src/ffi_converter_impls.rs#L516-L540 +[rust-callback-conversion]: https://github.com/mozilla/uniffi-rs/blob/05b45b110f652d58d94c653992aeb3adc3a094f4/uniffi_core/src/ffi/callbackinterface.rs#L150-L210 +[executor]: ../bindgen/src/bindings/cpp/templates/async.hpp#L20-L205 +[drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L236-L322 +[future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L457-L588 +[cancel-handle]: ../bindgen/src/bindings/cpp/templates/async.hpp#L435-L453 +[completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L345-L430 +[wait-guard]: ../bindgen/src/bindings/cpp/templates/async.hpp#L219-L223 +[function]: ../bindgen/src/bindings/cpp/templates/fn_def.cpp#L1-L14 +[object]: ../bindgen/src/bindings/cpp/templates/obj.cpp#L32-L72 +[value-methods]: ../bindgen/src/bindings/cpp/templates/value_methods.cpp#L1-L14 +[flat-enum-methods]: ../bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp#L1-L14 +[macros]: ../bindgen/src/bindings/cpp/templates/macros.cpp#L69-L102 +[init]: ../bindgen/src/bindings/cpp/templates/wrapper.cpp#L13-L37 +[handle-guard]: ../bindgen/src/bindings/cpp/templates/async.cpp#L117-L137 +[state-start]: ../bindgen/src/bindings/cpp/templates/async.cpp#L145-L208 +[poll]: ../bindgen/src/bindings/cpp/templates/async.cpp#L324-L328 +[continuation]: ../bindgen/src/bindings/cpp/templates/async.cpp#L210-L234 +[next-action]: ../bindgen/src/bindings/cpp/templates/async.cpp#L253-L275 +[finish]: ../bindgen/src/bindings/cpp/templates/async.cpp#L340-L402 +[status]: ../bindgen/src/bindings/cpp/templates/wrapper.cpp#L40-L66 +[call-async]: ../bindgen/src/bindings/cpp/templates/async.cpp#L410-L445 +[cancel]: ../bindgen/src/bindings/cpp/templates/async.cpp#L330-L338 +[callback-api]: ../bindgen/src/bindings/cpp/templates/callback.hpp#L6-L37 +[callback-entry]: ../bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp#L7-L22 +[callback-results]: ../bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp#L24-L140 +[foreign-state]: ../bindgen/src/bindings/cpp/templates/async.cpp#L7-L102 +[foreign-drop]: ../bindgen/src/bindings/cpp/templates/async.cpp#L70-L113 +[shutdown]: ../bindgen/src/bindings/cpp/templates/async.hpp#L105-L136 +[restart]: ../bindgen/src/bindings/cpp/templates/async.hpp#L89-L101 +[registration]: ../bindgen/src/bindings/cpp/templates/async.hpp#L335-L343 diff --git a/fixtures/Cargo.toml b/fixtures/Cargo.toml index a18f32e..e5a44d6 100644 --- a/fixtures/Cargo.toml +++ b/fixtures/Cargo.toml @@ -8,6 +8,7 @@ crate-type = ["cdylib", "lib", "staticlib"] [dependencies] uniffi-example-arithmetic = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } +uniffi-example-async-api-client = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } uniffi-example-callbacks = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } uniffi-example-custom-types = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } uniffi-example-geometry = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } @@ -18,6 +19,7 @@ uniffi-example-traits = { git = "https://github.com/mozilla/uniffi-rs.git", tag uniffi-fixture-callbacks = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } uniffi-fixture-coverall = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } uniffi-fixture-docstring = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } +uniffi-fixture-futures = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } uniffi-fixture-time = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } uniffi-fixture-trait-methods = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } diff --git a/fixtures/async-calls/Cargo.toml b/fixtures/async-calls/Cargo.toml index b25027b..2fd32ed 100644 --- a/fixtures/async-calls/Cargo.toml +++ b/fixtures/async-calls/Cargo.toml @@ -10,6 +10,7 @@ name = "uniffi_fixture_async_calls" crate-type = ["lib"] [dependencies] +async-trait = "0.1" futures-timer = "3.0" thiserror = "1.0" tokio = { version = "1.24.1", features = ["rt", "sync"] } diff --git a/fixtures/async-calls/README.md b/fixtures/async-calls/README.md index 582a990..ddf9354 100644 --- a/fixtures/async-calls/README.md +++ b/fixtures/async-calls/README.md @@ -1,4 +1,9 @@ # Async calls fixture -The fixture exercises generated C++ bindings with parked futures, Tokio stream reads, -async constructors, record methods, and typed errors from enum methods. +This fixture supplements the upstream futures tests with parked futures, Tokio +stream reads, async constructors, value receivers, and async callback lifecycle +cases. + +The fixture originated in the MPL-2.0-licensed +[`async-calls` fixture](https://github.com/jhugman/uniffi-bindgen-react-native/tree/main/fixtures/async-calls) +in `uniffi-bindgen-react-native`. diff --git a/fixtures/async-calls/src/lib.rs b/fixtures/async-calls/src/lib.rs index 2797648..d4ff9ff 100644 --- a/fixtures/async-calls/src/lib.rs +++ b/fixtures/async-calls/src/lib.rs @@ -4,6 +4,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use async_trait::async_trait; use futures_timer::Delay; use std::{ sync::{ @@ -129,4 +130,86 @@ impl ValidationMode { } } +#[derive(Debug, thiserror::Error, uniffi::Error)] +pub enum AsyncParserError { + #[error("invalid integer")] + InvalidInteger, + #[error("unexpected callback error")] + Unexpected, +} + +impl From for AsyncParserError { + fn from(_: uniffi::UnexpectedUniFFICallbackError) -> Self { + Self::Unexpected + } +} + +#[uniffi::export(with_foreign)] +#[async_trait::async_trait] +pub trait TestParser: Send + Sync { + async fn stringify(&self, value: i32) -> String; + async fn parse(&self, value: String) -> Result; + async fn wait(&self); +} + +#[uniffi::export] +pub async fn stringify_using_parser(parser: Arc, value: i32) -> String { + parser.stringify(value).await +} + +#[uniffi::export] +pub async fn parse_using_parser( + parser: Arc, + value: String, +) -> Result { + parser.parse(value).await +} + +#[uniffi::export] +pub async fn wait_using_parser(parser: Arc) { + parser.wait().await +} + +#[uniffi::export(async_runtime = "tokio")] +pub async fn stringify_on_tokio(parser: Arc, value: i32) -> String { + let parent = std::thread::current().id(); + tokio::spawn(async move { + assert_ne!(std::thread::current().id(), parent); + parser.stringify(value).await + }) + .await + .expect("async parser task failed") +} + +struct RustAsyncParser; + +#[async_trait::async_trait] +impl TestParser for RustAsyncParser { + async fn stringify(&self, value: i32) -> String { + value.to_string() + } + + async fn parse(&self, value: String) -> Result { + value.parse().map_err(|_| AsyncParserError::InvalidInteger) + } + + async fn wait(&self) {} +} + +#[uniffi::export] +pub fn rust_async_parser() -> Arc { + Arc::new(RustAsyncParser) +} + +#[uniffi::export(callback_interface)] +#[async_trait::async_trait] +pub trait AsyncGreeter: Send + Sync { + async fn greeting(&self) -> String; +} + +#[uniffi::export] +pub async fn greet_with(greeter: Box) -> String { + greeter.greeting().await +} + uniffi::setup_scaffolding!("async_calls"); diff --git a/fixtures/src/lib.rs b/fixtures/src/lib.rs index c78f32d..995059b 100644 --- a/fixtures/src/lib.rs +++ b/fixtures/src/lib.rs @@ -1,5 +1,6 @@ mod uniffi_fixtures { arithmetical::uniffi_reexport_scaffolding!(); + uniffi_async_api_client::uniffi_reexport_scaffolding!(); uniffi_callbacks::uniffi_reexport_scaffolding!(); custom_types::uniffi_reexport_scaffolding!(); uniffi_geometry::uniffi_reexport_scaffolding!(); @@ -12,6 +13,7 @@ mod uniffi_fixtures { uniffi_coverall::uniffi_reexport_scaffolding!(); uniffi_fixture_docstring::uniffi_reexport_scaffolding!(); uniffi_fixture_callbacks::uniffi_reexport_scaffolding!(); + uniffi_futures::uniffi_reexport_scaffolding!(); uniffi_cpp_error_types_builtin::uniffi_reexport_scaffolding!(); uniffi_cpp_custom_types_builtin::uniffi_reexport_scaffolding!();