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 d7cc9de..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]] @@ -140,6 +140,30 @@ dependencies = [ "winnow 0.7.13", ] +[[package]] +name = "async-compat" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c97d7ff3c25d6c10d64170c12acaf5d4245e76dece3779c1d92b153a64f11df" +dependencies = [ + "futures-core", + "futures-io", + "once_cell", + "pin-project-lite", + "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" @@ -245,7 +269,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -300,6 +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" @@ -430,6 +548,12 @@ version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + [[package]] name = "plain" version = "0.2.3" @@ -496,7 +620,7 @@ checksum = "7f81c2fde025af7e69b1d1420531c8a8811ca898919db177141a85313b1cb932" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -535,7 +659,7 @@ checksum = "8db53ae22f34573731bafa1db20f04027b2d25e02d8205921b569171699cdb33" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -566,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" @@ -595,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" @@ -644,7 +785,7 @@ checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -655,7 +796,7 @@ checksum = "6c5e1be1c48b9172ee610da68fd9cd2770e7a4056cb3fc98710ee6906f0c7960" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -673,6 +814,15 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "pin-project-lite", +] + [[package]] name = "toml" version = "0.9.12+spec-1.1.0" @@ -757,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", @@ -765,6 +917,17 @@ dependencies = [ "uniffi_pipeline", ] +[[package]] +name = "uniffi-async-calls" +version = "0.21.0" +dependencies = [ + "async-trait", + "futures-timer", + "thiserror 1.0.50", + "tokio", + "uniffi", +] + [[package]] name = "uniffi-bindgen-cpp" version = "0.10.0+v0.31.2" @@ -787,11 +950,13 @@ dependencies = [ name = "uniffi-bindgen-cpp-fixtures" version = "1.0.0" dependencies = [ + "uniffi-async-calls", "uniffi-custom-types-builtin", "uniffi-empty-type", "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", @@ -804,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", @@ -852,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" @@ -958,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" @@ -1033,6 +1224,7 @@ version = "0.31.2" source = "git+https://github.com/mozilla/uniffi-rs.git?tag=v0.31.2#05b45b110f652d58d94c653992aeb3adc3a094f4" dependencies = [ "anyhow", + "async-compat", "bytes", "once_cell", "static_assertions", @@ -1047,7 +1239,7 @@ dependencies = [ "indexmap", "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -1061,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 1aa195a..d8b8d36 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs @@ -143,7 +143,7 @@ impl CppCodeOracle { } pub(crate) fn fn_name(&self, nm: &str) -> String { - nm.to_string().to_snake_case() + self.var_name(nm) } pub(crate) fn var_name(&self, nm: &str) -> String { @@ -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) } @@ -350,6 +355,7 @@ pub(crate) fn ffi_type_name(ffi_type: &FfiType) -> Result { FfiType::VoidPointer => "void *".into(), FfiType::RustBuffer(_) => "RustBuffer".into(), FfiType::ForeignBytes => "ForeignBytes".into(), + FfiType::Callback(name) if name == "RustFutureContinuationCallback" => name.clone(), FfiType::Callback(_) => "void *".into(), FfiType::Struct(name) => ffi_struct_name(name)?, FfiType::RustCallStatus => "RustCallStatus*".into(), @@ -358,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 7a4bc6a..2729691 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/mod.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/mod.rs @@ -118,11 +118,20 @@ impl<'a> ScaffoldingHeader<'a> { .flat_map(|o| o.vtable_definition()), ) .map(Into::into) - .chain( - self.ci - .iter_ffi_function_definitions_non_async() - .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, + }) } } diff --git a/bindgen/src/bindings/cpp/mod.rs b/bindgen/src/bindings/cpp/mod.rs index 7ccd27d..1602a55 100644 --- a/bindgen/src/bindings/cpp/mod.rs +++ b/bindgen/src/bindings/cpp/mod.rs @@ -93,20 +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 ci.has_async_fns() { - eprintln!( - "Warning: omitting unsupported async functions from 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 new file mode 100644 index 0000000..d2bee40 --- /dev/null +++ b/bindgen/src/bindings/cpp/templates/async.cpp @@ -0,0 +1,445 @@ +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 { + public: + RustFutureHandleGuard(uint64_t handle, RustFutureHandleFn free) noexcept + : handle_(handle), free_(free) {} + + RustFutureHandleGuard(const RustFutureHandleGuard &) = delete; + RustFutureHandleGuard &operator=(const RustFutureHandleGuard &) = delete; + + ~RustFutureHandleGuard() { + if (active_) { + free_(handle_); + } + } + + void release() noexcept { active_ = false; } + + private: + uint64_t handle_; + RustFutureHandleFn free_; + bool active_ = true; +}; + +class RustFutureState : public std::enable_shared_from_this { + public: + using Poll = void (*)(uint64_t, RustFutureContinuationCallback, uint64_t); + + virtual ~RustFutureState() = default; + + bool start() { + const auto self = this->shared_from_this(); + auto &executor = ::uniffi::detail::async_executor(); + bool poll_on_caller = false; + { + std::lock_guard guard(mutex_); + operation_id_ = executor.track([self] { self->cancel(); }, &poll_on_caller); + if (!operation_id_) { + return false; + } + // Track the call before polling, and keep ownership if Rust wakes inline. + driving_ = poll_on_caller; + poll_requested_ = !poll_on_caller; + poll_outstanding_ = poll_on_caller; + } + if (poll_on_caller) { + executor.run_inline([this] { poll_first_turn(); }); + } else { + request_drive(); + } + return true; + } + + void cancel() noexcept { + { + std::lock_guard guard(mutex_); + if (terminal_) { + return; + } + cancel_requested_ = true; + } + request_drive(); + } + + protected: + RustFutureState(uint64_t handle, Poll poll, RustFutureHandleFn cancel, RustFutureHandleFn free) + : handle_(handle), poll_(poll), cancel_(cancel), free_(free) {} + + private: + enum class Action { + None, + PollFuture, + CancelFuture, + CompleteFuture, + }; + + void poll_first_turn() noexcept { + poll(); + + bool complete; + bool needs_drive; + { + std::lock_guard guard(mutex_); + complete = ready_; + terminal_ = complete; + needs_drive = cancel_requested_ || poll_requested_; + driving_ = false; + } + if (complete) { + complete_and_free(); + } else if (needs_drive) { + request_drive(); + } + } + + static void continuation(uint64_t callback_data, int8_t poll_result) noexcept { + // The active-operation registry owns the state until READY has been consumed and freed. + auto state = reinterpret_cast(callback_data)->shared_from_this(); + state->on_continuation(poll_result); + } + + void on_continuation(int8_t poll_result) noexcept { + { + std::lock_guard guard(mutex_); + if (terminal_) { + return; + } + poll_outstanding_ = false; + if (poll_result == UNIFFI_RUST_FUTURE_POLL_READY) { + ready_ = true; + } else if (poll_result == UNIFFI_RUST_FUTURE_POLL_WAKE) { + poll_requested_ = true; + } else { + failure_ = std::make_exception_ptr( + std::runtime_error("Unexpected UniFFI Rust future poll result")); + cancel_requested_ = true; + } + } + request_drive(); + } + + void request_drive() noexcept { + std::shared_ptr state; + { + std::lock_guard guard(mutex_); + if (terminal_ || driving_ || scheduled_) { + return; + } + scheduled_ = true; + state = this->shared_from_this(); + } + + if (!::uniffi::detail::enqueue_async([state] { state->drive(); })) { + // Active operations keep the executor alive until their handles have been released. + std::terminate(); + } + } + + Action next_action() noexcept { + std::lock_guard guard(mutex_); + if (terminal_) { + return Action::None; + } + if (ready_) { + terminal_ = true; + return Action::CompleteFuture; + } + const bool can_poll = poll_requested_ && !poll_outstanding_; + // Shutdown closes admission before it runs the registered cancellations. + if (!cancel_sent_ && + (cancel_requested_ || (can_poll && !::uniffi::detail::begin_async_call()))) { + cancel_sent_ = true; + return Action::CancelFuture; + } + if (can_poll) { + poll_requested_ = false; + poll_outstanding_ = true; + return Action::PollFuture; + } + return Action::None; + } + + void drive() noexcept { + { + std::lock_guard guard(mutex_); + scheduled_ = false; + if (terminal_ || driving_) { + return; + } + driving_ = true; + } + + // Bound each turn so a rapidly waking future cannot starve other calls. + for (unsigned turn = 0; turn < 64; ++turn) { + switch (next_action()) { + case Action::PollFuture: + poll(); + break; + case Action::CancelFuture: + cancel_rust_future(); + break; + case Action::CompleteFuture: + complete_and_free(); + { + std::lock_guard guard(mutex_); + driving_ = false; + } + return; + case Action::None: { + std::lock_guard guard(mutex_); + // A continuation can arrive after next_action() releases the mutex but before + // this block acquires it. It observes driving_ and deliberately does not enqueue + // another driver, so re-check the state before yielding ownership. + if (!terminal_ && (ready_ || (cancel_requested_ && !cancel_sent_) || + (poll_requested_ && !poll_outstanding_))) { + continue; + } + driving_ = false; + } + return; + } + } + { + std::lock_guard guard(mutex_); + driving_ = false; + } + request_drive(); + } + + void poll() noexcept { + // UniFFI invokes exactly one continuation per poll. Reuse the state's address instead of + // allocating callback userdata on every wake; the registry retains it until completion. + poll_(handle_, &RustFutureState::continuation, reinterpret_cast(this)); + } + + void cancel_rust_future() noexcept { + cancel_(handle_); + // If cancellation happened before the first poll there is no continuation to wake. Polling + // the cancelled Rust future yields READY immediately and keeps us on the documented path. + std::lock_guard guard(mutex_); + if (!poll_outstanding_ && !ready_) { + poll_requested_ = true; + } + } + + void complete_and_free() noexcept { + // terminal_ was set under the mutex, so no further continuation can change failure_. + complete_result(handle_, free_, failure_); + ::uniffi::detail::async_executor().untrack(operation_id_); + } + + virtual void complete_result(uint64_t handle, RustFutureHandleFn free, + std::exception_ptr protocol_failure) noexcept = 0; + + uint64_t handle_; + uint64_t operation_id_ = 0; + Poll poll_; + RustFutureHandleFn cancel_; + RustFutureHandleFn free_; + std::mutex mutex_; + std::exception_ptr failure_; + bool poll_requested_ = true; + bool poll_outstanding_ = false; + bool cancel_requested_ = false; + bool cancel_sent_ = false; + bool ready_ = false; + bool scheduled_ = false; + bool driving_ = false; + bool terminal_ = false; +}; + +template +class RustFutureResultState final : public RustFutureState { + public: + RustFutureResultState(uint64_t handle, Poll poll, RustFutureHandleFn cancel, + Complete complete, RustFutureHandleFn free, Lift lift, + ErrorHandler error_handler, + std::shared_ptr<::uniffi::detail::FutureCompletionState> completion_state) + : RustFutureState(handle, poll, cancel, free), complete_(std::move(complete)), + lift_(std::move(lift)), error_handler_(std::move(error_handler)), + completion_state_(std::move(completion_state)) {} + + private: + void complete_result(uint64_t handle, RustFutureHandleFn free, + std::exception_ptr protocol_failure) noexcept override { + std::optional<::uniffi::FutureResult> result; + try { + RustCallStatus status{}; + if constexpr (std::is_void_v) { + complete_(handle, &status); + check_rust_call(status, error_handler_); + result.emplace(); + } else { + auto value = complete_(handle, &status); + check_rust_call(status, error_handler_); + result.emplace(lift_(value)); + } + } catch (...) { + result.emplace(std::current_exception()); + } + + free(handle); + + if (protocol_failure) { + result.emplace(std::move(protocol_failure)); + } + completion_state_->complete(std::move(*result)); + } + + Complete complete_; + Lift lift_; + ErrorHandler error_handler_; + std::shared_ptr<::uniffi::detail::FutureCompletionState> completion_state_; +}; + +template +Future rust_call_async(RustFuture rust_future, RustFutureState::Poll poll, + RustFutureHandleFn cancel, Complete complete, RustFutureHandleFn free, + Lift lift, ErrorHandler error_handler) { + initialize(); + auto completion_state = std::make_shared<::uniffi::detail::FutureCompletionState>(); + auto rejected = [&completion_state] { + completion_state->complete( + ::uniffi::FutureResult(std::make_exception_ptr(::uniffi::AsyncExecutorError()))); + return Future(std::move(completion_state), nullptr); + }; + if (!::uniffi::detail::begin_async_call()) { + return rejected(); + } + + const auto handle = rust_future(); + RustFutureHandleGuard handle_guard(handle, free); + using State = RustFutureResultState; + + auto state = + std::make_shared(handle, poll, cancel, std::move(complete), + free, std::move(lift), std::move(error_handler), completion_state); + // Prepare the callback while the guard owns the handle. Arm Future cancellation after start() + // so a registration exception leaves the guard as the only cleanup path. + std::function cancel_future = [weak_state = std::weak_ptr(state)] { + if (auto state = weak_state.lock()) { + state->cancel(); + } + }; + + if (!state->start()) { + return rejected(); + } + handle_guard.release(); + return Future(std::move(completion_state), std::move(cancel_future)); +} diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp new file mode 100644 index 0000000..417ddc0 --- /dev/null +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -0,0 +1,588 @@ +// Reported when UniFFI completes a cancelled Rust future. +class AsyncCancelledError : public std::runtime_error { + public: + AsyncCancelledError() : std::runtime_error("UniFFI async call cancelled") {} +}; + +// Reported when the executor rejects a new Rust call or continuation. +class AsyncExecutorError : public std::runtime_error { + public: + AsyncExecutorError() : std::runtime_error("UniFFI async executor rejected a task") {} +}; + +// Used for queued tasks and registered cancellation actions. +using AsyncTask = std::function; + +namespace detail { + +// Generated components in a linked C++ image share one worker and its FIFO queue. +// Keep worker tasks short. Shutdown also tracks first polls that run on calling threads. +class AsyncExecutor { + public: + AsyncExecutor() : worker_([this] { run(); }) {} + AsyncExecutor(const AsyncExecutor &) = delete; + AsyncExecutor &operator=(const AsyncExecutor &) = delete; + + // Destroy a directly owned executor on an application thread so it can join its worker. + ~AsyncExecutor() { shutdown(); } + + // Queue a task, including cleanup after admission closes. Returns false once stopped. + bool enqueue(AsyncTask task) { + { + std::lock_guard guard(mutex_); + if (stopped_) { + return false; + } + tasks_.push_back(std::move(task)); + } + ready_.notify_one(); + return true; + } + + // Register a cancel action and return its ID, or zero if admission is closed. + // When the poll_on_caller output is true, finish that first poll through run_inline(). + uint64_t track(AsyncTask cancel, bool *poll_on_caller = nullptr) { + std::lock_guard guard(mutex_); + if (!accepting_.load(std::memory_order_relaxed)) { + return 0; + } + const auto id = ++next_id_; + active_.emplace(id, std::move(cancel)); + if (poll_on_caller) { + *poll_on_caller = !closing_.load(); + if (*poll_on_caller) { + ++inline_polls_; + } + } + return id; + } + + // Remove a registration so a waiting shutdown can recheck whether work has drained. + void untrack(uint64_t id) noexcept { + std::lock_guard guard(mutex_); + active_.erase(id); + if (!accepting()) { + drained_.notify_all(); + } + } + + // Admission stays open while shutdown waits for caller-thread first polls. + bool accepting() const noexcept { return accepting_.load(std::memory_order_acquire); } + + // Identifies the worker for blocking wait and lifecycle checks. + bool is_worker() const noexcept { return current_worker_ == this; } + + // Run the first poll counted by track() and release its count so shutdown can proceed. + template void run_inline(Call call) noexcept { + const auto previous = current_inline_; + current_inline_ = this; + call(); + current_inline_ = previous; + // Sequentially consistent with shutdown(): it sees zero polls, or this sees closing_. + if (--inline_polls_ == 0 && closing_.load()) { + std::lock_guard guard(mutex_); + drained_.notify_all(); + } + } + + // Restart the worker and reopen admission after a completed shutdown. + void start() { + if (is_worker() || current_inline_ == this) { + // Shutdown may be waiting for this call to finish. + return; + } + std::lock_guard shutdown_guard(shutdown_mutex_); + std::lock_guard guard(mutex_); + if (stopped_) { + worker_ = std::thread([this] { run(); }); + stopped_ = false; + accepting_.store(true, std::memory_order_release); + } + } + + // Wait for caller-thread first polls, then close admission, cancel and drain work, and join. + // New calls queue their first poll on the worker during the initial wait. + void shutdown() { + if (is_worker() || current_inline_ == this) { + throw std::logic_error("UniFFI executor cannot shut down from its own callback"); + } + std::lock_guard shutdown_guard(shutdown_mutex_); + std::vector cancellations; + { + std::unique_lock lock(mutex_); + if (stopped_) { + return; + } + // Let caller-thread polls finish while callbacks can still start, so none of them + // consumes a callback result that shutdown rejected. + closing_.store(true); + drained_.wait(lock, [this] { return inline_polls_.load() == 0; }); + closing_.store(false); + accepting_.store(false, std::memory_order_release); + for (const auto &entry : active_) { + cancellations.push_back(entry.second); + } + } + for (auto &cancel : cancellations) { + cancel(); + } + { + std::unique_lock lock(mutex_); + drained_.wait(lock, [this] { return active_.empty() && tasks_.empty() && !running_; }); + stopped_ = true; + } + ready_.notify_all(); + worker_.join(); + } + + private: + void run() noexcept { + current_worker_ = this; + std::unique_lock lock(mutex_); + for (;;) { + ready_.wait(lock, [this] { return !tasks_.empty() || stopped_; }); + if (tasks_.empty()) { + current_worker_ = nullptr; + return; + } + auto task = std::move(tasks_.front()); + tasks_.pop_front(); + running_ = true; + lock.unlock(); + + try { + task(); + } catch (...) { + // User continuations cannot throw across the executor boundary. + } + // Release captured objects before announcing that the executor has drained. + task = {}; + lock.lock(); + running_ = false; + if (!accepting()) { + drained_.notify_all(); + } + } + } + + // Protects the queue, active operations, and worker flags. + mutable std::mutex mutex_; + // Serializes start and shutdown through the worker join. + std::mutex shutdown_mutex_; + // Wakes the worker when a task is queued or shutdown signals it to exit. + std::condition_variable ready_; + // Wakes shutdown to recheck its first-poll and drain conditions. + std::condition_variable drained_; + // Holds tasks in the order the worker will run them. + std::deque tasks_; + // Maps active operation IDs to shutdown cancellation actions in registration order. + std::map active_; + // Supplies increasing operation IDs across restarts. + uint64_t next_id_ = 0; + // Lets callers check admission with an atomic read. + std::atomic accepting_{true}; + // Closes the task queue and tells the worker to exit. + bool stopped_ = false; + // Keeps shutdown waiting while a worker task runs and releases its captures. + bool running_ = false; + // Defers new first polls to the worker while shutdown waits for caller-thread polls. + std::atomic closing_{false}; + // Counts first polls assigned to callers by track() until run_inline() finishes them. + std::atomic inline_polls_{0}; + // Identifies the executor that owns the current worker thread. + inline static thread_local const AsyncExecutor *current_worker_ = nullptr; + // Identifies the executor running an inline first poll for reentrancy checks. + inline static thread_local const AsyncExecutor *current_inline_ = nullptr; + // Runs queued work and is joined by shutdown(). + std::thread worker_; +}; + +// Get the shared executor, creating its worker on first use. +inline AsyncExecutor &async_executor() { + // Explicit shutdown avoids running callbacks or joining during static destruction. + static auto *const executor = new AsyncExecutor(); + return *executor; +} + +inline bool enqueue_async(AsyncTask task) noexcept { + try { + return async_executor().enqueue(std::move(task)); + } catch (...) { + // An accepted operation must retain a deferred cleanup path even under allocation failure. + std::terminate(); + } +} + +inline bool begin_async_call() { return async_executor().accepting(); } + +// Reject a wait that would block the executor's worker. +inline void check_blocking_wait(bool ready) { + if (!ready && async_executor().is_worker()) { + throw std::logic_error("Cannot block the UniFFI executor; use Future::then instead"); + } +} + +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. +// Stop producers first and call from an application thread before unloading the bindings or Rust. +// Calling from the worker or inside a caller-thread first poll throws std::logic_error. +inline void shutdown_async_executor() { detail::async_executor().shutdown(); } + +// Start the shared worker or reopen admission after 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: + explicit FutureResult(T value) : value_(std::move(value)) {} + explicit FutureResult(std::exception_ptr error) noexcept : error_(std::move(error)) {} + + FutureResult(const FutureResult &) = default; + FutureResult &operator=(const FutureResult &) = default; + FutureResult &operator=(FutureResult &&) = default; + + FutureResult(FutureResult &&other) noexcept : error_(std::move(other.error_)) { + if (other.value_) { + try { + value_.emplace(std::move(*other.value_)); + } catch (...) { + // Deliver a failed value transfer through the future's normal error path. + error_ = std::current_exception(); + } + } + } + + bool has_value() const noexcept { return !error_; } + std::exception_ptr error() const noexcept { return error_; } + + // Move out the value or rethrow the stored exception. + T get() && { + if (error_) { + std::rethrow_exception(error_); + } + return std::move(*value_); + } + + private: + std::optional value_; + std::exception_ptr error_; +}; + +// Carries completion or an exception for a void result. +template <> class FutureResult { + public: + FutureResult() = default; + explicit FutureResult(std::exception_ptr error) noexcept : error_(std::move(error)) {} + + bool has_value() const noexcept { return !error_; } + std::exception_ptr error() const noexcept { return error_; } + + // Observe completion, rethrowing a stored exception. + void get() const { + if (error_) { + std::rethrow_exception(error_); + } + } + + private: + std::exception_ptr error_; +}; + +namespace detail { + +// Retains the executor through delivery, including when then() is attached to an already-ready +// call. +struct ContinuationRegistration { + ContinuationRegistration() : id(async_executor().track([] {})) { + if (!id) { + throw AsyncExecutorError(); + } + } + ~ContinuationRegistration() { async_executor().untrack(id); } + uint64_t id; +}; + +template class FutureCompletionState { + public: + using Result = FutureResult; + using Callback = std::function; + + void complete(Result result) noexcept { + Callback callback; + { + std::lock_guard guard(mutex_); + if (result_) { + return; + } + result_.emplace(std::move(result)); + callback = std::move(callback_); + } + ready_.notify_all(); + if (callback) { + enqueue_continuation(std::move(callback)); + } + } + + T get() { + std::unique_lock lock(mutex_); + check_blocking_wait(result_.has_value()); + ready_.wait(lock, [this] { return result_.has_value(); }); + auto result = std::move(*result_); + lock.unlock(); + return std::move(result).get(); + } + + void wait() const { + std::unique_lock lock(mutex_); + check_blocking_wait(result_.has_value()); + ready_.wait(lock, [this] { return result_.has_value(); }); + } + + template + std::future_status wait_for(const std::chrono::duration &timeout) const { + std::unique_lock lock(mutex_); + check_blocking_wait(result_.has_value() || timeout <= timeout.zero()); + return ready_.wait_for(lock, timeout, [this] { return result_.has_value(); }) + ? std::future_status::ready + : std::future_status::timeout; + } + + void then(Callback callback) { + auto registration = std::make_shared(); + callback = [registration, callback = std::move(callback)](Result result) mutable { + callback(std::move(result)); + }; + bool ready; + { + std::lock_guard guard(mutex_); + ready = result_.has_value(); + if (!ready) { + callback_ = std::move(callback); + return; + } + } + enqueue_continuation(std::move(callback)); + } + + private: + void enqueue_continuation(Callback callback) noexcept { + Result result = [&] { + std::lock_guard guard(mutex_); + return std::move(*result_); + }(); + auto delivery = + std::make_shared>(std::move(callback), std::move(result)); + if (!enqueue_async([delivery]() mutable { + try { + delivery->first(std::move(delivery->second)); + } catch (...) { + // User exceptions do not escape the executor thread. + } + })) { + std::terminate(); + } + } + + mutable std::mutex mutex_; + mutable std::condition_variable ready_; + std::optional result_; + Callback callback_; +}; + +} // namespace detail + +// Copyable handle for requesting cancellation from any thread. +class FutureCancelHandle { + public: + FutureCancelHandle() = default; + + // Request cancellation if the call is still active. + void cancel() const noexcept { + if (cancel_) { + cancel_(); + } + } + + private: + template friend class Future; + + explicit FutureCancelHandle(std::function cancel) noexcept + : cancel_(std::move(cancel)) {} + + std::function cancel_; +}; + +// Move-only token returned by Future::then(). Destroying it requests cancellation. +// Use the token from one thread at a time. +class FutureContinuation { + public: + FutureContinuation() = default; + explicit FutureContinuation(std::function cancel) : cancel_(std::move(cancel)) {} + + FutureContinuation(const FutureContinuation &) = delete; + FutureContinuation &operator=(const FutureContinuation &) = delete; + + FutureContinuation(FutureContinuation &&other) noexcept : cancel_(std::move(other.cancel_)) { + other.cancel_ = nullptr; + } + + FutureContinuation &operator=(FutureContinuation &&other) noexcept { + if (this != &other) { + cancel(); + cancel_ = std::move(other.cancel_); + other.cancel_ = nullptr; + } + return *this; + } + + ~FutureContinuation() { cancel(); } + + // Give up cancellation ownership so the call can continue after the token is destroyed. + void detach() noexcept { cancel_ = nullptr; } + + // Request cancellation. The worker still delivers the eventual result. + void cancel() noexcept { + if (cancel_) { + auto cancel = std::move(cancel_); + cancel_ = nullptr; + cancel(); + } + } + + private: + std::function cancel_; +}; + +// Move-only handle to an async Rust call. Destroying it while incomplete requests cancellation. +// Use the future from one thread at a time and use cancel_handle() for cross-thread cancellation. +// Blocking waits on the executor's worker throw std::logic_error. +template class Future { + public: + using Result = FutureResult; + using Callback = std::function; + + Future() = default; + Future(std::shared_ptr> state, + std::function cancel) noexcept + : state_(std::move(state)), cancel_(std::move(cancel)) {} + + Future(const Future &) = delete; + Future &operator=(const Future &) = delete; + + Future(Future &&other) noexcept + : state_(std::move(other.state_)), cancel_(std::move(other.cancel_)) { + other.cancel_ = nullptr; + } + + Future &operator=(Future &&other) noexcept { + if (this != &other) { + cancel(); + state_ = std::move(other.state_); + cancel_ = std::move(other.cancel_); + other.cancel_ = nullptr; + } + return *this; + } + + ~Future() { cancel(); } + + bool valid() const noexcept { return state_ != nullptr; } + + // Take an independent handle before consuming or moving this future. + [[nodiscard]] FutureCancelHandle cancel_handle() const { return FutureCancelHandle(cancel_); } + + // Wait for completion and consume the result, rethrowing any stored error. + decltype(auto) get() { + require_state(); + detail::check_blocking_wait(state_->wait_for(std::chrono::seconds(0)) == + std::future_status::ready); + auto state = std::move(state_); + cancel_ = nullptr; + return state->get(); + } + + // Wait for readiness and keep the result available for get() or then(). + void wait() const { + require_state(); + state_->wait(); + } + + // Wait up to timeout. A nonpositive timeout checks readiness immediately. + template + std::future_status wait_for(const std::chrono::duration &timeout) const { + require_state(); + return state_->wait_for(timeout); + } + + // Consume this future and deliver its result on the worker. The returned token owns cancellation. + [[nodiscard]] FutureContinuation then(Callback callback) && { + require_state(); + if (!callback) { + throw std::invalid_argument("UniFFI future continuation must not be empty"); + } + state_->then(std::move(callback)); + auto cancel = std::move(cancel_); + cancel_ = nullptr; + state_.reset(); + return FutureContinuation(std::move(cancel)); + } + + // Request cancellation and keep the result available for get() or then(). + void cancel() noexcept { + if (cancel_) { + auto cancel = std::move(cancel_); + cancel_ = nullptr; + cancel(); + } + } + + private: + void require_state() const { + if (!state_) { + throw std::future_error(std::future_errc::no_state); + } + } + + std::shared_ptr> state_; + std::function cancel_; +}; 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/flat_enum_methods.cpp b/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp index 5534b8a..3274666 100644 --- a/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp +++ b/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp @@ -1,15 +1,16 @@ {%- for method in methods %} -{%- if !method.is_async() %} -{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch -%} -{{ method.name()|fn_name }}({{ type_name }} _uniffi_self{% if !method.arguments().is_empty() %}, {% endif %}{% call macros::param_list(method) %}) { +{% call macros::callable_return_type(method) %} {{ method.name()|fn_name }}({{ type_name }} _uniffi_self{% if !method.arguments().is_empty() %}, {% endif %}{% call macros::param_list(method) %}) { + {%- if method.is_async() %} + return {% call macros::rust_call_async_with_value(method, typ, "_uniffi_self") %}; + {%- else %} {%- match method.return_type() %} {%- when Some with (return_type) %} return uniffi::{{ return_type|lift_fn }}({% call macros::rust_call_with_value(method, typ) %}); {%- when None %} {% call macros::rust_call_with_value(method, typ) %}; {%- endmatch %} + {%- endif %} } -{%- endif %} {%- endfor %} {%- if let Some(method) = uniffi_trait_methods.display_fmt %} diff --git a/bindgen/src/bindings/cpp/templates/flat_enum_methods.hpp b/bindgen/src/bindings/cpp/templates/flat_enum_methods.hpp index 0b2b0e4..422af51 100644 --- a/bindgen/src/bindings/cpp/templates/flat_enum_methods.hpp +++ b/bindgen/src/bindings/cpp/templates/flat_enum_methods.hpp @@ -1,9 +1,6 @@ {%- for method in methods %} -{%- if !method.is_async() %} {%- call macros::docstring(method, 0) %} -{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch -%} -{{ method.name()|fn_name }}({{ type_name }} _uniffi_self{% if !method.arguments().is_empty() %}, {% endif %}{% call macros::param_list(method) %}); -{%- endif %} +{% call macros::callable_return_type(method) %} {{ method.name()|fn_name }}({{ type_name }} _uniffi_self{% if !method.arguments().is_empty() %}, {% endif %}{% call macros::param_list(method) %}); {%- endfor %} {%- if uniffi_trait_methods.display_fmt.is_some() %} diff --git a/bindgen/src/bindings/cpp/templates/fn_def.cpp b/bindgen/src/bindings/cpp/templates/fn_def.cpp index 4f9cb1d..7c39629 100644 --- a/bindgen/src/bindings/cpp/templates/fn_def.cpp +++ b/bindgen/src/bindings/cpp/templates/fn_def.cpp @@ -1,12 +1,14 @@ -{%- match func.return_type() %} -{%- when Some with (return_type) %} -{{ return_type|type_name(ci) }} {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { +{% call macros::callable_return_type(func) %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { + {%- if func.is_async() %} + return {% call macros::rust_call_async(func, "") %}; + {%- else %} + {%- match func.return_type() %} + {%- when Some with (return_type) %} auto ret = {% call macros::rust_call(func) %}; return uniffi::{{ return_type|lift_fn }}(ret); -} -{%- when None -%} -void {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { + {%- when None %} {% call macros::rust_call(func) %}; + {%- endmatch %} + {%- endif %} } -{%- endmatch -%} diff --git a/bindgen/src/bindings/cpp/templates/macros.cpp b/bindgen/src/bindings/cpp/templates/macros.cpp index 0cf6f7c..aaf6a39 100644 --- a/bindgen/src/bindings/cpp/templates/macros.cpp +++ b/bindgen/src/bindings/cpp/templates/macros.cpp @@ -66,6 +66,50 @@ uniffi::{{ self_type|lower_fn }}(other)) {%- endmacro %} +{% macro rust_call_async(func, prefix) -%} + uniffi::rust_call_async<{% match func.return_type() %}{% when Some with (value_type) %}{{ value_type|type_name(ci) }}{% when None %}void{% endmatch %}>( + [&]() { + return {{ func.ffi_func().name() }}( + {%- if !prefix.to_string().is_empty() -%} + {{ prefix }}{% if !func.arguments().is_empty() %}, {% endif %} + {%- endif -%} + {%- call arg_list_lowered(func) -%} + ); + }, + {{ func.ffi_rust_future_poll(ci) }}, + {{ func.ffi_rust_future_cancel(ci) }}, + {{ func.ffi_rust_future_complete(ci) }}, + {{ func.ffi_rust_future_free(ci) }}, +{%- match func.return_type() %} +{% when Some with (value_type) %} + [](auto value) { return uniffi::{{ value_type|lift_fn }}(value); }, +{% when None %} + nullptr, +{%- endmatch %} +{%- match func.throws_type() %} +{% when Some with (e) %} + uniffi::{{ e|ffi_error_converter_name }}::lift +{%- else %} + nullptr +{%- endmatch %} + ) +{%- endmacro %} + +{% macro rust_call_async_with_value(func, self_type, receiver) -%} + {%- let converter = self_type|lower_fn -%} + {%- let prefix = "uniffi::" ~ converter ~ "(" ~ receiver ~ ")" -%} + {%- call rust_call_async(func, prefix) -%} +{%- endmacro %} + +{% macro callable_return_type(method) -%} + {%- if method.is_async() %}::uniffi::Future<{% endif -%} + {%- match method.return_type() -%} + {%- when Some with (return_type) -%}{{ return_type|type_name(ci) }} + {%- when None -%}void + {%- endmatch -%} + {%- if method.is_async() %}>{% endif -%} +{%- endmacro %} + {% macro param_list(func) %} {%- for arg in func.arguments() -%} {{ arg|parameter(ci) }} diff --git a/bindgen/src/bindings/cpp/templates/obj.cpp b/bindgen/src/bindings/cpp/templates/obj.cpp index a818598..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 %} @@ -30,37 +31,44 @@ namespace uniffi { {% match obj.primary_constructor() -%} {%- when Some with (ctor) %} -{%- if !ctor.is_async() %} -{{ type_name }} {{ impl_class_name }}::init({% call macros::param_list(ctor) %}) { +{% if ctor.is_async() %}uniffi::Future<{% endif %}{{ type_name }}{% if ctor.is_async() %}>{% endif %} {{ impl_class_name }}::init({% call macros::param_list(ctor) %}) { + {%- if ctor.is_async() %} + return {% call macros::rust_call_async(ctor, "") %}; + {%- else %} return {{ type_name }}( new {{ impl_class_name }}({%- call macros::rust_call(ctor) -%}) ); + {%- endif %} } -{%- endif %} {% else -%} {% endmatch -%} {% for ctor in obj.alternate_constructors() %} -{%- if !ctor.is_async() %} -{{ type_name }} {{ impl_class_name }}::{{ ctor.name() }}({% call macros::param_list(ctor) %}) { +{% if ctor.is_async() %}uniffi::Future<{% endif %}{{ type_name }}{% if ctor.is_async() %}>{% endif %} {{ impl_class_name }}::{{ ctor.name() }}({% call macros::param_list(ctor) %}) { + {%- if ctor.is_async() %} + return {% call macros::rust_call_async(ctor, "") %}; + {%- else %} return {{ type_name }}(new {{ impl_class_name }}({% call macros::rust_call(ctor) %})); + {%- endif %} } -{%- endif %} {% endfor %} {%- for method in obj.methods() %} -{%- if !method.is_async() %} -{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch -%} -{{ impl_class_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) { - auto ptr = this->_uniffi_internal_clone_pointer(); +{%- let clone_receiver = "this->_uniffi_internal_clone_pointer()" %} +{% call macros::callable_return_type(method) %} {{ impl_class_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) { + {# The async start callback clones the receiver only after the executor admission check. #} + {%- if method.is_async() %} + return {% call macros::rust_call_async(method, clone_receiver) %}; + {%- else %} + auto ptr = {{ clone_receiver }}; {%- match method.return_type() %} - {% when Some with (return_type) %} + {%- when Some with (return_type) %} return uniffi::{{ return_type|lift_fn }}({% call macros::rust_call_with_prefix("ptr", method) %}); - {%- else %} + {%- when None %} {% call macros::rust_call_with_prefix("ptr", method) -%}; {%- endmatch %} + {%- endif %} } -{%- endif %} {%- endfor %} {{ impl_class_name }}::~{{ impl_class_name }}() { diff --git a/bindgen/src/bindings/cpp/templates/obj.hpp b/bindgen/src/bindings/cpp/templates/obj.hpp index c0398ac..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 }}; @@ -38,26 +49,19 @@ struct {{ impl_class_name }} {%- match obj.primary_constructor() %} {%- when Some with (ctor) %} - {%- if !ctor.is_async() %} {%- call macros::docstring(ctor, 4) %} - static {{ type_name }} init({% call macros::param_list(ctor) %}); - {%- endif %} + static {% if ctor.is_async() %}::uniffi::Future<{% endif %}{{ type_name }}{% if ctor.is_async() %}>{% endif %} init({% call macros::param_list(ctor) %}); {%- else %} {%- endmatch %} {%- for ctor in obj.alternate_constructors() %} - {%- if !ctor.is_async() %} {%- call macros::docstring(ctor, 4) %} - static {{ type_name }} {{ ctor.name() }}({% call macros::param_list(ctor) %}); - {%- endif %} + static {% if ctor.is_async() %}::uniffi::Future<{% endif %}{{ type_name }}{% if ctor.is_async() %}>{% endif %} {{ ctor.name() }}({% call macros::param_list(ctor) %}); {%- endfor %} {%- for method in obj.methods() %} - {%- if !method.is_async() %} {%- call macros::docstring(method, 4) %} - {% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch %} - {{- method.name()|fn_name }}({% call macros::param_list(method) %}); - {%- endif %} + {% call macros::callable_return_type(method) %} {{ method.name()|fn_name }}({% call macros::param_list(method) %}); {%- endfor %} {%- for method in obj.uniffi_traits() %} diff --git a/bindgen/src/bindings/cpp/templates/scaffolding.hpp b/bindgen/src/bindings/cpp/templates/scaffolding.hpp index 216436d..7cf2c45 100644 --- a/bindgen/src/bindings/cpp/templates/scaffolding.hpp +++ b/bindgen/src/bindings/cpp/templates/scaffolding.hpp @@ -26,6 +26,16 @@ struct RustCallStatus { RustBuffer error_buf; }; +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() %} @@ -37,7 +47,7 @@ struct RustCallStatus { {%- 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/value_methods.cpp b/bindgen/src/bindings/cpp/templates/value_methods.cpp index 5ef16e7..b3d2932 100644 --- a/bindgen/src/bindings/cpp/templates/value_methods.cpp +++ b/bindgen/src/bindings/cpp/templates/value_methods.cpp @@ -1,15 +1,16 @@ {%- for method in methods %} -{%- if !method.is_async() %} -{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch -%} -{{ type_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) const { +{% call macros::callable_return_type(method) %} {{ type_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) const { + {%- if method.is_async() %} + return {% call macros::rust_call_async_with_value(method, typ, "*this") %}; + {%- else %} {%- match method.return_type() %} {%- when Some with (return_type) %} return uniffi::{{ return_type|lift_fn }}({% call macros::rust_call_with_self(method, typ) %}); {%- when None %} {% call macros::rust_call_with_self(method, typ) %}; {%- endmatch %} + {%- endif %} } -{%- endif %} {%- endfor %} {%- if let Some(method) = uniffi_trait_methods.display_fmt %} diff --git a/bindgen/src/bindings/cpp/templates/value_methods.hpp b/bindgen/src/bindings/cpp/templates/value_methods.hpp index 038a826..48af505 100644 --- a/bindgen/src/bindings/cpp/templates/value_methods.hpp +++ b/bindgen/src/bindings/cpp/templates/value_methods.hpp @@ -1,9 +1,6 @@ {%- for method in methods %} -{%- if !method.is_async() %} {%- call macros::docstring(method, 4) %} -{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch -%} -{{ method.name()|fn_name }}({% call macros::param_list(method) %}) const; -{%- endif %} +{% call macros::callable_return_type(method) %} {{ method.name()|fn_name }}({% call macros::param_list(method) %}) const; {%- endfor %} {%- if uniffi_trait_methods.display_fmt.is_some() %} diff --git a/bindgen/src/bindings/cpp/templates/wrapper.cpp b/bindgen/src/bindings/cpp/templates/wrapper.cpp index 2473e82..d3edc77 100644 --- a/bindgen/src/bindings/cpp/templates/wrapper.cpp +++ b/bindgen/src/bindings/cpp/templates/wrapper.cpp @@ -55,6 +55,11 @@ void check_rust_call(const RustCallStatus &status, F error_cb) { } throw std::runtime_error("A Rust panic has occurred"); + + {%- if ci.has_async_fns() %} + case 3: + throw ::uniffi::AsyncCancelledError(); + {%- endif %} } throw std::runtime_error("Unexpected Rust call status"); @@ -77,6 +82,10 @@ R rust_call(F f, EF error_cb, Args... args) { } } +{%- if ci.has_async_fns() %} +{% include "async.cpp" %} +{%- endif %} + template void rust_call_trait_interface(RustCallStatus* status, F make_call, W write_value) { initialize(); @@ -127,8 +136,6 @@ void rust_call_trait_interface_with_error(RustCallStatus* status, F make_call, W {{ type_helper_code }} {%- for func in ci.function_definitions() %} -{%- if !func.is_async() %} {% include "fn_def.cpp" %} -{%- endif %} {% endfor -%} } // namespace {{ namespace }} diff --git a/bindgen/src/bindings/cpp/templates/wrapper.hpp b/bindgen/src/bindings/cpp/templates/wrapper.hpp index 97842e7..2c9c46f 100644 --- a/bindgen/src/bindings/cpp/templates/wrapper.hpp +++ b/bindgen/src/bindings/cpp/templates/wrapper.hpp @@ -12,10 +12,20 @@ #include #include #include +#include #include +#include #include #include +{%- if ci.has_async_fns() %} +#include +#include +#include +#include +#include +{%- endif %} + {%- for include in self.includes() %} #include <{{ include }}> {%- endfor %} @@ -35,6 +45,17 @@ namespace uniffi { } #endif +{%- if ci.has_async_fns() %} +#ifndef UNIFFI_CPP_ASYNC_FUTURE_V1 +#define UNIFFI_CPP_ASYNC_FUTURE_V1 +namespace uniffi { +inline namespace cpp_async_v1 { +{% include "async.hpp" %} +} +} +#endif +{%- endif %} + {%- import "macros.cpp" as macros %} {% call macros::docstring_value(ci.namespace_docstring(), 0) %} namespace {{ namespace }} { @@ -89,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" %} @@ -99,6 +121,9 @@ typedef {{ type_name }} {{ name }}; namespace uniffi { using ::uniffi::RustStream; using ::uniffi::RustStreamBuffer; +{%- if ci.has_async_fns() %} +using ::uniffi::Future; +{%- endif %} {%- for converter in self.external_ffi_converters() %} using {{ converter }}; {%- endfor %} @@ -169,14 +194,7 @@ void rustbuffer_free(RustBuffer); } // namespace uniffi {%~ for func in ci.function_definitions() %} -{%- if !func.is_async() %} {%- call macros::docstring(func, 0) %} -{%- match func.return_type() %} -{%- when Some with (return_type) %} -{{ return_type|type_name(ci) }} {{ func.name()|fn_name }}({% call macros::param_list(func) %}); -{%- when None %} -void {{ func.name()|fn_name }}({% call macros::param_list(func) %}); -{%- endmatch %} -{%- endif %} +{% call macros::callable_return_type(func) %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}); {%- endfor %} } // namespace {{ namespace }} diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index 1243070..66538e2 100644 --- a/cpp-tests/CMakeLists.txt +++ b/cpp-tests/CMakeLists.txt @@ -4,10 +4,11 @@ set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) +# These fixture tests use assert-based checks, including in Release CI. if (MSVC) - add_compile_options(/permissive-) + add_compile_options(/permissive- /UNDEBUG) else() - add_compile_options(-pedantic-errors) + add_compile_options(-pedantic-errors -UNDEBUG) endif() include(CTest) @@ -20,7 +21,7 @@ set(BINDINGS_SRC_DIR ${BINDINGS_BUILD_DIR}/bindings) if (WIN32) set(UNIFFI_FIXTURES_LIB uniffi_bindgen_cpp_fixtures.dll) - set(ADDITIONAL_LIBS ws2_32 userenv advapi32 ntdll crypt32 Bcrypt) + set(ADDITIONAL_LIBS ws2_32 userenv advapi32 ntdll crypt32 Bcrypt synchronization) elseif(UNIX AND NOT APPLE) set(UNIFFI_FIXTURES_LIB libuniffi_bindgen_cpp_fixtures.so) set(ADDITIONAL_LIBS) @@ -42,9 +43,14 @@ if (VALGRIND) endif() endmacro(memcheck_test) -# Add a bindings test case +# Additional sources can supply the generated bindings for tests that reuse a fixture. macro(test_case TEST_NAME) -add_executable(${TEST_NAME}-test tests/${TEST_NAME}/main.cpp ${BINDINGS_SRC_DIR}/${TEST_NAME}.cpp) +set(TEST_SOURCES ${ARGN}) +if(NOT TEST_SOURCES) + set(TEST_SOURCES ${BINDINGS_SRC_DIR}/${TEST_NAME}.cpp) + list(APPEND BINDING_FILES ${TEST_SOURCES}) +endif() +add_executable(${TEST_NAME}-test tests/${TEST_NAME}/main.cpp ${TEST_SOURCES}) target_include_directories(${TEST_NAME}-test PRIVATE ${BINDINGS_SRC_DIR} include) target_link_directories(${TEST_NAME}-test PRIVATE ${BINDINGS_BUILD_DIR}) @@ -56,8 +62,6 @@ memcheck_test(${TEST_NAME}-test) add_dependencies(${TEST_NAME}-test bindings) -list(APPEND BINDING_FILES ${BINDINGS_SRC_DIR}/${TEST_NAME}.cpp) - endmacro(test_case) test_case(arithmetic) @@ -79,6 +83,14 @@ test_case(empty_type) test_case(error_types_builtin) test_case(reserved_field_name) test_case(type_flattening) +test_case(futures) +list(APPEND BINDING_FILES ${BINDINGS_SRC_DIR}/async_calls.cpp) +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_exit_from_continuation ${BINDINGS_SRC_DIR}/futures.cpp) +test_case(async_pending_at_exit ${BINDINGS_SRC_DIR}/async_calls.cpp) add_executable(ext_types_import-test tests/ext_types_import/main.cpp @@ -119,3 +131,13 @@ add_custom_target(bindings ALL WORKING_DIRECTORY ${BINDINGS_BUILD_DIR} COMMENT "Generating bindings" ) + +set_tests_properties(futures-test async_api_client-test async_executor-test PROPERTIES TIMEOUT 45) +set_tests_properties(async_exit_from_continuation-test async_pending_at_exit-test + PROPERTIES TIMEOUT 15) +if(VALGRIND) + 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_exit_from_continuation-test-test-memcheck + 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 new file mode 100644 index 0000000..c5458c8 --- /dev/null +++ b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp @@ -0,0 +1,550 @@ +#include "test_support.hpp" + +// Include the generated implementation once to exercise its private rust_call_async() driver. +// Scripted Rust FFI functions record the call order so we can verify repolling on WAKE, completion +// on READY, and exactly one free on success, cancellation, Rust errors, or C++ conversion failures. +// The stream tests in main.cpp exercise the same binding through its public API. +#include "async_calls.cpp" + +namespace executor_tests { +namespace { + +// https://mozilla.github.io/uniffi-rs/latest/internals/async-ffi.html#managing-the-rustfuture-handle +constexpr std::int8_t ready = 0; +constexpr std::int8_t wake = 1; +constexpr std::int8_t unexpected_error = 2; +constexpr std::int8_t cancelled = 3; + +enum class Step { Start, Poll, Cancel, Complete, Free }; +enum class PollReply { Park, WakeInline, Ready, Invalid }; +enum class Completion { Value, ErrorStatus, LiftError }; + +struct PollCallback { + RustFutureContinuationCallback callback; + std::uint64_t data; + + void notify(std::int8_t result) const { callback(data, result); } +}; + +class PausedTask { + public: + void pause() { + paused_.set_value(); + wait_for_future(resume_signal_); + } + + void wait_until_paused() { wait_for_future(paused_signal_); } + void resume() { resumed_.set_value(); } + + private: + std::promise paused_; + std::future paused_signal_ = paused_.get_future(); + std::promise resumed_; + std::future resume_signal_ = resumed_.get_future(); +}; + +class RustFutureProbe { + public: + explicit RustFutureProbe(std::vector replies, PausedTask *pause = nullptr) + : replies_(std::move(replies)), pause_(pause) {} + + RustFutureProbe(std::initializer_list replies) + : RustFutureProbe(std::vector(replies)) {} + + uniffi::Future start(Completion completion = Completion::Value) { + return start_with_lift([](int value) { return value + 1; }, completion); + } + + template + uniffi::Future> + start_with_lift(Lift lift, Completion completion = Completion::Value) { + return async_calls::uniffi::rust_call_async>( + [this] { + caller_ = std::this_thread::get_id(); + record(Step::Start); + return reinterpret_cast(this); + }, + [](std::uint64_t handle, RustFutureContinuationCallback callback, std::uint64_t data) { + from_handle(handle).poll(handle, {callback, data}); + }, + [](std::uint64_t handle) { + from_handle(handle).cancel(handle); + }, + [this, completion](auto handle, auto *status) { + record_ffi(handle, Step::Complete, replies_.front() == PollReply::Ready); + ASSERT_NE(status, nullptr); + if (was_cancelled_) { + status->code = cancelled; + } else if (completion == Completion::ErrorStatus) { + status->code = unexpected_error; + status->error_buf = async_calls::uniffi::FfiConverterString::lower("Rust completion failed"); + } + return 41; + }, + [](std::uint64_t handle) { + auto &probe = from_handle(handle); + probe.record_ffi(handle, Step::Free, probe.replies_.front() == PollReply::Ready); + probe.handle_freed = true; + }, + [this, completion, lift = std::move(lift)](int value) mutable { + ASSERT_FALSE(was_cancelled_); + ASSERT_NE(completion, Completion::ErrorStatus); + if (completion == Completion::LiftError) { + throw std::runtime_error("C++ lifting failed"); + } + return lift(value); + }, + nullptr); + } + + PollCallback wait_for_pending_poll() { return wait_for_future(parked_.get_future()); } + + void wake_from_caller(PollCallback callback) { + ASSERT_FALSE(uniffi::detail::async_executor().is_worker()); + wake_sent_ = true; + callback.notify(wake); + } + + void expect_steps(std::initializer_list expected) { + const std::lock_guard lock(mutex_); + ASSERT_EQ(steps_, std::vector(expected)); + } + + std::atomic handle_freed{false}; + + private: + static RustFutureProbe &from_handle(std::uint64_t handle) { + return *reinterpret_cast(handle); + } + + void cancel(std::uint64_t handle) { + record_ffi(handle, Step::Cancel, false); + was_cancelled_ = true; + if (parked_callback_) { + const auto callback = *parked_callback_; + parked_callback_.reset(); + callback.notify(ready); + } + } + + void record(Step step) { + const std::lock_guard lock(mutex_); + steps_.push_back(step); + } + + void record_ffi(std::uint64_t handle, Step step, bool on_caller) { + ASSERT_EQ(handle, reinterpret_cast(this)); + if (on_caller) { + ASSERT_EQ(std::this_thread::get_id(), caller_); + } else { + ASSERT_TRUE(uniffi::detail::async_executor().is_worker()); + } + // Even an inline Rust notification must return before the next FFI operation. + ASSERT_FALSE(in_poll_); + record(step); + } + + void poll(std::uint64_t handle, PollCallback callback) { + record_ffi(handle, Step::Poll, next_reply_ == 0); + ASSERT_NE(callback.callback, nullptr); + ASSERT_NE(callback.data, 0u); + ASSERT_TRUE(next_reply_ < replies_.size()); + if (parked_callback_) { + ASSERT_TRUE(wake_sent_.load()); + parked_callback_.reset(); + } + + in_poll_ = true; + if (next_reply_ == 0) { + EXPECT_EXCEPTION(uniffi::shutdown_async_executor(), std::logic_error); + } + switch (replies_[next_reply_++]) { + case PollReply::Park: + parked_callback_ = callback; + parked_.set_value(callback); + break; + case PollReply::WakeInline: + callback.notify(wake); + break; + case PollReply::Ready: + callback.notify(ready); + break; + case PollReply::Invalid: + callback.notify(-1); + break; + } + if (next_reply_ == 1 && pause_) { + pause_->pause(); + } + in_poll_ = false; + } + + const std::vector replies_; + PausedTask *const pause_; + std::thread::id caller_; + std::size_t next_reply_ = 0; + std::mutex mutex_; + std::vector steps_; + std::optional parked_callback_; + std::promise parked_; + std::atomic wake_sent_{false}; + bool in_poll_ = false; + bool was_cancelled_ = false; +}; + +// A ready first poll completes on the caller even while the worker is paused. +void test_first_poll_runs_on_caller() { + PausedTask worker; + ASSERT_TRUE(uniffi::detail::async_executor().enqueue([&] { worker.pause(); })); + worker.wait_until_paused(); + + RustFutureProbe immediate{PollReply::Ready}; + auto ready_result = immediate.start(); + ASSERT_EQ(wait_for_future(ready_result, std::chrono::seconds(0)), 42); + immediate.expect_steps({Step::Start, Step::Poll, Step::Complete, Step::Free}); + + RustFutureProbe deferred{PollReply::WakeInline, PollReply::Ready}; + auto pending_result = deferred.start(); + ASSERT_EQ(pending_result.wait_for(std::chrono::seconds(0)), std::future_status::timeout); + deferred.expect_steps({Step::Start, Step::Poll}); + + worker.resume(); + ASSERT_EQ(wait_for_future(pending_result), 42); + deferred.expect_steps({Step::Start, Step::Poll, Step::Poll, Step::Complete, Step::Free}); +} + +void test_pending_to_ready() { + RustFutureProbe probe{PollReply::Park, PollReply::WakeInline, PollReply::Ready}; + auto future = probe.start(); + const auto callback = probe.wait_for_pending_poll(); + probe.expect_steps({Step::Start, Step::Poll}); + ASSERT_EQ(future.wait_for(std::chrono::seconds(0)), std::future_status::timeout); + + probe.wake_from_caller(callback); + ASSERT_EQ(wait_for_future(future), 42); + probe.expect_steps({Step::Start, Step::Poll, Step::Poll, Step::Poll, Step::Complete, Step::Free}); +} + +// A future that wakes itself repeatedly yields the worker to other queued tasks. +void test_rapid_wakes_yield() { + auto &executor = uniffi::detail::async_executor(); + PausedTask worker; + ASSERT_TRUE(executor.enqueue([&] { worker.pause(); })); + worker.wait_until_paused(); + + std::vector replies(128, PollReply::WakeInline); + replies.push_back(PollReply::Ready); + RustFutureProbe probe(std::move(replies)); + auto future = probe.start(); + + std::promise yielded; + auto reached = yielded.get_future(); + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_FALSE(probe.handle_freed.load()); + yielded.set_value(); + })); + worker.resume(); + wait_for_future(reached); + ASSERT_EQ(wait_for_future(future), 42); +} + +// A bad poll code becomes a C++ error after the Rust handle is freed. +void test_invalid_poll_code() { + RustFutureProbe probe{PollReply::Invalid, PollReply::Ready}; + try { + wait_for_future(probe.start()); + assert(false && "expected an invalid poll result to throw"); + } catch (const std::runtime_error &error) { + ASSERT_EQ(std::string(error.what()), "Unexpected UniFFI Rust future poll result"); + } + probe.expect_steps({Step::Start, Step::Poll, Step::Cancel, Step::Poll, Step::Complete, Step::Free}); +} + +void test_cleanup_on_failure(Completion completion, const char *message) { + RustFutureProbe probe{PollReply::Ready}; + try { + wait_for_future(probe.start(completion)); + assert(false && "expected future completion to throw"); + } catch (const std::runtime_error &error) { + ASSERT_EQ(std::string(error.what()), message); + } + probe.expect_steps({Step::Start, Step::Poll, Step::Complete, Step::Free}); +} + +void test_cancellation_lifecycle() { + RustFutureProbe probe{PollReply::Park}; + auto future = probe.start(); + probe.wait_for_pending_poll(); + future.cancel(); + future.cancel(); + EXPECT_EXCEPTION(wait_for_future(future), uniffi::AsyncCancelledError); + probe.expect_steps({Step::Start, Step::Poll, Step::Cancel, Step::Complete, Step::Free}); +} + +class ValueMoveError : public std::exception {}; + +class ValueWithThrowingMove { + public: + explicit ValueWithThrowingMove(const std::atomic &fail) : fail_(fail) {} + ValueWithThrowingMove(ValueWithThrowingMove &&other) : fail_(other.fail_) { + if (fail_.load()) { + throw ValueMoveError(); + } + } + + private: + const std::atomic &fail_; +}; + +void test_result_publication_move_failure() { + RustFutureProbe probe{PollReply::Ready}; + auto result = probe.start_with_lift([&](int) { return ValueWithThrowingMove(probe.handle_freed); }); + EXPECT_EXCEPTION(wait_for_future(result), ValueMoveError); + probe.expect_steps({Step::Start, Step::Poll, Step::Complete, Step::Free}); +} + +void test_continuation_move_failure() { + std::atomic fail_move{false}; + RustFutureProbe probe{PollReply::Ready}; + auto result = probe.start_with_lift([&](int) { return ValueWithThrowingMove(fail_move); }); + ASSERT_EQ(result.wait_for(test_timeout), std::future_status::ready); + fail_move = true; + + auto delivered = std::make_shared>(); + auto delivery = delivered->get_future(); + auto continuation = std::move(result).then([delivered](auto completed) { + ASSERT_TRUE(uniffi::detail::async_executor().is_worker()); + EXPECT_EXCEPTION(std::move(completed).get(), ValueMoveError); + delivered->set_value(); + }); + wait_for_future(delivery); + 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(); }); + // A shutdown that does not wait closes admission within this window. + for (int i = 0; i < 100 && executor.accepting(); ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + 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() { + test_first_poll_runs_on_caller(); + test_pending_to_ready(); + test_rapid_wakes_yield(); + test_invalid_poll_code(); + test_cleanup_on_failure(Completion::ErrorStatus, "Rust completion failed"); + test_cleanup_on_failure(Completion::LiftError, "C++ lifting failed"); + test_cancellation_lifecycle(); + test_result_publication_move_failure(); + test_continuation_move_failure(); + 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; + const auto unexpected_ffi_call = [](auto...) { + assert(false && "the rejected Rust future entered the driver"); + }; + auto result = async_calls::uniffi::rust_call_async( + [&] { + uniffi::shutdown_async_executor(); + return reinterpret_cast(&frees); + }, + unexpected_ffi_call, unexpected_ffi_call, + [unexpected_ffi_call](auto... args) { + unexpected_ffi_call(args...); + return 0; + }, + [](std::uint64_t handle) { ++*reinterpret_cast(handle); }, + [](int value) { return value; }, nullptr); + EXPECT_EXCEPTION(wait_for_future(result), uniffi::AsyncExecutorError); + 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 new file mode 100644 index 0000000..aee5be8 --- /dev/null +++ b/cpp-tests/tests/async_executor/main.cpp @@ -0,0 +1,356 @@ +#include "test_support.hpp" + +#include + +namespace executor_tests { +namespace { + +using namespace std::chrono_literals; +using uniffi::detail::AsyncExecutor; +using uniffi::detail::async_executor; + +// A standalone executor runs tasks in FIFO order and continues after a task throws. +void test_executor_queue() { + AsyncExecutor executor; + const auto caller = std::this_thread::get_id(); + std::vector visited; + + ASSERT_TRUE(executor.accepting()); + ASSERT_FALSE(executor.is_worker()); + + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_TRUE(executor.is_worker()); + ASSERT_NE(std::this_thread::get_id(), caller); + visited.push_back(1); + EXPECT_EXCEPTION(executor.shutdown(), std::logic_error); + })); + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_TRUE(executor.is_worker()); + visited.push_back(2); + throw std::runtime_error("test task failure"); + })); + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_TRUE(executor.is_worker()); + visited.push_back(3); + })); + + executor.shutdown(); + ASSERT_EQ(visited, (std::vector{1, 2, 3})); + ASSERT_FALSE(executor.accepting()); + ASSERT_FALSE(executor.enqueue([] {})); + ASSERT_EQ(executor.track([] {}), 0u); + executor.shutdown(); + + // A new thread can reuse the ID of the joined worker. + std::thread caller_after_join([&] { + ASSERT_FALSE(executor.is_worker()); + executor.shutdown(); + }); + caller_after_join.join(); +} + +// Shutdown requests cancellation and waits for queued cleanup of tracked work. +void test_executor_shutdown_drains_active_work() { + AsyncExecutor executor; + auto cancelling = std::make_shared>(); + auto cancellation_started = cancelling->get_future(); + const auto finished = executor.track([] { assert(false && "completed operation was cancelled"); }); + ASSERT_NE(finished, 0u); + executor.untrack(finished); + const auto active = executor.track([&executor, cancelling] { + ASSERT_FALSE(executor.accepting()); + cancelling->set_value(); + }); + ASSERT_NE(active, 0u); + ASSERT_NE(active, finished); + + auto stopping = std::async(std::launch::async, [&] { executor.shutdown(); }); + wait_for_future(cancellation_started); + ASSERT_EQ(executor.track([] {}), 0u); + ASSERT_EQ(stopping.wait_for(0ms), std::future_status::timeout); + + bool cleaned_up = false; + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_TRUE(executor.is_worker()); + executor.untrack(active); + cleaned_up = true; + })); + wait_for_future(stopping); + ASSERT_TRUE(cleaned_up); + ASSERT_FALSE(executor.enqueue([] {})); +} + +// A standalone executor restarts with a worker and continues assigning new operation IDs. +void test_executor_restart() { + AsyncExecutor executor; + executor.start(); + const auto previous = executor.track([] {}); + ASSERT_NE(previous, 0u); + executor.untrack(previous); + executor.shutdown(); + ASSERT_FALSE(executor.enqueue([] {})); + + executor.start(); + executor.start(); + ASSERT_TRUE(executor.accepting()); + const auto active = executor.track([] {}); + ASSERT_TRUE(active > previous); + + bool ran = false; + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_TRUE(executor.is_worker()); + executor.start(); + ran = true; + executor.untrack(active); + })); + executor.shutdown(); + ASSERT_TRUE(ran); + ASSERT_FALSE(executor.enqueue([] {})); +} + +void wait_for_queued_work(AsyncExecutor &executor) { + auto reached = std::make_shared>(); + auto barrier = reached->get_future(); + ASSERT_TRUE(executor.enqueue([reached] { reached->set_value(); })); + 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 = async_calls::SampleStream::init(); + const auto second = async_calls::SampleStream::init(); + auto first_read = first->next(); + auto second_read = second->next(); + wait_for_queued_work(async_executor()); + ASSERT_TRUE(first->is_read_pending()); + ASSERT_TRUE(second->is_read_pending()); + + // Push from the caller thread while both readers are parked on the executor. + ASSERT_TRUE(second->push(20)); + ASSERT_EQ(wait_for_future(second_read), std::optional(20)); + ASSERT_EQ(first_read.wait_for(0ms), std::future_status::timeout); + + auto delivered = std::make_shared>>(); + auto result = delivered->get_future(); + auto continuation = std::move(first_read).then([delivered](auto completed) { + ASSERT_TRUE(async_executor().is_worker()); + delivered->set_value(std::move(completed).get()); + }); + ASSERT_TRUE(first->push(10)); + ASSERT_EQ(wait_for_future(result), std::optional(10)); + + auto end_of_stream = first->next(); + auto surviving_read = second->next(); + wait_for_queued_work(async_executor()); + ASSERT_TRUE(first->is_read_pending()); + ASSERT_TRUE(second->is_read_pending()); + first->close_stream(); + first->close_stream(); + ASSERT_EQ(wait_for_future(end_of_stream), std::nullopt); + ASSERT_EQ(wait_for_future(first->next()), std::nullopt); + ASSERT_FALSE(first->push(11)); + ASSERT_EQ(surviving_read.wait_for(0ms), std::future_status::timeout); + + ASSERT_TRUE(second->push(21)); + ASSERT_EQ(wait_for_future(surviving_read), std::optional(21)); + ASSERT_TRUE(second->push(22)); + ASSERT_TRUE(second->push(23)); + ASSERT_FALSE(second->push(24)); + ASSERT_EQ(wait_for_future(second->next()), std::optional(22)); + ASSERT_EQ(wait_for_future(second->next()), std::optional(23)); +} + +// Cancelling a pending read releases the receiver for the next read. +void test_cancel_pending_read() { + const auto stream = async_calls::SampleStream::init(); + auto read = stream->next(); + wait_for_queued_work(async_executor()); + ASSERT_TRUE(stream->is_read_pending()); + read.cancel(); + EXPECT_EXCEPTION(wait_for_future(read), uniffi::AsyncCancelledError); + ASSERT_FALSE(stream->is_read_pending()); + + // Cancelling an individual read releases its lock and leaves the stream usable. + ASSERT_TRUE(stream->push(42)); + ASSERT_EQ(wait_for_future(stream->next()), std::optional(42)); +} + +// A separate cancellation handle releases a thread waiting in get(). +void test_cancel_blocking_get() { + auto pending = async_calls::pending(); + const auto cancel = pending.cancel_handle(); + auto entering = std::make_shared>(); + auto entering_get = entering->get_future(); + auto waiter = std::async(std::launch::async, [pending = std::move(pending), entering]() mutable { + entering->set_value(); + EXPECT_EXCEPTION(pending.get(), uniffi::AsyncCancelledError); + }); + + wait_for_future(entering_get); + ASSERT_EQ(waiter.wait_for(20ms), std::future_status::timeout); + const auto copy = cancel; + copy.cancel(); + wait_for_future(waiter); + cancel.cancel(); +} + +// Handles survive completion, destruction of a future, and transfer into then(). +void test_cancel_handle_lifetime() { + uniffi::FutureCancelHandle finished; + { + auto ready = futures::always_ready(); + finished = ready.cancel_handle(); + ASSERT_TRUE(wait_for_future(ready)); + finished.cancel(); + } + finished.cancel(); + + auto pending = async_calls::pending(); + const auto cancel = pending.cancel_handle(); + auto delivered = std::make_shared>(); + auto result = delivered->get_future(); + auto continuation = std::move(pending).then([delivered](auto completed) { + EXPECT_EXCEPTION(completed.get(), uniffi::AsyncCancelledError); + delivered->set_value(); + }); + wait_for_queued_work(async_executor()); + cancel.cancel(); + wait_for_future(result); +} + +// A detached continuation delivers a stream read after its token is destroyed. +void test_detached_continuation() { + auto stream = async_calls::SampleStream::init(); + auto delivered = std::make_shared>(); + auto result = delivered->get_future(); + stream->next().then([delivered](auto completed) { + delivered->set_value(std::move(completed).get().value()); + }).detach(); + ASSERT_TRUE(stream->push(42)); + ASSERT_EQ(wait_for_future(result), 42u); +} + +// Move assignment cancels the previous owner and transfers the new result or continuation. +void test_future_move_assignment() { + uniffi::Future future; + ASSERT_FALSE(future.valid()); + EXPECT_EXCEPTION(future.get(), std::future_error); + + future = async_calls::pending(); + ASSERT_EQ(async_calls::pending_count(), 1u); + future = futures::void_(); + wait_for_future(future); + + auto delivered = std::make_shared>(); + auto cancellation = delivered->get_future(); + auto continuation = async_calls::pending().then([delivered](auto result) { + EXPECT_EXCEPTION(std::move(result).get(), uniffi::AsyncCancelledError); + delivered->set_value(); + }); + const auto completed = std::make_shared>(); + auto completion = completed->get_future(); + continuation = futures::always_ready().then([completed](auto result) { + completed->set_value(std::move(result).get()); + }); + wait_for_future(cancellation); + ASSERT_TRUE(wait_for_future(completion)); + ASSERT_EQ(async_calls::pending_count(), 0u); +} + +// Shutdown delivers cancellation, rejects new reads, and allows the Rust receiver to drop. +void test_singleton_shutdown() { + ASSERT_EQ(async_calls::sample_stream_count(), 0u); + auto stream = async_calls::SampleStream::init(); + auto delivered = std::make_shared>(); + auto result = delivered->get_future(); + auto continuation = stream->next().then([delivered](auto completed) { + ASSERT_TRUE(async_executor().is_worker()); + EXPECT_EXCEPTION(std::move(completed).get(), uniffi::AsyncCancelledError); + delivered->set_value(); + }); + wait_for_queued_work(async_executor()); + ASSERT_TRUE(stream->is_read_pending()); + + test_shutdown_during_handle_creation(); + wait_for_future(result, 0ms); + ASSERT_FALSE(stream->is_read_pending()); + ASSERT_FALSE(executor_from_peer().accepting()); + ASSERT_FALSE(executor_from_peer().enqueue([] {})); + EXPECT_EXCEPTION(wait_for_future(stream->next()), uniffi::AsyncExecutorError); + stream.reset(); + ASSERT_EQ(async_calls::sample_stream_count(), 0u); + 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_executor_queue(); + test_executor_shutdown_drains_active_work(); + test_executor_restart(); + test_singleton_across_components(); + test_rust_future_lifecycle(); + test_interleaved_stream_reads(); + test_cancel_pending_read(); + test_cancel_blocking_get(); + test_cancel_handle_lifetime(); + test_detached_continuation(); + test_future_move_assignment(); + // Check shutdown rejection before explicitly restarting the singleton. + 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 new file mode 100644 index 0000000..fdb1548 --- /dev/null +++ b/cpp-tests/tests/async_executor/test_support.hpp @@ -0,0 +1,23 @@ +#pragma once + +#include "async_calls.hpp" +#include "futures.hpp" +#include "test_common.hpp" + +namespace executor_tests { + +inline constexpr std::chrono::seconds test_timeout{10}; + +template +decltype(auto) wait_for_future(Future &&future, std::chrono::milliseconds timeout = test_timeout) { + ASSERT_EQ(future.wait_for(timeout), std::future_status::ready); + return future.get(); +} + +uniffi::detail::AsyncExecutor &executor_from_peer(); +void test_rust_future_lifecycle(); +void test_shutdown_during_handle_creation(); +void test_foreign_callback_after_shutdown(); +void test_foreign_states_across_restart(); + +} // namespace executor_tests diff --git a/cpp-tests/tests/async_exit_from_continuation/main.cpp b/cpp-tests/tests/async_exit_from_continuation/main.cpp new file mode 100644 index 0000000..c5a31ef --- /dev/null +++ b/cpp-tests/tests/async_exit_from_continuation/main.cpp @@ -0,0 +1,16 @@ +#include + +#include +#include +#include + +int main() { + auto continuation = futures::always_ready().then([](auto result) { + std::exit(std::move(result).get() ? EXIT_SUCCESS : EXIT_FAILURE); + }); + + // Keep the continuation alive until the worker exits the process. + std::promise running; + running.get_future().wait(); + return EXIT_FAILURE; +} diff --git a/cpp-tests/tests/async_pending_at_exit/main.cpp b/cpp-tests/tests/async_pending_at_exit/main.cpp new file mode 100644 index 0000000..2a956cb --- /dev/null +++ b/cpp-tests/tests/async_pending_at_exit/main.cpp @@ -0,0 +1,27 @@ +#include + +#include +#include +#include + +namespace { + +// Keep both owners reachable at exit without invoking their cancellation destructors. +uniffi::Future *volatile pending_future; +uniffi::FutureContinuation *volatile pending_continuation; + +} // namespace + +int main() { + pending_future = new uniffi::Future(async_calls::pending()); + pending_continuation = new uniffi::FutureContinuation( + async_calls::pending().then([](auto) { std::abort(); })); + + auto barrier = std::make_shared>(); + auto polled = barrier->get_future(); + if (!uniffi::detail::async_executor().enqueue([barrier] { barrier->set_value(); })) { + return EXIT_FAILURE; + } + polled.get(); + return async_calls::pending_count() == 2 ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/cpp-tests/tests/futures/main.cpp b/cpp-tests/tests/futures/main.cpp new file mode 100644 index 0000000..43e55be --- /dev/null +++ b/cpp-tests/tests/futures/main.cpp @@ -0,0 +1,336 @@ +#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; + +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()); + + { + auto pending = async_calls::pending(); + ASSERT_EQ(std::future_status::timeout, pending.wait_for(1ms)); + ASSERT_EQ(1, async_calls::pending_count()); + pending.cancel(); + EXPECT_EXCEPTION(pending.get(), uniffi::AsyncCancelledError); + ASSERT_EQ(0, async_calls::pending_count()); + } + + { + auto pending = async_calls::pending(); + ASSERT_EQ(1, async_calls::pending_count()); + } + eventually([] { return async_calls::pending_count() == 0; }); + + 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); + auto record_value = async_calls::MyRecord{"value", 17}.value_after(1); + ASSERT_EQ(17, record_value.get()); + + async_calls::validate(async_calls::ValidationMode::kAllow).get(); + EXPECT_EXCEPTION(async_calls::validate(async_calls::ValidationMode::kReject).get(), + async_calls::my_error::Foo); + + 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!", continuation_result->get_future().get()); + // 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)); + + std::atomic stop_producers{false}; + std::atomic produced{0}; + std::vector producers; + for (int i = 0; i < 4; ++i) { + producers.emplace_back([&] { + while (!stop_producers.load()) { + try { + ASSERT_TRUE(futures::always_ready().get()); + ++produced; + } catch (const uniffi::AsyncExecutorError &) { + std::this_thread::yield(); + } catch (const uniffi::AsyncCancelledError &) { + // Shutdown also cancels calls accepted immediately before it. + } + } + }); + } + 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::yield(); + } + auto late_continuation = futures::always_ready(); + late_continuation.wait(); + auto shutdown_pending = async_calls::pending(); + auto shutdown_foreign = async_calls::wait_using_parser( + std::make_shared(started_count, cancellation_count, destruction_count)); + 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(shutdown_pending.get(), uniffi::AsyncCancelledError); + EXPECT_EXCEPTION(shutdown_foreign.get(), uniffi::AsyncCancelledError); + 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 197551d..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,9 +19,11 @@ 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" } +uniffi-async-calls = { path = "async-calls" } uniffi-error-types-builtin = { path = "error-types-builtin" } uniffi-custom-types-builtin = { path = "custom-types-builtin" } uniffi-enum-style-test = { path = "enum-style-test" } diff --git a/fixtures/async-calls/Cargo.toml b/fixtures/async-calls/Cargo.toml new file mode 100644 index 0000000..2fd32ed --- /dev/null +++ b/fixtures/async-calls/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "uniffi-async-calls" +version = "0.21.0" +edition = "2021" +license = "MPL-2.0" +publish = false + +[lib] +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"] } +uniffi = { workspace = true, features = ["tokio"] } diff --git a/fixtures/async-calls/README.md b/fixtures/async-calls/README.md new file mode 100644 index 0000000..368a5f5 --- /dev/null +++ b/fixtures/async-calls/README.md @@ -0,0 +1,12 @@ +# Async calls fixture + +This fixture is adapted from 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`. + +The public async cases are retained, including the hybrid UDL/proc-macro API, functions, +constructors, object methods, records, optional objects, errors, and timeouts. The adaptation: + +- uses `futures-timer` in place of the upstream repository's private timer service; +- includes only the native shared-resource implementation needed by the C++ tests; and +- exports the upstream `void` function as `void_return`, since `void` is a C++ keyword. diff --git a/fixtures/async-calls/src/lib.rs b/fixtures/async-calls/src/lib.rs new file mode 100644 index 0000000..79f59dd --- /dev/null +++ b/fixtures/async-calls/src/lib.rs @@ -0,0 +1,209 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +use futures_timer::Delay; +use std::{ + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, Mutex, + }, + time::Duration, +}; +use tokio::sync::{mpsc, Mutex as AsyncMutex}; + +static PENDING_COUNT: AtomicU64 = AtomicU64::new(0); +static SAMPLE_STREAM_COUNT: AtomicU64 = AtomicU64::new(0); + +struct PendingGuard; + +impl Drop for PendingGuard { + fn drop(&mut self) { + PENDING_COUNT.fetch_sub(1, Ordering::SeqCst); + } +} + +#[uniffi::export] +pub async fn pending() { + PENDING_COUNT.fetch_add(1, Ordering::SeqCst); + let _guard = PendingGuard; + std::future::pending::<()>().await; +} + +#[uniffi::export] +pub fn pending_count() -> u64 { + PENDING_COUNT.load(Ordering::SeqCst) +} + +#[derive(uniffi::Object)] +pub struct SampleStream { + sender: Mutex>>, + receiver: AsyncMutex>, +} + +impl Drop for SampleStream { + fn drop(&mut self) { + SAMPLE_STREAM_COUNT.fetch_sub(1, Ordering::SeqCst); + } +} + +#[uniffi::export] +pub fn sample_stream_count() -> u64 { + SAMPLE_STREAM_COUNT.load(Ordering::SeqCst) +} + +#[uniffi::export(async_runtime = "tokio")] +impl SampleStream { + #[uniffi::constructor] + pub fn new() -> Arc { + let (sender, receiver) = mpsc::channel(2); + SAMPLE_STREAM_COUNT.fetch_add(1, Ordering::SeqCst); + Arc::new(Self { + sender: Mutex::new(Some(sender)), + receiver: AsyncMutex::new(receiver), + }) + } + + pub fn push(&self, sample: u32) -> bool { + self.sender + .lock() + .unwrap() + .as_ref() + .is_some_and(|sender| sender.try_send(sample).is_ok()) + } + + pub async fn next(&self) -> Option { + self.receiver.lock().await.recv().await + } + + pub fn close_stream(&self) { + drop(self.sender.lock().unwrap().take()); + } + + // A pending read holds the receiver lock until it receives a sample, closes, or is dropped. + pub fn is_read_pending(&self) -> bool { + self.receiver.try_lock().is_err() + } +} + +#[derive(thiserror::Error, uniffi::Error, Debug)] +pub enum MyError { + #[error("Foo")] + Foo, +} + +#[derive(uniffi::Record)] +pub struct MyRecord { + pub a: String, + pub b: u32, +} + +#[uniffi::export] +impl MyRecord { + pub async fn value_after(&self, ms: u16) -> u32 { + Delay::new(Duration::from_millis(ms.into())).await; + self.b + } +} + +#[derive(uniffi::Enum)] +pub enum ValidationMode { + Allow, + Reject, +} + +#[uniffi::export] +impl ValidationMode { + pub async fn validate(&self) -> Result<(), MyError> { + match self { + Self::Allow => Ok(()), + Self::Reject => Err(MyError::Foo), + } + } +} + +#[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 9c31212..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!(); @@ -19,6 +21,7 @@ mod uniffi_fixtures { uniffi_empty_type::uniffi_reexport_scaffolding!(); uniffi_reserved_field_name::uniffi_reexport_scaffolding!(); uniffi_type_flattening::uniffi_reexport_scaffolding!(); + uniffi_fixture_async_calls::uniffi_reexport_scaffolding!(); uniffi_ext_types_export::uniffi_reexport_scaffolding!(); uniffi_ext_types_import::uniffi_reexport_scaffolding!();