From d639434140f014a517797c2ca9ab8eb59e797bcc Mon Sep 17 00:00:00 2001 From: Alan George Date: Mon, 14 Sep 2026 21:38:50 -0600 Subject: [PATCH 01/19] Add Rust-to-C++ async function support --- Cargo.lock | 59 ++++ README.md | 9 +- .../src/bindings/cpp/gen_cpp/filters/mod.rs | 1 + bindgen/src/bindings/cpp/gen_cpp/mod.rs | 6 +- bindgen/src/bindings/cpp/mod.rs | 7 - bindgen/src/bindings/cpp/templates/async.cpp | 281 ++++++++++++++++++ bindgen/src/bindings/cpp/templates/async.hpp | 62 ++++ bindgen/src/bindings/cpp/templates/fn_def.cpp | 12 +- bindgen/src/bindings/cpp/templates/macros.cpp | 86 ++++++ bindgen/src/bindings/cpp/templates/obj.cpp | 28 +- bindgen/src/bindings/cpp/templates/obj.hpp | 13 +- .../bindings/cpp/templates/scaffolding.hpp | 2 + .../src/bindings/cpp/templates/wrapper.cpp | 7 +- .../src/bindings/cpp/templates/wrapper.hpp | 19 +- cpp-tests/CMakeLists.txt | 1 + cpp-tests/tests/futures/main.cpp | 102 +++++++ fixtures/Cargo.toml | 1 + fixtures/async-calls/Cargo.toml | 20 ++ fixtures/async-calls/README.md | 12 + fixtures/async-calls/build.rs | 9 + fixtures/async-calls/src/async-calls.udl | 15 + fixtures/async-calls/src/lib.rs | 205 +++++++++++++ .../async-calls/src/platform_specific/mod.rs | 8 + .../src/platform_specific/native.rs | 29 ++ fixtures/src/lib.rs | 1 + 25 files changed, 954 insertions(+), 41 deletions(-) create mode 100644 bindgen/src/bindings/cpp/templates/async.cpp create mode 100644 bindgen/src/bindings/cpp/templates/async.hpp create mode 100644 cpp-tests/tests/futures/main.cpp create mode 100644 fixtures/async-calls/Cargo.toml create mode 100644 fixtures/async-calls/README.md create mode 100644 fixtures/async-calls/build.rs create mode 100644 fixtures/async-calls/src/async-calls.udl create mode 100644 fixtures/async-calls/src/lib.rs create mode 100644 fixtures/async-calls/src/platform_specific/mod.rs create mode 100644 fixtures/async-calls/src/platform_specific/native.rs diff --git a/Cargo.lock b/Cargo.lock index d7cc9de..bca593c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -140,6 +140,19 @@ 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 = "autocfg" version = "1.1.0" @@ -300,6 +313,24 @@ dependencies = [ "autocfg", ] +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-timer" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" + [[package]] name = "glob" version = "0.3.1" @@ -430,6 +461,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" @@ -673,6 +710,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" @@ -765,6 +811,17 @@ dependencies = [ "uniffi_pipeline", ] +[[package]] +name = "uniffi-async-calls" +version = "0.21.0" +dependencies = [ + "futures-timer", + "once_cell", + "thiserror 1.0.50", + "tokio", + "uniffi", +] + [[package]] name = "uniffi-bindgen-cpp" version = "0.10.0+v0.31.2" @@ -787,6 +844,7 @@ 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", @@ -1033,6 +1091,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", diff --git a/README.md b/README.md index 5409f69..c4446ea 100644 --- a/README.md +++ b/README.md @@ -44,11 +44,18 @@ 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. +# Async functions + +Rust async functions, constructors, and object methods return a move-only `uniffi::Future`. +The future supports `get()`, `wait()`, `wait_for()`, and `cancel()`. Destroying an incomplete future +also requests cancellation. Each in-flight Rust future uses a dedicated worker thread to serialize +its UniFFI poll, cancel, complete, and free operations. + # Unsupported features The following uniffi features are unsupported. -* Async functions +* Async callback-interface methods # 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..c795cbd 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs @@ -350,6 +350,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(), diff --git a/bindgen/src/bindings/cpp/gen_cpp/mod.rs b/bindgen/src/bindings/cpp/gen_cpp/mod.rs index 7a4bc6a..66aeb0f 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/mod.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/mod.rs @@ -118,11 +118,7 @@ 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)) } } diff --git a/bindgen/src/bindings/cpp/mod.rs b/bindgen/src/bindings/cpp/mod.rs index 7ccd27d..ec0ffad 100644 --- a/bindgen/src/bindings/cpp/mod.rs +++ b/bindgen/src/bindings/cpp/mod.rs @@ -100,13 +100,6 @@ impl BindingGenerator for CppBindingGenerator { ); } - 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..99108fb --- /dev/null +++ b/bindgen/src/bindings/cpp/templates/async.cpp @@ -0,0 +1,281 @@ +constexpr int8_t UNIFFI_RUST_FUTURE_POLL_READY = 0; +constexpr int8_t UNIFFI_RUST_FUTURE_POLL_WAKE = 1; + +template +class RustFutureState: public std::enable_shared_from_this> { +public: + RustFutureState( + uint64_t handle, + Poll poll, + Cancel cancel, + Complete complete, + Free free, + Lift lift, + ErrorHandler error_handler + ): + handle_(handle), + poll_(std::move(poll)), + cancel_(std::move(cancel)), + complete_(std::move(complete)), + free_(std::move(free)), + lift_(std::move(lift)), + error_handler_(std::move(error_handler)) {} + + std::future get_future() { + return promise_.get_future(); + } + + void start() noexcept { + try { + auto state = this->shared_from_this(); + std::thread([state = std::move(state)]() { + state->run(); + }).detach(); + } catch (...) { + auto error = std::current_exception(); + free_(handle_); + { + std::lock_guard lock(mutex_); + finished_ = true; + } + try { + promise_.set_exception(std::move(error)); + } catch (...) { + } + } + } + + void cancel() noexcept { + { + std::lock_guard lock(mutex_); + if (finished_) { + return; + } + cancel_requested_ = true; + } + wake_.notify_one(); + } + +private: + enum class Work { + PollFuture, + CancelFuture, + CompleteFuture, + }; + + using State = RustFutureState; + + static void continuation(uint64_t callback_data, int8_t poll_result) noexcept { + auto callback_state = std::unique_ptr>( + reinterpret_cast *>(callback_data) + ); + (*callback_state)->resume(poll_result); + } + + void resume(int8_t poll_result) noexcept { + { + std::lock_guard lock(mutex_); + if (finished_) { + return; + } + + 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; + } + } + wake_.notify_one(); + } + + void run() noexcept { + for (;;) { + Work work; + { + std::unique_lock lock(mutex_); + wake_.wait(lock, [this]() { + return finished_ || ready_ || poll_requested_ || + (cancel_requested_ && !cancel_sent_); + }); + + if (finished_) { + return; + } + + if (cancel_requested_ && !cancel_sent_) { + cancel_sent_ = true; + work = Work::CancelFuture; + } else if (ready_) { + ready_ = false; + work = Work::CompleteFuture; + } else { + poll_requested_ = false; + work = Work::PollFuture; + } + } + + if (work == Work::PollFuture) { + poll(); + } else if (work == Work::CancelFuture) { + cancel_rust_future(); + } else { + complete(); + return; + } + } + } + + void poll() noexcept { + std::shared_ptr *callback_state = nullptr; + try { + callback_state = new std::shared_ptr(this->shared_from_this()); + poll_(handle_, &RustFutureState::continuation, reinterpret_cast(callback_state)); + } catch (...) { + delete callback_state; + fail(std::current_exception()); + } + } + + void cancel_rust_future() noexcept { + try { + cancel_(handle_); + } catch (...) { + fail(std::current_exception()); + } + + // Cancellation makes a Rust future ready even if it had not yet been polled. + { + std::lock_guard lock(mutex_); + ready_ = true; + } + wake_.notify_one(); + } + + void fail(std::exception_ptr error) noexcept { + { + std::lock_guard lock(mutex_); + if (!failure_) { + failure_ = std::move(error); + } + cancel_requested_ = true; + } + wake_.notify_one(); + } + + void complete() noexcept { + bool cancelled; + std::exception_ptr failure; + { + std::lock_guard lock(mutex_); + cancelled = cancel_requested_; + failure = failure_; + } + + try { + RustCallStatus status = { 0 }; + if constexpr (std::is_void_v) { + complete_(handle_, &status); + if (failure || cancelled) { + try { + check_rust_call(status, error_handler_); + } catch (...) { + } + set_terminal_exception(failure, cancelled); + } else { + check_rust_call(status, error_handler_); + promise_.set_value(); + } + } else { + auto value = complete_(handle_, &status); + if (failure || cancelled) { + try { + check_rust_call(status, error_handler_); + static_cast(lift_(value)); + } catch (...) { + } + set_terminal_exception(failure, cancelled); + } else { + check_rust_call(status, error_handler_); + promise_.set_value(lift_(value)); + } + } + } catch (...) { + try { + promise_.set_exception(std::current_exception()); + } catch (...) { + } + } + + free_(handle_); + { + std::lock_guard lock(mutex_); + finished_ = true; + } + } + + void set_terminal_exception(const std::exception_ptr &failure, bool cancelled) noexcept { + try { + if (failure) { + promise_.set_exception(failure); + } else if (cancelled) { + promise_.set_exception(std::make_exception_ptr(::uniffi::AsyncCancelledError())); + } + } catch (...) { + } + } + + uint64_t handle_; + Poll poll_; + Cancel cancel_; + Complete complete_; + Free free_; + Lift lift_; + ErrorHandler error_handler_; + std::promise promise_; + std::mutex mutex_; + std::condition_variable wake_; + std::exception_ptr failure_; + bool poll_requested_ = true; + bool cancel_requested_ = false; + bool cancel_sent_ = false; + bool ready_ = false; + bool finished_ = false; +}; + +template +Future rust_call_async( + RustFuture rust_future, + Poll poll, + Cancel cancel, + Complete complete, + Free free, + Lift lift, + ErrorHandler error_handler +) { + initialize(); + const auto handle = rust_future(); + using State = RustFutureState; + + auto state = std::make_shared( + handle, + std::move(poll), + std::move(cancel), + std::move(complete), + std::move(free), + std::move(lift), + std::move(error_handler) + ); + auto future = state->get_future(); + state->start(); + + return Future(std::move(future), [weak_state = std::weak_ptr(state)]() { + if (auto state = weak_state.lock()) { + state->cancel(); + } + }); +} diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp new file mode 100644 index 0000000..13d9a02 --- /dev/null +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -0,0 +1,62 @@ +class AsyncCancelledError: public std::runtime_error { +public: + AsyncCancelledError(): std::runtime_error("UniFFI async call cancelled") {} +}; + +template +class Future { +public: + Future(std::future future, std::function cancel): + future_(std::move(future)), cancel_(std::move(cancel)) {} + + Future(const Future &) = delete; + Future &operator=(const Future &) = delete; + + Future(Future &&other) noexcept: + future_(std::move(other.future_)), cancel_(std::move(other.cancel_)) { + other.cancel_ = nullptr; + } + + Future &operator=(Future &&other) noexcept { + if (this != &other) { + cancel(); + future_ = std::move(other.future_); + cancel_ = std::move(other.cancel_); + other.cancel_ = nullptr; + } + return *this; + } + + ~Future() { + cancel(); + } + + bool valid() const noexcept { + return future_.valid(); + } + + decltype(auto) get() { + return future_.get(); + } + + void wait() const { + future_.wait(); + } + + template + std::future_status wait_for(const std::chrono::duration &timeout) const { + return future_.wait_for(timeout); + } + + void cancel() noexcept { + if (cancel_) { + auto cancel_callback = std::move(cancel_); + cancel_ = nullptr; + cancel_callback(); + } + } + +private: + std::future future_; + std::function cancel_; +}; diff --git a/bindgen/src/bindings/cpp/templates/fn_def.cpp b/bindgen/src/bindings/cpp/templates/fn_def.cpp index 4f9cb1d..ba3a51c 100644 --- a/bindgen/src/bindings/cpp/templates/fn_def.cpp +++ b/bindgen/src/bindings/cpp/templates/fn_def.cpp @@ -1,12 +1,20 @@ {%- match func.return_type() %} {%- when Some with (return_type) %} -{{ return_type|type_name(ci) }} {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { +{% if func.is_async() %}uniffi::Future<{% endif %}{{ return_type|type_name(ci) }}{% if func.is_async() %}>{% endif %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { + {%- if func.is_async() %} + return {% call macros::rust_call_async(func, return_type|type_name(ci)) %}; + {%- else %} auto ret = {% call macros::rust_call(func) %}; return uniffi::{{ return_type|lift_fn }}(ret); + {%- endif %} } {%- when None -%} -void {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { +{% if func.is_async() %}uniffi::Future<{% endif %}void{% if func.is_async() %}>{% endif %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { + {%- if func.is_async() %} + return {% call macros::rust_call_async_void(func) %}; + {%- else %} {% call macros::rust_call(func) %}; + {%- endif %} } {%- endmatch -%} diff --git a/bindgen/src/bindings/cpp/templates/macros.cpp b/bindgen/src/bindings/cpp/templates/macros.cpp index 0cf6f7c..3bd6fbf 100644 --- a/bindgen/src/bindings/cpp/templates/macros.cpp +++ b/bindgen/src/bindings/cpp/templates/macros.cpp @@ -66,6 +66,92 @@ uniffi::{{ self_type|lower_fn }}(other)) {%- endmacro %} +{% macro rust_call_async(func, return_type) -%} + uniffi::rust_call_async<{{ return_type }}>( + [&]() { + return {{ func.ffi_func().name() }}( + {%- 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) }}, + [](auto value) { return uniffi::{{ func.return_type().unwrap()|lift_fn }}(value); }, +{%- match func.throws_type() %} +{% when Some with (e) %} + uniffi::{{ e|ffi_error_converter_name }}::lift +{%- else %} + nullptr +{%- endmatch %} + ) +{%- endmacro %} + +{% macro rust_call_async_void(func) -%} + uniffi::rust_call_async( + [&]() { + return {{ func.ffi_func().name() }}( + {%- 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) }}, + nullptr, +{%- match func.throws_type() %} +{% when Some with (e) %} + uniffi::{{ e|ffi_error_converter_name }}::lift +{%- else %} + nullptr +{%- endmatch %} + ) +{%- endmacro %} + +{% macro rust_call_async_with_prefix(prefix, func, return_type) -%} + uniffi::rust_call_async<{{ return_type }}>( + [&]() { + return {{ func.ffi_func().name() }}( + {{ prefix }}{% if !func.arguments().is_empty() %}, {% 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) }}, + [](auto value) { return uniffi::{{ func.return_type().unwrap()|lift_fn }}(value); }, +{%- match func.throws_type() %} +{% when Some with (e) %} + uniffi::{{ e|ffi_error_converter_name }}::lift +{%- else %} + nullptr +{%- endmatch %} + ) +{%- endmacro %} + +{% macro rust_call_async_void_with_prefix(prefix, func) -%} + uniffi::rust_call_async( + [&]() { + return {{ func.ffi_func().name() }}( + {{ prefix }}{% if !func.arguments().is_empty() %}, {% 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) }}, + nullptr, +{%- match func.throws_type() %} +{% when Some with (e) %} + uniffi::{{ e|ffi_error_converter_name }}::lift +{%- else %} + nullptr +{%- endmatch %} + ) +{%- 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..053ff3e 100644 --- a/bindgen/src/bindings/cpp/templates/obj.cpp +++ b/bindgen/src/bindings/cpp/templates/obj.cpp @@ -30,37 +30,47 @@ 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, type_name) %}; + {%- 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, type_name) %}; + {%- 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 -%} +{% if method.is_async() %}uniffi::Future<{% endif %}{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }}{% else %}void{% endmatch %}{% if method.is_async() %}>{% endif %} {{ impl_class_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) { auto ptr = this->_uniffi_internal_clone_pointer(); {%- match method.return_type() %} {% when Some with (return_type) %} + {%- if method.is_async() %} + return {% call macros::rust_call_async_with_prefix("ptr", method, return_type|type_name(ci)) %}; + {%- else %} return uniffi::{{ return_type|lift_fn }}({% call macros::rust_call_with_prefix("ptr", method) %}); + {%- endif %} + {%- else %} + {%- if method.is_async() %} + return {% call macros::rust_call_async_void_with_prefix("ptr", method) %}; {%- else %} {% call macros::rust_call_with_prefix("ptr", method) -%}; + {%- endif %} {%- endmatch %} } -{%- 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..c047977 100644 --- a/bindgen/src/bindings/cpp/templates/obj.hpp +++ b/bindgen/src/bindings/cpp/templates/obj.hpp @@ -38,26 +38,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 %} + {% if method.is_async() %}::uniffi::Future<{% 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) %}); {%- 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..d33b54c 100644 --- a/bindgen/src/bindings/cpp/templates/scaffolding.hpp +++ b/bindgen/src/bindings/cpp/templates/scaffolding.hpp @@ -26,6 +26,8 @@ struct RustCallStatus { RustBuffer error_buf; }; +typedef void (*RustFutureContinuationCallback)(uint64_t callback_data, int8_t poll_result); + #endif {%- for def in self.scaffolding_definitions() %} diff --git a/bindgen/src/bindings/cpp/templates/wrapper.cpp b/bindgen/src/bindings/cpp/templates/wrapper.cpp index 2473e82..1bf89e3 100644 --- a/bindgen/src/bindings/cpp/templates/wrapper.cpp +++ b/bindgen/src/bindings/cpp/templates/wrapper.cpp @@ -55,6 +55,9 @@ void check_rust_call(const RustCallStatus &status, F error_cb) { } throw std::runtime_error("A Rust panic has occurred"); + + case 3: + throw ::uniffi::AsyncCancelledError(); } throw std::runtime_error("Unexpected Rust call status"); @@ -77,6 +80,8 @@ R rust_call(F f, EF error_cb, Args... args) { } } +{% include "async.cpp" %} + template void rust_call_trait_interface(RustCallStatus* status, F make_call, W write_value) { initialize(); @@ -127,8 +132,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..dfef103 100644 --- a/bindgen/src/bindings/cpp/templates/wrapper.hpp +++ b/bindgen/src/bindings/cpp/templates/wrapper.hpp @@ -2,9 +2,11 @@ #include #include +#include #include #include #include +#include #include #include #include @@ -12,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -35,6 +38,13 @@ namespace uniffi { } #endif +#ifndef UNIFFI_CPP_ASYNC_FUTURE +#define UNIFFI_CPP_ASYNC_FUTURE +namespace uniffi { +{% include "async.hpp" %} +} +#endif + {%- import "macros.cpp" as macros %} {% call macros::docstring_value(ci.namespace_docstring(), 0) %} namespace {{ namespace }} { @@ -99,6 +109,7 @@ typedef {{ type_name }} {{ name }}; namespace uniffi { using ::uniffi::RustStream; using ::uniffi::RustStreamBuffer; +using ::uniffi::Future; {%- for converter in self.external_ffi_converters() %} using {{ converter }}; {%- endfor %} @@ -169,14 +180,12 @@ 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() %} +{% if func.is_async() %}uniffi::Future<{% endif %}{% match func.return_type() %} {%- when Some with (return_type) %} -{{ return_type|type_name(ci) }} {{ func.name()|fn_name }}({% call macros::param_list(func) %}); +{{ return_type|type_name(ci) }}{% if func.is_async() %}>{% endif %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}); {%- when None %} -void {{ func.name()|fn_name }}({% call macros::param_list(func) %}); +void{% if func.is_async() %}>{% endif %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}); {%- endmatch %} -{%- endif %} {%- endfor %} } // namespace {{ namespace }} diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index 1243070..7d39923 100644 --- a/cpp-tests/CMakeLists.txt +++ b/cpp-tests/CMakeLists.txt @@ -79,6 +79,7 @@ test_case(empty_type) test_case(error_types_builtin) test_case(reserved_field_name) test_case(type_flattening) +test_case(futures) add_executable(ext_types_import-test tests/ext_types_import/main.cpp diff --git a/cpp-tests/tests/futures/main.cpp b/cpp-tests/tests/futures/main.cpp new file mode 100644 index 0000000..e69a355 --- /dev/null +++ b/cpp-tests/tests/futures/main.cpp @@ -0,0 +1,102 @@ +#include + +#include + +#include +#include + +using namespace std::chrono_literals; + +int main() { + ASSERT_EQ("Hello, C++", futures::greet("C++")); + ASSERT_TRUE(futures::always_ready().get()); + futures::void_return().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(20, "Wait"); + ASSERT_EQ(std::future_status::timeout, waitable.wait_for(1ms)); + waitable.wait(); + ASSERT_EQ("Hello, Wait!", waitable.get()); + + { + auto pending = futures::pending(); + for (auto i = 0; i < 100 && futures::pending_count() == 0; ++i) { + std::this_thread::sleep_for(1ms); + } + ASSERT_EQ(1, futures::pending_count()); + pending.cancel(); + EXPECT_EXCEPTION(pending.get(), uniffi::AsyncCancelledError); + for (auto i = 0; i < 100 && futures::pending_count() != 0; ++i) { + std::this_thread::sleep_for(1ms); + } + ASSERT_EQ(0, futures::pending_count()); + } + + { + auto pending = futures::pending(); + for (auto i = 0; i < 100 && futures::pending_count() == 0; ++i) { + std::this_thread::sleep_for(1ms); + } + ASSERT_EQ(1, futures::pending_count()); + } + for (auto i = 0; i < 100 && futures::pending_count() != 0; ++i) { + std::this_thread::sleep_for(1ms); + } + ASSERT_EQ(0, futures::pending_count()); + + 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 holding = futures::use_shared_resource({2000, 4000}); + std::this_thread::sleep_for(500ms); + EXPECT_EXCEPTION( + futures::use_shared_resource({0, 250}).get(), + futures::async_error::Timeout + ); + holding.get(); + + return 0; +} diff --git a/fixtures/Cargo.toml b/fixtures/Cargo.toml index 197551d..a18f32e 100644 --- a/fixtures/Cargo.toml +++ b/fixtures/Cargo.toml @@ -21,6 +21,7 @@ uniffi-fixture-docstring = { git = "https://github.com/mozilla/uniffi-rs.git", t 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..e03383d --- /dev/null +++ b/fixtures/async-calls/Cargo.toml @@ -0,0 +1,20 @@ +[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] +once_cell = "1.18.0" +futures-timer = "3.0" +thiserror = "1.0" +tokio = { version = "1.24.1", features = ["time", "sync"] } +uniffi = { workspace = true, features = ["tokio"] } + +[build-dependencies] +uniffi = { workspace = true, features = ["build"] } 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/build.rs b/fixtures/async-calls/build.rs new file mode 100644 index 0000000..9a673b0 --- /dev/null +++ b/fixtures/async-calls/build.rs @@ -0,0 +1,9 @@ +/* + * 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/. + */ + +fn main() { + uniffi::generate_scaffolding("src/async-calls.udl").unwrap(); +} diff --git a/fixtures/async-calls/src/async-calls.udl b/fixtures/async-calls/src/async-calls.udl new file mode 100644 index 0000000..e567386 --- /dev/null +++ b/fixtures/async-calls/src/async-calls.udl @@ -0,0 +1,15 @@ +namespace futures { + [Async] + boolean always_ready(); +}; + +interface UdlMegaphone { + [Async] + constructor(); + + [Async, Name="secondary"] + constructor(); + + [Async] + string say_after(u16 ms, string who); +}; diff --git a/fixtures/async-calls/src/lib.rs b/fixtures/async-calls/src/lib.rs new file mode 100644 index 0000000..00f352c --- /dev/null +++ b/fixtures/async-calls/src/lib.rs @@ -0,0 +1,205 @@ +/* + * 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/. + */ + +mod platform_specific; +use platform_specific::acquire_with_timeout; + +use futures_timer::Delay; +use std::{ + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, + }, + time::Duration, +}; + +static PENDING_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 fn greet(who: String) -> String { + format!("Hello, {who}") +} + +pub async fn always_ready() -> bool { + true +} + +#[uniffi::export] +pub async fn void_return() {} + +#[uniffi::export] +pub async fn say() -> String { + Delay::new(Duration::from_secs(2)).await; + "Hello, Future!".to_string() +} + +#[uniffi::export] +pub async fn say_after(ms: u16, who: String) -> String { + Delay::new(Duration::from_millis(ms.into())).await; + format!("Hello, {who}!") +} + +#[uniffi::export] +pub async fn sleep(ms: u16) -> bool { + Delay::new(Duration::from_millis(ms.into())).await; + true +} + +#[uniffi::export] +pub async fn sleep_no_return(ms: u16) { + Delay::new(Duration::from_millis(ms.into())).await; +} + +#[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(thiserror::Error, uniffi::Error, Debug)] +pub enum MyError { + #[error("Foo")] + Foo, +} + +#[uniffi::export] +pub async fn fallible_me(do_fail: bool) -> Result { + if do_fail { + Err(MyError::Foo) + } else { + Ok(42) + } +} + +#[uniffi::export] +pub async fn fallible_struct(do_fail: bool) -> Result, MyError> { + if do_fail { + Err(MyError::Foo) + } else { + Ok(new_megaphone()) + } +} + +#[uniffi::export] +pub fn new_megaphone() -> Arc { + Arc::new(Megaphone) +} + +#[uniffi::export] +pub async fn async_new_megaphone() -> Arc { + new_megaphone() +} + +#[uniffi::export] +pub async fn async_maybe_new_megaphone(value: bool) -> Option> { + value.then(new_megaphone) +} + +#[uniffi::export] +pub async fn say_after_with_megaphone(megaphone: Arc, ms: u16, who: String) -> String { + megaphone.say_after(ms, who).await +} + +#[derive(uniffi::Object)] +pub struct Megaphone; + +#[uniffi::export] +impl Megaphone { + #[uniffi::constructor] + pub async fn new() -> Arc { + Delay::new(Duration::from_millis(0)).await; + Arc::new(Self) + } + + #[uniffi::constructor] + pub async fn secondary() -> Arc { + Delay::new(Duration::from_millis(0)).await; + Arc::new(Self) + } + + pub async fn say_after(self: Arc, ms: u16, who: String) -> String { + say_after(ms, who).await.to_uppercase() + } + + pub async fn silence(&self) -> String { + String::new() + } + + pub async fn fallible_me(self: Arc, do_fail: bool) -> Result { + fallible_me(do_fail).await + } +} + +#[derive(uniffi::Object)] +pub struct FallibleMegaphone; + +#[uniffi::export] +impl FallibleMegaphone { + #[uniffi::constructor] + pub async fn new() -> Result, MyError> { + Err(MyError::Foo) + } +} + +pub struct UdlMegaphone; + +impl UdlMegaphone { + pub async fn new() -> Self { + Self + } + + pub async fn secondary() -> Self { + Self + } + + pub async fn say_after(self: Arc, ms: u16, who: String) -> String { + say_after(ms, who).await.to_uppercase() + } +} + +#[derive(uniffi::Record)] +pub struct MyRecord { + pub a: String, + pub b: u32, +} + +#[uniffi::export] +pub async fn new_my_record(a: String, b: u32) -> MyRecord { + MyRecord { a, b } +} + +#[derive(uniffi::Record)] +pub struct SharedResourceOptions { + pub release_after_ms: u16, + pub timeout_ms: u16, +} + +#[derive(thiserror::Error, uniffi::Error, Debug)] +pub enum AsyncError { + #[error("Timeout")] + Timeout, +} + +#[uniffi::export(async_runtime = "tokio")] +pub async fn use_shared_resource(options: SharedResourceOptions) -> Result<(), AsyncError> { + acquire_with_timeout(options).await +} + +uniffi::include_scaffolding!("async-calls"); diff --git a/fixtures/async-calls/src/platform_specific/mod.rs b/fixtures/async-calls/src/platform_specific/mod.rs new file mode 100644 index 0000000..226fa51 --- /dev/null +++ b/fixtures/async-calls/src/platform_specific/mod.rs @@ -0,0 +1,8 @@ +/* + * 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/. + */ + +mod native; +pub(crate) use native::*; diff --git a/fixtures/async-calls/src/platform_specific/native.rs b/fixtures/async-calls/src/platform_specific/native.rs new file mode 100644 index 0000000..9750869 --- /dev/null +++ b/fixtures/async-calls/src/platform_specific/native.rs @@ -0,0 +1,29 @@ +/* + * 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 std::time::Duration; + +use crate::{AsyncError, SharedResourceOptions}; + +pub(crate) async fn acquire_with_timeout(options: SharedResourceOptions) -> Result<(), AsyncError> { + use once_cell::sync::Lazy; + use tokio::{ + sync::Mutex, + time::{sleep, timeout}, + }; + + static MUTEX: Lazy> = Lazy::new(|| Mutex::new(())); + + let _guard = timeout( + Duration::from_millis(options.timeout_ms.into()), + MUTEX.lock(), + ) + .await + .map_err(|_| AsyncError::Timeout)?; + + sleep(Duration::from_millis(options.release_after_ms.into())).await; + Ok(()) +} diff --git a/fixtures/src/lib.rs b/fixtures/src/lib.rs index 9c31212..c78f32d 100644 --- a/fixtures/src/lib.rs +++ b/fixtures/src/lib.rs @@ -19,6 +19,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!(); From 98dd8c1ca38a960fdcc97ded8aa2cd0789d78871 Mon Sep 17 00:00:00 2001 From: Alan George Date: Tue, 15 Sep 2026 11:23:50 -0600 Subject: [PATCH 02/19] Guard Rust future handle initialization --- bindgen/src/bindings/cpp/templates/async.cpp | 42 ++++++++++++++++++-- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/bindgen/src/bindings/cpp/templates/async.cpp b/bindgen/src/bindings/cpp/templates/async.cpp index 99108fb..2132eed 100644 --- a/bindgen/src/bindings/cpp/templates/async.cpp +++ b/bindgen/src/bindings/cpp/templates/async.cpp @@ -1,6 +1,35 @@ constexpr int8_t UNIFFI_RUST_FUTURE_POLL_READY = 0; constexpr int8_t UNIFFI_RUST_FUTURE_POLL_WAKE = 1; +template +class RustFutureHandleGuard { +public: + // Own the Rust handle until all potentially-throwing C++ wrappers exist. + RustFutureHandleGuard(uint64_t handle, Free &free) noexcept: + handle_(handle), free_(free) {} + + RustFutureHandleGuard(const RustFutureHandleGuard &) = delete; + RustFutureHandleGuard &operator=(const RustFutureHandleGuard &) = delete; + + ~RustFutureHandleGuard() { + if (active_) { + try { + free_(handle_); + } catch (...) { + } + } + } + + void release() noexcept { + active_ = false; + } + +private: + uint64_t handle_; + Free &free_; + bool active_ = true; +}; + template class RustFutureState: public std::enable_shared_from_this> { public: @@ -259,6 +288,7 @@ Future rust_call_async( ) { initialize(); const auto handle = rust_future(); + RustFutureHandleGuard handle_guard(handle, free); using State = RustFutureState; auto state = std::make_shared( @@ -266,16 +296,20 @@ Future rust_call_async( std::move(poll), std::move(cancel), std::move(complete), - std::move(free), + // Keep the guard's cleanup callable valid until ownership transfers. + free, std::move(lift), std::move(error_handler) ); auto future = state->get_future(); - state->start(); - - return Future(std::move(future), [weak_state = std::weak_ptr(state)]() { + Future result(std::move(future), [weak_state = std::weak_ptr(state)]() { if (auto state = weak_state.lock()) { state->cancel(); } }); + + // start() assumes cleanup responsibility, including thread-start failure. + handle_guard.release(); + state->start(); + return result; } From 0bef8555901ef54e856cfc962bb15642f3af7099 Mon Sep 17 00:00:00 2001 From: Alan George Date: Mon, 16 Nov 2026 15:11:34 -0700 Subject: [PATCH 03/19] Use one shared executor for C++ async bindings --- CHANGELOG.md | 2 +- Cargo.lock | 54 +- README.md | 56 ++- .../src/bindings/cpp/gen_cpp/filters/mod.rs | 15 +- bindgen/src/bindings/cpp/gen_cpp/mod.rs | 13 + bindgen/src/bindings/cpp/mod.rs | 7 - bindgen/src/bindings/cpp/templates/async.cpp | 474 +++++++++-------- bindgen/src/bindings/cpp/templates/async.hpp | 476 +++++++++++++++++- .../src/bindings/cpp/templates/callback.hpp | 6 +- .../cpp/templates/callback_iface_tmpl.cpp | 130 ++++- bindgen/src/bindings/cpp/templates/obj.cpp | 1 + bindgen/src/bindings/cpp/templates/obj.hpp | 13 +- .../bindings/cpp/templates/scaffolding.hpp | 10 +- bindgen/src/bindings/cpp/templates/types.cpp | 1 + .../src/bindings/cpp/templates/wrapper.hpp | 3 + cpp-tests/CMakeLists.txt | 1 + cpp-tests/integration/livekit/CMakeLists.txt | 25 + cpp-tests/integration/livekit/README.md | 61 +++ cpp-tests/integration/livekit/core.cpp | 136 +++++ cpp-tests/integration/livekit/room.cpp | 69 +++ cpp-tests/integration/livekit/room_main.cpp | 4 + cpp-tests/integration/livekit/room_probe.rs | 13 + cpp-tests/tests/async_api_client/main.cpp | 135 +++++ cpp-tests/tests/futures/main.cpp | 217 +++++++- docs/ASYNC_RUNTIME.md | 114 +++++ fixtures/Cargo.toml | 1 + fixtures/async-calls/Cargo.toml | 1 + fixtures/async-calls/src/lib.rs | 40 ++ fixtures/src/lib.rs | 1 + 29 files changed, 1819 insertions(+), 260 deletions(-) create mode 100644 cpp-tests/integration/livekit/CMakeLists.txt create mode 100644 cpp-tests/integration/livekit/README.md create mode 100644 cpp-tests/integration/livekit/core.cpp create mode 100644 cpp-tests/integration/livekit/room.cpp create mode 100644 cpp-tests/integration/livekit/room_main.cpp create mode 100644 cpp-tests/integration/livekit/room_probe.rs create mode 100644 cpp-tests/tests/async_api_client/main.cpp create mode 100644 docs/ASYNC_RUNTIME.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 57da3a5..5971cc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,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 bca593c..da751a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -96,7 +96,7 @@ dependencies = [ "rustc-hash", "serde", "serde_derive", - "syn", + "syn 2.0.106", ] [[package]] @@ -113,7 +113,7 @@ dependencies = [ "rustc-hash", "serde", "serde_derive", - "syn", + "syn 2.0.106", ] [[package]] @@ -153,6 +153,17 @@ dependencies = [ "tokio", ] +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "autocfg" version = "1.1.0" @@ -258,7 +269,7 @@ dependencies = [ "heck 0.4.1", "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -533,7 +544,7 @@ checksum = "7f81c2fde025af7e69b1d1420531c8a8811ca898919db177141a85313b1cb932" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -572,7 +583,7 @@ checksum = "8db53ae22f34573731bafa1db20f04027b2d25e02d8205921b569171699cdb33" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -632,6 +643,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "tempfile" version = "3.10.1" @@ -681,7 +703,7 @@ checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -692,7 +714,7 @@ checksum = "6c5e1be1c48b9172ee610da68fd9cd2770e7a4056cb3fc98710ee6906f0c7960" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -815,6 +837,7 @@ dependencies = [ name = "uniffi-async-calls" version = "0.21.0" dependencies = [ + "async-trait", "futures-timer", "once_cell", "thiserror 1.0.50", @@ -850,6 +873,7 @@ dependencies = [ "uniffi-enum-style-test", "uniffi-error-types-builtin", "uniffi-example-arithmetic", + "uniffi-example-async-api-client", "uniffi-example-callbacks", "uniffi-example-custom-types", "uniffi-example-geometry", @@ -910,6 +934,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" @@ -1106,7 +1142,7 @@ dependencies = [ "indexmap", "proc-macro2", "quote", - "syn", + "syn 2.0.106", ] [[package]] @@ -1120,7 +1156,7 @@ dependencies = [ "proc-macro2", "quote", "serde", - "syn", + "syn 2.0.106", "toml", "uniffi_meta", ] diff --git a/README.md b/README.md index c4446ea..d1469b7 100644 --- a/README.md +++ b/README.md @@ -47,15 +47,59 @@ C++17 or newer is required to compile the bindings. # Async functions Rust async functions, constructors, and object methods return a move-only `uniffi::Future`. -The future supports `get()`, `wait()`, `wait_for()`, and `cancel()`. Destroying an incomplete future -also requests cancellation. Each in-flight Rust future uses a dedicated worker thread to serialize -its UniFFI poll, cancel, complete, and free operations. +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. + +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. + +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); + } +}); +``` -# Unsupported features +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_dispatcher()` from an application +thread before unloading the Rust library. Shutdown rejects new calls, cancels active calls, drains +queued cleanup and continuations, and joins the worker. The executor cannot be restarted. A +nonreturning application callback can prevent shutdown from completing. + +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)); + } + ); +} +``` -The following uniffi features are unsupported. +Callback startup, cancellation, result delivery and continuations use the shared control executor. +Completion callbacks may be invoked from any application thread; the bridge defers 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. -* Async callback-interface methods +See [the runtime design review](docs/ASYNC_RUNTIME.md) for ownership, shutdown, performance checks, +and local LiveKit SDK verification. # 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 c795cbd..35eaeee 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs @@ -158,7 +158,12 @@ impl CppCodeOracle { let class_name = self.class_name(obj.name()); if obj.has_callback_interface() { let impl_name = format!("{class_name}Impl"); - (class_name, impl_name) + let interface_name = if obj.has_async_method() { + format!("{class_name}Foreign") + } else { + class_name + }; + (interface_name, impl_name) } else { (format!("I{class_name}"), class_name) } @@ -359,6 +364,14 @@ pub(crate) fn ffi_type_name(ffi_type: &FfiType) -> Result { }) } +pub(crate) fn ffi_field_type_name(ffi_type: &FfiType) -> Result { + if matches!(ffi_type, FfiType::RustCallStatus) { + Ok("RustCallStatus".into()) + } else { + ffi_type_name(ffi_type) + } +} + pub(crate) fn class_name(nm: &str) -> Result { Ok(CppCodeOracle.class_name(nm)) } diff --git a/bindgen/src/bindings/cpp/gen_cpp/mod.rs b/bindgen/src/bindings/cpp/gen_cpp/mod.rs index 66aeb0f..2729691 100644 --- a/bindgen/src/bindings/cpp/gen_cpp/mod.rs +++ b/bindgen/src/bindings/cpp/gen_cpp/mod.rs @@ -120,6 +120,19 @@ impl<'a> ScaffoldingHeader<'a> { .map(Into::into) .chain(self.ci.iter_ffi_function_definitions().map(Into::into)) } + + pub fn foreign_future_struct_definitions(&self) -> impl Iterator + '_ { + self.ci + .ffi_definitions() + .filter_map(|definition| match definition { + FfiDefinition::Struct(ffi_struct) + if ffi_struct.name().starts_with("ForeignFuture") => + { + Some(ffi_struct) + } + _ => None, + }) + } } #[derive(Template)] diff --git a/bindgen/src/bindings/cpp/mod.rs b/bindgen/src/bindings/cpp/mod.rs index ec0ffad..1602a55 100644 --- a/bindgen/src/bindings/cpp/mod.rs +++ b/bindgen/src/bindings/cpp/mod.rs @@ -93,13 +93,6 @@ impl BindingGenerator for CppBindingGenerator { components: &[uniffi_bindgen::Component], ) -> Result<()> { for Component { ci, config, .. } in components { - if ci.has_async_callback_interface_definition() { - unimplemented!( - "Cpp bindgen does not support async callback interfaces! Namespace: {}", - ci.namespace() - ); - } - if self.scaffolding_mode { unimplemented!("Cpp scaffolding is not supported yet!"); } else { diff --git a/bindgen/src/bindings/cpp/templates/async.cpp b/bindgen/src/bindings/cpp/templates/async.cpp index 2132eed..3a1e3e7 100644 --- a/bindgen/src/bindings/cpp/templates/async.cpp +++ b/bindgen/src/bindings/cpp/templates/async.cpp @@ -1,92 +1,172 @@ constexpr int8_t UNIFFI_RUST_FUTURE_POLL_READY = 0; constexpr int8_t UNIFFI_RUST_FUTURE_POLL_WAKE = 1; -template -class RustFutureHandleGuard { -public: - // Own the Rust handle until all potentially-throwing C++ wrappers exist. - RustFutureHandleGuard(uint64_t handle, Free &free) noexcept: - handle_(handle), free_(free) {} +// 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 start(const std::shared_ptr &self) { + std::lock_guard guard(mutex_); + auto weak = std::weak_ptr(self); + operation_id_ = ::uniffi::detail::default_async_dispatcher().track([weak] { + if (auto state = weak.lock()) { + ::uniffi::detail::dispatch_async([state] { state->cancel(); }); + } + }); + } - RustFutureHandleGuard(const RustFutureHandleGuard &) = delete; - RustFutureHandleGuard &operator=(const RustFutureHandleGuard &) = delete; + 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::default_async_dispatcher().untrack(operation_id_); + // Releasing captures can destroy application objects; do it outside the state mutex. + return true; + } - ~RustFutureHandleGuard() { - if (active_) { + 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 { - free_(handle_); + cancel_now(); } catch (...) { } } } - void release() noexcept { - active_ = false; + void set_cancel_completion(std::function complete_cancelled) { + std::lock_guard guard(mutex_); + complete_cancelled_ = std::move(complete_cancelled); } -private: + 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::default_async_dispatcher().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; + if (!::uniffi::detail::dispatch_async([task_state] { task_state->cancel(); })) { + task_state->cancel(); + } +} + +template class RustFutureHandleGuard { + public: + RustFutureHandleGuard(uint64_t handle, Free &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_; Free &free_; bool active_ = true; }; -template -class RustFutureState: public std::enable_shared_from_this> { -public: - RustFutureState( - uint64_t handle, - Poll poll, - Cancel cancel, - Complete complete, - Free free, - Lift lift, - ErrorHandler error_handler - ): - handle_(handle), - poll_(std::move(poll)), - cancel_(std::move(cancel)), - complete_(std::move(complete)), - free_(std::move(free)), - lift_(std::move(lift)), - error_handler_(std::move(error_handler)) {} - - std::future get_future() { - return promise_.get_future(); +template +class RustFutureState : public std::enable_shared_from_this< + RustFutureState> { + public: + RustFutureState(uint64_t handle, Poll poll, Cancel cancel, Complete complete, Free free, + Lift lift, ErrorHandler error_handler, + std::shared_ptr<::uniffi::detail::FutureCompletionState> completion_state) + : handle_(handle), poll_(std::move(poll)), cancel_(std::move(cancel)), + complete_(std::move(complete)), free_(std::move(free)), lift_(std::move(lift)), + error_handler_(std::move(error_handler)), completion_state_(std::move(completion_state)) { } - void start() noexcept { - try { - auto state = this->shared_from_this(); - std::thread([state = std::move(state)]() { - state->run(); - }).detach(); - } catch (...) { - auto error = std::current_exception(); + void start() { + const auto self = this->shared_from_this(); + { + std::lock_guard guard(mutex_); + operation_id_ = + ::uniffi::detail::default_async_dispatcher().track([self] { self->cancel(); }); + } + if (!operation_id_) { free_(handle_); - { - std::lock_guard lock(mutex_); - finished_ = true; - } - try { - promise_.set_exception(std::move(error)); - } catch (...) { - } + completion_state_->complete(::uniffi::FutureResult( + std::make_exception_ptr(::uniffi::AsyncDispatcherError()))); + return; } + request_drive(); } void cancel() noexcept { { - std::lock_guard lock(mutex_); - if (finished_) { + std::lock_guard guard(mutex_); + if (terminal_) { return; } cancel_requested_ = true; } - wake_.notify_one(); + request_drive(); } -private: - enum class Work { + private: + enum class Action { + None, PollFuture, CancelFuture, CompleteFuture, @@ -95,221 +175,219 @@ class RustFutureState: public std::enable_shared_from_this; static void continuation(uint64_t callback_data, int8_t poll_result) noexcept { - auto callback_state = std::unique_ptr>( - reinterpret_cast *>(callback_data) - ); - (*callback_state)->resume(poll_result); + // 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 resume(int8_t poll_result) noexcept { + void on_continuation(int8_t poll_result) noexcept { { - std::lock_guard lock(mutex_); - if (finished_) { + 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") - ); + std::runtime_error("Unexpected UniFFI Rust future poll result")); cancel_requested_ = true; } } - wake_.notify_one(); + request_drive(); } - void run() noexcept { - for (;;) { - Work work; - { - std::unique_lock lock(mutex_); - wake_.wait(lock, [this]() { - return finished_ || ready_ || poll_requested_ || - (cancel_requested_ && !cancel_sent_); - }); - - if (finished_) { - return; - } - - if (cancel_requested_ && !cancel_sent_) { - cancel_sent_ = true; - work = Work::CancelFuture; - } else if (ready_) { - ready_ = false; - work = Work::CompleteFuture; - } else { - poll_requested_ = false; - work = Work::PollFuture; - } - } - - if (work == Work::PollFuture) { - poll(); - } else if (work == Work::CancelFuture) { - cancel_rust_future(); - } else { - complete(); + 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(); } - } - void poll() noexcept { - std::shared_ptr *callback_state = nullptr; - try { - callback_state = new std::shared_ptr(this->shared_from_this()); - poll_(handle_, &RustFutureState::continuation, reinterpret_cast(callback_state)); - } catch (...) { - delete callback_state; - fail(std::current_exception()); + if (!::uniffi::detail::dispatch_async([state] { state->drive(); })) { + // Active operations keep the executor alive until their handles have been released. + std::terminate(); } } - void cancel_rust_future() noexcept { - try { - cancel_(handle_); - } catch (...) { - fail(std::current_exception()); + Action next_action() noexcept { + std::lock_guard guard(mutex_); + if (terminal_) { + return Action::None; } - - // Cancellation makes a Rust future ready even if it had not yet been polled. - { - std::lock_guard lock(mutex_); - ready_ = true; + if (ready_) { + terminal_ = true; + return Action::CompleteFuture; } - wake_.notify_one(); + if (cancel_requested_ && !cancel_sent_) { + cancel_sent_ = true; + return Action::CancelFuture; + } + if (poll_requested_ && !poll_outstanding_) { + poll_requested_ = false; + poll_outstanding_ = true; + return Action::PollFuture; + } + return Action::None; } - void fail(std::exception_ptr error) noexcept { + void drive() noexcept { { - std::lock_guard lock(mutex_); - if (!failure_) { - failure_ = std::move(error); + std::lock_guard guard(mutex_); + scheduled_ = false; + if (terminal_ || driving_) { + return; } - cancel_requested_ = true; + driving_ = true; } - wake_.notify_one(); - } - void complete() noexcept { - bool cancelled; - std::exception_ptr failure; + // 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 lock(mutex_); - cancelled = cancel_requested_; - failure = failure_; + 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 { + std::exception_ptr result_error; + using StoredResult = + std::conditional_t, std::monostate, std::optional>; + StoredResult result_value{}; try { - RustCallStatus status = { 0 }; + RustCallStatus status{}; if constexpr (std::is_void_v) { complete_(handle_, &status); - if (failure || cancelled) { - try { - check_rust_call(status, error_handler_); - } catch (...) { - } - set_terminal_exception(failure, cancelled); - } else { - check_rust_call(status, error_handler_); - promise_.set_value(); - } + check_rust_call(status, error_handler_); } else { auto value = complete_(handle_, &status); - if (failure || cancelled) { - try { - check_rust_call(status, error_handler_); - static_cast(lift_(value)); - } catch (...) { - } - set_terminal_exception(failure, cancelled); - } else { - check_rust_call(status, error_handler_); - promise_.set_value(lift_(value)); - } + check_rust_call(status, error_handler_); + result_value.emplace(lift_(value)); } } catch (...) { - try { - promise_.set_exception(std::current_exception()); - } catch (...) { - } + result_error = std::current_exception(); } - free_(handle_); + std::exception_ptr protocol_failure; { - std::lock_guard lock(mutex_); - finished_ = true; + std::lock_guard guard(mutex_); + protocol_failure = failure_; } - } - void set_terminal_exception(const std::exception_ptr &failure, bool cancelled) noexcept { - try { - if (failure) { - promise_.set_exception(failure); - } else if (cancelled) { - promise_.set_exception(std::make_exception_ptr(::uniffi::AsyncCancelledError())); - } - } catch (...) { + free_(handle_); + ::uniffi::detail::default_async_dispatcher().untrack(operation_id_); + + if (protocol_failure) { + completion_state_->complete(::uniffi::FutureResult(protocol_failure)); + } else if (result_error) { + completion_state_->complete(::uniffi::FutureResult(result_error)); + } else if constexpr (std::is_void_v) { + completion_state_->complete(::uniffi::FutureResult()); + } else { + completion_state_->complete(::uniffi::FutureResult(std::move(*result_value))); } } uint64_t handle_; + uint64_t operation_id_ = 0; Poll poll_; Cancel cancel_; Complete complete_; Free free_; Lift lift_; ErrorHandler error_handler_; - std::promise promise_; + std::shared_ptr<::uniffi::detail::FutureCompletionState> completion_state_; std::mutex mutex_; - std::condition_variable wake_; std::exception_ptr failure_; bool poll_requested_ = true; + bool poll_outstanding_ = false; bool cancel_requested_ = false; bool cancel_sent_ = false; bool ready_ = false; - bool finished_ = false; + bool scheduled_ = false; + bool driving_ = false; + bool terminal_ = false; }; -template -Future rust_call_async( - RustFuture rust_future, - Poll poll, - Cancel cancel, - Complete complete, - Free free, - Lift lift, - ErrorHandler error_handler -) { +template +Future rust_call_async(RustFuture rust_future, Poll poll, Cancel cancel, Complete complete, + Free free, Lift lift, ErrorHandler error_handler) { initialize(); + auto completion_state = std::make_shared<::uniffi::detail::FutureCompletionState>(); + if (!::uniffi::detail::begin_async_call()) { + completion_state->complete( + ::uniffi::FutureResult(std::make_exception_ptr(::uniffi::AsyncDispatcherError()))); + return Future(std::move(completion_state), nullptr); + } + const auto handle = rust_future(); RustFutureHandleGuard handle_guard(handle, free); using State = RustFutureState; - auto state = std::make_shared( - handle, - std::move(poll), - std::move(cancel), - std::move(complete), - // Keep the guard's cleanup callable valid until ownership transfers. - free, - std::move(lift), - std::move(error_handler) - ); - auto future = state->get_future(); - Future result(std::move(future), [weak_state = std::weak_ptr(state)]() { + auto state = + std::make_shared(handle, std::move(poll), std::move(cancel), std::move(complete), + free, std::move(lift), std::move(error_handler), completion_state); + Future result(completion_state, [weak_state = std::weak_ptr(state)] { if (auto state = weak_state.lock()) { state->cancel(); } }); - // start() assumes cleanup responsibility, including thread-start failure. - handle_guard.release(); state->start(); + handle_guard.release(); return result; } diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp index 13d9a02..023e0f7 100644 --- a/bindgen/src/bindings/cpp/templates/async.hpp +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -1,62 +1,490 @@ -class AsyncCancelledError: public std::runtime_error { -public: - AsyncCancelledError(): std::runtime_error("UniFFI async call cancelled") {} +class AsyncCancelledError : public std::runtime_error { + public: + AsyncCancelledError() : std::runtime_error("UniFFI async call cancelled") {} }; -template -class Future { -public: - Future(std::future future, std::function cancel): - future_(std::move(future)), cancel_(std::move(cancel)) {} +class AsyncDispatcherError : public std::runtime_error { + public: + AsyncDispatcherError() : std::runtime_error("UniFFI async dispatcher rejected a task") {} +}; + +using AsyncTask = std::function; + +namespace detail { + +// One control executor per linked C++ image, shared by all generated components. Tasks must not +// block. +class DefaultAsyncDispatcher { + public: + DefaultAsyncDispatcher() : worker_([this] { run(); }) {} + DefaultAsyncDispatcher(const DefaultAsyncDispatcher &) = delete; + DefaultAsyncDispatcher &operator=(const DefaultAsyncDispatcher &) = delete; + ~DefaultAsyncDispatcher() { shutdown(); } + + bool dispatch(AsyncTask task) { + { + std::lock_guard guard(mutex_); + if (stopped_) { + return false; + } + tasks_.push_back(std::move(task)); + } + ready_.notify_one(); + return true; + } + + uint64_t track(AsyncTask cancel) { + std::lock_guard guard(mutex_); + if (!accepting_) { + return 0; + } + const auto id = ++next_id_; + active_.emplace(id, std::move(cancel)); + return id; + } + + void untrack(uint64_t id) noexcept { + std::lock_guard guard(mutex_); + active_.erase(id); + drained_.notify_all(); + } + + bool accepting() const { + std::lock_guard guard(mutex_); + return accepting_; + } + + bool is_worker() const noexcept { return std::this_thread::get_id() == worker_id_; } + + void shutdown() { + if (is_worker()) { + throw std::logic_error("UniFFI executor cannot shut down from its own callback"); + } + std::lock_guard shutdown_guard(shutdown_mutex_); + std::vector cancellations; + { + std::lock_guard guard(mutex_); + if (stopped_) { + return; + } + accepting_ = false; + 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 { + for (;;) { + AsyncTask task; + { + std::unique_lock lock(mutex_); + ready_.wait(lock, [this] { return !tasks_.empty() || stopped_; }); + if (tasks_.empty()) { + return; + } + task = std::move(tasks_.front()); + tasks_.pop_front(); + running_ = true; + } + try { + task(); + } catch (...) { + // User continuations cannot throw across the executor boundary. + } + // Release captured objects before announcing that the executor has drained. + task = {}; + { + std::lock_guard guard(mutex_); + running_ = false; + } + drained_.notify_all(); + } + } + + mutable std::mutex mutex_; + std::mutex shutdown_mutex_; + std::condition_variable ready_; + std::condition_variable drained_; + std::deque tasks_; + std::map active_; + uint64_t next_id_ = 0; + bool accepting_ = true; + bool stopped_ = false; + bool running_ = false; + std::thread worker_; + const std::thread::id worker_id_ = worker_.get_id(); +}; + +inline DefaultAsyncDispatcher &default_async_dispatcher() { + static DefaultAsyncDispatcher dispatcher; + return dispatcher; +} + +inline bool dispatch_async(AsyncTask task) noexcept { + try { + return default_async_dispatcher().dispatch(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 default_async_dispatcher().accepting(); } + +inline void check_blocking_wait(bool ready) { + if (!ready && default_async_dispatcher().is_worker()) { + throw std::logic_error("Cannot block the UniFFI executor; use Future::then instead"); + } +} + +} // namespace detail + +// Cancels in-flight calls, drains their Rust handles and queued completions, and joins the worker. +// Stop producers first. Call from an application thread, before unloading the Rust library. +inline void shutdown_async_dispatcher() { detail::default_async_dispatcher().shutdown(); } + +// C++17 adapter for an async callback-interface method. The implementation starts work when the +// generated bridge supplies success and failure callbacks, and returns an optional cancel action. +template class ForeignFuture { + public: + using Cancel = std::function; + using Success = std::function; + 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; + + 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_; +}; + +template <> class ForeignFuture { + public: + using Cancel = std::function; + using Success = std::function; + 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; + + 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_; +}; + +template class FutureResult { + public: + explicit FutureResult(T value) : value_(std::move(value)) {} + explicit FutureResult(std::exception_ptr error) : error_(std::move(error)) {} + + bool has_value() const noexcept { return !error_; } + std::exception_ptr error() const noexcept { return error_; } + + T get() && { + if (error_) { + std::rethrow_exception(error_); + } + return std::move(*value_); + } + + private: + std::optional value_; + std::exception_ptr error_; +}; + +template <> class FutureResult { + public: + FutureResult() = default; + explicit FutureResult(std::exception_ptr error) : error_(std::move(error)) {} + + bool has_value() const noexcept { return !error_; } + std::exception_ptr error() const noexcept { return error_; } + + 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(default_async_dispatcher().track([] {})) { + if (!id) { + throw AsyncDispatcherError(); + } + } + ~ContinuationRegistration() { default_async_dispatcher().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) { + dispatch_continuation(std::move(callback)); + } + } + + T get() { + std::unique_lock lock(mutex_); + check_blocking_wait(result_.has_value()); + claim_locked(); + 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_); + claim_locked(); + ready = result_.has_value(); + if (!ready) { + callback_ = std::move(callback); + return; + } + } + dispatch_continuation(std::move(callback)); + } + + private: + void claim_locked() { + if (claimed_) { + throw std::logic_error("UniFFI future result has already been consumed"); + } + claimed_ = true; + } + + void dispatch_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 (!dispatch_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_; + bool claimed_ = false; + Callback callback_; +}; + +template <> inline void FutureCompletionState::get() { + std::unique_lock lock(mutex_); + check_blocking_wait(result_.has_value()); + claim_locked(); + ready_.wait(lock, [this] { return result_.has_value(); }); + auto result = std::move(*result_); + lock.unlock(); + result.get(); +} + +} // namespace detail + +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(); } + + void cancel() noexcept { + if (cancel_) { + auto cancel = std::move(cancel_); + cancel_ = nullptr; + cancel(); + } + } + + private: + std::function cancel_; +}; + +template class Future { + public: + using Result = FutureResult; + using Callback = std::function; + + Future() = default; + Future(std::shared_ptr> state, std::function cancel) + : state_(std::move(state)), cancel_(std::move(cancel)) {} Future(const Future &) = delete; Future &operator=(const Future &) = delete; - Future(Future &&other) noexcept: - future_(std::move(other.future_)), cancel_(std::move(other.cancel_)) { + 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(); - future_ = std::move(other.future_); + state_ = std::move(other.state_); cancel_ = std::move(other.cancel_); other.cancel_ = nullptr; } return *this; } - ~Future() { - cancel(); - } + ~Future() { cancel(); } - bool valid() const noexcept { - return future_.valid(); - } + bool valid() const noexcept { return state_ != nullptr; } decltype(auto) get() { - return future_.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(); } void wait() const { - future_.wait(); + require_state(); + state_->wait(); } template std::future_status wait_for(const std::chrono::duration &timeout) const { - return future_.wait_for(timeout); + require_state(); + return state_->wait_for(timeout); + } + + [[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)); } void cancel() noexcept { if (cancel_) { - auto cancel_callback = std::move(cancel_); + auto cancel = std::move(cancel_); cancel_ = nullptr; - cancel_callback(); + cancel(); + } + } + + private: + void require_state() const { + if (!state_) { + throw std::future_error(std::future_errc::no_state); } } -private: - std::future future_; + 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..b836215 100644 --- a/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp +++ b/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp @@ -4,7 +4,133 @@ {%- 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]({{ 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) { + ::uniffi::detail::dispatch_async([state, deliver_failure, error] { + deliver_failure(error); + }); + }; + {% match method.return_type() %} + {% when Some(t) %} + auto complete_success = [state, deliver_success]({{ t|type_name(ci) }} value) { + ::uniffi::detail::dispatch_async([state, deliver_success, value = std::move(value)]() mutable { + deliver_success(std::move(value)); + }); + }; + {% when None %} + auto complete_success = [state, deliver_success]() { + ::uniffi::detail::dispatch_async([state, 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 %} + ::uniffi::detail::dispatch_async([ + 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->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 +152,7 @@ uniffi_out_return = {{ t|lower_fn }}(v); }; {% when None %} + (void)uniffi_out_return; auto write_value = [](){}; {% endmatch %} @@ -35,6 +162,7 @@ {% when None %} rust_call_trait_interface(out_status, make_call, write_value); {% endmatch %} + {%- endif %} } {%- endfor %} diff --git a/bindgen/src/bindings/cpp/templates/obj.cpp b/bindgen/src/bindings/cpp/templates/obj.cpp index 053ff3e..8f3498a 100644 --- a/bindgen/src/bindings/cpp/templates/obj.cpp +++ b/bindgen/src/bindings/cpp/templates/obj.cpp @@ -1,5 +1,6 @@ {%- let obj = ci.get_object_definition(name).unwrap() %} {%- let (interface_name, impl_class_name) = obj|object_names %} +{%- let foreign_interface_name = interface_name %} {%- let class_name = type_name|class_name %} {%- let ffi_converter_name = typ|ffi_converter_name %} {%- let canonical_type_name = typ|canonical_name %} diff --git a/bindgen/src/bindings/cpp/templates/obj.hpp b/bindgen/src/bindings/cpp/templates/obj.hpp index c047977..c38d9f4 100644 --- a/bindgen/src/bindings/cpp/templates/obj.hpp +++ b/bindgen/src/bindings/cpp/templates/obj.hpp @@ -4,12 +4,23 @@ {%- let ffi_converter_name = typ|ffi_converter_name %} {%- let canonical_type_name = typ|canonical_name %} {%- if obj.has_callback_interface() %} +{%- if obj.has_async_method() %} +struct {{ canonical_type_name }} { + virtual ~{{ canonical_type_name }}() = default; +}; +{%- endif %} {%- let vtable = obj.vtable().expect("trait interface should have a vtable") %} {%- let vtable_methods = obj.vtable_methods() %} {%- let methods = obj.methods() %} {%- let ffi_init_callback = obj.ffi_init_callback() %} {%- let interface_docstring = obj.docstring() %} +{%- if obj.has_async_method() %} +{%- let interface_base_name = canonical_type_name %} {% include "callback.hpp" %} +{%- else %} +{%- let interface_base_name = "" %} +{% include "callback.hpp" %} +{%- endif %} {%- endif %} namespace uniffi { @@ -22,7 +33,7 @@ struct {{ impl_class_name }} Since an interface being a callback interface or an error is mutually exclusive, we don't need to complex branching for multiple inheritance #} -{% if obj.has_callback_interface() %} : public {{ interface_name }} {% endif %} +{% if obj.has_callback_interface() %} : public {% if obj.has_async_method() %}{{ canonical_type_name }}{% else %}{{ interface_name }}{% endif %} {% endif %} {% if ci.is_name_used_as_error(name) %} : public std::exception {% endif %} { friend uniffi::{{ ffi_converter_name|class_name }}; diff --git a/bindgen/src/bindings/cpp/templates/scaffolding.hpp b/bindgen/src/bindings/cpp/templates/scaffolding.hpp index d33b54c..7cf2c45 100644 --- a/bindgen/src/bindings/cpp/templates/scaffolding.hpp +++ b/bindgen/src/bindings/cpp/templates/scaffolding.hpp @@ -28,6 +28,14 @@ struct RustCallStatus { typedef void (*RustFutureContinuationCallback)(uint64_t callback_data, int8_t poll_result); +{%- for ffi_struct in self.foreign_future_struct_definitions() %} +struct {{ ffi_struct.name()|ffi_struct_name }} { + {%- for field in ffi_struct.fields() %} + {{ field.type_().borrow()|ffi_field_type_name }} {{ field.name()|var_name }}; + {%- endfor %} +}; +{%- endfor %} + #endif {%- for def in self.scaffolding_definitions() %} @@ -39,7 +47,7 @@ typedef void (*RustFutureContinuationCallback)(uint64_t callback_data, int8_t po {%- when FfiDefinition::Struct(ffi_struct) %} struct {{ ffi_struct.name()|ffi_struct_name }} { {%- for field in ffi_struct.fields() %} - {{ field.type_().borrow()|ffi_type_name }} {{ field.name()|var_name }}; + {{ field.type_().borrow()|ffi_field_type_name }} {{ field.name()|var_name }}; {%- endfor %} }; {%- when FfiDefinition::Function(func) %} diff --git a/bindgen/src/bindings/cpp/templates/types.cpp b/bindgen/src/bindings/cpp/templates/types.cpp index a486253..6110c6b 100644 --- a/bindgen/src/bindings/cpp/templates/types.cpp +++ b/bindgen/src/bindings/cpp/templates/types.cpp @@ -61,6 +61,7 @@ namespace uniffi { {%- let cbi = ci.get_callback_interface_definition(name).unwrap() %} {%- let ffi_init_callback = cbi.ffi_init_callback() %} {%- let interface_name = name %} +{%- let foreign_interface_name = interface_name %} {%- let methods = cbi.methods() %} {%- let vtable = cbi.vtable() %} {%- let vtable_methods = cbi.vtable_methods() %} diff --git a/bindgen/src/bindings/cpp/templates/wrapper.hpp b/bindgen/src/bindings/cpp/templates/wrapper.hpp index dfef103..3010e0a 100644 --- a/bindgen/src/bindings/cpp/templates/wrapper.hpp +++ b/bindgen/src/bindings/cpp/templates/wrapper.hpp @@ -1,9 +1,11 @@ #pragma once #include +#include #include #include #include +#include #include #include #include @@ -99,6 +101,7 @@ typedef {{ type_name }} {{ name }}; {%- let vtable = cbi.vtable() %} {%- let vtable_methods = cbi.vtable_methods() %} {%- let interface_docstring = cbi.docstring() %} +{%- let interface_base_name = "" %} {% include "callback.hpp" %} {%- when Type::Object { module_path, name, imp } %} {% include "obj.hpp" %} diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index 7d39923..b26b5ca 100644 --- a/cpp-tests/CMakeLists.txt +++ b/cpp-tests/CMakeLists.txt @@ -80,6 +80,7 @@ test_case(error_types_builtin) test_case(reserved_field_name) test_case(type_flattening) test_case(futures) +test_case(async_api_client) add_executable(ext_types_import-test tests/ext_types_import/main.cpp diff --git a/cpp-tests/integration/livekit/CMakeLists.txt b/cpp-tests/integration/livekit/CMakeLists.txt new file mode 100644 index 0000000..5900dda --- /dev/null +++ b/cpp-tests/integration/livekit/CMakeLists.txt @@ -0,0 +1,25 @@ +cmake_minimum_required(VERSION 3.16) +project(livekit-uniffi-core-probe LANGUAGES CXX) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +find_package(Threads REQUIRED) +if(NOT LIVEKIT_BINDINGS_DIR OR NOT LIVEKIT_FFI_LIBRARY) + message(FATAL_ERROR "Set LIVEKIT_BINDINGS_DIR and LIVEKIT_FFI_LIBRARY to generated core bindings and their matching Rust library") +endif() +file(GLOB BINDING_SOURCES CONFIGURE_DEPENDS "${LIVEKIT_BINDINGS_DIR}/*.cpp") +add_executable(core-probe core.cpp ${BINDING_SOURCES}) +target_include_directories(core-probe PRIVATE "${LIVEKIT_BINDINGS_DIR}") +target_link_libraries(core-probe PRIVATE "${LIVEKIT_FFI_LIBRARY}" Threads::Threads) +if(NOT MSVC) + target_compile_options(core-probe PRIVATE -pedantic-errors) +endif() +# Keep assert-based checks enabled even if a caller selects a release configuration. +if(MSVC) + target_compile_options(core-probe PRIVATE /UNDEBUG) +else() + target_compile_options(core-probe PRIVATE -UNDEBUG) +endif() +enable_testing() +add_test(NAME core-probe COMMAND core-probe) +set_tests_properties(core-probe PROPERTIES TIMEOUT 30) diff --git a/cpp-tests/integration/livekit/README.md b/cpp-tests/integration/livekit/README.md new file mode 100644 index 0000000..0babdf2 --- /dev/null +++ b/cpp-tests/integration/livekit/README.md @@ -0,0 +1,61 @@ +# Local LiveKit integration probes + +These are verification sources, not SDK changes or a new shipped API. Run against isolated snapshots +of the local SDK checkouts. Do not replace their generator pins or edit their submodules in place. + +## Core modules + +Build `livekit-ffi` from the local standalone `rust-sdks` checkout snapshot with +`--no-default-features --features core-modules`, using a separate Cargo target directory. Populate its +`livekit-protocol/protocol` submodule from that checkout too. Generate with this branch's +`target/debug/uniffi-bindgen-cpp --library --out-dir `. + +```sh +cmake -S cpp-tests/integration/livekit -B /tmp/livekit-core-probe \ + -DLIVEKIT_BINDINGS_DIR= \ + -DLIVEKIT_FFI_LIBRARY= +cmake --build /tmp/livekit-core-probe -j 6 +ctest --test-dir /tmp/livekit-core-probe --output-on-failure +``` + +`core.cpp` uses the real exported `livekit-net` HTTP and WebSocket self-tests with C++ async host +implementations. It covers records, bytes, optional values, nested object handles, typed errors, +cancellation, and shutdown with calls pending in multiple generated components. No server is needed. +The transports are mocks; this does not verify networking, TLS, or a LiveKit room connection. + +## C++ SDK and legacy protobuf + +Snapshot the local `client-sdk-cpp` checkout and **its checked-out `client-sdk-rust` submodule**. +A feature branch may require a protobuf schema that the standalone Rust checkout does not have. +Copy the Rust submodules (`livekit-protocol/protocol` and `yuv-sys/libyuv`) and C++ `cpp-tools` as well. +When reusing a build tree with newly archived sources, refresh source timestamps so Cargo and CMake +regenerate the protobufs rather than reusing output from a previous snapshot. + +Only inside these disposable snapshots: + +1. Copy `room_probe.rs` to `livekit-ffi/src/async_runtime_probe.rs`. Append + `#[cfg(feature = "room-apis")] mod async_runtime_probe;` to that crate's `src/lib.rs`. + These exports provide an async timer round trip and a permanently pending call without requiring + the unmerged room-mode UniFFI PRs or a running LiveKit server. +2. Replace the generation command in `cmake/uniffi_cpp.cmake` with this branch's local generator, + preserving its `--library` and `--out-dir` arguments. +3. Append these verification targets to the copied SDK's root `CMakeLists.txt`, replacing + `` with this directory's absolute path: + + ```cmake + target_sources(livekit PRIVATE "/room.cpp") + add_executable(livekit_local_async_probe "/room_main.cpp") + target_link_libraries(livekit_local_async_probe PRIVATE livekit) + ``` + +4. Configure a **Debug** SDK build so assertions remain enabled. Build `livekit_local_async_probe` + and run it. An existing matching WebRTC archive can be reused with `LK_CUSTOM_WEBRTC`. + +`room.cpp` runs *inside* the SDK shared library, sharing its generated bindings and executor. It +starts a generated async call, creates a Sox resampler through the actual SDK `FfiClient` protobuf +request path, takes UniFFI co-ownership, releases the legacy handle, processes samples, republishes +the object to legacy FFI, takes ownership again, and releases it. It then checks cancellation and +executor shutdown. The SDK's existing generated build-version adapter is exercised too. + +These probes do not modify production SDK source or publish artifacts. Full room/data-stream UniFFI +migration, live-server integration, and platform CI remain separate checks. diff --git a/cpp-tests/integration/livekit/core.cpp b/cpp-tests/integration/livekit/core.cpp new file mode 100644 index 0000000..3998032 --- /dev/null +++ b/cpp-tests/integration/livekit/core.cpp @@ -0,0 +1,136 @@ +// Copyright 2026 LiveKit, Inc. +// SPDX-License-Identifier: Apache-2.0 +#include +#include +#include + +#include "livekit_ffi.hpp" +#include "livekit_net.hpp" + +using namespace std::chrono_literals; +namespace net = livekit_net; + +class Http final : public net::HttpClientForeign { +public: + uniffi::ForeignFuture request(const net::HttpMethod&, const std::string& url, + const std::vector&, + std::optional>) override { + assert(uniffi::detail::default_async_dispatcher().is_worker()); + return uniffi::ForeignFuture([this, url](auto success, auto failure) { + assert(uniffi::detail::default_async_dispatcher().is_worker()); + if (url == "pending") { + { + std::lock_guard lock(mutex); + pending = std::move(success); + } + return uniffi::ForeignFuture::Cancel([this] { + assert(uniffi::detail::default_async_dispatcher().is_worker()); + std::lock_guard lock(mutex); + pending = {}; + ++cancelled; + }); + } + if (url == "error") { + failure(std::make_exception_ptr(net::transport_error::Closed())); + } else { + success(net::HttpResponse{200, {{"x-probe", "ok"}}, {1, 2, 3}}); + } + return uniffi::ForeignFuture::Cancel{}; + }); + } + + std::mutex mutex; + std::function pending; + std::atomic cancelled{0}; +}; + +class Connection final : public net::WsConnectionForeign { +public: + uniffi::ForeignFuture send(const std::vector& frame) override { + return uniffi::ForeignFuture([this, frame](auto success, auto) { + assert(uniffi::detail::default_async_dispatcher().is_worker()); + frame_ = frame; + success(); + return [] {}; + }); + } + uniffi::ForeignFuture>> recv() override { + return uniffi::ForeignFuture>>([this](auto success, auto) { + success(std::optional>(frame_)); + return [] {}; + }); + } + uniffi::ForeignFuture close() override { + return uniffi::ForeignFuture([](auto success, auto) { + success(); + return [] {}; + }); + } + +private: + std::vector frame_; +}; + +class Ws final : public net::WsClientForeign { +public: + uniffi::ForeignFuture connect(const std::string&, const std::vector&, + uint64_t) override { + return uniffi::ForeignFuture([](auto success, auto) { + success(net::WsConnectResult{std::make_shared()}); + return [] {}; + }); + } +}; + +int main() { + auto http = std::make_shared(); + net::set_http_client(http); + net::set_ws_client(std::make_shared()); + const auto response = net::self_test_http_get("ok").get(); + assert(response.status == 200 && response.body == std::vector({1, 2, 3})); + try { + net::self_test_http_get("error").get(); + assert(false); + } catch (const net::transport_error::Closed&) { + } + + std::vector bytes(4096, 42); + assert(net::self_test_ws_echo("mock", bytes).get() == bytes); + + auto pending = net::self_test_http_get("pending"); + const auto deadline = std::chrono::steady_clock::now() + 5s; + for (;;) { + { + std::lock_guard lock(http->mutex); + if (http->pending) { + break; + } + } + assert(std::chrono::steady_clock::now() < deadline); + std::this_thread::yield(); + } + pending.cancel(); + try { + pending.get(); + assert(false); + } catch (const uniffi::AsyncCancelledError&) { + } + + // Different generated components must share one executor and cancellation model. + livekit_ffi::log_forward_bootstrap(livekit_ffi::LogForwardFilter::kOff); + auto log = livekit_ffi::log_forward_receive(); + auto outstanding = net::self_test_http_get("pending"); + uniffi::shutdown_async_dispatcher(); + try { + log.get(); + assert(false); + } catch (const uniffi::AsyncCancelledError&) { + } + try { + outstanding.get(); + assert(false); + } catch (const uniffi::AsyncCancelledError&) { + } + assert(http->cancelled.load() >= 1); + std::cout << "LiveKit core: HTTP, WebSocket, typed errors, callbacks, cancellation, shutdown passed\n"; +} diff --git a/cpp-tests/integration/livekit/room.cpp b/cpp-tests/integration/livekit/room.cpp new file mode 100644 index 0000000..0c0261f --- /dev/null +++ b/cpp-tests/integration/livekit/room.cpp @@ -0,0 +1,69 @@ +// Copyright 2026 LiveKit, Inc. +// SPDX-License-Identifier: Apache-2.0 +// Compiled into the isolated C++ SDK so generated calls and the legacy client share the same library. +#include +#include + +#include "ffi.pb.h" +#include "ffi_client.h" +#include "livekit_ffi.hpp" +#include "uniffi_bindgen_adapter.h" + +#ifdef _WIN32 +#define PROBE_EXPORT __declspec(dllexport) +#else +#define PROBE_EXPORT __attribute__((visibility("default"))) +#endif + +extern "C" PROBE_EXPORT bool livekitLocalAsyncProbe() { + auto& client = livekit::FfiClient::instance(); + if (!client.initialize(false)) { + return false; + } + try { + assert(livekit::uniffiBindgenBuildVersion().has_value()); + auto future = livekit_ffi::async_probe_roundtrip(42); + + // Legacy protobuf creates the object while a generated async call is in flight. + livekit::proto::FfiRequest request; + auto* options = request.mutable_new_sox_resampler(); + options->set_input_rate(48000); + options->set_output_rate(24000); + options->set_num_channels(1); + options->set_input_data_type(livekit::proto::SOXR_DATATYPE_INT16I); + options->set_output_data_type(livekit::proto::SOXR_DATATYPE_INT16I); + options->set_quality_recipe(livekit::proto::SOXR_QUALITY_HIGH); + const auto response = client.sendRequest(request); + assert(response.new_sox_resampler().has_resampler()); + const auto id = response.new_sox_resampler().resampler().handle().id(); + + // UniFFI takes co-ownership; releasing the legacy handle must leave the object usable. + auto resampler = livekit_ffi::SoxResampler::from_ffi_handle_id(id); + assert(livekit::dropFfiHandle(id)); + auto samples = resampler->push(std::vector(4800, 100)); + auto tail = resampler->flush(); + assert(samples.size() + tail.size() == 2400); + assert(future.get() == 42); + + // Publish it back to legacy FFI, take ownership again, then release every owner. + assert(resampler->ffi_handle_id() == id); + resampler = resampler->take_ffi_handle_id(); + assert(!livekit::dropFfiHandle(id)); + resampler.reset(); + auto pending = livekit_ffi::async_probe_pending(); + uniffi::shutdown_async_dispatcher(); + try { + pending.get(); + assert(false); + } catch (const uniffi::AsyncCancelledError&) { + } + client.shutdown(); + std::cout << "C++ SDK: generated async + protobuf FFI + bidirectional resampler ownership passed\n"; + return true; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + uniffi::shutdown_async_dispatcher(); + client.shutdown(); + return false; + } +} diff --git a/cpp-tests/integration/livekit/room_main.cpp b/cpp-tests/integration/livekit/room_main.cpp new file mode 100644 index 0000000..f732b85 --- /dev/null +++ b/cpp-tests/integration/livekit/room_main.cpp @@ -0,0 +1,4 @@ +// Copyright 2026 LiveKit, Inc. +// SPDX-License-Identifier: Apache-2.0 +extern "C" bool livekitLocalAsyncProbe(); +int main() { return livekitLocalAsyncProbe() ? 0 : 1; } diff --git a/cpp-tests/integration/livekit/room_probe.rs b/cpp-tests/integration/livekit/room_probe.rs new file mode 100644 index 0000000..4e8d37e --- /dev/null +++ b/cpp-tests/integration/livekit/room_probe.rs @@ -0,0 +1,13 @@ +// Copyright 2026 LiveKit, Inc. +// SPDX-License-Identifier: Apache-2.0 +// Test-only exports installed into an isolated rust-sdks snapshot, never into shipped SDKs. +#[uniffi::export(async_runtime = "tokio")] +pub async fn async_probe_roundtrip(value: u64) -> u64 { + tokio::time::sleep(std::time::Duration::from_millis(1)).await; + value +} + +#[uniffi::export] +pub async fn async_probe_pending() { + std::future::pending::<()>().await; +} 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..3aa2bc4 --- /dev/null +++ b/cpp-tests/tests/async_api_client/main.cpp @@ -0,0 +1,135 @@ +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace api = async_api_client; + +class WorkerPool { +public: + WorkerPool(): worker_([this] { run(); }) {} + + ~WorkerPool() { + { + std::lock_guard guard(mutex_); + accepting_ = false; + } + ready_.notify_all(); + worker_.join(); + } + + bool dispatch(uniffi::AsyncTask task) { + { + std::lock_guard guard(mutex_); + if (!accepting_) { + return false; + } + tasks_.push_back(std::move(task)); + } + ready_.notify_one(); + return true; + } + +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(); + } + task(); + } + } + + std::mutex mutex_; + std::condition_variable ready_; + std::deque tasks_; + bool accepting_ = true; + std::thread worker_; +}; + +class TestHttpClient final : public api::HttpClientForeign { +public: + uniffi::ForeignFuture fetch( + const std::string &url, + const std::string &credentials + ) override { + return uniffi::ForeignFuture( + [url, credentials](auto success, auto failure) { + if ( + credentials == "username:password" && + url == "https://api.github.com/repos/mozilla/uniffi-rs/issues/2017" + ) { + success(api::test_response_data()); + } else { + failure(std::make_exception_ptr( + std::runtime_error("unexpected HTTP request") + )); + } + return [] {}; + } + ); + } +}; + +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 { + auto workers = workers_; + return uniffi::ForeignFuture( + [workers, task](auto success, auto failure) { + auto cancelled = std::make_shared>(false); + if (!workers->dispatch([task, success, failure, cancelled] { + if (cancelled->load()) { + return; + } + try { + task->execute(); + success(); + } catch (...) { + failure(std::current_exception()); + } + })) { + failure(std::make_exception_ptr( + std::runtime_error("task worker rejected work") + )); + } + return [cancelled] { cancelled->store(true); }; + } + ); + } + +private: + std::shared_ptr workers_; +}; + +int main() { + auto workers = std::make_shared(); + auto client = api::ApiClient::init( + std::make_shared(), + std::make_shared(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); + + return 0; +} diff --git a/cpp-tests/tests/futures/main.cpp b/cpp-tests/tests/futures/main.cpp index e69a355..54aba58 100644 --- a/cpp-tests/tests/futures/main.cpp +++ b/cpp-tests/tests/futures/main.cpp @@ -2,11 +2,93 @@ #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; +class TestAsyncParser final : public futures::AsyncParserForeign { + 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 { + return uniffi::ForeignFuture([value](auto success, auto) { + success(std::to_string(value)); + return [] {}; + }); + } + + uniffi::ForeignFuture parse(const std::string &value) override { + return uniffi::ForeignFuture([value](auto success, auto failure) { + try { + success(std::stoi(value)); + } catch (...) { + failure(std::make_exception_ptr( + futures::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_; +}; + int main() { ASSERT_EQ("Hello, C++", futures::greet("C++")); ASSERT_TRUE(futures::always_ready().get()); @@ -73,10 +155,7 @@ int main() { 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_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); @@ -92,11 +171,133 @@ int main() { auto holding = futures::use_shared_resource({2000, 4000}); std::this_thread::sleep_for(500ms); - EXPECT_EXCEPTION( - futures::use_shared_resource({0, 250}).get(), - futures::async_error::Timeout - ); + 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", futures::stringify_using_parser(parser, 42).get()); + ASSERT_EQ(42, futures::parse_using_parser(parser, "42").get()); + EXPECT_EXCEPTION(futures::parse_using_parser(parser, "not an integer").get(), + futures::async_parser_error::InvalidInteger); + + { + auto waiting = futures::wait_using_parser(parser); + for (auto i = 0; i < 100 && started_count->load() == 0; ++i) { + std::this_thread::sleep_for(1ms); + } + ASSERT_EQ(1, started_count->load()); + parser.reset(); + ASSERT_EQ(0, destruction_count->load()); + waiting.cancel(); + EXPECT_EXCEPTION(waiting.get(), uniffi::AsyncCancelledError); + } + for (auto i = 0; i < 100 && (cancellation_count->load() == 0 || destruction_count->load() == 0); + ++i) { + std::this_thread::sleep_for(1ms); + } + 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(futures::pending()); + } + const auto parked_deadline = std::chrono::steady_clock::now() + 5s; + while (futures::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); + std::cout << "2000 parked futures: process threads " << *threads_before << " -> " + << *threads_parked << "\n"; + } + for (auto &future : parked) { + future.cancel(); + } + for (auto &future : parked) { + EXPECT_EXCEPTION(future.get(), uniffi::AsyncCancelledError); + } + ASSERT_EQ(0, futures::pending_count()); + + const auto begin = std::chrono::steady_clock::now(); + std::vector> ready_batch; + for (int i = 0; i < 20000; ++i) { + ready_batch.push_back(futures::always_ready()); + } + for (auto &future : ready_batch) { + ASSERT_TRUE(future.get()); + } + const auto elapsed = + std::chrono::duration(std::chrono::steady_clock::now() - begin).count(); + std::cout << "20000 ready calls: " << elapsed << "s (" << 20000 / elapsed << " calls/s)\n"; + + // 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::default_async_dispatcher().is_worker()); + ASSERT_TRUE(std::move(result).get()); + auto inner = futures::pending(); + EXPECT_EXCEPTION(inner.get(), std::logic_error); + EXPECT_EXCEPTION(uniffi::shutdown_async_dispatcher(), 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::AsyncDispatcherError &) { + 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 = futures::pending(); + auto shutdown_foreign = futures::wait_using_parser( + std::make_shared(started_count, cancellation_count, destruction_count)); + uniffi::shutdown_async_dispatcher(); + stop_producers.store(true); + for (auto &producer : producers) { + producer.join(); + } + EXPECT_EXCEPTION(std::move(late_continuation).then([](auto) {}), uniffi::AsyncDispatcherError); + ASSERT_TRUE(late_continuation.get()); + uniffi::shutdown_async_dispatcher(); // Idempotent. + EXPECT_EXCEPTION(shutdown_pending.get(), uniffi::AsyncCancelledError); + EXPECT_EXCEPTION(shutdown_foreign.get(), uniffi::AsyncCancelledError); + EXPECT_EXCEPTION(futures::always_ready().get(), uniffi::AsyncDispatcherError); + return 0; } diff --git a/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md new file mode 100644 index 0000000..6142730 --- /dev/null +++ b/docs/ASYNC_RUNTIME.md @@ -0,0 +1,114 @@ +# C++17 async runtime + +## Branch and migration + +`livekit/dev-async-support` starts at `livekit/dev` (`e558880`, UniFFI 0.31.2 / C++17). +The original Rust-to-C++ async commits (`9d86abe`, `c4ad947`) were cherry-picked, then the async +work from stash `3e98bc0` was copied onto that base. All original branches and stashes remain intact. +The two older stashes concern non-async generator work; they were inspected, not applied wholesale. +IDE-only changes from the async stash were left out. + +Nothing was pushed, and neither SDK's production generator pin or checked-out sources were changed. + +## Review of the recovered design + +The original PR allocated a detached thread for every call. The recovered stash had already moved +to a shared dispatcher and introduced callback-based foreign futures and continuations. It was the +better starting point, but needed a consistent ownership and execution model: + +- A rejecting custom dispatcher started a second fallback executor. This created two control paths + and made cleanup depend on executor rejection policy. The implementation now has one owned control + executor, with no replaceable dispatcher or fallback worker. +- Shutdown required every caller to make every future terminal first. The executor now registers + active Rust and foreign operations, rejects new work at shutdown, cancels registered operations, + drains completions and continuations, and joins its worker. Concurrent application callers and + repeated shutdown calls are covered by tests. +- Foreign method startup could invoke user code inside Rust polling. Startup, cancellation, and + completion delivery are now deferred onto the same executor. Application completion callbacks can + come from other threads; they enqueue delivery instead of reentering Rust. +- Continuations required another executor argument and could fall back to inline execution on + rejection. `then(callback)` now uses the control executor and retains a registration through + delivery. Attaching a continuation after shutdown throws without consuming the original future. +- Blocking on an incomplete future in an executor callback could deadlock. Blocking waits now throw + on that thread; zero-duration readiness checks remain allowed. Self-shutdown also throws. +- The executor's work and drain conditions are separate, so a shutdown waiter cannot consume the + only notification intended for a sleeping worker. + +The older experimental branch's saved review also identified cancellation/free races, discarded +lowered results, and leaked foreign oneshot senders. Those fixes are retained: only the driver touches +Rust handles, READY always goes through complete/lift/free, and foreign cancellation sends exactly +one cancelled completion to release the sender even after Rust drops its receiver. + +## Execution and ownership + +All generated components linked into one C++ executable or shared library use the same inline +runtime instance. This is not a singleton shared across independently built DLLs/DSOs. + +One lazy, joinable worker executes short control tasks. Each Rust future has at most one queued or +running driver and one outstanding UniFFI poll. Wakes enqueue work only when progress is possible; +there is no timer scanning, blocking waiter, or C++ thread per operation. A driver yields after 64 +actions so repeated immediate wakes do not monopolize the queue. + +The executor's registry owns an active Rust state until completion frees its handle. This also lets +poll callbacks reuse the state's address instead of allocating a new userdata holder for every poll. +Future destruction and explicit cancellation request work through that state; neither calls +`rust_future_cancel` directly from an application thread. Rust's terminal call status decides whether +completion or cancellation won the race, so a successful result is not discarded or leaked. + +A C++ foreign operation returns `ForeignFuture` containing a start function. That function arranges +nonblocking application work and returns a cancellation action. The bridge keeps the implementation +alive until success, failure, or cancellation wins. Application captures are released outside internal +state locks. A `FutureContinuation` owns its cancellation action; retain it until delivery. Its return +from `then` is marked `nodiscard` to catch accidental immediate cancellation. + +Rust still owns its I/O runtimes. This executor supplies the missing C++ control/runtime boundary; +it does not replace Tokio or implement another network stack. + +## Limits and contract + +- Continuations, foreign method startup, cancellation actions, and Rust polls must return promptly. + Blocking I/O or CPU-heavy work belongs on an application's existing workers / async I/O service, + or the Rust runtime's appropriate task pool. A single long-running poll cannot be preempted. +- Shutdown is final for the binding image, not an operation to perform on every room disconnect. + Stop producers, call `shutdown_async_dispatcher()` on an application thread, and release generated + objects before unloading Rust. Restartable runtime instances are not implemented. +- A foreign cancellation action must release its operation's resources and prevent unbounded work. + The bridge cannot forcibly join application-owned workers. A nonreturning callback can stall + executor shutdown. +- Queue/state memory grows with requested concurrency and captured payloads. Driver wakeups are + coalesced; this is not a fixed-capacity or hard-real-time executor. Allocation exhaustion is fatal + where abandoning accepted cleanup would leak a handle or violate the FFI protocol. +- Async trait interfaces retain the recovered `Foo` / `FooForeign` / `FooImpl` split. A Rust-backed + async trait object returned as the common base needs a cast to `FooImpl` before invoking methods. + The integration probes verify foreign implementations crossing into Rust, not that reverse API. + +## Local verification + +Verified on macOS arm64 with Apple Clang 21 and C++17: + +- All 22 fixture CTest targets passed. +- The futures suite passed 10 consecutive runs, including simultaneous callers and shutdown, + cancellation/completion races, pending foreign calls, typed errors, methods and constructors. +- 2,000 simultaneously parked futures left process thread count unchanged: 4 before and 4 during. +- A debug-build batch of 20,000 ready calls measured about 0.06 seconds (roughly 330,000 calls/second) + on this workstation. This is a local throughput check, not a production benchmark or latency SLA. +- The futures executable passed AddressSanitizer + UndefinedBehaviorSanitizer, and separately + ThreadSanitizer. The Rust fixture library itself was not sanitizer-instrumented. +- A real `livekit-ffi/core-modules` build generated and compiled all four C++ components. The core + probe passed HTTP/WebSocket round trips through foreign C++ async interfaces, typed transport + errors, cancellation, and shutdown across `livekit-net` and `livekit-ffi`. +- A local C++ SDK shared library built with the unpublished generator. Its probe passed a generated + async timer call alongside the real legacy protobuf client, and transferred a Sox resampler's + ownership from protobuf FFI to UniFFI and back before cancellation and shutdown. + +Inputs were committed snapshots of the standalone `rust-sdks` checkout (`0a0fbe31`), +`client-sdk-cpp` (`158d078`), and the C++ checkout's Rust submodule (`6047bebd`), with their checked-out +native/protocol submodules. The C++ capture branch requires its own Rust schema; substituting the +standalone Rust checkout causes capture protobuf compilation failures unrelated to async support. +Original dirty files and submodule selections were preserved. + +The room-mode async exports exist only in the disposable snapshot: current main has not merged the +room-mode data-track/data-stream UniFFI APIs. See [the integration probes](../cpp-tests/integration/livekit/README.md) +for the test sources and reproduction steps. No live server, media traffic, Windows, or Linux runtime +was exercised. Cross-platform CI and long-duration / large-payload measurements remain necessary +before shipping. diff --git a/fixtures/Cargo.toml b/fixtures/Cargo.toml index a18f32e..b549673 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" } diff --git a/fixtures/async-calls/Cargo.toml b/fixtures/async-calls/Cargo.toml index e03383d..c491a06 100644 --- a/fixtures/async-calls/Cargo.toml +++ b/fixtures/async-calls/Cargo.toml @@ -10,6 +10,7 @@ name = "uniffi_fixture_async_calls" crate-type = ["lib"] [dependencies] +async-trait = "0.1" once_cell = "1.18.0" futures-timer = "3.0" thiserror = "1.0" diff --git a/fixtures/async-calls/src/lib.rs b/fixtures/async-calls/src/lib.rs index 00f352c..34cd3ad 100644 --- a/fixtures/async-calls/src/lib.rs +++ b/fixtures/async-calls/src/lib.rs @@ -202,4 +202,44 @@ pub async fn use_shared_resource(options: SharedResourceOptions) -> Result<(), A acquire_with_timeout(options).await } +#[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 AsyncParser: 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::include_scaffolding!("async-calls"); diff --git a/fixtures/src/lib.rs b/fixtures/src/lib.rs index c78f32d..1590896 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!(); From ef3f257011291b28ebacfbb543a8e8f99e6f325a Mon Sep 17 00:00:00 2001 From: Alan George Date: Fri, 20 Nov 2026 11:54:10 -0700 Subject: [PATCH 04/19] Keep async runtime coverage focused and remove development probes --- CHANGELOG.md | 1 + cpp-tests/CMakeLists.txt | 7 +- cpp-tests/include/async_api_client_test.hpp | 166 +++++++++++++++++ cpp-tests/integration/livekit/CMakeLists.txt | 25 --- cpp-tests/integration/livekit/README.md | 61 ------- cpp-tests/integration/livekit/core.cpp | 136 -------------- cpp-tests/integration/livekit/room.cpp | 69 ------- cpp-tests/integration/livekit/room_main.cpp | 4 - cpp-tests/integration/livekit/room_probe.rs | 13 -- cpp-tests/tests/async_api_client/main.cpp | 182 +++++++------------ docs/ASYNC_RUNTIME.md | 75 +------- 11 files changed, 240 insertions(+), 499 deletions(-) create mode 100644 cpp-tests/include/async_api_client_test.hpp delete mode 100644 cpp-tests/integration/livekit/CMakeLists.txt delete mode 100644 cpp-tests/integration/livekit/README.md delete mode 100644 cpp-tests/integration/livekit/core.cpp delete mode 100644 cpp-tests/integration/livekit/room.cpp delete mode 100644 cpp-tests/integration/livekit/room_main.cpp delete mode 100644 cpp-tests/integration/livekit/room_probe.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 5971cc2..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 diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index b26b5ca..b95489e 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) @@ -121,3 +122,5 @@ add_custom_target(bindings ALL WORKING_DIRECTORY ${BINDINGS_BUILD_DIR} COMMENT "Generating bindings" ) + +set_tests_properties(async_api_client-test PROPERTIES TIMEOUT 45) 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..0b6bd93 --- /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 dispatch(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::default_async_dispatcher().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->dispatch([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->dispatch([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/integration/livekit/CMakeLists.txt b/cpp-tests/integration/livekit/CMakeLists.txt deleted file mode 100644 index 5900dda..0000000 --- a/cpp-tests/integration/livekit/CMakeLists.txt +++ /dev/null @@ -1,25 +0,0 @@ -cmake_minimum_required(VERSION 3.16) -project(livekit-uniffi-core-probe LANGUAGES CXX) -set(CMAKE_CXX_STANDARD 17) -set(CMAKE_CXX_STANDARD_REQUIRED ON) -set(CMAKE_CXX_EXTENSIONS OFF) -find_package(Threads REQUIRED) -if(NOT LIVEKIT_BINDINGS_DIR OR NOT LIVEKIT_FFI_LIBRARY) - message(FATAL_ERROR "Set LIVEKIT_BINDINGS_DIR and LIVEKIT_FFI_LIBRARY to generated core bindings and their matching Rust library") -endif() -file(GLOB BINDING_SOURCES CONFIGURE_DEPENDS "${LIVEKIT_BINDINGS_DIR}/*.cpp") -add_executable(core-probe core.cpp ${BINDING_SOURCES}) -target_include_directories(core-probe PRIVATE "${LIVEKIT_BINDINGS_DIR}") -target_link_libraries(core-probe PRIVATE "${LIVEKIT_FFI_LIBRARY}" Threads::Threads) -if(NOT MSVC) - target_compile_options(core-probe PRIVATE -pedantic-errors) -endif() -# Keep assert-based checks enabled even if a caller selects a release configuration. -if(MSVC) - target_compile_options(core-probe PRIVATE /UNDEBUG) -else() - target_compile_options(core-probe PRIVATE -UNDEBUG) -endif() -enable_testing() -add_test(NAME core-probe COMMAND core-probe) -set_tests_properties(core-probe PROPERTIES TIMEOUT 30) diff --git a/cpp-tests/integration/livekit/README.md b/cpp-tests/integration/livekit/README.md deleted file mode 100644 index 0babdf2..0000000 --- a/cpp-tests/integration/livekit/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# Local LiveKit integration probes - -These are verification sources, not SDK changes or a new shipped API. Run against isolated snapshots -of the local SDK checkouts. Do not replace their generator pins or edit their submodules in place. - -## Core modules - -Build `livekit-ffi` from the local standalone `rust-sdks` checkout snapshot with -`--no-default-features --features core-modules`, using a separate Cargo target directory. Populate its -`livekit-protocol/protocol` submodule from that checkout too. Generate with this branch's -`target/debug/uniffi-bindgen-cpp --library --out-dir `. - -```sh -cmake -S cpp-tests/integration/livekit -B /tmp/livekit-core-probe \ - -DLIVEKIT_BINDINGS_DIR= \ - -DLIVEKIT_FFI_LIBRARY= -cmake --build /tmp/livekit-core-probe -j 6 -ctest --test-dir /tmp/livekit-core-probe --output-on-failure -``` - -`core.cpp` uses the real exported `livekit-net` HTTP and WebSocket self-tests with C++ async host -implementations. It covers records, bytes, optional values, nested object handles, typed errors, -cancellation, and shutdown with calls pending in multiple generated components. No server is needed. -The transports are mocks; this does not verify networking, TLS, or a LiveKit room connection. - -## C++ SDK and legacy protobuf - -Snapshot the local `client-sdk-cpp` checkout and **its checked-out `client-sdk-rust` submodule**. -A feature branch may require a protobuf schema that the standalone Rust checkout does not have. -Copy the Rust submodules (`livekit-protocol/protocol` and `yuv-sys/libyuv`) and C++ `cpp-tools` as well. -When reusing a build tree with newly archived sources, refresh source timestamps so Cargo and CMake -regenerate the protobufs rather than reusing output from a previous snapshot. - -Only inside these disposable snapshots: - -1. Copy `room_probe.rs` to `livekit-ffi/src/async_runtime_probe.rs`. Append - `#[cfg(feature = "room-apis")] mod async_runtime_probe;` to that crate's `src/lib.rs`. - These exports provide an async timer round trip and a permanently pending call without requiring - the unmerged room-mode UniFFI PRs or a running LiveKit server. -2. Replace the generation command in `cmake/uniffi_cpp.cmake` with this branch's local generator, - preserving its `--library` and `--out-dir` arguments. -3. Append these verification targets to the copied SDK's root `CMakeLists.txt`, replacing - `` with this directory's absolute path: - - ```cmake - target_sources(livekit PRIVATE "/room.cpp") - add_executable(livekit_local_async_probe "/room_main.cpp") - target_link_libraries(livekit_local_async_probe PRIVATE livekit) - ``` - -4. Configure a **Debug** SDK build so assertions remain enabled. Build `livekit_local_async_probe` - and run it. An existing matching WebRTC archive can be reused with `LK_CUSTOM_WEBRTC`. - -`room.cpp` runs *inside* the SDK shared library, sharing its generated bindings and executor. It -starts a generated async call, creates a Sox resampler through the actual SDK `FfiClient` protobuf -request path, takes UniFFI co-ownership, releases the legacy handle, processes samples, republishes -the object to legacy FFI, takes ownership again, and releases it. It then checks cancellation and -executor shutdown. The SDK's existing generated build-version adapter is exercised too. - -These probes do not modify production SDK source or publish artifacts. Full room/data-stream UniFFI -migration, live-server integration, and platform CI remain separate checks. diff --git a/cpp-tests/integration/livekit/core.cpp b/cpp-tests/integration/livekit/core.cpp deleted file mode 100644 index 3998032..0000000 --- a/cpp-tests/integration/livekit/core.cpp +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright 2026 LiveKit, Inc. -// SPDX-License-Identifier: Apache-2.0 -#include -#include -#include - -#include "livekit_ffi.hpp" -#include "livekit_net.hpp" - -using namespace std::chrono_literals; -namespace net = livekit_net; - -class Http final : public net::HttpClientForeign { -public: - uniffi::ForeignFuture request(const net::HttpMethod&, const std::string& url, - const std::vector&, - std::optional>) override { - assert(uniffi::detail::default_async_dispatcher().is_worker()); - return uniffi::ForeignFuture([this, url](auto success, auto failure) { - assert(uniffi::detail::default_async_dispatcher().is_worker()); - if (url == "pending") { - { - std::lock_guard lock(mutex); - pending = std::move(success); - } - return uniffi::ForeignFuture::Cancel([this] { - assert(uniffi::detail::default_async_dispatcher().is_worker()); - std::lock_guard lock(mutex); - pending = {}; - ++cancelled; - }); - } - if (url == "error") { - failure(std::make_exception_ptr(net::transport_error::Closed())); - } else { - success(net::HttpResponse{200, {{"x-probe", "ok"}}, {1, 2, 3}}); - } - return uniffi::ForeignFuture::Cancel{}; - }); - } - - std::mutex mutex; - std::function pending; - std::atomic cancelled{0}; -}; - -class Connection final : public net::WsConnectionForeign { -public: - uniffi::ForeignFuture send(const std::vector& frame) override { - return uniffi::ForeignFuture([this, frame](auto success, auto) { - assert(uniffi::detail::default_async_dispatcher().is_worker()); - frame_ = frame; - success(); - return [] {}; - }); - } - uniffi::ForeignFuture>> recv() override { - return uniffi::ForeignFuture>>([this](auto success, auto) { - success(std::optional>(frame_)); - return [] {}; - }); - } - uniffi::ForeignFuture close() override { - return uniffi::ForeignFuture([](auto success, auto) { - success(); - return [] {}; - }); - } - -private: - std::vector frame_; -}; - -class Ws final : public net::WsClientForeign { -public: - uniffi::ForeignFuture connect(const std::string&, const std::vector&, - uint64_t) override { - return uniffi::ForeignFuture([](auto success, auto) { - success(net::WsConnectResult{std::make_shared()}); - return [] {}; - }); - } -}; - -int main() { - auto http = std::make_shared(); - net::set_http_client(http); - net::set_ws_client(std::make_shared()); - const auto response = net::self_test_http_get("ok").get(); - assert(response.status == 200 && response.body == std::vector({1, 2, 3})); - try { - net::self_test_http_get("error").get(); - assert(false); - } catch (const net::transport_error::Closed&) { - } - - std::vector bytes(4096, 42); - assert(net::self_test_ws_echo("mock", bytes).get() == bytes); - - auto pending = net::self_test_http_get("pending"); - const auto deadline = std::chrono::steady_clock::now() + 5s; - for (;;) { - { - std::lock_guard lock(http->mutex); - if (http->pending) { - break; - } - } - assert(std::chrono::steady_clock::now() < deadline); - std::this_thread::yield(); - } - pending.cancel(); - try { - pending.get(); - assert(false); - } catch (const uniffi::AsyncCancelledError&) { - } - - // Different generated components must share one executor and cancellation model. - livekit_ffi::log_forward_bootstrap(livekit_ffi::LogForwardFilter::kOff); - auto log = livekit_ffi::log_forward_receive(); - auto outstanding = net::self_test_http_get("pending"); - uniffi::shutdown_async_dispatcher(); - try { - log.get(); - assert(false); - } catch (const uniffi::AsyncCancelledError&) { - } - try { - outstanding.get(); - assert(false); - } catch (const uniffi::AsyncCancelledError&) { - } - assert(http->cancelled.load() >= 1); - std::cout << "LiveKit core: HTTP, WebSocket, typed errors, callbacks, cancellation, shutdown passed\n"; -} diff --git a/cpp-tests/integration/livekit/room.cpp b/cpp-tests/integration/livekit/room.cpp deleted file mode 100644 index 0c0261f..0000000 --- a/cpp-tests/integration/livekit/room.cpp +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2026 LiveKit, Inc. -// SPDX-License-Identifier: Apache-2.0 -// Compiled into the isolated C++ SDK so generated calls and the legacy client share the same library. -#include -#include - -#include "ffi.pb.h" -#include "ffi_client.h" -#include "livekit_ffi.hpp" -#include "uniffi_bindgen_adapter.h" - -#ifdef _WIN32 -#define PROBE_EXPORT __declspec(dllexport) -#else -#define PROBE_EXPORT __attribute__((visibility("default"))) -#endif - -extern "C" PROBE_EXPORT bool livekitLocalAsyncProbe() { - auto& client = livekit::FfiClient::instance(); - if (!client.initialize(false)) { - return false; - } - try { - assert(livekit::uniffiBindgenBuildVersion().has_value()); - auto future = livekit_ffi::async_probe_roundtrip(42); - - // Legacy protobuf creates the object while a generated async call is in flight. - livekit::proto::FfiRequest request; - auto* options = request.mutable_new_sox_resampler(); - options->set_input_rate(48000); - options->set_output_rate(24000); - options->set_num_channels(1); - options->set_input_data_type(livekit::proto::SOXR_DATATYPE_INT16I); - options->set_output_data_type(livekit::proto::SOXR_DATATYPE_INT16I); - options->set_quality_recipe(livekit::proto::SOXR_QUALITY_HIGH); - const auto response = client.sendRequest(request); - assert(response.new_sox_resampler().has_resampler()); - const auto id = response.new_sox_resampler().resampler().handle().id(); - - // UniFFI takes co-ownership; releasing the legacy handle must leave the object usable. - auto resampler = livekit_ffi::SoxResampler::from_ffi_handle_id(id); - assert(livekit::dropFfiHandle(id)); - auto samples = resampler->push(std::vector(4800, 100)); - auto tail = resampler->flush(); - assert(samples.size() + tail.size() == 2400); - assert(future.get() == 42); - - // Publish it back to legacy FFI, take ownership again, then release every owner. - assert(resampler->ffi_handle_id() == id); - resampler = resampler->take_ffi_handle_id(); - assert(!livekit::dropFfiHandle(id)); - resampler.reset(); - auto pending = livekit_ffi::async_probe_pending(); - uniffi::shutdown_async_dispatcher(); - try { - pending.get(); - assert(false); - } catch (const uniffi::AsyncCancelledError&) { - } - client.shutdown(); - std::cout << "C++ SDK: generated async + protobuf FFI + bidirectional resampler ownership passed\n"; - return true; - } catch (const std::exception& error) { - std::cerr << error.what() << '\n'; - uniffi::shutdown_async_dispatcher(); - client.shutdown(); - return false; - } -} diff --git a/cpp-tests/integration/livekit/room_main.cpp b/cpp-tests/integration/livekit/room_main.cpp deleted file mode 100644 index f732b85..0000000 --- a/cpp-tests/integration/livekit/room_main.cpp +++ /dev/null @@ -1,4 +0,0 @@ -// Copyright 2026 LiveKit, Inc. -// SPDX-License-Identifier: Apache-2.0 -extern "C" bool livekitLocalAsyncProbe(); -int main() { return livekitLocalAsyncProbe() ? 0 : 1; } diff --git a/cpp-tests/integration/livekit/room_probe.rs b/cpp-tests/integration/livekit/room_probe.rs deleted file mode 100644 index 4e8d37e..0000000 --- a/cpp-tests/integration/livekit/room_probe.rs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2026 LiveKit, Inc. -// SPDX-License-Identifier: Apache-2.0 -// Test-only exports installed into an isolated rust-sdks snapshot, never into shipped SDKs. -#[uniffi::export(async_runtime = "tokio")] -pub async fn async_probe_roundtrip(value: u64) -> u64 { - tokio::time::sleep(std::time::Duration::from_millis(1)).await; - value -} - -#[uniffi::export] -pub async fn async_probe_pending() { - std::future::pending::<()>().await; -} diff --git a/cpp-tests/tests/async_api_client/main.cpp b/cpp-tests/tests/async_api_client/main.cpp index 3aa2bc4..1c9b0d1 100644 --- a/cpp-tests/tests/async_api_client/main.cpp +++ b/cpp-tests/tests/async_api_client/main.cpp @@ -1,135 +1,75 @@ +#include #include -#include - -#include -#include -#include -#include -#include -#include - +using namespace std::chrono_literals; namespace api = async_api_client; +using namespace async_api_client_test; -class WorkerPool { -public: - WorkerPool(): worker_([this] { run(); }) {} - - ~WorkerPool() { - { - std::lock_guard guard(mutex_); - accepting_ = false; - } - ready_.notify_all(); - worker_.join(); +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(); } - - bool dispatch(uniffi::AsyncTask task) { - { - std::lock_guard guard(mutex_); - if (!accepting_) { - return false; - } - tasks_.push_back(std::move(task)); - } - ready_.notify_one(); - return true; - } - -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(); - } - task(); - } - } - - std::mutex mutex_; - std::condition_variable ready_; - std::deque tasks_; - bool accepting_ = true; - std::thread worker_; -}; - -class TestHttpClient final : public api::HttpClientForeign { -public: - uniffi::ForeignFuture fetch( - const std::string &url, - const std::string &credentials - ) override { - return uniffi::ForeignFuture( - [url, credentials](auto success, auto failure) { - if ( - credentials == "username:password" && - url == "https://api.github.com/repos/mozilla/uniffi-rs/issues/2017" - ) { - success(api::test_response_data()); - } else { - failure(std::make_exception_ptr( - std::runtime_error("unexpected HTTP request") - )); - } - return [] {}; - } - ); - } -}; - -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 { - auto workers = workers_; - return uniffi::ForeignFuture( - [workers, task](auto success, auto failure) { - auto cancelled = std::make_shared>(false); - if (!workers->dispatch([task, success, failure, cancelled] { - if (cancelled->load()) { - return; - } - try { - task->execute(); - success(); - } catch (...) { - failure(std::current_exception()); - } - })) { - failure(std::make_exception_ptr( - std::runtime_error("task worker rejected work") - )); - } - return [cancelled] { cancelled->store(true); }; - } - ); - } - -private: - std::shared_ptr workers_; -}; +} int main() { auto workers = std::make_shared(); - auto client = api::ApiClient::init( - std::make_shared(), - std::make_shared(workers) - ); + 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->dispatch([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()); - return 0; + client.reset(); + uniffi::shutdown_async_dispatcher(); + workers->shutdown(); } diff --git a/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md index 6142730..e4d0c73 100644 --- a/docs/ASYNC_RUNTIME.md +++ b/docs/ASYNC_RUNTIME.md @@ -1,44 +1,5 @@ # C++17 async runtime -## Branch and migration - -`livekit/dev-async-support` starts at `livekit/dev` (`e558880`, UniFFI 0.31.2 / C++17). -The original Rust-to-C++ async commits (`9d86abe`, `c4ad947`) were cherry-picked, then the async -work from stash `3e98bc0` was copied onto that base. All original branches and stashes remain intact. -The two older stashes concern non-async generator work; they were inspected, not applied wholesale. -IDE-only changes from the async stash were left out. - -Nothing was pushed, and neither SDK's production generator pin or checked-out sources were changed. - -## Review of the recovered design - -The original PR allocated a detached thread for every call. The recovered stash had already moved -to a shared dispatcher and introduced callback-based foreign futures and continuations. It was the -better starting point, but needed a consistent ownership and execution model: - -- A rejecting custom dispatcher started a second fallback executor. This created two control paths - and made cleanup depend on executor rejection policy. The implementation now has one owned control - executor, with no replaceable dispatcher or fallback worker. -- Shutdown required every caller to make every future terminal first. The executor now registers - active Rust and foreign operations, rejects new work at shutdown, cancels registered operations, - drains completions and continuations, and joins its worker. Concurrent application callers and - repeated shutdown calls are covered by tests. -- Foreign method startup could invoke user code inside Rust polling. Startup, cancellation, and - completion delivery are now deferred onto the same executor. Application completion callbacks can - come from other threads; they enqueue delivery instead of reentering Rust. -- Continuations required another executor argument and could fall back to inline execution on - rejection. `then(callback)` now uses the control executor and retains a registration through - delivery. Attaching a continuation after shutdown throws without consuming the original future. -- Blocking on an incomplete future in an executor callback could deadlock. Blocking waits now throw - on that thread; zero-duration readiness checks remain allowed. Self-shutdown also throws. -- The executor's work and drain conditions are separate, so a shutdown waiter cannot consume the - only notification intended for a sleeping worker. - -The older experimental branch's saved review also identified cancellation/free races, discarded -lowered results, and leaked foreign oneshot senders. Those fixes are retained: only the driver touches -Rust handles, READY always goes through complete/lift/free, and foreign cancellation sends exactly -one cancelled completion to release the sender even after Rust drops its receiver. - ## Execution and ownership All generated components linked into one C++ executable or shared library use the same inline @@ -80,35 +41,13 @@ it does not replace Tokio or implement another network stack. where abandoning accepted cleanup would leak a handle or violate the FFI protocol. - Async trait interfaces retain the recovered `Foo` / `FooForeign` / `FooImpl` split. A Rust-backed async trait object returned as the common base needs a cast to `FooImpl` before invoking methods. - The integration probes verify foreign implementations crossing into Rust, not that reverse API. - -## Local verification - -Verified on macOS arm64 with Apple Clang 21 and C++17: + The generic fixtures verify foreign implementations crossing into Rust, not that reverse API. -- All 22 fixture CTest targets passed. -- The futures suite passed 10 consecutive runs, including simultaneous callers and shutdown, - cancellation/completion races, pending foreign calls, typed errors, methods and constructors. -- 2,000 simultaneously parked futures left process thread count unchanged: 4 before and 4 during. -- A debug-build batch of 20,000 ready calls measured about 0.06 seconds (roughly 330,000 calls/second) - on this workstation. This is a local throughput check, not a production benchmark or latency SLA. -- The futures executable passed AddressSanitizer + UndefinedBehaviorSanitizer, and separately - ThreadSanitizer. The Rust fixture library itself was not sanitizer-instrumented. -- A real `livekit-ffi/core-modules` build generated and compiled all four C++ components. The core - probe passed HTTP/WebSocket round trips through foreign C++ async interfaces, typed transport - errors, cancellation, and shutdown across `livekit-net` and `livekit-ffi`. -- A local C++ SDK shared library built with the unpublished generator. Its probe passed a generated - async timer call alongside the real legacy protobuf client, and transferred a Sox resampler's - ownership from protobuf FFI to UniFFI and back before cancellation and shutdown. +## Verification -Inputs were committed snapshots of the standalone `rust-sdks` checkout (`0a0fbe31`), -`client-sdk-cpp` (`158d078`), and the C++ checkout's Rust submodule (`6047bebd`), with their checked-out -native/protocol submodules. The C++ capture branch requires its own Rust schema; substituting the -standalone Rust checkout causes capture protobuf compilation failures unrelated to async support. -Original dirty files and submodule selections were preserved. +The 22 fixture tests cover async functions, methods, constructors, typed errors, cancellation, +continuations, foreign implementations, and executor shutdown. The async API client test exercises +the upstream example with application-owned workers for blocking work. -The room-mode async exports exist only in the disposable snapshot: current main has not merged the -room-mode data-track/data-stream UniFFI APIs. See [the integration probes](../cpp-tests/integration/livekit/README.md) -for the test sources and reproduction steps. No live server, media traffic, Windows, or Linux runtime -was exercised. Cross-platform CI and long-duration / large-payload measurements remain necessary -before shipping. +Downstream SDK integration tests belong in their consuming repositories. This repository keeps +only the fixtures needed to verify generated bindings and the async runtime protocol. From 1e745be678cfbc969e85d4e6922184384ad5d47b Mon Sep 17 00:00:00 2001 From: Alan George Date: Fri, 20 Nov 2026 17:55:09 -0700 Subject: [PATCH 05/19] Harden and test the UniFFI async executor Use AsyncExecutor throughout the generated bindings. Keep shutdown idempotent, free rejected Rust handles once, and deliver callback and value-transfer failures through the future lifecycle. Generate async record and enum methods, cover executor and FFI behavior with focused tests, and replace benchmark output with functional assertions. Document the runtime and its UniFFI contract. --- README.md | 18 +- bindgen/src/bindings/cpp/templates/async.cpp | 71 ++--- bindgen/src/bindings/cpp/templates/async.hpp | 74 +++-- .../cpp/templates/callback_iface_tmpl.cpp | 38 ++- .../cpp/templates/flat_enum_methods.cpp | 9 +- .../cpp/templates/flat_enum_methods.hpp | 5 +- bindgen/src/bindings/cpp/templates/macros.cpp | 20 ++ bindgen/src/bindings/cpp/templates/obj.cpp | 10 +- .../bindings/cpp/templates/value_methods.cpp | 9 +- .../bindings/cpp/templates/value_methods.hpp | 5 +- cpp-tests/CMakeLists.txt | 14 +- cpp-tests/include/async_api_client_test.hpp | 8 +- cpp-tests/tests/async_api_client/main.cpp | 4 +- .../tests/async_executor/ffi_lifecycle.cpp | 287 ++++++++++++++++++ cpp-tests/tests/async_executor/main.cpp | 214 +++++++++++++ cpp-tests/tests/async_executor/peer.cpp | 9 + .../tests/async_executor/test_support.hpp | 21 ++ cpp-tests/tests/futures/main.cpp | 35 +-- docs/ASYNC_RUNTIME.md | 281 +++++++++++++---- fixtures/async-calls/src/lib.rs | 79 ++++- 20 files changed, 1021 insertions(+), 190 deletions(-) create mode 100644 cpp-tests/tests/async_executor/ffi_lifecycle.cpp create mode 100644 cpp-tests/tests/async_executor/main.cpp create mode 100644 cpp-tests/tests/async_executor/peer.cpp create mode 100644 cpp-tests/tests/async_executor/test_support.hpp diff --git a/README.md b/README.md index d1469b7..02ce523 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,11 @@ C++17 or newer is required to compile the bindings. # Async functions -Rust async functions, constructors, and object methods return a move-only `uniffi::Future`. +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. @@ -74,10 +78,11 @@ Keep continuations and foreign callback startup/cancellation actions short and n 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_dispatcher()` from an application -thread before unloading the Rust library. Shutdown rejects new calls, cancels active calls, drains -queued cleanup and continuations, and joins the worker. The executor cannot be restarted. A -nonreturning application callback can prevent shutdown from completing. +Stop application producers, then call `uniffi::shutdown_async_executor()` from an application +thread before unloading the Rust library. Shutdown rejects new C++ calls to async Rust exports +with `uniffi::AsyncExecutorError`, cancels active calls, drains queued cleanup and continuations, +and joins the worker. Shutdown is terminal. A nonreturning application callback can prevent +shutdown from completing. Async callback-interface methods return `uniffi::ForeignFuture` from their C++ implementation. The start function arranges application work, invokes exactly one supplied completion callback, and @@ -98,8 +103,7 @@ Completion callbacks may be invoked from any application thread; the bridge defe 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. -See [the runtime design review](docs/ASYNC_RUNTIME.md) for ownership, shutdown, performance checks, -and local LiveKit SDK verification. +See [the async runtime design](docs/ASYNC_RUNTIME.md) for handle ownership, scheduling, and shutdown. # Configuration options diff --git a/bindgen/src/bindings/cpp/templates/async.cpp b/bindgen/src/bindings/cpp/templates/async.cpp index 3a1e3e7..aa058de 100644 --- a/bindgen/src/bindings/cpp/templates/async.cpp +++ b/bindgen/src/bindings/cpp/templates/async.cpp @@ -6,12 +6,18 @@ constexpr int8_t UNIFFI_RUST_FUTURE_POLL_WAKE = 1; // 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::default_async_dispatcher().track([weak] { + operation_id_ = ::uniffi::detail::async_executor().track([weak] { if (auto state = weak.lock()) { - ::uniffi::detail::dispatch_async([state] { state->cancel(); }); + state->enqueue_or_cancel([state] { state->cancel(); }); } }); } @@ -28,7 +34,7 @@ class ForeignFutureTaskState { cancel = std::move(cancel_); complete_cancelled = std::move(complete_cancelled_); } - ::uniffi::detail::default_async_dispatcher().untrack(operation_id_); + ::uniffi::detail::async_executor().untrack(operation_id_); // Releasing captures can destroy application objects; do it outside the state mutex. return true; } @@ -78,7 +84,7 @@ class ForeignFutureTaskState { if (complete_cancelled) { complete_cancelled(); } - ::uniffi::detail::default_async_dispatcher().untrack(operation_id_); + ::uniffi::detail::async_executor().untrack(operation_id_); } private: @@ -98,9 +104,7 @@ inline void foreign_future_drop(uint64_t handle) noexcept { auto state = std::unique_ptr>( reinterpret_cast *>(handle)); auto task_state = *state; - if (!::uniffi::detail::dispatch_async([task_state] { task_state->cancel(); })) { - task_state->cancel(); - } + task_state->enqueue_or_cancel([task_state] { task_state->cancel(); }); } template class RustFutureHandleGuard { @@ -137,20 +141,18 @@ class RustFutureState : public std::enable_shared_from_this< error_handler_(std::move(error_handler)), completion_state_(std::move(completion_state)) { } - void start() { + bool start() { const auto self = this->shared_from_this(); { std::lock_guard guard(mutex_); operation_id_ = - ::uniffi::detail::default_async_dispatcher().track([self] { self->cancel(); }); + ::uniffi::detail::async_executor().track([self] { self->cancel(); }); } if (!operation_id_) { - free_(handle_); - completion_state_->complete(::uniffi::FutureResult( - std::make_exception_ptr(::uniffi::AsyncDispatcherError()))); - return; + return false; } request_drive(); + return true; } void cancel() noexcept { @@ -211,7 +213,7 @@ class RustFutureState : public std::enable_shared_from_this< state = this->shared_from_this(); } - if (!::uniffi::detail::dispatch_async([state] { state->drive(); })) { + if (!::uniffi::detail::enqueue_async([state] { state->drive(); })) { // Active operations keep the executor alive until their handles have been released. std::terminate(); } @@ -302,23 +304,20 @@ class RustFutureState : public std::enable_shared_from_this< } void complete_and_free() noexcept { - std::exception_ptr result_error; - using StoredResult = - std::conditional_t, std::monostate, std::optional>; - StoredResult result_value{}; - + 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_value.emplace(lift_(value)); + result.emplace(lift_(value)); } } catch (...) { - result_error = std::current_exception(); + result.emplace(std::current_exception()); } std::exception_ptr protocol_failure; @@ -328,17 +327,12 @@ class RustFutureState : public std::enable_shared_from_this< } free_(handle_); - ::uniffi::detail::default_async_dispatcher().untrack(operation_id_); + ::uniffi::detail::async_executor().untrack(operation_id_); if (protocol_failure) { - completion_state_->complete(::uniffi::FutureResult(protocol_failure)); - } else if (result_error) { - completion_state_->complete(::uniffi::FutureResult(result_error)); - } else if constexpr (std::is_void_v) { - completion_state_->complete(::uniffi::FutureResult()); - } else { - completion_state_->complete(::uniffi::FutureResult(std::move(*result_value))); + result.emplace(std::move(protocol_failure)); } + completion_state_->complete(std::move(*result)); } uint64_t handle_; @@ -368,10 +362,13 @@ Future rust_call_async(RustFuture rust_future, Poll poll, Cancel cancel, Comp Free free, Lift lift, ErrorHandler error_handler) { initialize(); auto completion_state = std::make_shared<::uniffi::detail::FutureCompletionState>(); - if (!::uniffi::detail::begin_async_call()) { + auto rejected = [&completion_state] { completion_state->complete( - ::uniffi::FutureResult(std::make_exception_ptr(::uniffi::AsyncDispatcherError()))); + ::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(); @@ -381,13 +378,17 @@ Future rust_call_async(RustFuture rust_future, Poll poll, Cancel cancel, Comp auto state = std::make_shared(handle, std::move(poll), std::move(cancel), std::move(complete), free, std::move(lift), std::move(error_handler), completion_state); - Future result(completion_state, [weak_state = std::weak_ptr(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(); } - }); + }; - state->start(); + if (!state->start()) { + return rejected(); + } handle_guard.release(); - return result; + 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 index 023e0f7..626767a 100644 --- a/bindgen/src/bindings/cpp/templates/async.hpp +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -3,9 +3,9 @@ class AsyncCancelledError : public std::runtime_error { AsyncCancelledError() : std::runtime_error("UniFFI async call cancelled") {} }; -class AsyncDispatcherError : public std::runtime_error { +class AsyncExecutorError : public std::runtime_error { public: - AsyncDispatcherError() : std::runtime_error("UniFFI async dispatcher rejected a task") {} + AsyncExecutorError() : std::runtime_error("UniFFI async executor rejected a task") {} }; using AsyncTask = std::function; @@ -14,14 +14,14 @@ namespace detail { // One control executor per linked C++ image, shared by all generated components. Tasks must not // block. -class DefaultAsyncDispatcher { +class AsyncExecutor { public: - DefaultAsyncDispatcher() : worker_([this] { run(); }) {} - DefaultAsyncDispatcher(const DefaultAsyncDispatcher &) = delete; - DefaultAsyncDispatcher &operator=(const DefaultAsyncDispatcher &) = delete; - ~DefaultAsyncDispatcher() { shutdown(); } + AsyncExecutor() : worker_([this] { run(); }) {} + AsyncExecutor(const AsyncExecutor &) = delete; + AsyncExecutor &operator=(const AsyncExecutor &) = delete; + ~AsyncExecutor() { shutdown(); } - bool dispatch(AsyncTask task) { + bool enqueue(AsyncTask task) { { std::lock_guard guard(mutex_); if (stopped_) { @@ -54,7 +54,7 @@ class DefaultAsyncDispatcher { return accepting_; } - bool is_worker() const noexcept { return std::this_thread::get_id() == worker_id_; } + bool is_worker() const noexcept { return current_worker_ == this; } void shutdown() { if (is_worker()) { @@ -86,12 +86,14 @@ class DefaultAsyncDispatcher { private: void run() noexcept { + current_worker_ = this; for (;;) { AsyncTask task; { std::unique_lock lock(mutex_); ready_.wait(lock, [this] { return !tasks_.empty() || stopped_; }); if (tasks_.empty()) { + current_worker_ = nullptr; return; } task = std::move(tasks_.front()); @@ -123,28 +125,28 @@ class DefaultAsyncDispatcher { bool accepting_ = true; bool stopped_ = false; bool running_ = false; + inline static thread_local const AsyncExecutor *current_worker_ = nullptr; std::thread worker_; - const std::thread::id worker_id_ = worker_.get_id(); }; -inline DefaultAsyncDispatcher &default_async_dispatcher() { - static DefaultAsyncDispatcher dispatcher; - return dispatcher; +inline AsyncExecutor &async_executor() { + static AsyncExecutor executor; + return executor; } -inline bool dispatch_async(AsyncTask task) noexcept { +inline bool enqueue_async(AsyncTask task) noexcept { try { - return default_async_dispatcher().dispatch(std::move(task)); + 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 default_async_dispatcher().accepting(); } +inline bool begin_async_call() { return async_executor().accepting(); } inline void check_blocking_wait(bool ready) { - if (!ready && default_async_dispatcher().is_worker()) { + if (!ready && async_executor().is_worker()) { throw std::logic_error("Cannot block the UniFFI executor; use Future::then instead"); } } @@ -153,7 +155,7 @@ inline void check_blocking_wait(bool ready) { // Cancels in-flight calls, drains their Rust handles and queued completions, and joins the worker. // Stop producers first. Call from an application thread, before unloading the Rust library. -inline void shutdown_async_dispatcher() { detail::default_async_dispatcher().shutdown(); } +inline void shutdown_async_executor() { detail::async_executor().shutdown(); } // C++17 adapter for an async callback-interface method. The implementation starts work when the // generated bridge supplies success and failure callbacks, and returns an optional cancel action. @@ -214,7 +216,22 @@ template <> class ForeignFuture { template class FutureResult { public: explicit FutureResult(T value) : value_(std::move(value)) {} - explicit FutureResult(std::exception_ptr error) : error_(std::move(error)) {} + 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_; } @@ -234,7 +251,7 @@ template class FutureResult { template <> class FutureResult { public: FutureResult() = default; - explicit FutureResult(std::exception_ptr error) : error_(std::move(error)) {} + 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_; } @@ -254,12 +271,12 @@ namespace detail { // Retains the executor through delivery, including when then() is attached to an already-ready // call. struct ContinuationRegistration { - ContinuationRegistration() : id(default_async_dispatcher().track([] {})) { + ContinuationRegistration() : id(async_executor().track([] {})) { if (!id) { - throw AsyncDispatcherError(); + throw AsyncExecutorError(); } } - ~ContinuationRegistration() { default_async_dispatcher().untrack(id); } + ~ContinuationRegistration() { async_executor().untrack(id); } uint64_t id; }; @@ -280,7 +297,7 @@ template class FutureCompletionState { } ready_.notify_all(); if (callback) { - dispatch_continuation(std::move(callback)); + enqueue_continuation(std::move(callback)); } } @@ -324,7 +341,7 @@ template class FutureCompletionState { return; } } - dispatch_continuation(std::move(callback)); + enqueue_continuation(std::move(callback)); } private: @@ -335,14 +352,14 @@ template class FutureCompletionState { claimed_ = true; } - void dispatch_continuation(Callback callback) noexcept { + 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 (!dispatch_async([delivery]() mutable { + if (!enqueue_async([delivery]() mutable { try { delivery->first(std::move(delivery->second)); } catch (...) { @@ -413,7 +430,8 @@ template class Future { using Callback = std::function; Future() = default; - Future(std::shared_ptr> state, std::function cancel) + Future(std::shared_ptr> state, + std::function cancel) noexcept : state_(std::move(state)), cancel_(std::move(cancel)) {} Future(const Future &) = delete; diff --git a/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp b/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp index b836215..01c4048 100644 --- a/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp +++ b/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp @@ -53,7 +53,7 @@ {% match method.return_type() %} {% when Some(t) %} - auto deliver_success = [state, complete, uniffi_callback_data]({{ t|type_name(ci) }} value) { + auto deliver_success = [state, complete, uniffi_callback_data](const {{ t|type_name(ci) }} &value) { if (!state->finish()) { return; } @@ -80,20 +80,24 @@ {% endmatch %} auto complete_failure = [state, deliver_failure](std::exception_ptr error) { - ::uniffi::detail::dispatch_async([state, deliver_failure, error] { + state->enqueue_or_cancel([deliver_failure, error] { deliver_failure(error); }); }; {% match method.return_type() %} {% when Some(t) %} - auto complete_success = [state, deliver_success]({{ t|type_name(ci) }} value) { - ::uniffi::detail::dispatch_async([state, deliver_success, value = std::move(value)]() mutable { - deliver_success(std::move(value)); - }); + 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]() { - ::uniffi::detail::dispatch_async([state, deliver_success] { deliver_success(); }); + state->enqueue_or_cancel([deliver_success] { deliver_success(); }); }; {% endmatch %} @@ -107,7 +111,7 @@ {%- for arg in method.arguments() %} auto arg{{ loop.index0 }} = {{- arg|lift_fn }}({{ arg.name()|var_name }}); {%- endfor %} - ::uniffi::detail::dispatch_async([ + 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 { @@ -116,13 +120,17 @@ 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(); } }); + 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()); } diff --git a/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp b/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp index 5534b8a..bf46f90 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::value_method_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..b5cc7fb 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::value_method_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/macros.cpp b/bindgen/src/bindings/cpp/templates/macros.cpp index 3bd6fbf..6993295 100644 --- a/bindgen/src/bindings/cpp/templates/macros.cpp +++ b/bindgen/src/bindings/cpp/templates/macros.cpp @@ -152,6 +152,26 @@ ) {%- endmacro %} +{% macro rust_call_async_with_value(func, self_type, receiver) -%} + {%- let converter = self_type|lower_fn -%} + {%- let prefix = "uniffi::" ~ converter ~ "(" ~ receiver ~ ")" -%} + {%- match func.return_type() -%} + {%- when Some with (return_type) -%} + {%- call rust_call_async_with_prefix(prefix, func, return_type|type_name(ci)) -%} + {%- when None -%} + {%- call rust_call_async_void_with_prefix(prefix, func) -%} + {%- endmatch -%} +{%- endmacro %} + +{% macro value_method_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 8f3498a..39a5e40 100644 --- a/bindgen/src/bindings/cpp/templates/obj.cpp +++ b/bindgen/src/bindings/cpp/templates/obj.cpp @@ -54,19 +54,23 @@ namespace uniffi { {% endfor %} {%- for method in obj.methods() %} +{%- let clone_receiver = "this->_uniffi_internal_clone_pointer()" %} {% if method.is_async() %}uniffi::Future<{% endif %}{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }}{% else %}void{% endmatch %}{% if method.is_async() %}>{% endif %} {{ impl_class_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) { - auto ptr = this->_uniffi_internal_clone_pointer(); + {# The async start callback clones the receiver only after the executor admission check. #} + {%- if !method.is_async() %} + auto ptr = {{ clone_receiver }}; + {%- endif %} {%- match method.return_type() %} {% when Some with (return_type) %} {%- if method.is_async() %} - return {% call macros::rust_call_async_with_prefix("ptr", method, return_type|type_name(ci)) %}; + return {% call macros::rust_call_async_with_prefix(clone_receiver, method, return_type|type_name(ci)) %}; {%- else %} return uniffi::{{ return_type|lift_fn }}({% call macros::rust_call_with_prefix("ptr", method) %}); {%- endif %} {%- else %} {%- if method.is_async() %} - return {% call macros::rust_call_async_void_with_prefix("ptr", method) %}; + return {% call macros::rust_call_async_void_with_prefix(clone_receiver, method) %}; {%- else %} {% call macros::rust_call_with_prefix("ptr", method) -%}; {%- endif %} diff --git a/bindgen/src/bindings/cpp/templates/value_methods.cpp b/bindgen/src/bindings/cpp/templates/value_methods.cpp index 5ef16e7..74d51c7 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::value_method_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..b2aa1c5 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::value_method_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/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index b95489e..048605c 100644 --- a/cpp-tests/CMakeLists.txt +++ b/cpp-tests/CMakeLists.txt @@ -43,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}) @@ -57,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) @@ -82,6 +85,7 @@ test_case(reserved_field_name) test_case(type_flattening) test_case(futures) test_case(async_api_client) +test_case(async_executor tests/async_executor/ffi_lifecycle.cpp tests/async_executor/peer.cpp) add_executable(ext_types_import-test tests/ext_types_import/main.cpp @@ -123,4 +127,4 @@ add_custom_target(bindings ALL COMMENT "Generating bindings" ) -set_tests_properties(async_api_client-test PROPERTIES TIMEOUT 45) +set_tests_properties(async_api_client-test async_executor-test PROPERTIES TIMEOUT 45) diff --git a/cpp-tests/include/async_api_client_test.hpp b/cpp-tests/include/async_api_client_test.hpp index 0b6bd93..d26ee79 100644 --- a/cpp-tests/include/async_api_client_test.hpp +++ b/cpp-tests/include/async_api_client_test.hpp @@ -17,7 +17,7 @@ class WorkerPool { } ~WorkerPool() { shutdown(); } - bool dispatch(uniffi::AsyncTask task) { + bool enqueue(uniffi::AsyncTask task) { { std::lock_guard lock(mutex_); if (!accepting_ || tasks_.size() >= capacity_) { @@ -68,7 +68,7 @@ class WorkerPool { tasks_.pop_front(); ++running_; } - if (uniffi::detail::default_async_dispatcher().is_worker()) { + if (uniffi::detail::async_executor().is_worker()) { ran_on_control = true; } task(); @@ -101,7 +101,7 @@ class TestHttpClient final : public api::HttpClientForeign { return uniffi::ForeignFuture([workers = workers_, response = response_, url, credentials](auto success, auto failure) { auto cancelled = std::make_shared>(false); - if (!workers->dispatch([response, url, credentials, success, failure, cancelled] { + if (!workers->enqueue([response, url, credentials, success, failure, cancelled] { if (cancelled->load()) { return; } @@ -133,7 +133,7 @@ class TestTaskRunner final : public api::TaskRunnerForeign { return uniffi::ForeignFuture([counters = counters_, workers = workers_, task](auto success, auto failure) { auto cancelled = std::make_shared>(false); - if (!workers->dispatch([counters, task, success, failure, cancelled] { + if (!workers->enqueue([counters, task, success, failure, cancelled] { if (cancelled->load()) { return; } diff --git a/cpp-tests/tests/async_api_client/main.cpp b/cpp-tests/tests/async_api_client/main.cpp index 1c9b0d1..fd92c4c 100644 --- a/cpp-tests/tests/async_api_client/main.cpp +++ b/cpp-tests/tests/async_api_client/main.cpp @@ -52,7 +52,7 @@ int main() { auto entered = std::make_shared>(); auto release = std::make_shared>(); auto released = release->get_future().share(); - ASSERT_TRUE(workers->dispatch([entered, released] { + ASSERT_TRUE(workers->enqueue([entered, released] { entered->set_value(); released.wait(); })); @@ -70,6 +70,6 @@ int main() { ASSERT_FALSE(workers->ran_on_control.load()); client.reset(); - uniffi::shutdown_async_dispatcher(); + 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..3e8909d --- /dev/null +++ b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp @@ -0,0 +1,287 @@ +#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 "futures.cpp" + +namespace executor_tests { +namespace { + +// https://mozilla.github.io/uniffi-rs/latest/internals/async-ffi.html#managing-the-rustfuture-handle +constexpr std::uint64_t rust_handle = 0xfedcba9801234567ULL; +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 }; +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 RustFutureProbe { + public: + explicit RustFutureProbe(std::initializer_list replies) : replies_(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 futures::uniffi::rust_call_async>( + [this] { + ASSERT_FALSE(uniffi::detail::async_executor().is_worker()); + record(Step::Start); + return rust_handle; + }, + [this](auto handle, auto callback, auto data) { poll(handle, {callback, data}); }, + [this](auto handle) { + record_on_worker(handle, Step::Cancel); + ASSERT_TRUE(parked_callback_.has_value()); + was_cancelled_ = true; + const auto callback = *parked_callback_; + parked_callback_.reset(); + callback.notify(ready); + }, + [this, completion](auto handle, auto *status) { + record_on_worker(handle, Step::Complete); + ASSERT_NE(status, nullptr); + if (was_cancelled_) { + status->code = cancelled; + } else if (completion == Completion::ErrorStatus) { + status->code = unexpected_error; + status->error_buf = futures::uniffi::FfiConverterString::lower("Rust completion failed"); + } + return 41; + }, + [this](auto handle) { + record_on_worker(handle, Step::Free); + 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: + void record(Step step) { + const std::lock_guard lock(mutex_); + steps_.push_back(step); + } + + void record_on_worker(std::uint64_t handle, Step step) { + ASSERT_EQ(handle, rust_handle); + 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_on_worker(handle, Step::Poll); + 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; + 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; + } + in_poll_ = false; + } + + const std::vector replies_; + 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; +}; + +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}); +} + +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 futures::AsyncParserForeign { + 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 {}; + } +}; + +} // namespace + +void test_rust_future_lifecycle() { + test_pending_to_ready(); + 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(); +} + +// 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"); + return 0; + }; + auto result = futures::uniffi::rust_call_async( + [] { + uniffi::shutdown_async_executor(); + return rust_handle; + }, + unexpected_ffi_call, unexpected_ffi_call, unexpected_ffi_call, + [&](std::uint64_t handle) { + ASSERT_EQ(handle, rust_handle); + ++frees; + }, + [](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 = futures::uniffi::UniffiCallbackInterfaceAsyncParser; + const auto handle = futures::uniffi::FfiConverterAsyncParser::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); +} + +} // 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..ff0f984 --- /dev/null +++ b/cpp-tests/tests/async_executor/main.cpp @@ -0,0 +1,214 @@ +#include "test_support.hpp" + +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([] {})); +} + +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 = futures::SampleStream::init(); + const auto second = futures::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 = futures::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)); +} + +// Shutdown delivers cancellation, rejects new reads, and allows the Rust receiver to drop. +void test_singleton_shutdown() { + ASSERT_EQ(futures::sample_stream_count(), 0u); + auto stream = futures::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(futures::sample_stream_count(), 0u); + uniffi::shutdown_async_executor(); +} + +} // namespace +} // namespace executor_tests + +int main() { + using namespace executor_tests; + test_executor_queue(); + test_executor_shutdown_drains_active_work(); + test_singleton_across_components(); + test_rust_future_lifecycle(); + test_interleaved_stream_reads(); + test_cancel_pending_read(); + // Singleton shutdown is terminal for this test process. + test_singleton_shutdown(); + test_foreign_callback_after_shutdown(); +} diff --git a/cpp-tests/tests/async_executor/peer.cpp b/cpp-tests/tests/async_executor/peer.cpp new file mode 100644 index 0000000..6c77aea --- /dev/null +++ b/cpp-tests/tests/async_executor/peer.cpp @@ -0,0 +1,9 @@ +#include "arithmetic.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..f8bf00a --- /dev/null +++ b/cpp-tests/tests/async_executor/test_support.hpp @@ -0,0 +1,21 @@ +#pragma once + +#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(); + +} // namespace executor_tests diff --git a/cpp-tests/tests/futures/main.cpp b/cpp-tests/tests/futures/main.cpp index 54aba58..fd614ff 100644 --- a/cpp-tests/tests/futures/main.cpp +++ b/cpp-tests/tests/futures/main.cpp @@ -168,6 +168,12 @@ int main() { auto record = futures::new_my_record("value", 42).get(); ASSERT_EQ("value", record.a); ASSERT_EQ(42, record.b); + auto record_value = futures::MyRecord{"value", 17}.value_after(1); + ASSERT_EQ(17, record_value.get()); + + futures::validate(futures::ValidationMode::kAllow).get(); + EXPECT_EXCEPTION(futures::validate(futures::ValidationMode::kReject).get(), + futures::my_error::Foo); auto holding = futures::use_shared_resource({2000, 4000}); std::this_thread::sleep_for(500ms); @@ -225,8 +231,6 @@ int main() { } if (auto threads_parked = thread_count(); threads_before && threads_parked) { ASSERT_TRUE(*threads_parked <= *threads_before + 1); - std::cout << "2000 parked futures: process threads " << *threads_before << " -> " - << *threads_parked << "\n"; } for (auto &future : parked) { future.cancel(); @@ -236,26 +240,14 @@ int main() { } ASSERT_EQ(0, futures::pending_count()); - const auto begin = std::chrono::steady_clock::now(); - std::vector> ready_batch; - for (int i = 0; i < 20000; ++i) { - ready_batch.push_back(futures::always_ready()); - } - for (auto &future : ready_batch) { - ASSERT_TRUE(future.get()); - } - const auto elapsed = - std::chrono::duration(std::chrono::steady_clock::now() - begin).count(); - std::cout << "20000 ready calls: " << elapsed << "s (" << 20000 / elapsed << " calls/s)\n"; - // 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::default_async_dispatcher().is_worker()); + ASSERT_TRUE(uniffi::detail::async_executor().is_worker()); ASSERT_TRUE(std::move(result).get()); auto inner = futures::pending(); EXPECT_EXCEPTION(inner.get(), std::logic_error); - EXPECT_EXCEPTION(uniffi::shutdown_async_dispatcher(), std::logic_error); + 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)); @@ -269,7 +261,7 @@ int main() { try { ASSERT_TRUE(futures::always_ready().get()); ++produced; - } catch (const uniffi::AsyncDispatcherError &) { + } catch (const uniffi::AsyncExecutorError &) { std::this_thread::yield(); } catch (const uniffi::AsyncCancelledError &) { // Shutdown also cancels calls accepted immediately before it. @@ -287,17 +279,18 @@ int main() { auto shutdown_pending = futures::pending(); auto shutdown_foreign = futures::wait_using_parser( std::make_shared(started_count, cancellation_count, destruction_count)); - uniffi::shutdown_async_dispatcher(); + uniffi::shutdown_async_executor(); stop_producers.store(true); for (auto &producer : producers) { producer.join(); } - EXPECT_EXCEPTION(std::move(late_continuation).then([](auto) {}), uniffi::AsyncDispatcherError); + EXPECT_EXCEPTION(static_cast(std::move(late_continuation).then([](auto) {})), + uniffi::AsyncExecutorError); ASSERT_TRUE(late_continuation.get()); - uniffi::shutdown_async_dispatcher(); // Idempotent. + 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::AsyncDispatcherError); + EXPECT_EXCEPTION(futures::always_ready().get(), uniffi::AsyncExecutorError); return 0; } diff --git a/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md index e4d0c73..5756363 100644 --- a/docs/ASYNC_RUNTIME.md +++ b/docs/ASYNC_RUNTIME.md @@ -1,53 +1,228 @@ -# C++17 async runtime - -## Execution and ownership - -All generated components linked into one C++ executable or shared library use the same inline -runtime instance. This is not a singleton shared across independently built DLLs/DSOs. - -One lazy, joinable worker executes short control tasks. Each Rust future has at most one queued or -running driver and one outstanding UniFFI poll. Wakes enqueue work only when progress is possible; -there is no timer scanning, blocking waiter, or C++ thread per operation. A driver yields after 64 -actions so repeated immediate wakes do not monopolize the queue. - -The executor's registry owns an active Rust state until completion frees its handle. This also lets -poll callbacks reuse the state's address instead of allocating a new userdata holder for every poll. -Future destruction and explicit cancellation request work through that state; neither calls -`rust_future_cancel` directly from an application thread. Rust's terminal call status decides whether -completion or cancellation won the race, so a successful result is not discarded or leaked. - -A C++ foreign operation returns `ForeignFuture` containing a start function. That function arranges -nonblocking application work and returns a cancellation action. The bridge keeps the implementation -alive until success, failure, or cancellation wins. Application captures are released outside internal -state locks. A `FutureContinuation` owns its cancellation action; retain it until delivery. Its return -from `then` is marked `nodiscard` to catch accidental immediate cancellation. - -Rust still owns its I/O runtimes. This executor supplies the missing C++ control/runtime boundary; -it does not replace Tokio or implement another network stack. - -## Limits and contract - -- Continuations, foreign method startup, cancellation actions, and Rust polls must return promptly. - Blocking I/O or CPU-heavy work belongs on an application's existing workers / async I/O service, - or the Rust runtime's appropriate task pool. A single long-running poll cannot be preempted. -- Shutdown is final for the binding image, not an operation to perform on every room disconnect. - Stop producers, call `shutdown_async_dispatcher()` on an application thread, and release generated - objects before unloading Rust. Restartable runtime instances are not implemented. -- A foreign cancellation action must release its operation's resources and prevent unbounded work. - The bridge cannot forcibly join application-owned workers. A nonreturning callback can stall - executor shutdown. -- Queue/state memory grows with requested concurrency and captured payloads. Driver wakeups are - coalesced; this is not a fixed-capacity or hard-real-time executor. Allocation exhaustion is fatal - where abandoning accepted cleanup would leak a handle or violate the FFI protocol. -- Async trait interfaces retain the recovered `Foo` / `FooForeign` / `FooImpl` split. A Rust-backed - async trait object returned as the common base needs a cast to `FooImpl` before invoking methods. - The generic fixtures verify foreign implementations crossing into Rust, not that reverse API. - -## Verification - -The 22 fixture tests cover async functions, methods, constructors, typed errors, cancellation, -continuations, foreign implementations, and executor shutdown. The async API client test exercises -the upstream example with application-owned workers for blocking work. - -Downstream SDK integration tests belong in their consuming repositories. This repository keeps -only the fixtures needed to verify generated bindings and the async runtime protocol. +# 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 on the caller's thread. + The worker calls `rust_future_poll` and repolls on `WAKE`. On `READY` it calls + `rust_future_complete` to collect the value or error, then `rust_future_free` to release the + handle. It requests cancellation with `rust_future_cancel`. [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.** Call `shutdown_async_executor()` from an application thread to stop admission, + cancel outstanding work, drain the queue, and join the worker. [Shutdown][shutdown] + +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 + B->>E: Queue drive() for the first poll + B-->>C: Return Future + + 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 this future waits for a wake + 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->>E: Untrack the call + E->>B: Publish to FutureCompletionState + 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. Pending Rust +futures retain their state and wake callback. Each driver runs at most 64 actions per turn before +yielding to the queue. [Executor][executor] · [Driver][drive] + +```mermaid +flowchart LR + A[Application thread] -->|Schedule driver| Q[Control queue] + Q --> W[One C++ worker] + W -->|Poll or finish| R[Rust scaffolding] + R -->|Wake callback| Q + W -->|Publish result| F[C++ future or 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] + +## 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 and schedules the first poll. The poll passes the state's address as callback data. + 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. + `next_action()` sets `poll_outstanding_` before invoking Rust and admits another poll only after + that 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.** `next_action()` gives `READY` priority and sets `terminal_` + before returning `CompleteFuture`. That flag closes the driver, callback, and cancellation paths. + The worker completes once, checks `RustCallStatus`, and lifts the value on success. + [Action selection][next-action] · [Result conversion][finish] · [Status handling][status] +- **Free the handle as the last FFI operation.** The driver frees the handle before removing the + registry entry and publishing the result. 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 signal completion from that worker. [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 +closes admission, requests cancellation for registered calls, drains the queue and in-flight work, +and joins the worker. New C++ calls to async Rust exports receive `AsyncExecutorError` after +shutdown. The callback trampoline reports cancellation to Rust if the executor rejects startup. +Continuation delivery retains its own registration until its callback is released. Shutdown is +terminal for the binding image. Keep control callbacks short so other calls and shutdown can make +progress. [Drain and join][shutdown] · [Continuation registration][registration] · +[Callback bridge][callback-results] + +[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 +[executor]: ../bindgen/src/bindings/cpp/templates/async.hpp#L15-L135 +[drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L205-L288 +[future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L392-L497 +[completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L283-L371 +[wait-guard]: ../bindgen/src/bindings/cpp/templates/async.hpp#L146-L152 +[function]: ../bindgen/src/bindings/cpp/templates/fn_def.cpp#L1-L20 +[object]: ../bindgen/src/bindings/cpp/templates/obj.cpp#L32-L78 +[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-L164 +[init]: ../bindgen/src/bindings/cpp/templates/wrapper.cpp#L13-L37 +[handle-guard]: ../bindgen/src/bindings/cpp/templates/async.cpp#L110-L129 +[state-start]: ../bindgen/src/bindings/cpp/templates/async.cpp#L144-L183 +[poll]: ../bindgen/src/bindings/cpp/templates/async.cpp#L290-L294 +[continuation]: ../bindgen/src/bindings/cpp/templates/async.cpp#L179-L203 +[next-action]: ../bindgen/src/bindings/cpp/templates/async.cpp#L222-L241 +[finish]: ../bindgen/src/bindings/cpp/templates/async.cpp#L306-L336 +[status]: ../bindgen/src/bindings/cpp/templates/wrapper.cpp#L40-L64 +[call-async]: ../bindgen/src/bindings/cpp/templates/async.cpp#L359-L394 +[cancel]: ../bindgen/src/bindings/cpp/templates/async.cpp#L296-L304 +[callback-api]: ../bindgen/src/bindings/cpp/templates/callback.hpp#L6-L35 +[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#L9-L88 +[foreign-drop]: ../bindgen/src/bindings/cpp/templates/async.cpp#L65-L108 +[shutdown]: ../bindgen/src/bindings/cpp/templates/async.hpp#L59-L85 +[registration]: ../bindgen/src/bindings/cpp/templates/async.hpp#L273-L281 diff --git a/fixtures/async-calls/src/lib.rs b/fixtures/async-calls/src/lib.rs index 34cd3ad..22102f8 100644 --- a/fixtures/async-calls/src/lib.rs +++ b/fixtures/async-calls/src/lib.rs @@ -11,12 +11,14 @@ use futures_timer::Delay; use std::{ sync::{ atomic::{AtomicU64, Ordering}, - Arc, + 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; @@ -73,6 +75,57 @@ 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")] @@ -180,11 +233,35 @@ pub struct MyRecord { 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 + } +} + #[uniffi::export] pub async fn new_my_record(a: String, b: u32) -> MyRecord { MyRecord { a, 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(uniffi::Record)] pub struct SharedResourceOptions { pub release_after_ms: u16, From d34f8f1a5861ca0fd1d0bff21d016f0bf27bf708 Mon Sep 17 00:00:00 2001 From: Alan George Date: Sun, 22 Nov 2026 15:41:21 -0700 Subject: [PATCH 06/19] Fix Windows builds for the async fixtures Link the Windows synchronization library for the Rust fixtures and include the string declarations used by async bindings and tests. --- bindgen/src/bindings/cpp/templates/wrapper.hpp | 1 + cpp-tests/CMakeLists.txt | 2 +- cpp-tests/tests/futures/main.cpp | 1 + 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/bindgen/src/bindings/cpp/templates/wrapper.hpp b/bindgen/src/bindings/cpp/templates/wrapper.hpp index 3010e0a..2d6c31c 100644 --- a/bindgen/src/bindings/cpp/templates/wrapper.hpp +++ b/bindgen/src/bindings/cpp/templates/wrapper.hpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index 048605c..a78706c 100644 --- a/cpp-tests/CMakeLists.txt +++ b/cpp-tests/CMakeLists.txt @@ -21,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) diff --git a/cpp-tests/tests/futures/main.cpp b/cpp-tests/tests/futures/main.cpp index fd614ff..f72bc70 100644 --- a/cpp-tests/tests/futures/main.cpp +++ b/cpp-tests/tests/futures/main.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #if defined(__APPLE__) From a933b62637d05f828b38378fa4d295416c54f8ac Mon Sep 17 00:00:00 2001 From: Alan George Date: Sun, 22 Nov 2026 15:45:08 -0700 Subject: [PATCH 07/19] Keep async executor shutdown out of static destruction Retain the shared executor for process lifetime and keep explicit shutdown available. Verify exit from a continuation and exit with pending Rust futures in separate test processes. --- README.md | 12 ++++++--- bindgen/src/bindings/cpp/templates/async.hpp | 7 ++--- cpp-tests/CMakeLists.txt | 8 ++++++ .../async_exit_from_continuation/main.cpp | 16 +++++++++++ .../tests/async_pending_at_exit/main.cpp | 27 +++++++++++++++++++ docs/ASYNC_RUNTIME.md | 15 +++++++---- 6 files changed, 73 insertions(+), 12 deletions(-) create mode 100644 cpp-tests/tests/async_exit_from_continuation/main.cpp create mode 100644 cpp-tests/tests/async_pending_at_exit/main.cpp diff --git a/README.md b/README.md index 02ce523..28f7191 100644 --- a/README.md +++ b/README.md @@ -79,10 +79,14 @@ blocking application work to an existing application worker pool or async I/O se 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 Rust library. Shutdown rejects new C++ calls to async Rust exports -with `uniffi::AsyncExecutorError`, cancels active calls, drains queued cleanup and continuations, -and joins the worker. Shutdown is terminal. A nonreturning application callback can prevent -shutdown from completing. +thread before unloading the bindings or the Rust library. Shutdown rejects new calls to async Rust +exports with `uniffi::AsyncExecutorError`, cancels active calls, drains queued cleanup and +continuations, and joins the worker. Shutdown is terminal. A nonreturning application callback can +prevent shutdown from completing. + +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 diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp index 626767a..97dbe83 100644 --- a/bindgen/src/bindings/cpp/templates/async.hpp +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -130,8 +130,9 @@ class AsyncExecutor { }; inline AsyncExecutor &async_executor() { - static AsyncExecutor executor; - return 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 { @@ -154,7 +155,7 @@ inline void check_blocking_wait(bool ready) { } // namespace detail // Cancels in-flight calls, drains their Rust handles and queued completions, and joins the worker. -// Stop producers first. Call from an application thread, before unloading the Rust library. +// Stop producers first. Call from an application thread before unloading the bindings or Rust. inline void shutdown_async_executor() { detail::async_executor().shutdown(); } // C++17 adapter for an async callback-interface method. The implementation starts work when the diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index a78706c..521abba 100644 --- a/cpp-tests/CMakeLists.txt +++ b/cpp-tests/CMakeLists.txt @@ -86,6 +86,8 @@ test_case(type_flattening) test_case(futures) test_case(async_api_client) test_case(async_executor tests/async_executor/ffi_lifecycle.cpp tests/async_executor/peer.cpp) +test_case(async_exit_from_continuation ${BINDINGS_SRC_DIR}/futures.cpp) +test_case(async_pending_at_exit ${BINDINGS_SRC_DIR}/futures.cpp) add_executable(ext_types_import-test tests/ext_types_import/main.cpp @@ -128,3 +130,9 @@ add_custom_target(bindings ALL ) set_tests_properties(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(async_exit_from_continuation-test-test-memcheck + async_pending_at_exit-test-test-memcheck PROPERTIES TIMEOUT 30) +endif() 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..cb86a35 --- /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(futures::pending()); + pending_continuation = new uniffi::FutureContinuation( + futures::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 futures::pending_count() == 2 ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md index 5756363..e4e20e9 100644 --- a/docs/ASYNC_RUNTIME.md +++ b/docs/ASYNC_RUNTIME.md @@ -190,6 +190,11 @@ terminal for the binding image. Keep control callbacks short so other calls and progress. [Drain and join][shutdown] · [Continuation registration][registration] · [Callback bridge][callback-results] +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] + [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 @@ -199,11 +204,11 @@ progress. [Drain and join][shutdown] · [Continuation registration][registration [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 -[executor]: ../bindgen/src/bindings/cpp/templates/async.hpp#L15-L135 +[executor]: ../bindgen/src/bindings/cpp/templates/async.hpp#L15-L136 [drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L205-L288 -[future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L392-L497 -[completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L283-L371 -[wait-guard]: ../bindgen/src/bindings/cpp/templates/async.hpp#L146-L152 +[future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L393-L498 +[completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L284-L372 +[wait-guard]: ../bindgen/src/bindings/cpp/templates/async.hpp#L147-L153 [function]: ../bindgen/src/bindings/cpp/templates/fn_def.cpp#L1-L20 [object]: ../bindgen/src/bindings/cpp/templates/obj.cpp#L32-L78 [value-methods]: ../bindgen/src/bindings/cpp/templates/value_methods.cpp#L1-L14 @@ -225,4 +230,4 @@ progress. [Drain and join][shutdown] · [Continuation registration][registration [foreign-state]: ../bindgen/src/bindings/cpp/templates/async.cpp#L9-L88 [foreign-drop]: ../bindgen/src/bindings/cpp/templates/async.cpp#L65-L108 [shutdown]: ../bindgen/src/bindings/cpp/templates/async.hpp#L59-L85 -[registration]: ../bindgen/src/bindings/cpp/templates/async.hpp#L273-L281 +[registration]: ../bindgen/src/bindings/cpp/templates/async.hpp#L274-L282 From ea7edbb1ef2e28a7ee7aa0be6ddfd34932c4f711 Mon Sep 17 00:00:00 2001 From: Alan George Date: Sun, 22 Nov 2026 15:48:34 -0700 Subject: [PATCH 08/19] Allow explicit restart of the async executor Serialize restart with shutdown and keep operation IDs monotonic. Prevent retired callbacks from starting in a subsequent run, and verify restarted workers and Rust callback round trips. --- README.md | 9 +-- bindgen/src/bindings/cpp/templates/async.cpp | 5 ++ bindgen/src/bindings/cpp/templates/async.hpp | 17 ++++++ .../cpp/templates/callback_iface_tmpl.cpp | 2 +- .../tests/async_executor/ffi_lifecycle.cpp | 18 ++++++ cpp-tests/tests/async_executor/main.cpp | 58 ++++++++++++++++++- .../tests/async_executor/test_support.hpp | 1 + docs/ASYNC_RUNTIME.md | 54 +++++++++-------- 8 files changed, 134 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 28f7191..972320f 100644 --- a/README.md +++ b/README.md @@ -79,10 +79,11 @@ blocking application work to an existing application worker pool or async I/O se 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 rejects new calls to async Rust -exports with `uniffi::AsyncExecutorError`, cancels active calls, drains queued cleanup and -continuations, and joins the worker. Shutdown is terminal. A nonreturning application callback can -prevent shutdown from completing. +thread before unloading the bindings or the Rust library. Shutdown 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 application callback can prevent +shutdown from completing. 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 diff --git a/bindgen/src/bindings/cpp/templates/async.cpp b/bindgen/src/bindings/cpp/templates/async.cpp index aa058de..ef31193 100644 --- a/bindgen/src/bindings/cpp/templates/async.cpp +++ b/bindgen/src/bindings/cpp/templates/async.cpp @@ -22,6 +22,11 @@ class ForeignFutureTaskState { }); } + bool can_start() { + std::lock_guard guard(mutex_); + return operation_id_ != 0 && !finished_; + } + bool finish() noexcept { std::function cancel; std::function complete_cancelled; diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp index 97dbe83..837c342 100644 --- a/bindgen/src/bindings/cpp/templates/async.hpp +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -56,6 +56,20 @@ class AsyncExecutor { bool is_worker() const noexcept { return current_worker_ == this; } + void start() { + if (is_worker()) { + // Shutdown may be waiting for this worker 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_ = true; + } + } + void shutdown() { if (is_worker()) { throw std::logic_error("UniFFI executor cannot shut down from its own callback"); @@ -158,6 +172,9 @@ inline void check_blocking_wait(bool ready) { // Stop producers first. Call from an application thread before unloading the bindings or Rust. inline void shutdown_async_executor() { detail::async_executor().shutdown(); } +// Reopen admission and start a worker after the previous worker has joined. +inline void start_async_executor() { detail::async_executor().start(); } + // C++17 adapter for an async callback-interface method. The implementation starts work when the // generated bridge supplies success and failure callbacks, and returns an optional cancel action. template class ForeignFuture { diff --git a/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp b/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp index 01c4048..04639b7 100644 --- a/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp +++ b/bindgen/src/bindings/cpp/templates/callback_iface_tmpl.cpp @@ -115,7 +115,7 @@ 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()) { + if (!::uniffi::detail::begin_async_call() || !state->can_start()) { state->cancel(); return; } diff --git a/cpp-tests/tests/async_executor/ffi_lifecycle.cpp b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp index 3e8909d..26c96f3 100644 --- a/cpp-tests/tests/async_executor/ffi_lifecycle.cpp +++ b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp @@ -284,4 +284,22 @@ void test_foreign_callback_after_shutdown() { 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 = futures::uniffi::ForeignFutureTaskState; + auto rejected = std::make_shared(); + rejected->start(rejected); + uniffi::start_async_executor(); + ASSERT_FALSE(rejected->can_start()); + + auto previous = std::make_shared(); + previous->start(previous); + ASSERT_TRUE(previous->can_start()); + uniffi::shutdown_async_executor(); + uniffi::start_async_executor(); + ASSERT_FALSE(previous->can_start()); + ASSERT_FALSE(previous->finish()); + uniffi::shutdown_async_executor(); +} + } // namespace executor_tests diff --git a/cpp-tests/tests/async_executor/main.cpp b/cpp-tests/tests/async_executor/main.cpp index ff0f984..38a50af 100644 --- a/cpp-tests/tests/async_executor/main.cpp +++ b/cpp-tests/tests/async_executor/main.cpp @@ -1,5 +1,7 @@ #include "test_support.hpp" +#include + namespace executor_tests { namespace { @@ -78,6 +80,34 @@ void test_executor_shutdown_drains_active_work() { 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(); @@ -197,6 +227,29 @@ void test_singleton_shutdown() { uniffi::shutdown_async_executor(); } +class RestartParser final : public futures::AsyncParserForeign { + 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(futures::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 @@ -204,11 +257,14 @@ 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(); - // Singleton shutdown is terminal for this test process. + // 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/test_support.hpp b/cpp-tests/tests/async_executor/test_support.hpp index f8bf00a..bdf4666 100644 --- a/cpp-tests/tests/async_executor/test_support.hpp +++ b/cpp-tests/tests/async_executor/test_support.hpp @@ -17,5 +17,6 @@ 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/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md index e4e20e9..32d6c4e 100644 --- a/docs/ASYNC_RUNTIME.md +++ b/docs/ASYNC_RUNTIME.md @@ -18,8 +18,9 @@ C++ callback methods that Rust awaits. 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.** Call `shutdown_async_executor()` from an application thread to stop admission, - cancel outstanding work, drain the queue, and join the worker. [Shutdown][shutdown] +- **Shutdown and restart.** Call `shutdown_async_executor()` from an application thread to stop + 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. @@ -183,11 +184,15 @@ gate, a later drop just releases the C++ handle. Stop producers before calling `shutdown_async_executor()` from an application thread. The executor closes admission, requests cancellation for registered calls, drains the queue and in-flight work, -and joins the worker. New C++ calls to async Rust exports receive `AsyncExecutorError` after -shutdown. The callback trampoline reports cancellation to Rust if the executor rejects startup. -Continuation delivery retains its own registration until its callback is released. Shutdown is -terminal for the binding image. Keep control callbacks short so other calls and shutdown can make -progress. [Drain and join][shutdown] · [Continuation registration][registration] · +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] + +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] The singleton has process lifetime. Returning from `main` or calling `std::exit` leaves pending @@ -204,30 +209,31 @@ the generated bindings or the Rust library. [Singleton lifetime][executor] [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 -[executor]: ../bindgen/src/bindings/cpp/templates/async.hpp#L15-L136 -[drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L205-L288 -[future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L393-L498 -[completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L284-L372 -[wait-guard]: ../bindgen/src/bindings/cpp/templates/async.hpp#L147-L153 +[executor]: ../bindgen/src/bindings/cpp/templates/async.hpp#L15-L150 +[drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L210-L293 +[future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L410-L515 +[completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L301-L389 +[wait-guard]: ../bindgen/src/bindings/cpp/templates/async.hpp#L161-L167 [function]: ../bindgen/src/bindings/cpp/templates/fn_def.cpp#L1-L20 [object]: ../bindgen/src/bindings/cpp/templates/obj.cpp#L32-L78 [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-L164 [init]: ../bindgen/src/bindings/cpp/templates/wrapper.cpp#L13-L37 -[handle-guard]: ../bindgen/src/bindings/cpp/templates/async.cpp#L110-L129 -[state-start]: ../bindgen/src/bindings/cpp/templates/async.cpp#L144-L183 -[poll]: ../bindgen/src/bindings/cpp/templates/async.cpp#L290-L294 -[continuation]: ../bindgen/src/bindings/cpp/templates/async.cpp#L179-L203 -[next-action]: ../bindgen/src/bindings/cpp/templates/async.cpp#L222-L241 -[finish]: ../bindgen/src/bindings/cpp/templates/async.cpp#L306-L336 +[handle-guard]: ../bindgen/src/bindings/cpp/templates/async.cpp#L115-L134 +[state-start]: ../bindgen/src/bindings/cpp/templates/async.cpp#L149-L188 +[poll]: ../bindgen/src/bindings/cpp/templates/async.cpp#L295-L299 +[continuation]: ../bindgen/src/bindings/cpp/templates/async.cpp#L184-L208 +[next-action]: ../bindgen/src/bindings/cpp/templates/async.cpp#L227-L246 +[finish]: ../bindgen/src/bindings/cpp/templates/async.cpp#L311-L341 [status]: ../bindgen/src/bindings/cpp/templates/wrapper.cpp#L40-L64 -[call-async]: ../bindgen/src/bindings/cpp/templates/async.cpp#L359-L394 -[cancel]: ../bindgen/src/bindings/cpp/templates/async.cpp#L296-L304 +[call-async]: ../bindgen/src/bindings/cpp/templates/async.cpp#L364-L399 +[cancel]: ../bindgen/src/bindings/cpp/templates/async.cpp#L301-L309 [callback-api]: ../bindgen/src/bindings/cpp/templates/callback.hpp#L6-L35 [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#L9-L88 -[foreign-drop]: ../bindgen/src/bindings/cpp/templates/async.cpp#L65-L108 -[shutdown]: ../bindgen/src/bindings/cpp/templates/async.hpp#L59-L85 -[registration]: ../bindgen/src/bindings/cpp/templates/async.hpp#L274-L282 +[foreign-state]: ../bindgen/src/bindings/cpp/templates/async.cpp#L9-L93 +[foreign-drop]: ../bindgen/src/bindings/cpp/templates/async.cpp#L70-L113 +[shutdown]: ../bindgen/src/bindings/cpp/templates/async.hpp#L73-L99 +[restart]: ../bindgen/src/bindings/cpp/templates/async.hpp#L59-L71 +[registration]: ../bindgen/src/bindings/cpp/templates/async.hpp#L291-L299 From 4f0b5ca675ea06a5e5fa4c1b5d5f6db7380622f1 Mon Sep 17 00:00:00 2001 From: Alan George Date: Sun, 22 Nov 2026 15:54:13 -0700 Subject: [PATCH 09/19] Add a cross-thread future cancellation handle Keep a copy of the weak cancellation action so another thread can cancel a blocking get or a future transferred into then. Test the handle after completion and destruction of the owning future. --- README.md | 7 ++- bindgen/src/bindings/cpp/templates/async.hpp | 21 +++++++++ cpp-tests/tests/async_executor/main.cpp | 45 ++++++++++++++++++++ docs/ASYNC_RUNTIME.md | 9 +++- 4 files changed, 79 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 972320f..194f761 100644 --- a/README.md +++ b/README.md @@ -54,8 +54,11 @@ Rust async functions, constructors, and methods return a move-only `uniffi::Futu 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. +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. diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp index 837c342..724a1cc 100644 --- a/bindgen/src/bindings/cpp/templates/async.hpp +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -407,6 +407,25 @@ template <> inline void FutureCompletionState::get() { } // namespace detail +class FutureCancelHandle { + public: + FutureCancelHandle() = default; + + 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_; +}; + class FutureContinuation { public: FutureContinuation() = default; @@ -474,6 +493,8 @@ template class Future { bool valid() const noexcept { return state_ != nullptr; } + [[nodiscard]] FutureCancelHandle cancel_handle() const { return FutureCancelHandle(cancel_); } + decltype(auto) get() { require_state(); detail::check_blocking_wait(state_->wait_for(std::chrono::seconds(0)) == diff --git a/cpp-tests/tests/async_executor/main.cpp b/cpp-tests/tests/async_executor/main.cpp index 38a50af..467b874 100644 --- a/cpp-tests/tests/async_executor/main.cpp +++ b/cpp-tests/tests/async_executor/main.cpp @@ -202,6 +202,49 @@ void test_cancel_pending_read() { 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 = futures::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 = futures::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); +} + // Shutdown delivers cancellation, rejects new reads, and allows the Rust receiver to drop. void test_singleton_shutdown() { ASSERT_EQ(futures::sample_stream_count(), 0u); @@ -262,6 +305,8 @@ int main() { test_rust_future_lifecycle(); test_interleaved_stream_reads(); test_cancel_pending_read(); + test_cancel_blocking_get(); + test_cancel_handle_lifetime(); // Check shutdown rejection before explicitly restarting the singleton. test_singleton_shutdown(); test_foreign_callback_after_shutdown(); diff --git a/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md index 32d6c4e..bb92a37 100644 --- a/docs/ASYNC_RUNTIME.md +++ b/docs/ASYNC_RUNTIME.md @@ -82,6 +82,12 @@ the worker. Hold that token until delivery or cancel it to request cancellation. 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 @@ -211,7 +217,8 @@ the generated bindings or the Rust library. [Singleton lifetime][executor] [rust-foreign]: https://github.com/mozilla/uniffi-rs/blob/05b45b110f652d58d94c653992aeb3adc3a094f4/uniffi_core/src/ffi/foreignfuture.rs#L67-L99 [executor]: ../bindgen/src/bindings/cpp/templates/async.hpp#L15-L150 [drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L210-L293 -[future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L410-L515 +[future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L429-L547 +[cancel-handle]: ../bindgen/src/bindings/cpp/templates/async.hpp#L410-L427 [completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L301-L389 [wait-guard]: ../bindgen/src/bindings/cpp/templates/async.hpp#L161-L167 [function]: ../bindgen/src/bindings/cpp/templates/fn_def.cpp#L1-L20 From 44d07af5239b460d6eac7b165ca6c39ac36c3bc6 Mon Sep 17 00:00:00 2001 From: Alan George Date: Sun, 22 Nov 2026 18:22:33 -0700 Subject: [PATCH 10/19] Cancel Rust futures before repolling during shutdown Closing admission can reject a queued C++ callback before shutdown reaches the Rust call that awaits it. Send cancellation before the next poll and preserve completion for futures that already signaled READY. Exercise the ordering with a queued callback and a paused shutdown cancellation in the executor fixture. --- bindgen/src/bindings/cpp/templates/async.cpp | 7 ++- .../tests/async_executor/ffi_lifecycle.cpp | 51 +++++++++++++++++++ docs/ASYNC_RUNTIME.md | 17 ++++--- 3 files changed, 67 insertions(+), 8 deletions(-) diff --git a/bindgen/src/bindings/cpp/templates/async.cpp b/bindgen/src/bindings/cpp/templates/async.cpp index ef31193..baa5f17 100644 --- a/bindgen/src/bindings/cpp/templates/async.cpp +++ b/bindgen/src/bindings/cpp/templates/async.cpp @@ -233,11 +233,14 @@ class RustFutureState : public std::enable_shared_from_this< terminal_ = true; return Action::CompleteFuture; } - if (cancel_requested_ && !cancel_sent_) { + 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 (poll_requested_ && !poll_outstanding_) { + if (can_poll) { poll_requested_ = false; poll_outstanding_ = true; return Action::PollFuture; diff --git a/cpp-tests/tests/async_executor/ffi_lifecycle.cpp b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp index 26c96f3..1eea980 100644 --- a/cpp-tests/tests/async_executor/ffi_lifecycle.cpp +++ b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp @@ -228,6 +228,56 @@ class RejectedParser final : public futures::AsyncParserForeign { } }; +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(); +}; + +// 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); + + std::promise> call; + auto handoff = call.get_future(); + ASSERT_TRUE(executor.enqueue([&] { + auto future = futures::wait_using_parser(std::make_shared()); + // The first poll queues the callback startup behind this pause. + ASSERT_TRUE(executor.enqueue([&] { before_callback_start.pause(); })); + call.set_value(std::move(future)); + })); + auto future = wait_for_future(handoff); + before_callback_start.wait_until_paused(); + + 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(); +} + } // namespace void test_rust_future_lifecycle() { @@ -237,6 +287,7 @@ void test_rust_future_lifecycle() { test_cancellation_lifecycle(); test_result_publication_move_failure(); test_continuation_move_failure(); + test_shutdown_cancels_before_repoll(); } // Close admission after the start check while the caller still owns the new Rust handle. diff --git a/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md index bb92a37..a80e3ff 100644 --- a/docs/ASYNC_RUNTIME.md +++ b/docs/ASYNC_RUNTIME.md @@ -194,6 +194,11 @@ and joins the worker. Continuation delivery retains its own registration until i 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 @@ -216,7 +221,7 @@ the generated bindings or the Rust library. [Singleton lifetime][executor] [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 [executor]: ../bindgen/src/bindings/cpp/templates/async.hpp#L15-L150 -[drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L210-L293 +[drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L210-L296 [future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L429-L547 [cancel-handle]: ../bindgen/src/bindings/cpp/templates/async.hpp#L410-L427 [completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L301-L389 @@ -229,13 +234,13 @@ the generated bindings or the Rust library. [Singleton lifetime][executor] [init]: ../bindgen/src/bindings/cpp/templates/wrapper.cpp#L13-L37 [handle-guard]: ../bindgen/src/bindings/cpp/templates/async.cpp#L115-L134 [state-start]: ../bindgen/src/bindings/cpp/templates/async.cpp#L149-L188 -[poll]: ../bindgen/src/bindings/cpp/templates/async.cpp#L295-L299 +[poll]: ../bindgen/src/bindings/cpp/templates/async.cpp#L298-L302 [continuation]: ../bindgen/src/bindings/cpp/templates/async.cpp#L184-L208 -[next-action]: ../bindgen/src/bindings/cpp/templates/async.cpp#L227-L246 -[finish]: ../bindgen/src/bindings/cpp/templates/async.cpp#L311-L341 +[next-action]: ../bindgen/src/bindings/cpp/templates/async.cpp#L227-L249 +[finish]: ../bindgen/src/bindings/cpp/templates/async.cpp#L314-L344 [status]: ../bindgen/src/bindings/cpp/templates/wrapper.cpp#L40-L64 -[call-async]: ../bindgen/src/bindings/cpp/templates/async.cpp#L364-L399 -[cancel]: ../bindgen/src/bindings/cpp/templates/async.cpp#L301-L309 +[call-async]: ../bindgen/src/bindings/cpp/templates/async.cpp#L367-L402 +[cancel]: ../bindgen/src/bindings/cpp/templates/async.cpp#L304-L312 [callback-api]: ../bindgen/src/bindings/cpp/templates/callback.hpp#L6-L35 [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 From 7dde82ec1431b35e43e58b110114f5b51b99425a Mon Sep 17 00:00:00 2001 From: Alan George Date: Sun, 22 Nov 2026 19:18:25 -0700 Subject: [PATCH 11/19] Document callback shutdown for Rust-owned tasks Explain how UniFFI lifts a callback cancellation and how a Rust trait method can convert it into its declared error. Clarify where applications may invoke the completion callbacks. --- README.md | 11 +++++++++-- docs/ASYNC_RUNTIME.md | 19 ++++++++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 194f761..a7c32fe 100644 --- a/README.md +++ b/README.md @@ -107,11 +107,18 @@ uniffi::ForeignFuture fetch(Request request) override { ``` Callback startup, cancellation, result delivery and continuations use the shared control executor. -Completion callbacks may be invoked from any application thread; the bridge defers delivery to Rust. +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. -See [the async runtime design](docs/ASYNC_RUNTIME.md) for handle ownership, scheduling, and shutdown. +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. + +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/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md index a80e3ff..05300d2 100644 --- a/docs/ASYNC_RUNTIME.md +++ b/docs/ASYNC_RUNTIME.md @@ -146,7 +146,8 @@ function accepts success and failure callbacks and returns an optional cancellat 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 signal completion from that worker. [C++ callback surface][callback-api] · +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 @@ -211,6 +212,19 @@ work and its Rust handles to process teardown. Python, Kotlin, and TypeScript Un 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. 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 @@ -220,6 +234,9 @@ the generated bindings or the Rust library. [Singleton lifetime][executor] [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-L193 [executor]: ../bindgen/src/bindings/cpp/templates/async.hpp#L15-L150 [drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L210-L296 [future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L429-L547 From 3adfb1f6d473e9ed346e2cd3cad4550065a296f3 Mon Sep 17 00:00:00 2001 From: Alan George Date: Sun, 22 Nov 2026 19:18:25 -0700 Subject: [PATCH 12/19] Test shutdown before the first Rust future poll Hold the worker until admission closes and pause shutdown before per-call cancellation. Verify that the outer call receives AsyncCancelledError. --- .../tests/async_executor/ffi_lifecycle.cpp | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/cpp-tests/tests/async_executor/ffi_lifecycle.cpp b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp index 1eea980..995b2fb 100644 --- a/cpp-tests/tests/async_executor/ffi_lifecycle.cpp +++ b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp @@ -278,6 +278,33 @@ void test_shutdown_cancels_before_repoll() { uniffi::start_async_executor(); } +// Shutdown cancels a pending Rust call whose first poll comes after admission closes. +void test_shutdown_cancels_before_first_poll() { + auto &executor = uniffi::detail::async_executor(); + PausedTask before_first_poll; + 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); + + // Hold the worker so the call's first poll stays queued until admission has closed. + ASSERT_TRUE(executor.enqueue([&] { before_first_poll.pause(); })); + before_first_poll.wait_until_paused(); + auto future = futures::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_first_poll.resume(); + EXPECT_EXCEPTION(wait_for_future(future), uniffi::AsyncCancelledError); + + executor.untrack(blocker); + before_call_cancellation.resume(); + wait_for_future(stopping); + uniffi::start_async_executor(); +} + } // namespace void test_rust_future_lifecycle() { @@ -288,6 +315,7 @@ void test_rust_future_lifecycle() { test_result_publication_move_failure(); test_continuation_move_failure(); test_shutdown_cancels_before_repoll(); + test_shutdown_cancels_before_first_poll(); } // Close admission after the start check while the caller still owns the new Rust handle. From 8895b57a6a4aec570d37734097b3f890983fb0da Mon Sep 17 00:00:00 2001 From: Alan George Date: Sun, 22 Nov 2026 20:57:33 -0700 Subject: [PATCH 13/19] Clarify callbacks rejected while the executor is stopped Document callback rejection after shutdown and link to the complete UniFFI error conversion macro. --- docs/ASYNC_RUNTIME.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md index 05300d2..402baa5 100644 --- a/docs/ASYNC_RUNTIME.md +++ b/docs/ASYNC_RUNTIME.md @@ -215,8 +215,9 @@ 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. 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 +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] @@ -236,7 +237,7 @@ method or when conversion to the declared error type fails. [Result handling][ru [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-L193 +[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#L15-L150 [drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L210-L296 [future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L429-L547 From 17b3b2882cf0ae0c87975164025606515bda2b33 Mon Sep 17 00:00:00 2001 From: Alan George Date: Mon, 23 Nov 2026 11:06:29 -0700 Subject: [PATCH 14/19] Poll Rust futures on the caller and share the C++ driver Complete ready futures inline and keep pending work on the executor. Share the driver across exports, cover Rust-backed traits and callbacks from Tokio, and reuse the upstream futures fixture. --- Cargo.lock | 99 +++++- .../src/bindings/cpp/gen_cpp/filters/mod.rs | 2 +- bindgen/src/bindings/cpp/templates/async.cpp | 154 +++++---- bindgen/src/bindings/cpp/templates/async.hpp | 119 +++---- .../cpp/templates/flat_enum_methods.cpp | 2 +- .../cpp/templates/flat_enum_methods.hpp | 2 +- bindgen/src/bindings/cpp/templates/fn_def.cpp | 18 +- bindgen/src/bindings/cpp/templates/macros.cpp | 84 +---- bindgen/src/bindings/cpp/templates/obj.cpp | 25 +- bindgen/src/bindings/cpp/templates/obj.hpp | 2 +- .../bindings/cpp/templates/value_methods.cpp | 2 +- .../bindings/cpp/templates/value_methods.hpp | 2 +- .../src/bindings/cpp/templates/wrapper.cpp | 4 + .../src/bindings/cpp/templates/wrapper.hpp | 31 +- cpp-tests/CMakeLists.txt | 11 +- .../tests/async_executor/ffi_lifecycle.cpp | 293 +++++++++++++----- cpp-tests/tests/async_executor/main.cpp | 61 +++- cpp-tests/tests/async_executor/peer.cpp | 2 +- .../tests/async_executor/test_support.hpp | 1 + .../tests/async_pending_at_exit/main.cpp | 8 +- cpp-tests/tests/futures/main.cpp | 141 ++++++--- fixtures/Cargo.toml | 1 + fixtures/async-calls/Cargo.toml | 6 +- fixtures/async-calls/build.rs | 9 - fixtures/async-calls/src/async-calls.udl | 15 - fixtures/async-calls/src/lib.rs | 207 +++---------- .../async-calls/src/platform_specific/mod.rs | 8 - .../src/platform_specific/native.rs | 29 -- fixtures/src/lib.rs | 1 + 29 files changed, 717 insertions(+), 622 deletions(-) delete mode 100644 fixtures/async-calls/build.rs delete mode 100644 fixtures/async-calls/src/async-calls.udl delete mode 100644 fixtures/async-calls/src/platform_specific/mod.rs delete mode 100644 fixtures/async-calls/src/platform_specific/native.rs diff --git a/Cargo.lock b/Cargo.lock index da751a5..8ce3602 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -324,24 +324,100 @@ dependencies = [ "autocfg", ] +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + [[package]] name = "futures-io" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + [[package]] name = "futures-timer" version = "3.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af43fadb8a98512d547e37b4e92e0ced13e205c061b87b4623eff01d918d6968" +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + [[package]] name = "glob" version = "0.3.1" @@ -614,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" @@ -825,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", @@ -839,7 +923,6 @@ version = "0.21.0" dependencies = [ "async-trait", "futures-timer", - "once_cell", "thiserror 1.0.50", "tokio", "uniffi", @@ -886,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", @@ -1052,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" diff --git a/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs b/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs index 35eaeee..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 { diff --git a/bindgen/src/bindings/cpp/templates/async.cpp b/bindgen/src/bindings/cpp/templates/async.cpp index baa5f17..136d1b6 100644 --- a/bindgen/src/bindings/cpp/templates/async.cpp +++ b/bindgen/src/bindings/cpp/templates/async.cpp @@ -112,9 +112,12 @@ inline void foreign_future_drop(uint64_t handle) noexcept { task_state->enqueue_or_cancel([task_state] { task_state->cancel(); }); } -template class RustFutureHandleGuard { +using RustFutureHandleFn = void (*)(uint64_t); + +class RustFutureHandleGuard { public: - RustFutureHandleGuard(uint64_t handle, Free &free) noexcept : handle_(handle), free_(free) {} + RustFutureHandleGuard(uint64_t handle, RustFutureHandleFn free) noexcept + : handle_(handle), free_(free) {} RustFutureHandleGuard(const RustFutureHandleGuard &) = delete; RustFutureHandleGuard &operator=(const RustFutureHandleGuard &) = delete; @@ -129,34 +132,37 @@ template class RustFutureHandleGuard { private: uint64_t handle_; - Free &free_; + RustFutureHandleFn free_; bool active_ = true; }; -template -class RustFutureState : public std::enable_shared_from_this< - RustFutureState> { +class RustFutureState : public std::enable_shared_from_this { public: - RustFutureState(uint64_t handle, Poll poll, Cancel cancel, Complete complete, Free free, - Lift lift, ErrorHandler error_handler, - std::shared_ptr<::uniffi::detail::FutureCompletionState> completion_state) - : handle_(handle), poll_(std::move(poll)), cancel_(std::move(cancel)), - complete_(std::move(complete)), free_(std::move(free)), lift_(std::move(lift)), - error_handler_(std::move(error_handler)), completion_state_(std::move(completion_state)) { - } + 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; { std::lock_guard guard(mutex_); - operation_id_ = - ::uniffi::detail::async_executor().track([self] { self->cancel(); }); + operation_id_ = executor.track([self] { self->cancel(); }); + if (!operation_id_) { + return false; + } + // Track the call before polling, and keep ownership if Rust wakes inline. + poll_on_caller = executor.accepting(); + driving_ = poll_on_caller; + poll_requested_ = !poll_on_caller; + poll_outstanding_ = poll_on_caller; } - if (!operation_id_) { - return false; + if (poll_on_caller) { + executor.run_inline([this] { poll_first_turn(); }); + } else { + request_drive(); } - request_drive(); return true; } @@ -171,6 +177,10 @@ class RustFutureState : public std::enable_shared_from_this< 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, @@ -179,11 +189,28 @@ class RustFutureState : public std::enable_shared_from_this< CompleteFuture, }; - using State = RustFutureState; + 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(); + auto state = reinterpret_cast(callback_data)->shared_from_this(); state->on_continuation(poll_result); } @@ -208,7 +235,7 @@ class RustFutureState : public std::enable_shared_from_this< } void request_drive() noexcept { - std::shared_ptr state; + std::shared_ptr state; { std::lock_guard guard(mutex_); if (terminal_ || driving_ || scheduled_) { @@ -312,15 +339,54 @@ class RustFutureState : public std::enable_shared_from_this< } 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); + complete_(handle, &status); check_rust_call(status, error_handler_); result.emplace(); } else { - auto value = complete_(handle_, &status); + auto value = complete_(handle, &status); check_rust_call(status, error_handler_); result.emplace(lift_(value)); } @@ -328,14 +394,7 @@ class RustFutureState : public std::enable_shared_from_this< result.emplace(std::current_exception()); } - std::exception_ptr protocol_failure; - { - std::lock_guard guard(mutex_); - protocol_failure = failure_; - } - - free_(handle_); - ::uniffi::detail::async_executor().untrack(operation_id_); + free(handle); if (protocol_failure) { result.emplace(std::move(protocol_failure)); @@ -343,31 +402,16 @@ class RustFutureState : public std::enable_shared_from_this< completion_state_->complete(std::move(*result)); } - uint64_t handle_; - uint64_t operation_id_ = 0; - Poll poll_; - Cancel cancel_; Complete complete_; - Free free_; Lift lift_; ErrorHandler error_handler_; std::shared_ptr<::uniffi::detail::FutureCompletionState> completion_state_; - 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 -Future rust_call_async(RustFuture rust_future, Poll poll, Cancel cancel, Complete complete, - Free free, Lift lift, ErrorHandler error_handler) { +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] { @@ -380,15 +424,15 @@ Future rust_call_async(RustFuture rust_future, Poll poll, Cancel cancel, Comp } const auto handle = rust_future(); - RustFutureHandleGuard handle_guard(handle, free); - using State = RustFutureState; + RustFutureHandleGuard handle_guard(handle, free); + using State = RustFutureResultState; auto state = - std::make_shared(handle, std::move(poll), std::move(cancel), std::move(complete), + 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)] { + std::function cancel_future = [weak_state = std::weak_ptr(state)] { if (auto state = weak_state.lock()) { state->cancel(); } diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp index 724a1cc..c7d709a 100644 --- a/bindgen/src/bindings/cpp/templates/async.hpp +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -35,7 +35,7 @@ class AsyncExecutor { uint64_t track(AsyncTask cancel) { std::lock_guard guard(mutex_); - if (!accepting_) { + if (!accepting_.load(std::memory_order_relaxed)) { return 0; } const auto id = ++next_id_; @@ -46,19 +46,25 @@ class AsyncExecutor { void untrack(uint64_t id) noexcept { std::lock_guard guard(mutex_); active_.erase(id); - drained_.notify_all(); + if (!accepting()) { + drained_.notify_all(); + } } - bool accepting() const { - std::lock_guard guard(mutex_); - return accepting_; - } + bool accepting() const noexcept { return accepting_.load(std::memory_order_acquire); } bool is_worker() const noexcept { return current_worker_ == this; } + template void run_inline(Call call) noexcept { + const auto previous = current_inline_; + current_inline_ = this; + call(); + current_inline_ = previous; + } + void start() { - if (is_worker()) { - // Shutdown may be waiting for this worker to finish. + if (is_worker() || current_inline_ == this) { + // Shutdown may be waiting for this call to finish. return; } std::lock_guard shutdown_guard(shutdown_mutex_); @@ -66,12 +72,12 @@ class AsyncExecutor { if (stopped_) { worker_ = std::thread([this] { run(); }); stopped_ = false; - accepting_ = true; + accepting_.store(true, std::memory_order_release); } } void shutdown() { - if (is_worker()) { + 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_); @@ -81,7 +87,7 @@ class AsyncExecutor { if (stopped_) { return; } - accepting_ = false; + accepting_.store(false, std::memory_order_release); for (const auto &entry : active_) { cancellations.push_back(entry.second); } @@ -101,19 +107,18 @@ class AsyncExecutor { private: void run() noexcept { current_worker_ = this; + std::unique_lock lock(mutex_); for (;;) { - AsyncTask task; - { - std::unique_lock lock(mutex_); - ready_.wait(lock, [this] { return !tasks_.empty() || stopped_; }); - if (tasks_.empty()) { - current_worker_ = nullptr; - return; - } - task = std::move(tasks_.front()); - tasks_.pop_front(); - running_ = true; + 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 (...) { @@ -121,11 +126,11 @@ class AsyncExecutor { } // Release captured objects before announcing that the executor has drained. task = {}; - { - std::lock_guard guard(mutex_); - running_ = false; + lock.lock(); + running_ = false; + if (!accepting()) { + drained_.notify_all(); } - drained_.notify_all(); } } @@ -136,10 +141,11 @@ class AsyncExecutor { std::deque tasks_; std::map active_; uint64_t next_id_ = 0; - bool accepting_ = true; + std::atomic accepting_{true}; bool stopped_ = false; bool running_ = false; inline static thread_local const AsyncExecutor *current_worker_ = nullptr; + inline static thread_local const AsyncExecutor *current_inline_ = nullptr; std::thread worker_; }; @@ -166,6 +172,14 @@ inline void check_blocking_wait(bool ready) { } } +template struct ForeignFutureSuccess { + using Type = std::function; +}; + +template <> struct ForeignFutureSuccess { + using Type = std::function; +}; + } // namespace detail // Cancels in-flight calls, drains their Rust handles and queued completions, and joins the worker. @@ -180,34 +194,7 @@ inline void start_async_executor() { detail::async_executor().start(); } template class ForeignFuture { public: using Cancel = std::function; - using Success = std::function; - 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; - - 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_; -}; - -template <> class ForeignFuture { - public: - using Cancel = std::function; - using Success = std::function; + using Success = typename detail::ForeignFutureSuccess::Type; using Failure = std::function; using Start = std::function; @@ -322,7 +309,6 @@ template class FutureCompletionState { T get() { std::unique_lock lock(mutex_); check_blocking_wait(result_.has_value()); - claim_locked(); ready_.wait(lock, [this] { return result_.has_value(); }); auto result = std::move(*result_); lock.unlock(); @@ -352,7 +338,6 @@ template class FutureCompletionState { bool ready; { std::lock_guard guard(mutex_); - claim_locked(); ready = result_.has_value(); if (!ready) { callback_ = std::move(callback); @@ -363,13 +348,6 @@ template class FutureCompletionState { } private: - void claim_locked() { - if (claimed_) { - throw std::logic_error("UniFFI future result has already been consumed"); - } - claimed_ = true; - } - void enqueue_continuation(Callback callback) noexcept { Result result = [&] { std::lock_guard guard(mutex_); @@ -391,20 +369,9 @@ template class FutureCompletionState { mutable std::mutex mutex_; mutable std::condition_variable ready_; std::optional result_; - bool claimed_ = false; Callback callback_; }; -template <> inline void FutureCompletionState::get() { - std::unique_lock lock(mutex_); - check_blocking_wait(result_.has_value()); - claim_locked(); - ready_.wait(lock, [this] { return result_.has_value(); }); - auto result = std::move(*result_); - lock.unlock(); - result.get(); -} - } // namespace detail class FutureCancelHandle { @@ -449,6 +416,8 @@ class FutureContinuation { ~FutureContinuation() { cancel(); } + void detach() noexcept { cancel_ = nullptr; } + void cancel() noexcept { if (cancel_) { auto cancel = std::move(cancel_); diff --git a/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp b/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp index bf46f90..3274666 100644 --- a/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp +++ b/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp @@ -1,5 +1,5 @@ {%- for method in methods %} -{% call macros::value_method_return_type(method) %} {{ 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 %} diff --git a/bindgen/src/bindings/cpp/templates/flat_enum_methods.hpp b/bindgen/src/bindings/cpp/templates/flat_enum_methods.hpp index b5cc7fb..422af51 100644 --- a/bindgen/src/bindings/cpp/templates/flat_enum_methods.hpp +++ b/bindgen/src/bindings/cpp/templates/flat_enum_methods.hpp @@ -1,6 +1,6 @@ {%- for method in methods %} {%- call macros::docstring(method, 0) %} -{% call macros::value_method_return_type(method) %} {{ 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) %}); {%- 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 ba3a51c..7c39629 100644 --- a/bindgen/src/bindings/cpp/templates/fn_def.cpp +++ b/bindgen/src/bindings/cpp/templates/fn_def.cpp @@ -1,20 +1,14 @@ -{%- match func.return_type() %} -{%- when Some with (return_type) %} -{% if func.is_async() %}uniffi::Future<{% endif %}{{ return_type|type_name(ci) }}{% if func.is_async() %}>{% endif %} {{ 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, return_type|type_name(ci)) %}; + 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); - {%- endif %} -} -{%- when None -%} -{% if func.is_async() %}uniffi::Future<{% endif %}void{% if func.is_async() %}>{% endif %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { - {%- if func.is_async() %} - return {% call macros::rust_call_async_void(func) %}; - {%- else %} + {%- 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 6993295..aaf6a39 100644 --- a/bindgen/src/bindings/cpp/templates/macros.cpp +++ b/bindgen/src/bindings/cpp/templates/macros.cpp @@ -66,75 +66,13 @@ uniffi::{{ self_type|lower_fn }}(other)) {%- endmacro %} -{% macro rust_call_async(func, return_type) -%} - uniffi::rust_call_async<{{ return_type }}>( - [&]() { - return {{ func.ffi_func().name() }}( - {%- 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) }}, - [](auto value) { return uniffi::{{ func.return_type().unwrap()|lift_fn }}(value); }, -{%- match func.throws_type() %} -{% when Some with (e) %} - uniffi::{{ e|ffi_error_converter_name }}::lift -{%- else %} - nullptr -{%- endmatch %} - ) -{%- endmacro %} - -{% macro rust_call_async_void(func) -%} - uniffi::rust_call_async( - [&]() { - return {{ func.ffi_func().name() }}( - {%- 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) }}, - nullptr, -{%- match func.throws_type() %} -{% when Some with (e) %} - uniffi::{{ e|ffi_error_converter_name }}::lift -{%- else %} - nullptr -{%- endmatch %} - ) -{%- endmacro %} - -{% macro rust_call_async_with_prefix(prefix, func, return_type) -%} - uniffi::rust_call_async<{{ return_type }}>( - [&]() { - return {{ func.ffi_func().name() }}( - {{ prefix }}{% if !func.arguments().is_empty() %}, {% 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) }}, - [](auto value) { return uniffi::{{ func.return_type().unwrap()|lift_fn }}(value); }, -{%- match func.throws_type() %} -{% when Some with (e) %} - uniffi::{{ e|ffi_error_converter_name }}::lift -{%- else %} - nullptr -{%- endmatch %} - ) -{%- endmacro %} - -{% macro rust_call_async_void_with_prefix(prefix, func) -%} - uniffi::rust_call_async( +{% 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) -%} ); }, @@ -142,7 +80,12 @@ {{ 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 @@ -155,15 +98,10 @@ {% macro rust_call_async_with_value(func, self_type, receiver) -%} {%- let converter = self_type|lower_fn -%} {%- let prefix = "uniffi::" ~ converter ~ "(" ~ receiver ~ ")" -%} - {%- match func.return_type() -%} - {%- when Some with (return_type) -%} - {%- call rust_call_async_with_prefix(prefix, func, return_type|type_name(ci)) -%} - {%- when None -%} - {%- call rust_call_async_void_with_prefix(prefix, func) -%} - {%- endmatch -%} + {%- call rust_call_async(func, prefix) -%} {%- endmacro %} -{% macro value_method_return_type(method) -%} +{% 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) }} diff --git a/bindgen/src/bindings/cpp/templates/obj.cpp b/bindgen/src/bindings/cpp/templates/obj.cpp index 39a5e40..3975c2b 100644 --- a/bindgen/src/bindings/cpp/templates/obj.cpp +++ b/bindgen/src/bindings/cpp/templates/obj.cpp @@ -33,7 +33,7 @@ namespace uniffi { {%- when Some with (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, type_name) %}; + return {% call macros::rust_call_async(ctor, "") %}; {%- else %} return {{ type_name }}( new {{ impl_class_name }}({%- call macros::rust_call(ctor) -%}) @@ -46,7 +46,7 @@ namespace uniffi { {% for ctor in obj.alternate_constructors() %} {% 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, type_name) %}; + return {% call macros::rust_call_async(ctor, "") %}; {%- else %} return {{ type_name }}(new {{ impl_class_name }}({% call macros::rust_call(ctor) %})); {%- endif %} @@ -55,26 +55,19 @@ namespace uniffi { {%- for method in obj.methods() %} {%- let clone_receiver = "this->_uniffi_internal_clone_pointer()" %} -{% if method.is_async() %}uniffi::Future<{% endif %}{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }}{% else %}void{% endmatch %}{% if method.is_async() %}>{% endif %} -{{ impl_class_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) { +{% 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() %} - auto ptr = {{ clone_receiver }}; - {%- endif %} - {%- match method.return_type() %} - {% when Some with (return_type) %} {%- if method.is_async() %} - return {% call macros::rust_call_async_with_prefix(clone_receiver, method, return_type|type_name(ci)) %}; + return {% call macros::rust_call_async(method, clone_receiver) %}; {%- else %} + auto ptr = {{ clone_receiver }}; + {%- match method.return_type() %} + {%- when Some with (return_type) %} return uniffi::{{ return_type|lift_fn }}({% call macros::rust_call_with_prefix("ptr", method) %}); - {%- endif %} - {%- else %} - {%- if method.is_async() %} - return {% call macros::rust_call_async_void_with_prefix(clone_receiver, method) %}; - {%- else %} + {%- when None %} {% call macros::rust_call_with_prefix("ptr", method) -%}; - {%- endif %} {%- endmatch %} + {%- endif %} } {%- endfor %} diff --git a/bindgen/src/bindings/cpp/templates/obj.hpp b/bindgen/src/bindings/cpp/templates/obj.hpp index c38d9f4..9a3f3f4 100644 --- a/bindgen/src/bindings/cpp/templates/obj.hpp +++ b/bindgen/src/bindings/cpp/templates/obj.hpp @@ -61,7 +61,7 @@ struct {{ impl_class_name }} {%- for method in obj.methods() %} {%- call macros::docstring(method, 4) %} - {% if method.is_async() %}::uniffi::Future<{% 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) %}); + {% 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/value_methods.cpp b/bindgen/src/bindings/cpp/templates/value_methods.cpp index 74d51c7..b3d2932 100644 --- a/bindgen/src/bindings/cpp/templates/value_methods.cpp +++ b/bindgen/src/bindings/cpp/templates/value_methods.cpp @@ -1,5 +1,5 @@ {%- for method in methods %} -{% call macros::value_method_return_type(method) %} {{ 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 %} diff --git a/bindgen/src/bindings/cpp/templates/value_methods.hpp b/bindgen/src/bindings/cpp/templates/value_methods.hpp index b2aa1c5..48af505 100644 --- a/bindgen/src/bindings/cpp/templates/value_methods.hpp +++ b/bindgen/src/bindings/cpp/templates/value_methods.hpp @@ -1,6 +1,6 @@ {%- for method in methods %} {%- call macros::docstring(method, 4) %} -{% call macros::value_method_return_type(method) %} {{ method.name()|fn_name }}({% call macros::param_list(method) %}) const; +{% 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 1bf89e3..d3edc77 100644 --- a/bindgen/src/bindings/cpp/templates/wrapper.cpp +++ b/bindgen/src/bindings/cpp/templates/wrapper.cpp @@ -56,8 +56,10 @@ 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"); @@ -80,7 +82,9 @@ 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) { diff --git a/bindgen/src/bindings/cpp/templates/wrapper.hpp b/bindgen/src/bindings/cpp/templates/wrapper.hpp index 2d6c31c..2c9c46f 100644 --- a/bindgen/src/bindings/cpp/templates/wrapper.hpp +++ b/bindgen/src/bindings/cpp/templates/wrapper.hpp @@ -1,14 +1,10 @@ #pragma once #include -#include #include -#include #include -#include #include #include -#include #include #include #include @@ -17,11 +13,19 @@ #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 %} @@ -41,12 +45,16 @@ namespace uniffi { } #endif -#ifndef UNIFFI_CPP_ASYNC_FUTURE -#define UNIFFI_CPP_ASYNC_FUTURE +{%- 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) %} @@ -113,7 +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 %} @@ -185,11 +195,6 @@ void rustbuffer_free(RustBuffer); {%~ for func in ci.function_definitions() %} {%- call macros::docstring(func, 0) %} -{% if func.is_async() %}uniffi::Future<{% endif %}{% match func.return_type() %} -{%- when Some with (return_type) %} -{{ return_type|type_name(ci) }}{% if func.is_async() %}>{% endif %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}); -{%- when None %} -void{% if func.is_async() %}>{% endif %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}); -{%- endmatch %} +{% 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 521abba..66538e2 100644 --- a/cpp-tests/CMakeLists.txt +++ b/cpp-tests/CMakeLists.txt @@ -84,10 +84,13 @@ 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) +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}/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 @@ -129,10 +132,12 @@ add_custom_target(bindings ALL COMMENT "Generating bindings" ) -set_tests_properties(async_api_client-test async_executor-test PROPERTIES TIMEOUT 45) +set_tests_properties(futures-test async_api_client-test async_executor-test PROPERTIES TIMEOUT 45) set_tests_properties(async_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/tests/async_executor/ffi_lifecycle.cpp b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp index 995b2fb..8d4bae5 100644 --- a/cpp-tests/tests/async_executor/ffi_lifecycle.cpp +++ b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp @@ -4,20 +4,19 @@ // 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 "futures.cpp" +#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::uint64_t rust_handle = 0xfedcba9801234567ULL; 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 }; +enum class PollReply { Park, WakeInline, Ready, Invalid }; enum class Completion { Value, ErrorStatus, LiftError }; struct PollCallback { @@ -27,9 +26,30 @@ struct PollCallback { 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::initializer_list replies) : replies_(replies) {} + 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); @@ -38,35 +58,33 @@ class RustFutureProbe { template uniffi::Future> start_with_lift(Lift lift, Completion completion = Completion::Value) { - return futures::uniffi::rust_call_async>( + return async_calls::uniffi::rust_call_async>( [this] { - ASSERT_FALSE(uniffi::detail::async_executor().is_worker()); + caller_ = std::this_thread::get_id(); record(Step::Start); - return rust_handle; + return reinterpret_cast(this); + }, + [](std::uint64_t handle, RustFutureContinuationCallback callback, std::uint64_t data) { + from_handle(handle).poll(handle, {callback, data}); }, - [this](auto handle, auto callback, auto data) { poll(handle, {callback, data}); }, - [this](auto handle) { - record_on_worker(handle, Step::Cancel); - ASSERT_TRUE(parked_callback_.has_value()); - was_cancelled_ = true; - const auto callback = *parked_callback_; - parked_callback_.reset(); - callback.notify(ready); + [](std::uint64_t handle) { + from_handle(handle).cancel(handle); }, [this, completion](auto handle, auto *status) { - record_on_worker(handle, Step::Complete); + 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 = futures::uniffi::FfiConverterString::lower("Rust completion failed"); + status->error_buf = async_calls::uniffi::FfiConverterString::lower("Rust completion failed"); } return 41; }, - [this](auto handle) { - record_on_worker(handle, Step::Free); - handle_freed = true; + [](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_); @@ -95,21 +113,39 @@ class RustFutureProbe { 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_on_worker(std::uint64_t handle, Step step) { - ASSERT_EQ(handle, rust_handle); - ASSERT_TRUE(uniffi::detail::async_executor().is_worker()); + 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_on_worker(handle, Step::Poll); + record_ffi(handle, Step::Poll, next_reply_ == 0); ASSERT_NE(callback.callback, nullptr); ASSERT_NE(callback.data, 0u); ASSERT_TRUE(next_reply_ < replies_.size()); @@ -119,6 +155,9 @@ class RustFutureProbe { } 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; @@ -130,11 +169,19 @@ class RustFutureProbe { 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_; @@ -145,6 +192,27 @@ class RustFutureProbe { 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(); @@ -157,6 +225,41 @@ void test_pending_to_ready() { 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 { @@ -218,7 +321,7 @@ void test_continuation_move_failure() { probe.expect_steps({Step::Start, Step::Poll, Step::Complete, Step::Free}); } -class RejectedParser final : public futures::AsyncParserForeign { +class RejectedParser final : public async_calls::TestParserForeign { public: uniffi::ForeignFuture stringify(std::int32_t) override { return {}; } uniffi::ForeignFuture parse(const std::string &) override { return {}; } @@ -228,23 +331,61 @@ class RejectedParser final : public futures::AsyncParserForeign { } }; -class PausedTask { +class DeferredParser final : public async_calls::TestParserForeign { public: - void pause() { - paused_.set_value(); - wait_for_future(resume_signal_); + 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; }; + }); } - 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(); + 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(); @@ -255,16 +396,9 @@ void test_shutdown_cancels_before_repoll() { const auto blocker = executor.track([&] { before_call_cancellation.pause(); }); ASSERT_NE(blocker, 0u); - std::promise> call; - auto handoff = call.get_future(); - ASSERT_TRUE(executor.enqueue([&] { - auto future = futures::wait_using_parser(std::make_shared()); - // The first poll queues the callback startup behind this pause. - ASSERT_TRUE(executor.enqueue([&] { before_callback_start.pause(); })); - call.set_value(std::move(future)); - })); - auto future = wait_for_future(handoff); + 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(); @@ -278,44 +412,51 @@ void test_shutdown_cancels_before_repoll() { uniffi::start_async_executor(); } -// Shutdown cancels a pending Rust call whose first poll comes after admission closes. -void test_shutdown_cancels_before_first_poll() { +// Shutdown waits for an in-flight caller-thread poll before cancelling and freeing the handle. +void test_shutdown_during_first_poll() { auto &executor = uniffi::detail::async_executor(); - PausedTask before_first_poll; - 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); - - // Hold the worker so the call's first poll stays queued until admission has closed. - ASSERT_TRUE(executor.enqueue([&] { before_first_poll.pause(); })); - before_first_poll.wait_until_paused(); - auto future = futures::wait_using_parser(std::make_shared()); + PausedTask first_poll; + RustFutureProbe probe({PollReply::Park}, &first_poll); + auto call = std::async(std::launch::async, [&] { return probe.start(); }); + first_poll.wait_until_paused(); + + std::promise cancelling; + auto cancellation_requested = cancelling.get_future(); + const std::uint64_t observer = executor.track([&] { + executor.untrack(observer); + cancelling.set_value(); + }); + ASSERT_NE(observer, 0u); auto stopping = std::async(std::launch::async, [] { uniffi::shutdown_async_executor(); }); - before_call_cancellation.wait_until_paused(); + wait_for_future(cancellation_requested); ASSERT_FALSE(executor.accepting()); - before_first_poll.resume(); - EXPECT_EXCEPTION(wait_for_future(future), uniffi::AsyncCancelledError); + ASSERT_EQ(stopping.wait_for(std::chrono::seconds(0)), std::future_status::timeout); + probe.expect_steps({Step::Start, Step::Poll}); - executor.untrack(blocker); - before_call_cancellation.resume(); + 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}); 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_cancels_before_first_poll(); + test_shutdown_during_first_poll(); } // Close admission after the start check while the caller still owns the new Rust handle. @@ -323,18 +464,18 @@ void test_shutdown_during_handle_creation() { unsigned frees = 0; const auto unexpected_ffi_call = [](auto...) { assert(false && "the rejected Rust future entered the driver"); - return 0; }; - auto result = futures::uniffi::rust_call_async( - [] { + auto result = async_calls::uniffi::rust_call_async( + [&] { uniffi::shutdown_async_executor(); - return rust_handle; + return reinterpret_cast(&frees); }, - unexpected_ffi_call, unexpected_ffi_call, unexpected_ffi_call, - [&](std::uint64_t handle) { - ASSERT_EQ(handle, rust_handle); - ++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); @@ -351,8 +492,8 @@ void test_foreign_callback_after_shutdown() { ++received.calls; received.status = result.call_status.code; }; - using Trampoline = futures::uniffi::UniffiCallbackInterfaceAsyncParser; - const auto handle = futures::uniffi::FfiConverterAsyncParser::lower(std::make_shared()); + 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); @@ -365,7 +506,7 @@ void test_foreign_callback_after_shutdown() { // A delayed callback startup stays rejected if its state was rejected or cancelled before restart. void test_foreign_states_across_restart() { - using State = futures::uniffi::ForeignFutureTaskState; + using State = async_calls::uniffi::ForeignFutureTaskState; auto rejected = std::make_shared(); rejected->start(rejected); uniffi::start_async_executor(); diff --git a/cpp-tests/tests/async_executor/main.cpp b/cpp-tests/tests/async_executor/main.cpp index 467b874..aee5be8 100644 --- a/cpp-tests/tests/async_executor/main.cpp +++ b/cpp-tests/tests/async_executor/main.cpp @@ -144,8 +144,8 @@ void test_singleton_across_components() { // Two Rust streams receive independently, with bounded buffering and clean end-of-stream. void test_interleaved_stream_reads() { - const auto first = futures::SampleStream::init(); - const auto second = futures::SampleStream::init(); + 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()); @@ -189,7 +189,7 @@ void test_interleaved_stream_reads() { // Cancelling a pending read releases the receiver for the next read. void test_cancel_pending_read() { - const auto stream = futures::SampleStream::init(); + const auto stream = async_calls::SampleStream::init(); auto read = stream->next(); wait_for_queued_work(async_executor()); ASSERT_TRUE(stream->is_read_pending()); @@ -204,7 +204,7 @@ void test_cancel_pending_read() { // A separate cancellation handle releases a thread waiting in get(). void test_cancel_blocking_get() { - auto pending = futures::pending(); + auto pending = async_calls::pending(); const auto cancel = pending.cancel_handle(); auto entering = std::make_shared>(); auto entering_get = entering->get_future(); @@ -232,7 +232,7 @@ void test_cancel_handle_lifetime() { } finished.cancel(); - auto pending = futures::pending(); + auto pending = async_calls::pending(); const auto cancel = pending.cancel_handle(); auto delivered = std::make_shared>(); auto result = delivered->get_future(); @@ -245,10 +245,49 @@ void test_cancel_handle_lifetime() { 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(futures::sample_stream_count(), 0u); - auto stream = futures::SampleStream::init(); + 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) { @@ -266,11 +305,11 @@ void test_singleton_shutdown() { ASSERT_FALSE(executor_from_peer().enqueue([] {})); EXPECT_EXCEPTION(wait_for_future(stream->next()), uniffi::AsyncExecutorError); stream.reset(); - ASSERT_EQ(futures::sample_stream_count(), 0u); + ASSERT_EQ(async_calls::sample_stream_count(), 0u); uniffi::shutdown_async_executor(); } -class RestartParser final : public futures::AsyncParserForeign { +class RestartParser final : public async_calls::TestParserForeign { public: uniffi::ForeignFuture stringify(std::int32_t value) override { return uniffi::ForeignFuture([value](auto success, auto) { @@ -287,7 +326,7 @@ 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(futures::stringify_using_parser(std::make_shared(), 42)), + 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); @@ -307,6 +346,8 @@ int main() { 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(); diff --git a/cpp-tests/tests/async_executor/peer.cpp b/cpp-tests/tests/async_executor/peer.cpp index 6c77aea..c5f359f 100644 --- a/cpp-tests/tests/async_executor/peer.cpp +++ b/cpp-tests/tests/async_executor/peer.cpp @@ -1,4 +1,4 @@ -#include "arithmetic.hpp" +#include "async_api_client.hpp" namespace executor_tests { diff --git a/cpp-tests/tests/async_executor/test_support.hpp b/cpp-tests/tests/async_executor/test_support.hpp index bdf4666..fdb1548 100644 --- a/cpp-tests/tests/async_executor/test_support.hpp +++ b/cpp-tests/tests/async_executor/test_support.hpp @@ -1,5 +1,6 @@ #pragma once +#include "async_calls.hpp" #include "futures.hpp" #include "test_common.hpp" diff --git a/cpp-tests/tests/async_pending_at_exit/main.cpp b/cpp-tests/tests/async_pending_at_exit/main.cpp index cb86a35..2a956cb 100644 --- a/cpp-tests/tests/async_pending_at_exit/main.cpp +++ b/cpp-tests/tests/async_pending_at_exit/main.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include @@ -13,9 +13,9 @@ uniffi::FutureContinuation *volatile pending_continuation; } // namespace int main() { - pending_future = new uniffi::Future(futures::pending()); + pending_future = new uniffi::Future(async_calls::pending()); pending_continuation = new uniffi::FutureContinuation( - futures::pending().then([](auto) { std::abort(); })); + async_calls::pending().then([](auto) { std::abort(); })); auto barrier = std::make_shared>(); auto polled = barrier->get_future(); @@ -23,5 +23,5 @@ int main() { return EXIT_FAILURE; } polled.get(); - return futures::pending_count() == 2 ? EXIT_SUCCESS : EXIT_FAILURE; + 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 index f72bc70..43e55be 100644 --- a/cpp-tests/tests/futures/main.cpp +++ b/cpp-tests/tests/futures/main.cpp @@ -1,5 +1,6 @@ #include +#include #include #include @@ -45,7 +46,15 @@ std::optional thread_count() { using namespace std::chrono_literals; -class TestAsyncParser final : public futures::AsyncParserForeign { +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, @@ -57,19 +66,33 @@ class TestAsyncParser final : public futures::AsyncParserForeign { ~TestAsyncParser() override { destruction_count_->fetch_add(1); } uniffi::ForeignFuture stringify(int32_t value) override { - return uniffi::ForeignFuture([value](auto success, auto) { + 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) { - try { - success(std::stoi(value)); - } catch (...) { - failure(std::make_exception_ptr( - futures::async_parser_error::InvalidInteger("invalid integer"))); + 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 [] {}; }); @@ -90,45 +113,43 @@ class TestAsyncParser final : public futures::AsyncParserForeign { 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_return().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(20, "Wait"); - ASSERT_EQ(std::future_status::timeout, waitable.wait_for(1ms)); + auto waitable = futures::say_after(1, "Wait"); waitable.wait(); ASSERT_EQ("Hello, Wait!", waitable.get()); { - auto pending = futures::pending(); - for (auto i = 0; i < 100 && futures::pending_count() == 0; ++i) { - std::this_thread::sleep_for(1ms); - } - ASSERT_EQ(1, futures::pending_count()); + 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); - for (auto i = 0; i < 100 && futures::pending_count() != 0; ++i) { - std::this_thread::sleep_for(1ms); - } - ASSERT_EQ(0, futures::pending_count()); + ASSERT_EQ(0, async_calls::pending_count()); } { - auto pending = futures::pending(); - for (auto i = 0; i < 100 && futures::pending_count() == 0; ++i) { - std::this_thread::sleep_for(1ms); - } - ASSERT_EQ(1, futures::pending_count()); + auto pending = async_calls::pending(); + ASSERT_EQ(1, async_calls::pending_count()); } - for (auto i = 0; i < 100 && futures::pending_count() != 0; ++i) { - std::this_thread::sleep_for(1ms); - } - ASSERT_EQ(0, futures::pending_count()); + eventually([] { return async_calls::pending_count() == 0; }); for (auto i = 0; i < 100; ++i) { auto racing = futures::say_after(1, "Race"); @@ -169,15 +190,21 @@ int main() { auto record = futures::new_my_record("value", 42).get(); ASSERT_EQ("value", record.a); ASSERT_EQ(42, record.b); - auto record_value = futures::MyRecord{"value", 17}.value_after(1); + auto record_value = async_calls::MyRecord{"value", 17}.value_after(1); ASSERT_EQ(17, record_value.get()); - futures::validate(futures::ValidationMode::kAllow).get(); - EXPECT_EXCEPTION(futures::validate(futures::ValidationMode::kReject).get(), - futures::my_error::Foo); + 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}); - std::this_thread::sleep_for(500ms); EXPECT_EXCEPTION(futures::use_shared_resource({0, 250}).get(), futures::async_error::Timeout); holding.get(); @@ -186,26 +213,35 @@ int main() { auto destruction_count = std::make_shared>(0); auto parser = std::make_shared(started_count, cancellation_count, destruction_count); - ASSERT_EQ("42", futures::stringify_using_parser(parser, 42).get()); - ASSERT_EQ(42, futures::parse_using_parser(parser, "42").get()); - EXPECT_EXCEPTION(futures::parse_using_parser(parser, "not an integer").get(), - futures::async_parser_error::InvalidInteger); + 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 = futures::wait_using_parser(parser); - for (auto i = 0; i < 100 && started_count->load() == 0; ++i) { - std::this_thread::sleep_for(1ms); - } + 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); } - for (auto i = 0; i < 100 && (cancellation_count->load() == 0 || destruction_count->load() == 0); - ++i) { - std::this_thread::sleep_for(1ms); - } + eventually([&] { return cancellation_count->load() != 0 && destruction_count->load() != 0; }); ASSERT_EQ(1, cancellation_count->load()); ASSERT_EQ(1, destruction_count->load()); @@ -223,10 +259,10 @@ int main() { const auto threads_before = thread_count(); std::vector> parked; for (int i = 0; i < 2000; ++i) { - parked.push_back(futures::pending()); + parked.push_back(async_calls::pending()); } const auto parked_deadline = std::chrono::steady_clock::now() + 5s; - while (futures::pending_count() != 2000) { + while (async_calls::pending_count() != 2000) { ASSERT_TRUE(std::chrono::steady_clock::now() < parked_deadline); std::this_thread::yield(); } @@ -239,15 +275,18 @@ int main() { for (auto &future : parked) { EXPECT_EXCEPTION(future.get(), uniffi::AsyncCancelledError); } - ASSERT_EQ(0, futures::pending_count()); + 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 = futures::pending(); + 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(); }); @@ -277,8 +316,8 @@ int main() { } auto late_continuation = futures::always_ready(); late_continuation.wait(); - auto shutdown_pending = futures::pending(); - auto shutdown_foreign = futures::wait_using_parser( + 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); diff --git a/fixtures/Cargo.toml b/fixtures/Cargo.toml index b549673..e5a44d6 100644 --- a/fixtures/Cargo.toml +++ b/fixtures/Cargo.toml @@ -19,6 +19,7 @@ uniffi-example-traits = { git = "https://github.com/mozilla/uniffi-rs.git", tag uniffi-fixture-callbacks = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } uniffi-fixture-coverall = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } uniffi-fixture-docstring = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } +uniffi-fixture-futures = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } uniffi-fixture-time = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } uniffi-fixture-trait-methods = { git = "https://github.com/mozilla/uniffi-rs.git", tag = "v0.31.2" } diff --git a/fixtures/async-calls/Cargo.toml b/fixtures/async-calls/Cargo.toml index c491a06..2fd32ed 100644 --- a/fixtures/async-calls/Cargo.toml +++ b/fixtures/async-calls/Cargo.toml @@ -11,11 +11,7 @@ crate-type = ["lib"] [dependencies] async-trait = "0.1" -once_cell = "1.18.0" futures-timer = "3.0" thiserror = "1.0" -tokio = { version = "1.24.1", features = ["time", "sync"] } +tokio = { version = "1.24.1", features = ["rt", "sync"] } uniffi = { workspace = true, features = ["tokio"] } - -[build-dependencies] -uniffi = { workspace = true, features = ["build"] } diff --git a/fixtures/async-calls/build.rs b/fixtures/async-calls/build.rs deleted file mode 100644 index 9a673b0..0000000 --- a/fixtures/async-calls/build.rs +++ /dev/null @@ -1,9 +0,0 @@ -/* - * 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/. - */ - -fn main() { - uniffi::generate_scaffolding("src/async-calls.udl").unwrap(); -} diff --git a/fixtures/async-calls/src/async-calls.udl b/fixtures/async-calls/src/async-calls.udl deleted file mode 100644 index e567386..0000000 --- a/fixtures/async-calls/src/async-calls.udl +++ /dev/null @@ -1,15 +0,0 @@ -namespace futures { - [Async] - boolean always_ready(); -}; - -interface UdlMegaphone { - [Async] - constructor(); - - [Async, Name="secondary"] - constructor(); - - [Async] - string say_after(u16 ms, string who); -}; diff --git a/fixtures/async-calls/src/lib.rs b/fixtures/async-calls/src/lib.rs index 22102f8..79f59dd 100644 --- a/fixtures/async-calls/src/lib.rs +++ b/fixtures/async-calls/src/lib.rs @@ -4,9 +4,6 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -mod platform_specific; -use platform_specific::acquire_with_timeout; - use futures_timer::Delay; use std::{ sync::{ @@ -28,41 +25,6 @@ impl Drop for PendingGuard { } } -#[uniffi::export] -pub fn greet(who: String) -> String { - format!("Hello, {who}") -} - -pub async fn always_ready() -> bool { - true -} - -#[uniffi::export] -pub async fn void_return() {} - -#[uniffi::export] -pub async fn say() -> String { - Delay::new(Duration::from_secs(2)).await; - "Hello, Future!".to_string() -} - -#[uniffi::export] -pub async fn say_after(ms: u16, who: String) -> String { - Delay::new(Duration::from_millis(ms.into())).await; - format!("Hello, {who}!") -} - -#[uniffi::export] -pub async fn sleep(ms: u16) -> bool { - Delay::new(Duration::from_millis(ms.into())).await; - true -} - -#[uniffi::export] -pub async fn sleep_no_return(ms: u16) { - Delay::new(Duration::from_millis(ms.into())).await; -} - #[uniffi::export] pub async fn pending() { PENDING_COUNT.fetch_add(1, Ordering::SeqCst); @@ -132,101 +94,6 @@ pub enum MyError { Foo, } -#[uniffi::export] -pub async fn fallible_me(do_fail: bool) -> Result { - if do_fail { - Err(MyError::Foo) - } else { - Ok(42) - } -} - -#[uniffi::export] -pub async fn fallible_struct(do_fail: bool) -> Result, MyError> { - if do_fail { - Err(MyError::Foo) - } else { - Ok(new_megaphone()) - } -} - -#[uniffi::export] -pub fn new_megaphone() -> Arc { - Arc::new(Megaphone) -} - -#[uniffi::export] -pub async fn async_new_megaphone() -> Arc { - new_megaphone() -} - -#[uniffi::export] -pub async fn async_maybe_new_megaphone(value: bool) -> Option> { - value.then(new_megaphone) -} - -#[uniffi::export] -pub async fn say_after_with_megaphone(megaphone: Arc, ms: u16, who: String) -> String { - megaphone.say_after(ms, who).await -} - -#[derive(uniffi::Object)] -pub struct Megaphone; - -#[uniffi::export] -impl Megaphone { - #[uniffi::constructor] - pub async fn new() -> Arc { - Delay::new(Duration::from_millis(0)).await; - Arc::new(Self) - } - - #[uniffi::constructor] - pub async fn secondary() -> Arc { - Delay::new(Duration::from_millis(0)).await; - Arc::new(Self) - } - - pub async fn say_after(self: Arc, ms: u16, who: String) -> String { - say_after(ms, who).await.to_uppercase() - } - - pub async fn silence(&self) -> String { - String::new() - } - - pub async fn fallible_me(self: Arc, do_fail: bool) -> Result { - fallible_me(do_fail).await - } -} - -#[derive(uniffi::Object)] -pub struct FallibleMegaphone; - -#[uniffi::export] -impl FallibleMegaphone { - #[uniffi::constructor] - pub async fn new() -> Result, MyError> { - Err(MyError::Foo) - } -} - -pub struct UdlMegaphone; - -impl UdlMegaphone { - pub async fn new() -> Self { - Self - } - - pub async fn secondary() -> Self { - Self - } - - pub async fn say_after(self: Arc, ms: u16, who: String) -> String { - say_after(ms, who).await.to_uppercase() - } -} - #[derive(uniffi::Record)] pub struct MyRecord { pub a: String, @@ -241,11 +108,6 @@ impl MyRecord { } } -#[uniffi::export] -pub async fn new_my_record(a: String, b: u32) -> MyRecord { - MyRecord { a, b } -} - #[derive(uniffi::Enum)] pub enum ValidationMode { Allow, @@ -262,23 +124,6 @@ impl ValidationMode { } } -#[derive(uniffi::Record)] -pub struct SharedResourceOptions { - pub release_after_ms: u16, - pub timeout_ms: u16, -} - -#[derive(thiserror::Error, uniffi::Error, Debug)] -pub enum AsyncError { - #[error("Timeout")] - Timeout, -} - -#[uniffi::export(async_runtime = "tokio")] -pub async fn use_shared_resource(options: SharedResourceOptions) -> Result<(), AsyncError> { - acquire_with_timeout(options).await -} - #[derive(Debug, thiserror::Error, uniffi::Error)] pub enum AsyncParserError { #[error("invalid integer")] @@ -295,28 +140,70 @@ impl From for AsyncParserError { #[uniffi::export(with_foreign)] #[async_trait::async_trait] -pub trait AsyncParser: Send + Sync { +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 { +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, + parser: Arc, value: String, ) -> Result { parser.parse(value).await } #[uniffi::export] -pub async fn wait_using_parser(parser: Arc) { +pub async fn wait_using_parser(parser: Arc) { parser.wait().await } -uniffi::include_scaffolding!("async-calls"); +#[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/async-calls/src/platform_specific/mod.rs b/fixtures/async-calls/src/platform_specific/mod.rs deleted file mode 100644 index 226fa51..0000000 --- a/fixtures/async-calls/src/platform_specific/mod.rs +++ /dev/null @@ -1,8 +0,0 @@ -/* - * 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/. - */ - -mod native; -pub(crate) use native::*; diff --git a/fixtures/async-calls/src/platform_specific/native.rs b/fixtures/async-calls/src/platform_specific/native.rs deleted file mode 100644 index 9750869..0000000 --- a/fixtures/async-calls/src/platform_specific/native.rs +++ /dev/null @@ -1,29 +0,0 @@ -/* - * 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 std::time::Duration; - -use crate::{AsyncError, SharedResourceOptions}; - -pub(crate) async fn acquire_with_timeout(options: SharedResourceOptions) -> Result<(), AsyncError> { - use once_cell::sync::Lazy; - use tokio::{ - sync::Mutex, - time::{sleep, timeout}, - }; - - static MUTEX: Lazy> = Lazy::new(|| Mutex::new(())); - - let _guard = timeout( - Duration::from_millis(options.timeout_ms.into()), - MUTEX.lock(), - ) - .await - .map_err(|_| AsyncError::Timeout)?; - - sleep(Duration::from_millis(options.release_after_ms.into())).await; - Ok(()) -} diff --git a/fixtures/src/lib.rs b/fixtures/src/lib.rs index 1590896..995059b 100644 --- a/fixtures/src/lib.rs +++ b/fixtures/src/lib.rs @@ -13,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!(); From fe3c2b1fa0e6239081b54f4604e613ea837fc7ac Mon Sep 17 00:00:00 2001 From: Alan George Date: Mon, 23 Nov 2026 11:11:35 -0700 Subject: [PATCH 15/19] Use a linked binding for the executor peer test GCC emits the included binding's vtable initializers. Use the futures binding already linked by this test. --- cpp-tests/tests/async_executor/peer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp-tests/tests/async_executor/peer.cpp b/cpp-tests/tests/async_executor/peer.cpp index c5f359f..ce7b547 100644 --- a/cpp-tests/tests/async_executor/peer.cpp +++ b/cpp-tests/tests/async_executor/peer.cpp @@ -1,4 +1,4 @@ -#include "async_api_client.hpp" +#include "futures.hpp" namespace executor_tests { From 1dc711673d7a34e1524634c3e8dfebc289e5f265 Mon Sep 17 00:00:00 2001 From: Alan George Date: Mon, 23 Nov 2026 12:53:33 -0700 Subject: [PATCH 16/19] Wait for caller-thread polls before closing async admission Queue new first polls on the worker while shutdown waits for inline polls. Cover callback startup during the wait and cancellation after the poll returns. --- bindgen/src/bindings/cpp/templates/async.cpp | 5 +- bindgen/src/bindings/cpp/templates/async.hpp | 24 +++++++++- .../tests/async_executor/ffi_lifecycle.cpp | 47 ++++++++++++++----- 3 files changed, 60 insertions(+), 16 deletions(-) diff --git a/bindgen/src/bindings/cpp/templates/async.cpp b/bindgen/src/bindings/cpp/templates/async.cpp index 136d1b6..d2bee40 100644 --- a/bindgen/src/bindings/cpp/templates/async.cpp +++ b/bindgen/src/bindings/cpp/templates/async.cpp @@ -145,15 +145,14 @@ class RustFutureState : public std::enable_shared_from_this { bool start() { const auto self = this->shared_from_this(); auto &executor = ::uniffi::detail::async_executor(); - bool poll_on_caller; + bool poll_on_caller = false; { std::lock_guard guard(mutex_); - operation_id_ = executor.track([self] { self->cancel(); }); + 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. - poll_on_caller = executor.accepting(); driving_ = poll_on_caller; poll_requested_ = !poll_on_caller; poll_outstanding_ = poll_on_caller; diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp index c7d709a..aa1f9db 100644 --- a/bindgen/src/bindings/cpp/templates/async.hpp +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -33,13 +33,21 @@ class AsyncExecutor { return true; } - uint64_t track(AsyncTask cancel) { + // Registers a call. With poll_on_caller, also reports whether its first poll may run on the + // calling thread; a true answer must be followed by 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; } @@ -60,6 +68,11 @@ class AsyncExecutor { 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(); + } } void start() { @@ -83,10 +96,15 @@ class AsyncExecutor { std::lock_guard shutdown_guard(shutdown_mutex_); std::vector cancellations; { - std::lock_guard guard(mutex_); + 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); @@ -144,6 +162,8 @@ class AsyncExecutor { std::atomic accepting_{true}; bool stopped_ = false; bool running_ = false; + std::atomic closing_{false}; + std::atomic inline_polls_{0}; inline static thread_local const AsyncExecutor *current_worker_ = nullptr; inline static thread_local const AsyncExecutor *current_inline_ = nullptr; std::thread worker_; diff --git a/cpp-tests/tests/async_executor/ffi_lifecycle.cpp b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp index 8d4bae5..c5458c8 100644 --- a/cpp-tests/tests/async_executor/ffi_lifecycle.cpp +++ b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp @@ -412,7 +412,20 @@ void test_shutdown_cancels_before_repoll() { uniffi::start_async_executor(); } -// Shutdown waits for an in-flight caller-thread poll before cancelling and freeing the handle. +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; @@ -420,18 +433,29 @@ void test_shutdown_during_first_poll() { auto call = std::async(std::launch::async, [&] { return probe.start(); }); first_poll.wait_until_paused(); - std::promise cancelling; - auto cancellation_requested = cancelling.get_future(); - const std::uint64_t observer = executor.track([&] { - executor.untrack(observer); - cancelling.set_value(); - }); - ASSERT_NE(observer, 0u); - auto stopping = std::async(std::launch::async, [] { uniffi::shutdown_async_executor(); }); - wait_for_future(cancellation_requested); - ASSERT_FALSE(executor.accepting()); + // 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(); @@ -439,6 +463,7 @@ void test_shutdown_during_first_poll() { 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(); } From 3e0f4f0e14ae1406ebaa9fd754d9a0119f3e21e9 Mon Sep 17 00:00:00 2001 From: Alan George Date: Mon, 23 Nov 2026 12:56:52 -0700 Subject: [PATCH 17/19] Document caller-thread polling and executor shutdown --- README.md | 16 ++-- docs/ASYNC_RUNTIME.md | 177 ++++++++++++++++++++++++++---------------- 2 files changed, 120 insertions(+), 73 deletions(-) diff --git a/README.md b/README.md index a7c32fe..262eb57 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,9 @@ One shared control executor drives all generated components linked into the same 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: @@ -82,11 +85,14 @@ blocking application work to an existing application worker pool or async I/O se 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 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 application callback can prevent -shutdown from completing. +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 diff --git a/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md index 402baa5..08a8c01 100644 --- a/docs/ASYNC_RUNTIME.md +++ b/docs/ASYNC_RUNTIME.md @@ -9,18 +9,20 @@ 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 on the caller's thread. - The worker calls `rust_future_poll` and repolls on `WAKE`. On `READY` it calls - `rust_future_complete` to collect the value or error, then `rust_future_free` to release the - handle. It requests cancellation with `rust_future_cancel`. [UniFFI handle rules][rust-handle-rules] +- **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 stop - admission, cancel outstanding work, drain the queue, and join the worker. Call - `start_async_executor()` to reopen admission. [Shutdown][shutdown] · [Restart][restart] +- **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. @@ -35,44 +37,71 @@ sequenceDiagram B->>R: call scaffolding function R-->>B: return RustFuture handle B->>B: Register RustFutureState with the executor - B->>E: Queue drive() for the first poll + 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 - 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 this future waits for a wake + opt Call is pending or its first poll was queued + opt Pending after a caller-thread poll R->>B: continuation(state, WAKE) - B->>E: Request another poll - else READY - R->>B: continuation(state, READY) - B->>B: Record readiness + 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 - - 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->>E: Untrack the call - E->>B: Publish to FutureCompletionState 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. Pending Rust -futures retain their state and wake callback. Each driver runs at most 64 actions per turn before -yielding to the queue. [Executor][executor] · [Driver][drive] +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] -->|Schedule driver| Q[Control queue] + 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 or finish| R[Rust scaffolding] + W -->|Poll, cancel or finish| R R -->|Wake callback| Q - W -->|Publish result| F[C++ future or continuation] + W -->|Publish result| F + W -->|Deliver| T[C++ continuation] ``` A move-only `Future` supports `wait()`, `wait_for()`, `get()`, `cancel()`, and a consuming @@ -103,23 +132,28 @@ an out pointer on completion. [Function template][function] · [Object template] - **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 and schedules the first poll. The poll passes the state's address as callback data. - The callback takes a strong reference to the state on entry. + 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. - `next_action()` sets `poll_outstanding_` before invoking Rust and admits another poll only after - that callback. Rust guarantees one callback per poll, which can arrive from another thread. + `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.** `next_action()` gives `READY` priority and sets `terminal_` - before returning `CompleteFuture`. That flag closes the driver, callback, and cancellation paths. - The worker completes once, checks `RustCallStatus`, and lifts the value on success. - [Action selection][next-action] · [Result conversion][finish] · [Status handling][status] -- **Free the handle as the last FFI operation.** The driver frees the handle before removing the - registry entry and publishing the result. 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. +- **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 @@ -190,9 +224,12 @@ gate, a later drop just releases the C++ handle. ## Shutdown Stop producers before calling `shutdown_async_executor()` from an application thread. 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. +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. @@ -207,6 +244,10 @@ increasing across restarts. The callback trampoline checks admission and its own 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 @@ -238,32 +279,32 @@ method or when conversion to the declared error type fails. [Result handling][ru [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#L15-L150 -[drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L210-L296 -[future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L429-L547 -[cancel-handle]: ../bindgen/src/bindings/cpp/templates/async.hpp#L410-L427 -[completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L301-L389 -[wait-guard]: ../bindgen/src/bindings/cpp/templates/async.hpp#L161-L167 -[function]: ../bindgen/src/bindings/cpp/templates/fn_def.cpp#L1-L20 -[object]: ../bindgen/src/bindings/cpp/templates/obj.cpp#L32-L78 +[executor]: ../bindgen/src/bindings/cpp/templates/async.hpp#L17-L176 +[drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L236-L322 +[future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L416-L536 +[cancel-handle]: ../bindgen/src/bindings/cpp/templates/async.hpp#L397-L414 +[completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L308-L393 +[wait-guard]: ../bindgen/src/bindings/cpp/templates/async.hpp#L189-L193 +[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-L164 +[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#L115-L134 -[state-start]: ../bindgen/src/bindings/cpp/templates/async.cpp#L149-L188 -[poll]: ../bindgen/src/bindings/cpp/templates/async.cpp#L298-L302 -[continuation]: ../bindgen/src/bindings/cpp/templates/async.cpp#L184-L208 -[next-action]: ../bindgen/src/bindings/cpp/templates/async.cpp#L227-L249 -[finish]: ../bindgen/src/bindings/cpp/templates/async.cpp#L314-L344 -[status]: ../bindgen/src/bindings/cpp/templates/wrapper.cpp#L40-L64 -[call-async]: ../bindgen/src/bindings/cpp/templates/async.cpp#L367-L402 -[cancel]: ../bindgen/src/bindings/cpp/templates/async.cpp#L304-L312 -[callback-api]: ../bindgen/src/bindings/cpp/templates/callback.hpp#L6-L35 +[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#L9-L93 +[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#L73-L99 -[restart]: ../bindgen/src/bindings/cpp/templates/async.hpp#L59-L71 -[registration]: ../bindgen/src/bindings/cpp/templates/async.hpp#L291-L299 +[shutdown]: ../bindgen/src/bindings/cpp/templates/async.hpp#L92-L123 +[restart]: ../bindgen/src/bindings/cpp/templates/async.hpp#L78-L90 +[registration]: ../bindgen/src/bindings/cpp/templates/async.hpp#L298-L306 From a8a5446fa2a562d84f0f0ea42c2816cd27a552cf Mon Sep 17 00:00:00 2001 From: Alan George Date: Mon, 23 Nov 2026 13:38:54 -0700 Subject: [PATCH 18/19] Add doc comments --- bindgen/src/bindings/cpp/templates/async.hpp | 55 ++++++++++++++++---- docs/ASYNC_RUNTIME.md | 16 +++--- 2 files changed, 54 insertions(+), 17 deletions(-) diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp index aa1f9db..2cbd280 100644 --- a/bindgen/src/bindings/cpp/templates/async.hpp +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -1,26 +1,32 @@ +// 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 { -// One control executor per linked C++ image, shared by all generated components. Tasks must not -// block. +// 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_); @@ -33,8 +39,8 @@ class AsyncExecutor { return true; } - // Registers a call. With poll_on_caller, also reports whether its first poll may run on the - // calling thread; a true answer must be followed by run_inline(). + // 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)) { @@ -51,6 +57,7 @@ class AsyncExecutor { 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); @@ -59,10 +66,13 @@ class AsyncExecutor { } } + // 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; @@ -75,6 +85,7 @@ class AsyncExecutor { } } + // 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. @@ -89,6 +100,8 @@ class AsyncExecutor { } } + // 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"); @@ -169,6 +182,7 @@ class AsyncExecutor { 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(); @@ -186,6 +200,7 @@ inline bool enqueue_async(AsyncTask task) noexcept { 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"); @@ -202,15 +217,17 @@ template <> struct ForeignFutureSuccess { } // namespace detail -// Cancels in-flight calls, drains their Rust handles and queued completions, and joins the worker. -// Stop producers first. Call from an application thread before unloading the bindings or Rust. +// 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(); } -// Reopen admission and start a worker after the previous worker has joined. +// 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(); } -// C++17 adapter for an async callback-interface method. The implementation starts work when the -// generated bridge supplies success and failure callbacks, and returns an optional cancel action. +// 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; @@ -226,6 +243,7 @@ template class ForeignFuture { 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"); @@ -238,6 +256,7 @@ template class ForeignFuture { 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)) {} @@ -261,6 +280,7 @@ template class FutureResult { 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_); @@ -273,6 +293,7 @@ template class FutureResult { std::exception_ptr error_; }; +// Carries completion or an exception for a void result. template <> class FutureResult { public: FutureResult() = default; @@ -281,6 +302,7 @@ template <> class FutureResult { 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_); @@ -394,10 +416,12 @@ template class FutureCompletionState { } // 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_(); @@ -413,6 +437,8 @@ class FutureCancelHandle { 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; @@ -436,8 +462,10 @@ class FutureContinuation { ~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_); @@ -450,6 +478,9 @@ class FutureContinuation { 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; @@ -482,8 +513,10 @@ template class Future { 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)) == @@ -493,17 +526,20 @@ template class Future { 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) { @@ -516,6 +552,7 @@ template class Future { 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_); diff --git a/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md index 08a8c01..2d7a5ea 100644 --- a/docs/ASYNC_RUNTIME.md +++ b/docs/ASYNC_RUNTIME.md @@ -279,12 +279,12 @@ method or when conversion to the declared error type fails. [Result handling][ru [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#L17-L176 +[executor]: ../bindgen/src/bindings/cpp/templates/async.hpp#L20-L190 [drive]: ../bindgen/src/bindings/cpp/templates/async.cpp#L236-L322 -[future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L416-L536 -[cancel-handle]: ../bindgen/src/bindings/cpp/templates/async.hpp#L397-L414 -[completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L308-L393 -[wait-guard]: ../bindgen/src/bindings/cpp/templates/async.hpp#L189-L193 +[future]: ../bindgen/src/bindings/cpp/templates/async.hpp#L442-L573 +[cancel-handle]: ../bindgen/src/bindings/cpp/templates/async.hpp#L420-L438 +[completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L330-L415 +[wait-guard]: ../bindgen/src/bindings/cpp/templates/async.hpp#L204-L208 [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 @@ -305,6 +305,6 @@ method or when conversion to the declared error type fails. [Result handling][ru [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#L92-L123 -[restart]: ../bindgen/src/bindings/cpp/templates/async.hpp#L78-L90 -[registration]: ../bindgen/src/bindings/cpp/templates/async.hpp#L298-L306 +[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#L320-L328 From 4253ddab90f82d171e5d9f6250ed18f80e72fd8f Mon Sep 17 00:00:00 2001 From: Alan George Date: Mon, 23 Nov 2026 13:44:24 -0700 Subject: [PATCH 19/19] More doc comments --- bindgen/src/bindings/cpp/templates/async.hpp | 15 +++++++++++++++ docs/ASYNC_RUNTIME.md | 12 ++++++------ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp index 2cbd280..417ddc0 100644 --- a/bindgen/src/bindings/cpp/templates/async.hpp +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -165,20 +165,35 @@ class AsyncExecutor { } } + // 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_; }; diff --git a/docs/ASYNC_RUNTIME.md b/docs/ASYNC_RUNTIME.md index 2d7a5ea..c0c80be 100644 --- a/docs/ASYNC_RUNTIME.md +++ b/docs/ASYNC_RUNTIME.md @@ -279,12 +279,12 @@ method or when conversion to the declared error type fails. [Result handling][ru [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-L190 +[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#L442-L573 -[cancel-handle]: ../bindgen/src/bindings/cpp/templates/async.hpp#L420-L438 -[completion]: ../bindgen/src/bindings/cpp/templates/async.hpp#L330-L415 -[wait-guard]: ../bindgen/src/bindings/cpp/templates/async.hpp#L204-L208 +[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 @@ -307,4 +307,4 @@ method or when conversion to the declared error type fails. [Result handling][ru [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#L320-L328 +[registration]: ../bindgen/src/bindings/cpp/templates/async.hpp#L335-L343