From b1850010f12d19756eaa0d4c76b009068f3a4125 Mon Sep 17 00:00:00 2001 From: Alan George Date: Mon, 23 Nov 2026 16:00:12 -0700 Subject: [PATCH] Generate C++ bindings for async Rust exports --- Cargo.lock | 58 +++ .../src/bindings/cpp/gen_cpp/filters/mod.rs | 3 +- bindgen/src/bindings/cpp/gen_cpp/mod.rs | 6 +- bindgen/src/bindings/cpp/mod.rs | 7 - bindgen/src/bindings/cpp/templates/async.cpp | 334 ++++++++++++++++ .../cpp/templates/flat_enum_methods.cpp | 9 +- .../cpp/templates/flat_enum_methods.hpp | 5 +- bindgen/src/bindings/cpp/templates/fn_def.cpp | 16 +- bindgen/src/bindings/cpp/templates/macros.cpp | 44 +++ bindgen/src/bindings/cpp/templates/obj.cpp | 33 +- bindgen/src/bindings/cpp/templates/obj.hpp | 13 +- .../bindings/cpp/templates/scaffolding.hpp | 2 + .../bindings/cpp/templates/value_methods.cpp | 9 +- .../bindings/cpp/templates/value_methods.hpp | 5 +- .../src/bindings/cpp/templates/wrapper.cpp | 11 +- .../src/bindings/cpp/templates/wrapper.hpp | 33 +- cpp-tests/CMakeLists.txt | 23 +- .../tests/async_executor/ffi_lifecycle.cpp | 360 ++++++++++++++++++ cpp-tests/tests/async_executor/main.cpp | 233 ++++++++++++ .../tests/async_executor/test_support.hpp | 11 + .../tests/async_pending_at_exit/main.cpp | 27 ++ fixtures/Cargo.toml | 1 + fixtures/async-calls/Cargo.toml | 16 + fixtures/async-calls/README.md | 4 + fixtures/async-calls/src/lib.rs | 132 +++++++ fixtures/src/lib.rs | 1 + 26 files changed, 1322 insertions(+), 74 deletions(-) create mode 100644 bindgen/src/bindings/cpp/templates/async.cpp 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/test_support.hpp create mode 100644 cpp-tests/tests/async_pending_at_exit/main.cpp create mode 100644 fixtures/async-calls/Cargo.toml create mode 100644 fixtures/async-calls/README.md create mode 100644 fixtures/async-calls/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index d7cc9de..019bf5c 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,16 @@ dependencies = [ "uniffi_pipeline", ] +[[package]] +name = "uniffi-async-calls" +version = "0.21.0" +dependencies = [ + "futures-timer", + "thiserror 1.0.50", + "tokio", + "uniffi", +] + [[package]] name = "uniffi-bindgen-cpp" version = "0.10.0+v0.31.2" @@ -787,6 +843,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 +1090,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/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs b/bindgen/src/bindings/cpp/gen_cpp/filters/mod.rs index 1aa195a..3b0cd0c 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 { @@ -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..7f83d4a --- /dev/null +++ b/bindgen/src/bindings/cpp/templates/async.cpp @@ -0,0 +1,334 @@ +constexpr int8_t UNIFFI_RUST_FUTURE_POLL_READY = 0; +constexpr int8_t UNIFFI_RUST_FUTURE_POLL_WAKE = 1; + +using RustFutureHandleFn = void (*)(uint64_t); + +class RustFutureHandleGuard { + public: + RustFutureHandleGuard(uint64_t handle, RustFutureHandleFn free) noexcept + : handle_(handle), free_(free) {} + + RustFutureHandleGuard(const RustFutureHandleGuard &) = delete; + RustFutureHandleGuard &operator=(const RustFutureHandleGuard &) = delete; + + ~RustFutureHandleGuard() { + if (active_) { + free_(handle_); + } + } + + void release() noexcept { active_ = false; } + + private: + uint64_t handle_; + RustFutureHandleFn free_; + bool active_ = true; +}; + +class RustFutureState : public std::enable_shared_from_this { + public: + using Poll = void (*)(uint64_t, RustFutureContinuationCallback, uint64_t); + + virtual ~RustFutureState() = default; + + bool start() { + const auto self = this->shared_from_this(); + auto &executor = ::uniffi::detail::async_executor(); + bool poll_on_caller = false; + { + std::lock_guard guard(mutex_); + operation_id_ = executor.track([self] { self->cancel(); }, &poll_on_caller); + if (!operation_id_) { + return false; + } + // Track the call before polling, and keep ownership if Rust wakes inline. + driving_ = poll_on_caller; + poll_requested_ = !poll_on_caller; + poll_outstanding_ = poll_on_caller; + } + if (poll_on_caller) { + executor.run_inline([this] { poll_first_turn(); }); + } else { + request_drive(); + } + return true; + } + + void cancel() noexcept { + { + std::lock_guard guard(mutex_); + if (terminal_) { + return; + } + cancel_requested_ = true; + } + request_drive(); + } + + protected: + RustFutureState(uint64_t handle, Poll poll, RustFutureHandleFn cancel, RustFutureHandleFn free) + : handle_(handle), poll_(poll), cancel_(cancel), free_(free) {} + + private: + enum class Action { + None, + PollFuture, + CancelFuture, + CompleteFuture, + }; + + void poll_first_turn() noexcept { + poll(); + + bool complete; + bool needs_drive; + { + std::lock_guard guard(mutex_); + complete = ready_; + terminal_ = complete; + needs_drive = cancel_requested_ || poll_requested_; + driving_ = false; + } + if (complete) { + complete_and_free(); + } else if (needs_drive) { + request_drive(); + } + } + + static void continuation(uint64_t callback_data, int8_t poll_result) noexcept { + // The active-operation registry owns the state until READY has been consumed and freed. + auto state = reinterpret_cast(callback_data)->shared_from_this(); + state->on_continuation(poll_result); + } + + void on_continuation(int8_t poll_result) noexcept { + { + std::lock_guard guard(mutex_); + if (terminal_) { + return; + } + poll_outstanding_ = false; + if (poll_result == UNIFFI_RUST_FUTURE_POLL_READY) { + ready_ = true; + } else if (poll_result == UNIFFI_RUST_FUTURE_POLL_WAKE) { + poll_requested_ = true; + } else { + failure_ = std::make_exception_ptr( + std::runtime_error("Unexpected UniFFI Rust future poll result")); + cancel_requested_ = true; + } + } + request_drive(); + } + + void request_drive() noexcept { + std::shared_ptr state; + { + std::lock_guard guard(mutex_); + if (terminal_ || driving_ || scheduled_) { + return; + } + scheduled_ = true; + state = this->shared_from_this(); + } + + if (!::uniffi::detail::enqueue_async([state] { state->drive(); })) { + // Active operations keep the executor alive until their handles have been released. + std::terminate(); + } + } + + Action next_action() noexcept { + std::lock_guard guard(mutex_); + if (terminal_) { + return Action::None; + } + if (ready_) { + terminal_ = true; + return Action::CompleteFuture; + } + const bool can_poll = poll_requested_ && !poll_outstanding_; + // Shutdown closes admission before it runs the registered cancellations. + if (!cancel_sent_ && + (cancel_requested_ || (can_poll && !::uniffi::detail::begin_async_call()))) { + cancel_sent_ = true; + return Action::CancelFuture; + } + if (can_poll) { + poll_requested_ = false; + poll_outstanding_ = true; + return Action::PollFuture; + } + return Action::None; + } + + void drive() noexcept { + { + std::lock_guard guard(mutex_); + scheduled_ = false; + if (terminal_ || driving_) { + return; + } + driving_ = true; + } + + // Bound each turn so a rapidly waking future cannot starve other calls. + for (unsigned turn = 0; turn < 64; ++turn) { + switch (next_action()) { + case Action::PollFuture: + poll(); + break; + case Action::CancelFuture: + cancel_rust_future(); + break; + case Action::CompleteFuture: + complete_and_free(); + { + std::lock_guard guard(mutex_); + driving_ = false; + } + return; + case Action::None: { + std::lock_guard guard(mutex_); + // A continuation can arrive after next_action() releases the mutex but before + // this block acquires it. It observes driving_ and deliberately does not enqueue + // another driver, so re-check the state before yielding ownership. + if (!terminal_ && (ready_ || (cancel_requested_ && !cancel_sent_) || + (poll_requested_ && !poll_outstanding_))) { + continue; + } + driving_ = false; + } + return; + } + } + { + std::lock_guard guard(mutex_); + driving_ = false; + } + request_drive(); + } + + void poll() noexcept { + // UniFFI invokes exactly one continuation per poll. Reuse the state's address instead of + // allocating callback userdata on every wake; the registry retains it until completion. + poll_(handle_, &RustFutureState::continuation, reinterpret_cast(this)); + } + + void cancel_rust_future() noexcept { + cancel_(handle_); + // If cancellation happened before the first poll there is no continuation to wake. Polling + // the cancelled Rust future yields READY immediately and keeps us on the documented path. + std::lock_guard guard(mutex_); + if (!poll_outstanding_ && !ready_) { + poll_requested_ = true; + } + } + + void complete_and_free() noexcept { + // terminal_ was set under the mutex, so no further continuation can change failure_. + complete_result(handle_, free_, failure_); + ::uniffi::detail::async_executor().untrack(operation_id_); + } + + virtual void complete_result(uint64_t handle, RustFutureHandleFn free, + std::exception_ptr protocol_failure) noexcept = 0; + + uint64_t handle_; + uint64_t operation_id_ = 0; + Poll poll_; + RustFutureHandleFn cancel_; + RustFutureHandleFn free_; + std::mutex mutex_; + std::exception_ptr failure_; + bool poll_requested_ = true; + bool poll_outstanding_ = false; + bool cancel_requested_ = false; + bool cancel_sent_ = false; + bool ready_ = false; + bool scheduled_ = false; + bool driving_ = false; + bool terminal_ = false; +}; + +template +class RustFutureResultState final : public RustFutureState { + public: + RustFutureResultState(uint64_t handle, Poll poll, RustFutureHandleFn cancel, + Complete complete, RustFutureHandleFn free, Lift lift, + ErrorHandler error_handler, + std::shared_ptr<::uniffi::detail::FutureCompletionState> completion_state) + : RustFutureState(handle, poll, cancel, free), complete_(std::move(complete)), + lift_(std::move(lift)), error_handler_(std::move(error_handler)), + completion_state_(std::move(completion_state)) {} + + private: + void complete_result(uint64_t handle, RustFutureHandleFn free, + std::exception_ptr protocol_failure) noexcept override { + std::optional<::uniffi::FutureResult> result; + try { + RustCallStatus status{}; + if constexpr (std::is_void_v) { + complete_(handle, &status); + check_rust_call(status, error_handler_); + result.emplace(); + } else { + auto value = complete_(handle, &status); + check_rust_call(status, error_handler_); + result.emplace(lift_(value)); + } + } catch (...) { + result.emplace(std::current_exception()); + } + + free(handle); + + if (protocol_failure) { + result.emplace(std::move(protocol_failure)); + } + completion_state_->complete(std::move(*result)); + } + + Complete complete_; + Lift lift_; + ErrorHandler error_handler_; + std::shared_ptr<::uniffi::detail::FutureCompletionState> completion_state_; +}; + +template +Future rust_call_async(RustFuture rust_future, RustFutureState::Poll poll, + RustFutureHandleFn cancel, Complete complete, RustFutureHandleFn free, + Lift lift, ErrorHandler error_handler) { + initialize(); + auto completion_state = std::make_shared<::uniffi::detail::FutureCompletionState>(); + auto rejected = [&completion_state] { + completion_state->complete( + ::uniffi::FutureResult(std::make_exception_ptr(::uniffi::AsyncExecutorError()))); + return Future(std::move(completion_state), nullptr); + }; + if (!::uniffi::detail::begin_async_call()) { + return rejected(); + } + + const auto handle = rust_future(); + RustFutureHandleGuard handle_guard(handle, free); + using State = RustFutureResultState; + + auto state = + std::make_shared(handle, poll, cancel, std::move(complete), + free, std::move(lift), std::move(error_handler), completion_state); + // Prepare the callback while the guard owns the handle. Arm Future cancellation after start() + // so a registration exception leaves the guard as the only cleanup path. + std::function cancel_future = [weak_state = std::weak_ptr(state)] { + if (auto state = weak_state.lock()) { + state->cancel(); + } + }; + + if (!state->start()) { + return rejected(); + } + handle_guard.release(); + return Future(std::move(completion_state), std::move(cancel_future)); +} diff --git a/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp b/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp index 5534b8a..3274666 100644 --- a/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp +++ b/bindgen/src/bindings/cpp/templates/flat_enum_methods.cpp @@ -1,15 +1,16 @@ {%- for method in methods %} -{%- if !method.is_async() %} -{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch -%} -{{ method.name()|fn_name }}({{ type_name }} _uniffi_self{% if !method.arguments().is_empty() %}, {% endif %}{% call macros::param_list(method) %}) { +{% call macros::callable_return_type(method) %} {{ method.name()|fn_name }}({{ type_name }} _uniffi_self{% if !method.arguments().is_empty() %}, {% endif %}{% call macros::param_list(method) %}) { + {%- if method.is_async() %} + return {% call macros::rust_call_async_with_value(method, typ, "_uniffi_self") %}; + {%- else %} {%- match method.return_type() %} {%- when Some with (return_type) %} return uniffi::{{ return_type|lift_fn }}({% call macros::rust_call_with_value(method, typ) %}); {%- when None %} {% call macros::rust_call_with_value(method, typ) %}; {%- endmatch %} + {%- endif %} } -{%- endif %} {%- endfor %} {%- if let Some(method) = uniffi_trait_methods.display_fmt %} diff --git a/bindgen/src/bindings/cpp/templates/flat_enum_methods.hpp b/bindgen/src/bindings/cpp/templates/flat_enum_methods.hpp index 0b2b0e4..422af51 100644 --- a/bindgen/src/bindings/cpp/templates/flat_enum_methods.hpp +++ b/bindgen/src/bindings/cpp/templates/flat_enum_methods.hpp @@ -1,9 +1,6 @@ {%- for method in methods %} -{%- if !method.is_async() %} {%- call macros::docstring(method, 0) %} -{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch -%} -{{ method.name()|fn_name }}({{ type_name }} _uniffi_self{% if !method.arguments().is_empty() %}, {% endif %}{% call macros::param_list(method) %}); -{%- endif %} +{% call macros::callable_return_type(method) %} {{ method.name()|fn_name }}({{ type_name }} _uniffi_self{% if !method.arguments().is_empty() %}, {% endif %}{% call macros::param_list(method) %}); {%- endfor %} {%- if uniffi_trait_methods.display_fmt.is_some() %} diff --git a/bindgen/src/bindings/cpp/templates/fn_def.cpp b/bindgen/src/bindings/cpp/templates/fn_def.cpp index 4f9cb1d..7c39629 100644 --- a/bindgen/src/bindings/cpp/templates/fn_def.cpp +++ b/bindgen/src/bindings/cpp/templates/fn_def.cpp @@ -1,12 +1,14 @@ -{%- match func.return_type() %} -{%- when Some with (return_type) %} -{{ return_type|type_name(ci) }} {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { +{% call macros::callable_return_type(func) %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { + {%- if func.is_async() %} + return {% call macros::rust_call_async(func, "") %}; + {%- else %} + {%- match func.return_type() %} + {%- when Some with (return_type) %} auto ret = {% call macros::rust_call(func) %}; return uniffi::{{ return_type|lift_fn }}(ret); -} -{%- when None -%} -void {{ func.name()|fn_name }}({% call macros::param_list(func) %}) { + {%- when None %} {% call macros::rust_call(func) %}; + {%- endmatch %} + {%- endif %} } -{%- endmatch -%} diff --git a/bindgen/src/bindings/cpp/templates/macros.cpp b/bindgen/src/bindings/cpp/templates/macros.cpp index 0cf6f7c..aaf6a39 100644 --- a/bindgen/src/bindings/cpp/templates/macros.cpp +++ b/bindgen/src/bindings/cpp/templates/macros.cpp @@ -66,6 +66,50 @@ uniffi::{{ self_type|lower_fn }}(other)) {%- endmacro %} +{% macro rust_call_async(func, prefix) -%} + uniffi::rust_call_async<{% match func.return_type() %}{% when Some with (value_type) %}{{ value_type|type_name(ci) }}{% when None %}void{% endmatch %}>( + [&]() { + return {{ func.ffi_func().name() }}( + {%- if !prefix.to_string().is_empty() -%} + {{ prefix }}{% if !func.arguments().is_empty() %}, {% endif %} + {%- endif -%} + {%- call arg_list_lowered(func) -%} + ); + }, + {{ func.ffi_rust_future_poll(ci) }}, + {{ func.ffi_rust_future_cancel(ci) }}, + {{ func.ffi_rust_future_complete(ci) }}, + {{ func.ffi_rust_future_free(ci) }}, +{%- match func.return_type() %} +{% when Some with (value_type) %} + [](auto value) { return uniffi::{{ value_type|lift_fn }}(value); }, +{% when None %} + nullptr, +{%- endmatch %} +{%- match func.throws_type() %} +{% when Some with (e) %} + uniffi::{{ e|ffi_error_converter_name }}::lift +{%- else %} + nullptr +{%- endmatch %} + ) +{%- endmacro %} + +{% macro rust_call_async_with_value(func, self_type, receiver) -%} + {%- let converter = self_type|lower_fn -%} + {%- let prefix = "uniffi::" ~ converter ~ "(" ~ receiver ~ ")" -%} + {%- call rust_call_async(func, prefix) -%} +{%- endmacro %} + +{% macro callable_return_type(method) -%} + {%- if method.is_async() %}::uniffi::Future<{% endif -%} + {%- match method.return_type() -%} + {%- when Some with (return_type) -%}{{ return_type|type_name(ci) }} + {%- when None -%}void + {%- endmatch -%} + {%- if method.is_async() %}>{% endif -%} +{%- endmacro %} + {% macro param_list(func) %} {%- for arg in func.arguments() -%} {{ arg|parameter(ci) }} diff --git a/bindgen/src/bindings/cpp/templates/obj.cpp b/bindgen/src/bindings/cpp/templates/obj.cpp index a818598..98658a1 100644 --- a/bindgen/src/bindings/cpp/templates/obj.cpp +++ b/bindgen/src/bindings/cpp/templates/obj.cpp @@ -30,37 +30,44 @@ namespace uniffi { {% match obj.primary_constructor() -%} {%- when Some with (ctor) %} -{%- if !ctor.is_async() %} -{{ type_name }} {{ impl_class_name }}::init({% call macros::param_list(ctor) %}) { +{% if ctor.is_async() %}uniffi::Future<{% endif %}{{ type_name }}{% if ctor.is_async() %}>{% endif %} {{ impl_class_name }}::init({% call macros::param_list(ctor) %}) { + {%- if ctor.is_async() %} + return {% call macros::rust_call_async(ctor, "") %}; + {%- else %} return {{ type_name }}( new {{ impl_class_name }}({%- call macros::rust_call(ctor) -%}) ); + {%- endif %} } -{%- endif %} {% else -%} {% endmatch -%} {% for ctor in obj.alternate_constructors() %} -{%- if !ctor.is_async() %} -{{ type_name }} {{ impl_class_name }}::{{ ctor.name() }}({% call macros::param_list(ctor) %}) { +{% if ctor.is_async() %}uniffi::Future<{% endif %}{{ type_name }}{% if ctor.is_async() %}>{% endif %} {{ impl_class_name }}::{{ ctor.name() }}({% call macros::param_list(ctor) %}) { + {%- if ctor.is_async() %} + return {% call macros::rust_call_async(ctor, "") %}; + {%- else %} return {{ type_name }}(new {{ impl_class_name }}({% call macros::rust_call(ctor) %})); + {%- endif %} } -{%- endif %} {% endfor %} {%- for method in obj.methods() %} -{%- if !method.is_async() %} -{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch -%} -{{ impl_class_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) { - auto ptr = this->_uniffi_internal_clone_pointer(); +{%- let clone_receiver = "this->_uniffi_internal_clone_pointer()" %} +{% call macros::callable_return_type(method) %} {{ impl_class_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) { + {# The async start callback clones the receiver only after the executor admission check. #} + {%- if method.is_async() %} + return {% call macros::rust_call_async(method, clone_receiver) %}; + {%- else %} + auto ptr = {{ clone_receiver }}; {%- match method.return_type() %} - {% when Some with (return_type) %} + {%- when Some with (return_type) %} return uniffi::{{ return_type|lift_fn }}({% call macros::rust_call_with_prefix("ptr", method) %}); - {%- else %} + {%- when None %} {% call macros::rust_call_with_prefix("ptr", method) -%}; {%- endmatch %} + {%- endif %} } -{%- endif %} {%- endfor %} {{ impl_class_name }}::~{{ impl_class_name }}() { diff --git a/bindgen/src/bindings/cpp/templates/obj.hpp b/bindgen/src/bindings/cpp/templates/obj.hpp index c0398ac..7647861 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 %} + {% call macros::callable_return_type(method) %} {{ method.name()|fn_name }}({% call macros::param_list(method) %}); {%- endfor %} {%- for method in obj.uniffi_traits() %} diff --git a/bindgen/src/bindings/cpp/templates/scaffolding.hpp b/bindgen/src/bindings/cpp/templates/scaffolding.hpp index 216436d..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/value_methods.cpp b/bindgen/src/bindings/cpp/templates/value_methods.cpp index 5ef16e7..b3d2932 100644 --- a/bindgen/src/bindings/cpp/templates/value_methods.cpp +++ b/bindgen/src/bindings/cpp/templates/value_methods.cpp @@ -1,15 +1,16 @@ {%- for method in methods %} -{%- if !method.is_async() %} -{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch -%} -{{ type_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) const { +{% call macros::callable_return_type(method) %} {{ type_name }}::{{ method.name()|fn_name }}({% call macros::param_list(method) %}) const { + {%- if method.is_async() %} + return {% call macros::rust_call_async_with_value(method, typ, "*this") %}; + {%- else %} {%- match method.return_type() %} {%- when Some with (return_type) %} return uniffi::{{ return_type|lift_fn }}({% call macros::rust_call_with_self(method, typ) %}); {%- when None %} {% call macros::rust_call_with_self(method, typ) %}; {%- endmatch %} + {%- endif %} } -{%- endif %} {%- endfor %} {%- if let Some(method) = uniffi_trait_methods.display_fmt %} diff --git a/bindgen/src/bindings/cpp/templates/value_methods.hpp b/bindgen/src/bindings/cpp/templates/value_methods.hpp index 038a826..48af505 100644 --- a/bindgen/src/bindings/cpp/templates/value_methods.hpp +++ b/bindgen/src/bindings/cpp/templates/value_methods.hpp @@ -1,9 +1,6 @@ {%- for method in methods %} -{%- if !method.is_async() %} {%- call macros::docstring(method, 4) %} -{% match method.return_type() %}{% when Some with (return_type) %}{{ return_type|type_name(ci) }} {% else %}void {% endmatch -%} -{{ method.name()|fn_name }}({% call macros::param_list(method) %}) const; -{%- endif %} +{% call macros::callable_return_type(method) %} {{ method.name()|fn_name }}({% call macros::param_list(method) %}) const; {%- endfor %} {%- if uniffi_trait_methods.display_fmt.is_some() %} diff --git a/bindgen/src/bindings/cpp/templates/wrapper.cpp b/bindgen/src/bindings/cpp/templates/wrapper.cpp index 2473e82..d3edc77 100644 --- a/bindgen/src/bindings/cpp/templates/wrapper.cpp +++ b/bindgen/src/bindings/cpp/templates/wrapper.cpp @@ -55,6 +55,11 @@ void check_rust_call(const RustCallStatus &status, F error_cb) { } throw std::runtime_error("A Rust panic has occurred"); + + {%- if ci.has_async_fns() %} + case 3: + throw ::uniffi::AsyncCancelledError(); + {%- endif %} } throw std::runtime_error("Unexpected Rust call status"); @@ -77,6 +82,10 @@ R rust_call(F f, EF error_cb, Args... args) { } } +{%- if ci.has_async_fns() %} +{% include "async.cpp" %} +{%- endif %} + template void rust_call_trait_interface(RustCallStatus* status, F make_call, W write_value) { initialize(); @@ -127,8 +136,6 @@ void rust_call_trait_interface_with_error(RustCallStatus* status, F make_call, W {{ type_helper_code }} {%- for func in ci.function_definitions() %} -{%- if !func.is_async() %} {% include "fn_def.cpp" %} -{%- endif %} {% endfor -%} } // namespace {{ namespace }} diff --git a/bindgen/src/bindings/cpp/templates/wrapper.hpp b/bindgen/src/bindings/cpp/templates/wrapper.hpp index 97842e7..b6aafef 100644 --- a/bindgen/src/bindings/cpp/templates/wrapper.hpp +++ b/bindgen/src/bindings/cpp/templates/wrapper.hpp @@ -12,10 +12,20 @@ #include #include #include +#include #include +#include #include #include +{%- if ci.has_async_fns() %} +#include +#include +#include +#include +#include +{%- endif %} + {%- for include in self.includes() %} #include <{{ include }}> {%- endfor %} @@ -35,6 +45,17 @@ namespace uniffi { } #endif +{%- if ci.has_async_fns() %} +#ifndef UNIFFI_CPP_ASYNC_FUTURE_V1 +#define UNIFFI_CPP_ASYNC_FUTURE_V1 +namespace uniffi { +inline namespace cpp_async_v1 { +{% include "async.hpp" %} +} +} +#endif +{%- endif %} + {%- import "macros.cpp" as macros %} {% call macros::docstring_value(ci.namespace_docstring(), 0) %} namespace {{ namespace }} { @@ -99,6 +120,9 @@ typedef {{ type_name }} {{ name }}; namespace uniffi { using ::uniffi::RustStream; using ::uniffi::RustStreamBuffer; +{%- if ci.has_async_fns() %} +using ::uniffi::Future; +{%- endif %} {%- for converter in self.external_ffi_converters() %} using {{ converter }}; {%- endfor %} @@ -169,14 +193,7 @@ void rustbuffer_free(RustBuffer); } // namespace uniffi {%~ for func in ci.function_definitions() %} -{%- if !func.is_async() %} {%- call macros::docstring(func, 0) %} -{%- match func.return_type() %} -{%- when Some with (return_type) %} -{{ return_type|type_name(ci) }} {{ func.name()|fn_name }}({% call macros::param_list(func) %}); -{%- when None %} -void {{ func.name()|fn_name }}({% call macros::param_list(func) %}); -{%- endmatch %} -{%- endif %} +{% call macros::callable_return_type(func) %} {{ func.name()|fn_name }}({% call macros::param_list(func) %}); {%- endfor %} } // namespace {{ namespace }} diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index db217af..154521b 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) @@ -65,9 +65,14 @@ if(VALGRIND) set_tests_properties(async_exit_from_continuation-test-test-memcheck PROPERTIES TIMEOUT 30) endif() -# 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}) @@ -79,8 +84,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) @@ -102,6 +105,9 @@ test_case(empty_type) test_case(error_types_builtin) test_case(reserved_field_name) test_case(type_flattening) +list(APPEND BINDING_FILES ${BINDINGS_SRC_DIR}/async_calls.cpp) +test_case(async_executor tests/async_executor/ffi_lifecycle.cpp) +test_case(async_pending_at_exit ${BINDINGS_SRC_DIR}/async_calls.cpp) add_executable(ext_types_import-test tests/ext_types_import/main.cpp @@ -142,3 +148,10 @@ add_custom_target(bindings ALL WORKING_DIRECTORY ${BINDINGS_BUILD_DIR} COMMENT "Generating bindings" ) + +set_tests_properties(async_executor-test PROPERTIES TIMEOUT 45) +set_tests_properties(async_pending_at_exit-test PROPERTIES TIMEOUT 15) +if(VALGRIND) + set_tests_properties(async_executor-test-test-memcheck PROPERTIES TIMEOUT 90) + set_tests_properties(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 new file mode 100644 index 0000000..100f351 --- /dev/null +++ b/cpp-tests/tests/async_executor/ffi_lifecycle.cpp @@ -0,0 +1,360 @@ +#include "test_support.hpp" + +// Include the generated implementation once to exercise its private rust_call_async() driver. +// Scripted Rust FFI functions record the call order so we can verify repolling on WAKE, completion +// on READY, and exactly one free on success, cancellation, Rust errors, or C++ conversion failures. +// The stream tests in main.cpp exercise the same binding through its public API. +#include "async_calls.cpp" + +namespace executor_tests { +namespace { + +// https://mozilla.github.io/uniffi-rs/latest/internals/async-ffi.html#managing-the-rustfuture-handle +constexpr std::int8_t ready = 0; +constexpr std::int8_t wake = 1; +constexpr std::int8_t unexpected_error = 2; +constexpr std::int8_t cancelled = 3; + +enum class Step { Start, Poll, Cancel, Complete, Free }; +enum class PollReply { Park, WakeInline, Ready, Invalid }; +enum class Completion { Value, ErrorStatus, LiftError }; + +struct PollCallback { + RustFutureContinuationCallback callback; + std::uint64_t data; + + void notify(std::int8_t result) const { callback(data, result); } +}; + +class PausedTask { + public: + void pause() { + paused_.set_value(); + wait_for_future(resume_signal_); + } + + void wait_until_paused() { wait_for_future(paused_signal_); } + void resume() { resumed_.set_value(); } + + private: + std::promise paused_; + std::future paused_signal_ = paused_.get_future(); + std::promise resumed_; + std::future resume_signal_ = resumed_.get_future(); +}; + +class RustFutureProbe { + public: + explicit RustFutureProbe(std::vector replies, PausedTask *pause = nullptr) + : replies_(std::move(replies)), pause_(pause) {} + + RustFutureProbe(std::initializer_list replies) + : RustFutureProbe(std::vector(replies)) {} + + uniffi::Future start(Completion completion = Completion::Value) { + return start_with_lift([](int value) { return value + 1; }, completion); + } + + template + uniffi::Future> + start_with_lift(Lift lift, Completion completion = Completion::Value) { + return async_calls::uniffi::rust_call_async>( + [this] { + caller_ = std::this_thread::get_id(); + record(Step::Start); + return reinterpret_cast(this); + }, + [](std::uint64_t handle, RustFutureContinuationCallback callback, std::uint64_t data) { + from_handle(handle).poll(handle, {callback, data}); + }, + [](std::uint64_t handle) { + from_handle(handle).cancel(handle); + }, + [this, completion](auto handle, auto *status) { + record_ffi(handle, Step::Complete, replies_.front() == PollReply::Ready); + ASSERT_NE(status, nullptr); + if (was_cancelled_) { + status->code = cancelled; + } else if (completion == Completion::ErrorStatus) { + status->code = unexpected_error; + status->error_buf = async_calls::uniffi::FfiConverterString::lower("Rust completion failed"); + } + return 41; + }, + [](std::uint64_t handle) { + auto &probe = from_handle(handle); + probe.record_ffi(handle, Step::Free, probe.replies_.front() == PollReply::Ready); + probe.handle_freed = true; + }, + [this, completion, lift = std::move(lift)](int value) mutable { + ASSERT_FALSE(was_cancelled_); + ASSERT_NE(completion, Completion::ErrorStatus); + if (completion == Completion::LiftError) { + throw std::runtime_error("C++ lifting failed"); + } + return lift(value); + }, + nullptr); + } + + PollCallback wait_for_pending_poll() { return wait_for_future(parked_.get_future()); } + + void wake_from_caller(PollCallback callback) { + ASSERT_FALSE(uniffi::detail::async_executor().is_worker()); + wake_sent_ = true; + callback.notify(wake); + } + + void expect_steps(std::initializer_list expected) { + const std::lock_guard lock(mutex_); + ASSERT_EQ(steps_, std::vector(expected)); + } + + std::atomic handle_freed{false}; + + private: + static RustFutureProbe &from_handle(std::uint64_t handle) { + return *reinterpret_cast(handle); + } + + void cancel(std::uint64_t handle) { + record_ffi(handle, Step::Cancel, false); + was_cancelled_ = true; + if (parked_callback_) { + const auto callback = *parked_callback_; + parked_callback_.reset(); + callback.notify(ready); + } + } + + void record(Step step) { + const std::lock_guard lock(mutex_); + steps_.push_back(step); + } + + void record_ffi(std::uint64_t handle, Step step, bool on_caller) { + ASSERT_EQ(handle, reinterpret_cast(this)); + if (on_caller) { + ASSERT_EQ(std::this_thread::get_id(), caller_); + } else { + ASSERT_TRUE(uniffi::detail::async_executor().is_worker()); + } + // Even an inline Rust notification must return before the next FFI operation. + ASSERT_FALSE(in_poll_); + record(step); + } + + void poll(std::uint64_t handle, PollCallback callback) { + record_ffi(handle, Step::Poll, next_reply_ == 0); + ASSERT_NE(callback.callback, nullptr); + ASSERT_NE(callback.data, 0u); + ASSERT_TRUE(next_reply_ < replies_.size()); + if (parked_callback_) { + ASSERT_TRUE(wake_sent_.load()); + parked_callback_.reset(); + } + + in_poll_ = true; + if (next_reply_ == 0) { + EXPECT_EXCEPTION(uniffi::shutdown_async_executor(), std::logic_error); + } + switch (replies_[next_reply_++]) { + case PollReply::Park: + parked_callback_ = callback; + parked_.set_value(callback); + break; + case PollReply::WakeInline: + callback.notify(wake); + break; + case PollReply::Ready: + callback.notify(ready); + break; + case PollReply::Invalid: + callback.notify(-1); + break; + } + if (next_reply_ == 1 && pause_) { + pause_->pause(); + } + in_poll_ = false; + } + + const std::vector replies_; + PausedTask *const pause_; + std::thread::id caller_; + std::size_t next_reply_ = 0; + std::mutex mutex_; + std::vector steps_; + std::optional parked_callback_; + std::promise parked_; + std::atomic wake_sent_{false}; + bool in_poll_ = false; + bool was_cancelled_ = false; +}; + +// A ready first poll completes on the caller even while the worker is paused. +void test_first_poll_runs_on_caller() { + PausedTask worker; + ASSERT_TRUE(uniffi::detail::async_executor().enqueue([&] { worker.pause(); })); + worker.wait_until_paused(); + + RustFutureProbe immediate{PollReply::Ready}; + auto ready_result = immediate.start(); + ASSERT_EQ(wait_for_future(ready_result, std::chrono::seconds(0)), 42); + immediate.expect_steps({Step::Start, Step::Poll, Step::Complete, Step::Free}); + + RustFutureProbe deferred{PollReply::WakeInline, PollReply::Ready}; + auto pending_result = deferred.start(); + ASSERT_EQ(pending_result.wait_for(std::chrono::seconds(0)), std::future_status::timeout); + deferred.expect_steps({Step::Start, Step::Poll}); + + worker.resume(); + ASSERT_EQ(wait_for_future(pending_result), 42); + deferred.expect_steps({Step::Start, Step::Poll, Step::Poll, Step::Complete, Step::Free}); +} + +void test_pending_to_ready() { + RustFutureProbe probe{PollReply::Park, PollReply::WakeInline, PollReply::Ready}; + auto future = probe.start(); + const auto callback = probe.wait_for_pending_poll(); + probe.expect_steps({Step::Start, Step::Poll}); + ASSERT_EQ(future.wait_for(std::chrono::seconds(0)), std::future_status::timeout); + + probe.wake_from_caller(callback); + ASSERT_EQ(wait_for_future(future), 42); + probe.expect_steps({Step::Start, Step::Poll, Step::Poll, Step::Poll, Step::Complete, Step::Free}); +} + +// A future that wakes itself repeatedly yields the worker to other queued tasks. +void test_rapid_wakes_yield() { + auto &executor = uniffi::detail::async_executor(); + PausedTask worker; + ASSERT_TRUE(executor.enqueue([&] { worker.pause(); })); + worker.wait_until_paused(); + + std::vector replies(128, PollReply::WakeInline); + replies.push_back(PollReply::Ready); + RustFutureProbe probe(std::move(replies)); + auto future = probe.start(); + + std::promise yielded; + auto reached = yielded.get_future(); + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_FALSE(probe.handle_freed.load()); + yielded.set_value(); + })); + worker.resume(); + wait_for_future(reached); + ASSERT_EQ(wait_for_future(future), 42); +} + +// A bad poll code becomes a C++ error after the Rust handle is freed. +void test_invalid_poll_code() { + RustFutureProbe probe{PollReply::Invalid, PollReply::Ready}; + try { + wait_for_future(probe.start()); + assert(false && "expected an invalid poll result to throw"); + } catch (const std::runtime_error &error) { + ASSERT_EQ(std::string(error.what()), "Unexpected UniFFI Rust future poll result"); + } + probe.expect_steps({Step::Start, Step::Poll, Step::Cancel, Step::Poll, Step::Complete, Step::Free}); +} + +void test_cleanup_on_failure(Completion completion, const char *message) { + RustFutureProbe probe{PollReply::Ready}; + try { + wait_for_future(probe.start(completion)); + assert(false && "expected future completion to throw"); + } catch (const std::runtime_error &error) { + ASSERT_EQ(std::string(error.what()), message); + } + probe.expect_steps({Step::Start, Step::Poll, Step::Complete, Step::Free}); +} + +void test_cancellation_lifecycle() { + RustFutureProbe probe{PollReply::Park}; + auto future = probe.start(); + probe.wait_for_pending_poll(); + future.cancel(); + future.cancel(); + EXPECT_EXCEPTION(wait_for_future(future), uniffi::AsyncCancelledError); + probe.expect_steps({Step::Start, Step::Poll, Step::Cancel, Step::Complete, Step::Free}); +} + +class ValueMoveError : public std::exception {}; + +class ValueWithThrowingMove { + public: + explicit ValueWithThrowingMove(const std::atomic &fail) : fail_(fail) {} + ValueWithThrowingMove(ValueWithThrowingMove &&other) : fail_(other.fail_) { + if (fail_.load()) { + throw ValueMoveError(); + } + } + + private: + const std::atomic &fail_; +}; + +void test_result_publication_move_failure() { + RustFutureProbe probe{PollReply::Ready}; + auto result = probe.start_with_lift([&](int) { return ValueWithThrowingMove(probe.handle_freed); }); + EXPECT_EXCEPTION(wait_for_future(result), ValueMoveError); + probe.expect_steps({Step::Start, Step::Poll, Step::Complete, Step::Free}); +} + +void test_continuation_move_failure() { + std::atomic fail_move{false}; + RustFutureProbe probe{PollReply::Ready}; + auto result = probe.start_with_lift([&](int) { return ValueWithThrowingMove(fail_move); }); + ASSERT_EQ(result.wait_for(test_timeout), std::future_status::ready); + fail_move = true; + + auto delivered = std::make_shared>(); + auto delivery = delivered->get_future(); + auto continuation = std::move(result).then([delivered](auto completed) { + ASSERT_TRUE(uniffi::detail::async_executor().is_worker()); + EXPECT_EXCEPTION(std::move(completed).get(), ValueMoveError); + delivered->set_value(); + }); + wait_for_future(delivery); + probe.expect_steps({Step::Start, Step::Poll, Step::Complete, Step::Free}); +} + +} // 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(); +} + +// Close admission after the start check while the caller still owns the new Rust handle. +void test_shutdown_during_handle_creation() { + unsigned frees = 0; + const auto unexpected_ffi_call = [](auto...) { + assert(false && "the rejected Rust future entered the driver"); + }; + auto result = async_calls::uniffi::rust_call_async( + [&] { + uniffi::shutdown_async_executor(); + return reinterpret_cast(&frees); + }, + unexpected_ffi_call, unexpected_ffi_call, + [unexpected_ffi_call](auto... args) { + unexpected_ffi_call(args...); + return 0; + }, + [](std::uint64_t handle) { ++*reinterpret_cast(handle); }, + [](int value) { return value; }, nullptr); + EXPECT_EXCEPTION(wait_for_future(result), uniffi::AsyncExecutorError); + ASSERT_EQ(frees, 1u); +} + +} // 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..2f9cecc --- /dev/null +++ b/cpp-tests/tests/async_executor/main.cpp @@ -0,0 +1,233 @@ +#include "test_support.hpp" + +#include + +namespace executor_tests { +namespace { + +using namespace std::chrono_literals; +using uniffi::detail::AsyncExecutor; +using uniffi::detail::async_executor; + +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); +} + +// Two Rust streams receive independently, with bounded buffering and clean end-of-stream. +void test_interleaved_stream_reads() { + const auto first = wait_for_future(async_calls::SampleStream::open()); + const auto second = async_calls::SampleStream::init(); + auto first_read = first->next(); + auto second_read = second->next(); + wait_for_queued_work(async_executor()); + ASSERT_TRUE(first->is_read_pending()); + ASSERT_TRUE(second->is_read_pending()); + + // Push from the caller thread while both readers are parked on the executor. + ASSERT_TRUE(second->push(20)); + ASSERT_EQ(wait_for_future(second_read), std::optional(20)); + ASSERT_EQ(first_read.wait_for(0ms), std::future_status::timeout); + + auto delivered = std::make_shared>>(); + auto result = delivered->get_future(); + auto continuation = std::move(first_read).then([delivered](auto completed) { + ASSERT_TRUE(async_executor().is_worker()); + delivered->set_value(std::move(completed).get()); + }); + ASSERT_TRUE(first->push(10)); + ASSERT_EQ(wait_for_future(result), std::optional(10)); + + auto end_of_stream = first->next(); + auto surviving_read = second->next(); + wait_for_queued_work(async_executor()); + ASSERT_TRUE(first->is_read_pending()); + ASSERT_TRUE(second->is_read_pending()); + first->close_stream(); + first->close_stream(); + ASSERT_EQ(wait_for_future(end_of_stream), std::nullopt); + ASSERT_EQ(wait_for_future(first->next()), std::nullopt); + ASSERT_FALSE(first->push(11)); + ASSERT_EQ(surviving_read.wait_for(0ms), std::future_status::timeout); + + ASSERT_TRUE(second->push(21)); + ASSERT_EQ(wait_for_future(surviving_read), std::optional(21)); + ASSERT_TRUE(second->push(22)); + ASSERT_TRUE(second->push(23)); + ASSERT_FALSE(second->push(24)); + ASSERT_EQ(wait_for_future(second->next()), std::optional(22)); + ASSERT_EQ(wait_for_future(second->next()), std::optional(23)); +} + +// Cancelling a pending read releases the receiver for the next read. +void test_cancel_pending_read() { + const auto stream = async_calls::SampleStream::init(); + auto read = stream->next(); + wait_for_queued_work(async_executor()); + ASSERT_TRUE(stream->is_read_pending()); + read.cancel(); + EXPECT_EXCEPTION(wait_for_future(read), uniffi::AsyncCancelledError); + ASSERT_FALSE(stream->is_read_pending()); + + // Cancelling an individual read releases its lock and leaves the stream usable. + ASSERT_TRUE(stream->push(42)); + ASSERT_EQ(wait_for_future(stream->next()), std::optional(42)); +} + +// Generated record and enum wrappers lift a value and a declared error. +void test_value_receivers() { + auto record_value = async_calls::MyRecord{"value", 17}.value_after(1); + ASSERT_EQ(17, wait_for_future(record_value)); + + wait_for_future(async_calls::validate(async_calls::ValidationMode::kAllow)); + EXPECT_EXCEPTION(wait_for_future(async_calls::validate(async_calls::ValidationMode::kReject)), + async_calls::my_error::Foo); +} + +// A separate cancellation handle releases a thread waiting in get(). +void test_cancel_blocking_get() { + auto pending = async_calls::pending(); + const auto cancel = pending.cancel_handle(); + auto entering = std::make_shared>(); + auto entering_get = entering->get_future(); + auto waiter = std::async(std::launch::async, [pending = std::move(pending), entering]() mutable { + entering->set_value(); + EXPECT_EXCEPTION(pending.get(), uniffi::AsyncCancelledError); + }); + + wait_for_future(entering_get); + ASSERT_EQ(waiter.wait_for(20ms), std::future_status::timeout); + const auto copy = cancel; + copy.cancel(); + wait_for_future(waiter); + cancel.cancel(); +} + +// Handles survive completion, destruction of a future, and transfer into then(). +void test_cancel_handle_lifetime() { + uniffi::FutureCancelHandle finished; + { + auto ready = async_calls::SampleStream::open(); + finished = ready.cancel_handle(); + ASSERT_NE(wait_for_future(ready), nullptr); + finished.cancel(); + } + finished.cancel(); + + auto pending = async_calls::pending(); + const auto cancel = pending.cancel_handle(); + auto delivered = std::make_shared>(); + auto result = delivered->get_future(); + auto continuation = std::move(pending).then([delivered](auto completed) { + EXPECT_EXCEPTION(completed.get(), uniffi::AsyncCancelledError); + delivered->set_value(); + }); + wait_for_queued_work(async_executor()); + cancel.cancel(); + wait_for_future(result); +} + +// A detached continuation delivers a stream read after its token is destroyed. +void test_detached_continuation() { + auto stream = async_calls::SampleStream::init(); + auto delivered = std::make_shared>(); + auto result = delivered->get_future(); + stream->next().then([delivered](auto completed) { + delivered->set_value(std::move(completed).get().value()); + }).detach(); + ASSERT_TRUE(stream->push(42)); + ASSERT_EQ(wait_for_future(result), 42u); +} + +// Move assignment cancels the previous owner and transfers the new result or continuation. +void test_future_move_assignment() { + uniffi::Future future; + ASSERT_FALSE(future.valid()); + EXPECT_EXCEPTION(future.get(), std::future_error); + + future = async_calls::pending(); + ASSERT_EQ(async_calls::pending_count(), 1u); + future = async_calls::validate(async_calls::ValidationMode::kAllow); + 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 = async_calls::validate(async_calls::ValidationMode::kAllow).then([completed](auto result) { + std::move(result).get(); + completed->set_value(); + }); + wait_for_future(cancellation); + wait_for_future(completion); + ASSERT_EQ(async_calls::pending_count(), 0u); +} + +// Generated pending futures support wait, explicit cancellation, and abandonment. +void test_pending_future() { + { + auto pending = async_calls::pending(); + ASSERT_EQ(pending.wait_for(1ms), std::future_status::timeout); + ASSERT_EQ(async_calls::pending_count(), 1u); + pending.cancel(); + EXPECT_EXCEPTION(wait_for_future(pending), uniffi::AsyncCancelledError); + ASSERT_EQ(async_calls::pending_count(), 0u); + } + { + auto pending = async_calls::pending(); + ASSERT_EQ(async_calls::pending_count(), 1u); + } + wait_for_queued_work(async_executor()); + ASSERT_EQ(async_calls::pending_count(), 0u); +} + +// Shutdown delivers cancellation, rejects new reads, and allows the Rust receiver to drop. +void test_singleton_shutdown() { + ASSERT_EQ(async_calls::sample_stream_count(), 0u); + auto stream = async_calls::SampleStream::init(); + auto delivered = std::make_shared>(); + auto result = delivered->get_future(); + auto continuation = stream->next().then([delivered](auto completed) { + ASSERT_TRUE(async_executor().is_worker()); + EXPECT_EXCEPTION(std::move(completed).get(), uniffi::AsyncCancelledError); + delivered->set_value(); + }); + wait_for_queued_work(async_executor()); + ASSERT_TRUE(stream->is_read_pending()); + + test_shutdown_during_handle_creation(); + wait_for_future(result, 0ms); + ASSERT_FALSE(stream->is_read_pending()); + ASSERT_FALSE(async_executor().accepting()); + ASSERT_FALSE(async_executor().enqueue([] {})); + EXPECT_EXCEPTION(wait_for_future(stream->next()), uniffi::AsyncExecutorError); + stream.reset(); + ASSERT_EQ(async_calls::sample_stream_count(), 0u); + uniffi::shutdown_async_executor(); + uniffi::start_async_executor(); + ASSERT_NE(wait_for_future(async_calls::SampleStream::open()), nullptr); + uniffi::shutdown_async_executor(); +} + +} // namespace +} // namespace executor_tests + +int main() { + using namespace executor_tests; + test_rust_future_lifecycle(); + test_pending_future(); + test_interleaved_stream_reads(); + test_cancel_pending_read(); + test_value_receivers(); + test_cancel_blocking_get(); + test_cancel_handle_lifetime(); + test_detached_continuation(); + test_future_move_assignment(); + test_singleton_shutdown(); +} 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..24d781a --- /dev/null +++ b/cpp-tests/tests/async_executor/test_support.hpp @@ -0,0 +1,11 @@ +#pragma once + +#include "async_calls.hpp" +#include "async_test_support.hpp" + +namespace executor_tests { + +void test_rust_future_lifecycle(); +void test_shutdown_during_handle_creation(); + +} // namespace executor_tests diff --git a/cpp-tests/tests/async_pending_at_exit/main.cpp b/cpp-tests/tests/async_pending_at_exit/main.cpp new file mode 100644 index 0000000..2a956cb --- /dev/null +++ b/cpp-tests/tests/async_pending_at_exit/main.cpp @@ -0,0 +1,27 @@ +#include + +#include +#include +#include + +namespace { + +// Keep both owners reachable at exit without invoking their cancellation destructors. +uniffi::Future *volatile pending_future; +uniffi::FutureContinuation *volatile pending_continuation; + +} // namespace + +int main() { + pending_future = new uniffi::Future(async_calls::pending()); + pending_continuation = new uniffi::FutureContinuation( + async_calls::pending().then([](auto) { std::abort(); })); + + auto barrier = std::make_shared>(); + auto polled = barrier->get_future(); + if (!uniffi::detail::async_executor().enqueue([barrier] { barrier->set_value(); })) { + return EXIT_FAILURE; + } + polled.get(); + return async_calls::pending_count() == 2 ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/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..b25027b --- /dev/null +++ b/fixtures/async-calls/Cargo.toml @@ -0,0 +1,16 @@ +[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] +futures-timer = "3.0" +thiserror = "1.0" +tokio = { version = "1.24.1", features = ["rt", "sync"] } +uniffi = { workspace = true, features = ["tokio"] } diff --git a/fixtures/async-calls/README.md b/fixtures/async-calls/README.md new file mode 100644 index 0000000..582a990 --- /dev/null +++ b/fixtures/async-calls/README.md @@ -0,0 +1,4 @@ +# Async calls fixture + +The fixture exercises generated C++ bindings with parked futures, Tokio stream reads, +async constructors, record methods, and typed errors from enum methods. diff --git a/fixtures/async-calls/src/lib.rs b/fixtures/async-calls/src/lib.rs new file mode 100644 index 0000000..2797648 --- /dev/null +++ b/fixtures/async-calls/src/lib.rs @@ -0,0 +1,132 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. + */ + +use futures_timer::Delay; +use std::{ + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, Mutex, + }, + time::Duration, +}; +use tokio::sync::{mpsc, Mutex as AsyncMutex}; + +static PENDING_COUNT: AtomicU64 = AtomicU64::new(0); +static SAMPLE_STREAM_COUNT: AtomicU64 = AtomicU64::new(0); + +struct PendingGuard; + +impl Drop for PendingGuard { + fn drop(&mut self) { + PENDING_COUNT.fetch_sub(1, Ordering::SeqCst); + } +} + +#[uniffi::export] +pub async fn pending() { + PENDING_COUNT.fetch_add(1, Ordering::SeqCst); + let _guard = PendingGuard; + std::future::pending::<()>().await; +} + +#[uniffi::export] +pub fn pending_count() -> u64 { + PENDING_COUNT.load(Ordering::SeqCst) +} + +#[derive(uniffi::Object)] +pub struct SampleStream { + sender: Mutex>>, + receiver: AsyncMutex>, +} + +impl Drop for SampleStream { + fn drop(&mut self) { + SAMPLE_STREAM_COUNT.fetch_sub(1, Ordering::SeqCst); + } +} + +#[uniffi::export] +pub fn sample_stream_count() -> u64 { + SAMPLE_STREAM_COUNT.load(Ordering::SeqCst) +} + +#[uniffi::export(async_runtime = "tokio")] +impl SampleStream { + #[uniffi::constructor] + pub fn new() -> Arc { + let (sender, receiver) = mpsc::channel(2); + SAMPLE_STREAM_COUNT.fetch_add(1, Ordering::SeqCst); + Arc::new(Self { + sender: Mutex::new(Some(sender)), + receiver: AsyncMutex::new(receiver), + }) + } + + #[uniffi::constructor] + pub async fn open() -> Arc { + Self::new() + } + + pub fn push(&self, sample: u32) -> bool { + self.sender + .lock() + .unwrap() + .as_ref() + .is_some_and(|sender| sender.try_send(sample).is_ok()) + } + + pub async fn next(&self) -> Option { + self.receiver.lock().await.recv().await + } + + pub fn close_stream(&self) { + drop(self.sender.lock().unwrap().take()); + } + + // A pending read holds the receiver lock until it receives a sample, closes, or is dropped. + pub fn is_read_pending(&self) -> bool { + self.receiver.try_lock().is_err() + } +} + +#[derive(thiserror::Error, uniffi::Error, Debug)] +pub enum MyError { + #[error("Foo")] + Foo, +} + +#[derive(uniffi::Record)] +pub struct MyRecord { + pub a: String, + pub b: u32, +} + +#[uniffi::export] +impl MyRecord { + pub async fn value_after(&self, ms: u16) -> u32 { + Delay::new(Duration::from_millis(ms.into())).await; + self.b + } +} + +#[derive(uniffi::Enum)] +pub enum ValidationMode { + Allow, + Reject, +} + +#[uniffi::export] +impl ValidationMode { + pub async fn validate(&self) -> Result<(), MyError> { + match self { + Self::Allow => Ok(()), + Self::Reject => Err(MyError::Foo), + } + } +} + +uniffi::setup_scaffolding!("async_calls"); 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!();