From 7c84710d21c9680625ca26a3c68b58a71693bf9a Mon Sep 17 00:00:00 2001 From: Alan George Date: Mon, 23 Nov 2026 15:57:57 -0700 Subject: [PATCH 1/2] Add the shared C++ async executor --- bindgen/src/bindings/cpp/templates/async.hpp | 215 +++++++++++++++++++ cpp-tests/CMakeLists.txt | 21 +- cpp-tests/include/async_runtime_test.hpp | 23 ++ cpp-tests/include/async_test_support.hpp | 38 ++++ cpp-tests/tests/async_executor_unit/main.cpp | 184 ++++++++++++++++ cpp-tests/tests/async_executor_unit/peer.cpp | 9 + 6 files changed, 488 insertions(+), 2 deletions(-) create mode 100644 bindgen/src/bindings/cpp/templates/async.hpp create mode 100644 cpp-tests/include/async_runtime_test.hpp create mode 100644 cpp-tests/include/async_test_support.hpp create mode 100644 cpp-tests/tests/async_executor_unit/main.cpp create mode 100644 cpp-tests/tests/async_executor_unit/peer.cpp diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp new file mode 100644 index 0000000..2052702 --- /dev/null +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -0,0 +1,215 @@ +// Used for queued tasks and registered cancellation actions. +using AsyncTask = std::function; + +namespace detail { + +// Generated components in a linked C++ image share one worker and its FIFO queue. +// Keep worker tasks short. Shutdown also tracks first polls that run on calling threads. +class AsyncExecutor { + public: + AsyncExecutor() : worker_([this] { run(); }) {} + AsyncExecutor(const AsyncExecutor &) = delete; + AsyncExecutor &operator=(const AsyncExecutor &) = delete; + + // Destroy a directly owned executor on an application thread so it can join its worker. + ~AsyncExecutor() { shutdown(); } + + // Queue a task, including cleanup after admission closes. Returns false once stopped. + bool enqueue(AsyncTask task) { + { + std::lock_guard guard(mutex_); + if (stopped_) { + return false; + } + tasks_.push_back(std::move(task)); + } + ready_.notify_one(); + return true; + } + + // Register a cancel action and return its ID, or zero if admission is closed. + // When the poll_on_caller output is true, finish that first poll through run_inline(). + uint64_t track(AsyncTask cancel, bool *poll_on_caller = nullptr) { + std::lock_guard guard(mutex_); + if (!accepting_.load(std::memory_order_relaxed)) { + return 0; + } + const auto id = ++next_id_; + active_.emplace(id, std::move(cancel)); + if (poll_on_caller) { + *poll_on_caller = !closing_.load(); + if (*poll_on_caller) { + ++inline_polls_; + } + } + return id; + } + + // Remove a registration so a waiting shutdown can recheck whether work has drained. + void untrack(uint64_t id) noexcept { + std::lock_guard guard(mutex_); + active_.erase(id); + if (!accepting()) { + drained_.notify_all(); + } + } + + // Admission stays open while shutdown waits for caller-thread first polls. + bool accepting() const noexcept { return accepting_.load(std::memory_order_acquire); } + + // Identifies the worker for blocking wait and lifecycle checks. + bool is_worker() const noexcept { return current_worker_ == this; } + + // Run the first poll counted by track() and release its count so shutdown can proceed. + template void run_inline(Call call) noexcept { + const auto previous = current_inline_; + current_inline_ = this; + call(); + current_inline_ = previous; + // Sequentially consistent with shutdown(): it sees zero polls, or this sees closing_. + if (--inline_polls_ == 0 && closing_.load()) { + std::lock_guard guard(mutex_); + drained_.notify_all(); + } + } + + // Restart the worker and reopen admission after a completed shutdown. + void start() { + if (is_worker() || current_inline_ == this) { + // Shutdown may be waiting for this call to finish. + return; + } + std::lock_guard shutdown_guard(shutdown_mutex_); + std::lock_guard guard(mutex_); + if (stopped_) { + worker_ = std::thread([this] { run(); }); + stopped_ = false; + accepting_.store(true, std::memory_order_release); + } + } + + // Wait for caller-thread first polls, then close admission, cancel and drain work, and join. + // New calls queue their first poll on the worker during the initial wait. + void shutdown() { + if (is_worker() || current_inline_ == this) { + throw std::logic_error("UniFFI executor cannot shut down from its own callback"); + } + std::lock_guard shutdown_guard(shutdown_mutex_); + std::vector cancellations; + { + std::unique_lock lock(mutex_); + if (stopped_) { + return; + } + // Let caller-thread polls finish while callbacks can still start, so none of them + // consumes a callback result that shutdown rejected. + closing_.store(true); + drained_.wait(lock, [this] { return inline_polls_.load() == 0; }); + closing_.store(false); + accepting_.store(false, std::memory_order_release); + for (const auto &entry : active_) { + cancellations.push_back(entry.second); + } + } + for (auto &cancel : cancellations) { + cancel(); + } + { + std::unique_lock lock(mutex_); + drained_.wait(lock, [this] { return active_.empty() && tasks_.empty() && !running_; }); + stopped_ = true; + } + ready_.notify_all(); + worker_.join(); + } + + private: + void run() noexcept { + current_worker_ = this; + std::unique_lock lock(mutex_); + for (;;) { + ready_.wait(lock, [this] { return !tasks_.empty() || stopped_; }); + if (tasks_.empty()) { + current_worker_ = nullptr; + return; + } + auto task = std::move(tasks_.front()); + tasks_.pop_front(); + running_ = true; + lock.unlock(); + + try { + task(); + } catch (...) { + // User continuations cannot throw across the executor boundary. + } + // Release captured objects before announcing that the executor has drained. + task = {}; + lock.lock(); + running_ = false; + if (!accepting()) { + drained_.notify_all(); + } + } + } + + // Protects the queue, active operations, and worker flags. + mutable std::mutex mutex_; + // Serializes start and shutdown through the worker join. + std::mutex shutdown_mutex_; + // Wakes the worker when a task is queued or shutdown signals it to exit. + std::condition_variable ready_; + // Wakes shutdown to recheck its first-poll and drain conditions. + std::condition_variable drained_; + // Holds tasks in the order the worker will run them. + std::deque tasks_; + // Maps active operation IDs to shutdown cancellation actions in registration order. + std::map active_; + // Supplies increasing operation IDs across restarts. + uint64_t next_id_ = 0; + // Lets callers check admission with an atomic read. + std::atomic accepting_{true}; + // Closes the task queue and tells the worker to exit. + bool stopped_ = false; + // Keeps shutdown waiting while a worker task runs and releases its captures. + bool running_ = false; + // Defers new first polls to the worker while shutdown waits for caller-thread polls. + std::atomic closing_{false}; + // Counts first polls assigned to callers by track() until run_inline() finishes them. + std::atomic inline_polls_{0}; + // Identifies the executor that owns the current worker thread. + inline static thread_local const AsyncExecutor *current_worker_ = nullptr; + // Identifies the executor running an inline first poll for reentrancy checks. + inline static thread_local const AsyncExecutor *current_inline_ = nullptr; + // Runs queued work and is joined by shutdown(). + std::thread worker_; +}; + +// Get the shared executor, creating its worker on first use. +inline AsyncExecutor &async_executor() { + // Explicit shutdown avoids running callbacks or joining during static destruction. + static auto *const executor = new AsyncExecutor(); + return *executor; +} + +inline bool enqueue_async(AsyncTask task) noexcept { + try { + return async_executor().enqueue(std::move(task)); + } catch (...) { + // An accepted operation must retain a deferred cleanup path even under allocation failure. + std::terminate(); + } +} + +inline bool begin_async_call() { return async_executor().accepting(); } + +} // namespace detail + +// Joins the shared worker after waiting for first polls, cancelling calls, and draining cleanup. +// Stop producers first and call from an application thread before unloading the bindings or Rust. +// Calling from the worker or inside a caller-thread first poll throws std::logic_error. +inline void shutdown_async_executor() { detail::async_executor().shutdown(); } + +// Start the shared worker or reopen admission after shutdown. +// Calls from the worker or inside a caller-thread first poll return immediately. +inline void start_async_executor() { detail::async_executor().start(); } diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index 1243070..24fb348 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) +# Keep fixture assertions active in Release builds. 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) @@ -42,6 +43,22 @@ if (VALGRIND) endif() endmacro(memcheck_test) +# Compile the runtime template directly for tests that need no generated bindings. +function(runtime_test TEST_NAME) + add_executable(${TEST_NAME}-test tests/${TEST_NAME}/main.cpp ${ARGN}) + target_include_directories(${TEST_NAME}-test PRIVATE include + ../bindgen/src/bindings/cpp/templates) + target_link_libraries(${TEST_NAME}-test PRIVATE Threads::Threads) + add_test(NAME ${TEST_NAME}-test COMMAND ${TEST_NAME}-test) + set_tests_properties(${TEST_NAME}-test PROPERTIES TIMEOUT 45) + memcheck_test(${TEST_NAME}-test) + if(VALGRIND) + set_tests_properties(${TEST_NAME}-test-test-memcheck PROPERTIES TIMEOUT 90) + endif() +endfunction() + +runtime_test(async_executor_unit tests/async_executor_unit/peer.cpp) + # Add a bindings test case macro(test_case TEST_NAME) add_executable(${TEST_NAME}-test tests/${TEST_NAME}/main.cpp ${BINDINGS_SRC_DIR}/${TEST_NAME}.cpp) diff --git a/cpp-tests/include/async_runtime_test.hpp b/cpp-tests/include/async_runtime_test.hpp new file mode 100644 index 0000000..88aadff --- /dev/null +++ b/cpp-tests/include/async_runtime_test.hpp @@ -0,0 +1,23 @@ +#pragma once + +#include "async_test_support.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Use the same runtime fragment and namespace as a generated binding header. +namespace uniffi { +inline namespace cpp_async_v1 { +#include "async.hpp" +} +} diff --git a/cpp-tests/include/async_test_support.hpp b/cpp-tests/include/async_test_support.hpp new file mode 100644 index 0000000..a5c37ed --- /dev/null +++ b/cpp-tests/include/async_test_support.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include "test_common.hpp" + +#include +#include +#include + +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(); +} + +// Called while an inline poll is gated. Detect that shutdown is deferring new first polls. +template void wait_for_deferred_first_poll(Executor &executor) { + const auto deadline = std::chrono::steady_clock::now() + test_timeout; + for (;;) { + bool poll_on_caller = false; + const auto id = executor.track([] {}, &poll_on_caller); + ASSERT_NE(id, 0u); + if (poll_on_caller) { + executor.run_inline([] {}); + } + executor.untrack(id); + if (!poll_on_caller) { + return; + } + ASSERT_TRUE(std::chrono::steady_clock::now() < deadline); + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } +} + +} // namespace executor_tests diff --git a/cpp-tests/tests/async_executor_unit/main.cpp b/cpp-tests/tests/async_executor_unit/main.cpp new file mode 100644 index 0000000..e66a6d2 --- /dev/null +++ b/cpp-tests/tests/async_executor_unit/main.cpp @@ -0,0 +1,184 @@ +#include "async_runtime_test.hpp" + +using namespace std::chrono_literals; + +namespace executor_tests { + +uniffi::detail::AsyncExecutor &executor_from_peer(); + +namespace { + +using uniffi::detail::AsyncExecutor; +using uniffi::detail::async_executor; + +// A standalone executor runs tasks in FIFO order and continues after a task throws. +void test_executor_queue() { + AsyncExecutor executor; + const auto caller = std::this_thread::get_id(); + std::vector visited; + + ASSERT_TRUE(executor.accepting()); + ASSERT_FALSE(executor.is_worker()); + + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_TRUE(executor.is_worker()); + ASSERT_NE(std::this_thread::get_id(), caller); + visited.push_back(1); + EXPECT_EXCEPTION(executor.shutdown(), std::logic_error); + })); + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_TRUE(executor.is_worker()); + visited.push_back(2); + throw std::runtime_error("test task failure"); + })); + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_TRUE(executor.is_worker()); + visited.push_back(3); + })); + + executor.shutdown(); + ASSERT_EQ(visited, (std::vector{1, 2, 3})); + ASSERT_FALSE(executor.accepting()); + ASSERT_FALSE(executor.enqueue([] {})); + ASSERT_EQ(executor.track([] {}), 0u); + executor.shutdown(); + + // A new thread can reuse the ID of the joined worker. + std::thread caller_after_join([&] { + ASSERT_FALSE(executor.is_worker()); + executor.shutdown(); + }); + caller_after_join.join(); +} + +// Shutdown requests cancellation and waits for queued cleanup of tracked work. +void test_executor_shutdown_drains_active_work() { + AsyncExecutor executor; + auto cancelling = std::make_shared>(); + auto cancellation_started = cancelling->get_future(); + const auto finished = executor.track([] { assert(false && "completed operation was cancelled"); }); + ASSERT_NE(finished, 0u); + executor.untrack(finished); + const auto active = executor.track([&executor, cancelling] { + ASSERT_FALSE(executor.accepting()); + cancelling->set_value(); + }); + ASSERT_NE(active, 0u); + ASSERT_NE(active, finished); + + auto stopping = std::async(std::launch::async, [&] { executor.shutdown(); }); + wait_for_future(cancellation_started); + ASSERT_EQ(executor.track([] {}), 0u); + ASSERT_EQ(stopping.wait_for(0ms), std::future_status::timeout); + + bool cleaned_up = false; + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_TRUE(executor.is_worker()); + executor.untrack(active); + cleaned_up = true; + })); + wait_for_future(stopping); + ASSERT_TRUE(cleaned_up); + ASSERT_FALSE(executor.enqueue([] {})); +} + +// A standalone executor restarts with a worker and continues assigning new operation IDs. +void test_executor_restart() { + AsyncExecutor executor; + executor.start(); + const auto previous = executor.track([] {}); + ASSERT_NE(previous, 0u); + executor.untrack(previous); + executor.shutdown(); + ASSERT_FALSE(executor.enqueue([] {})); + + executor.start(); + executor.start(); + ASSERT_TRUE(executor.accepting()); + const auto active = executor.track([] {}); + ASSERT_TRUE(active > previous); + + bool ran = false; + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_TRUE(executor.is_worker()); + executor.start(); + ran = true; + executor.untrack(active); + })); + executor.shutdown(); + ASSERT_TRUE(ran); + ASSERT_FALSE(executor.enqueue([] {})); +} + +// The shared executor is lazy and its accessor resolves to one worker across translation units. +void test_shared_executor() { + auto &executor = async_executor(); + ASSERT_EQ(&executor, &executor_from_peer()); + + std::promise ran; + auto task = ran.get_future(); + ASSERT_TRUE(executor_from_peer().enqueue([&] { + ASSERT_TRUE(executor.is_worker()); + ran.set_value(); + })); + wait_for_future(task); + uniffi::shutdown_async_executor(); + ASSERT_FALSE(executor.accepting()); + uniffi::start_async_executor(); + ASSERT_TRUE(executor.accepting()); + uniffi::shutdown_async_executor(); +} + +// Closing waits for caller work and keeps the queue available for cleanup and new first polls. +void test_shutdown_waits_for_inline_work() { + AsyncExecutor executor; + std::promise entered; + auto inline_entered = entered.get_future(); + std::promise release; + auto inline_released = release.get_future(); + + auto caller = std::async(std::launch::async, [&] { + bool poll_on_caller = false; + const auto id = executor.track([] {}, &poll_on_caller); + ASSERT_NE(id, 0u); + ASSERT_TRUE(poll_on_caller); + executor.run_inline([&] { + EXPECT_EXCEPTION(executor.shutdown(), std::logic_error); + executor.start(); + entered.set_value(); + wait_for_future(inline_released); + executor.untrack(id); + }); + }); + wait_for_future(inline_entered); + + auto stopping = std::async(std::launch::async, [&] { executor.shutdown(); }); + wait_for_deferred_first_poll(executor); + ASSERT_TRUE(executor.accepting()); + ASSERT_EQ(stopping.wait_for(0ms), std::future_status::timeout); + + std::promise ran; + auto queued = ran.get_future(); + ASSERT_TRUE(executor.enqueue([&] { + ASSERT_TRUE(executor.is_worker()); + ran.set_value(); + })); + wait_for_future(queued); + + release.set_value(); + wait_for_future(caller); + wait_for_future(stopping); + ASSERT_FALSE(executor.accepting()); +} + +} // namespace +} // namespace executor_tests + +int main() { + using namespace executor_tests; + test_executor_queue(); + test_executor_shutdown_drains_active_work(); + test_executor_restart(); + test_shared_executor(); + test_shutdown_waits_for_inline_work(); +} diff --git a/cpp-tests/tests/async_executor_unit/peer.cpp b/cpp-tests/tests/async_executor_unit/peer.cpp new file mode 100644 index 0000000..7d8a1e1 --- /dev/null +++ b/cpp-tests/tests/async_executor_unit/peer.cpp @@ -0,0 +1,9 @@ +#include "async_runtime_test.hpp" + +namespace executor_tests { + +uniffi::detail::AsyncExecutor &executor_from_peer() { + return uniffi::detail::async_executor(); +} + +} // namespace executor_tests From 81debf8f936543328ef4084b282e4a0fe4be2562 Mon Sep 17 00:00:00 2001 From: Alan George Date: Mon, 23 Nov 2026 16:07:44 -0700 Subject: [PATCH 2/2] Link the Windows synchronization library for fixtures --- cpp-tests/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index 24fb348..513ffc6 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)