diff --git a/bindgen/src/bindings/cpp/templates/async.hpp b/bindgen/src/bindings/cpp/templates/async.hpp index 2052702..c8e113c 100644 --- a/bindgen/src/bindings/cpp/templates/async.hpp +++ b/bindgen/src/bindings/cpp/templates/async.hpp @@ -1,3 +1,15 @@ +// 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; @@ -203,6 +215,13 @@ 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"); + } +} + } // namespace detail // Joins the shared worker after waiting for first polls, cancelling calls, and draining cleanup. @@ -213,3 +232,319 @@ 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(); } + +// Carries the lifted value or exception delivered when an async call completes. +template class FutureResult { + public: + explicit FutureResult(T value) : value_(std::move(value)) {} + explicit FutureResult(std::exception_ptr error) noexcept : error_(std::move(error)) {} + + FutureResult(const FutureResult &) = default; + FutureResult &operator=(const FutureResult &) = default; + FutureResult &operator=(FutureResult &&) = default; + + FutureResult(FutureResult &&other) noexcept : error_(std::move(other.error_)) { + if (other.value_) { + try { + value_.emplace(std::move(*other.value_)); + } catch (...) { + // Deliver a failed value transfer through the future's normal error path. + error_ = std::current_exception(); + } + } + } + + bool has_value() const noexcept { return !error_; } + std::exception_ptr error() const noexcept { return error_; } + + // Move out the value or rethrow the stored exception. + T get() && { + if (error_) { + std::rethrow_exception(error_); + } + return std::move(*value_); + } + + private: + std::optional value_; + std::exception_ptr error_; +}; + +// Carries completion or an exception for a void result. +template <> class FutureResult { + public: + FutureResult() = default; + explicit FutureResult(std::exception_ptr error) noexcept : error_(std::move(error)) {} + + bool has_value() const noexcept { return !error_; } + std::exception_ptr error() const noexcept { return error_; } + + // Observe completion, rethrowing a stored exception. + void get() const { + if (error_) { + std::rethrow_exception(error_); + } + } + + private: + std::exception_ptr error_; +}; + +namespace detail { + +// Retains the executor through delivery, including when then() is attached to an already-ready +// call. +struct ContinuationRegistration { + ContinuationRegistration() : id(async_executor().track([] {})) { + if (!id) { + throw AsyncExecutorError(); + } + } + ~ContinuationRegistration() { async_executor().untrack(id); } + uint64_t id; +}; + +template class FutureCompletionState { + public: + using Result = FutureResult; + using Callback = std::function; + + void complete(Result result) noexcept { + Callback callback; + { + std::lock_guard guard(mutex_); + if (result_) { + return; + } + result_.emplace(std::move(result)); + callback = std::move(callback_); + } + ready_.notify_all(); + if (callback) { + enqueue_continuation(std::move(callback)); + } + } + + T get() { + std::unique_lock lock(mutex_); + check_blocking_wait(result_.has_value()); + ready_.wait(lock, [this] { return result_.has_value(); }); + auto result = std::move(*result_); + lock.unlock(); + return std::move(result).get(); + } + + void wait() const { + std::unique_lock lock(mutex_); + check_blocking_wait(result_.has_value()); + ready_.wait(lock, [this] { return result_.has_value(); }); + } + + template + std::future_status wait_for(const std::chrono::duration &timeout) const { + std::unique_lock lock(mutex_); + check_blocking_wait(result_.has_value() || timeout <= timeout.zero()); + return ready_.wait_for(lock, timeout, [this] { return result_.has_value(); }) + ? std::future_status::ready + : std::future_status::timeout; + } + + void then(Callback callback) { + auto registration = std::make_shared(); + callback = [registration, callback = std::move(callback)](Result result) mutable { + callback(std::move(result)); + }; + bool ready; + { + std::lock_guard guard(mutex_); + ready = result_.has_value(); + if (!ready) { + callback_ = std::move(callback); + return; + } + } + enqueue_continuation(std::move(callback)); + } + + private: + void enqueue_continuation(Callback callback) noexcept { + Result result = [&] { + std::lock_guard guard(mutex_); + return std::move(*result_); + }(); + auto delivery = + std::make_shared>(std::move(callback), std::move(result)); + if (!enqueue_async([delivery]() mutable { + try { + delivery->first(std::move(delivery->second)); + } catch (...) { + // User exceptions do not escape the executor thread. + } + })) { + std::terminate(); + } + } + + mutable std::mutex mutex_; + mutable std::condition_variable ready_; + std::optional result_; + Callback callback_; +}; + +} // namespace detail + +// Copyable handle for requesting cancellation from any thread. +class FutureCancelHandle { + public: + FutureCancelHandle() = default; + + // Request cancellation if the call is still active. + void cancel() const noexcept { + if (cancel_) { + cancel_(); + } + } + + private: + template friend class Future; + + explicit FutureCancelHandle(std::function cancel) noexcept + : cancel_(std::move(cancel)) {} + + std::function cancel_; +}; + +// Move-only token returned by Future::then(). Destroying it requests cancellation. +// Use the token from one thread at a time. +class FutureContinuation { + public: + FutureContinuation() = default; + explicit FutureContinuation(std::function cancel) : cancel_(std::move(cancel)) {} + + FutureContinuation(const FutureContinuation &) = delete; + FutureContinuation &operator=(const FutureContinuation &) = delete; + + FutureContinuation(FutureContinuation &&other) noexcept : cancel_(std::move(other.cancel_)) { + other.cancel_ = nullptr; + } + + FutureContinuation &operator=(FutureContinuation &&other) noexcept { + if (this != &other) { + cancel(); + cancel_ = std::move(other.cancel_); + other.cancel_ = nullptr; + } + return *this; + } + + ~FutureContinuation() { cancel(); } + + // Give up cancellation ownership so the call can continue after the token is destroyed. + void detach() noexcept { cancel_ = nullptr; } + + // Request cancellation. The worker still delivers the eventual result. + void cancel() noexcept { + if (cancel_) { + auto cancel = std::move(cancel_); + cancel_ = nullptr; + cancel(); + } + } + + private: + std::function cancel_; +}; + +// Move-only handle to an async Rust call. Destroying it while incomplete requests cancellation. +// Use the future from one thread at a time and use cancel_handle() for cross-thread cancellation. +// Blocking waits on the executor's worker throw std::logic_error. +template class Future { + public: + using Result = FutureResult; + using Callback = std::function; + + Future() = default; + Future(std::shared_ptr> state, + std::function cancel) noexcept + : state_(std::move(state)), cancel_(std::move(cancel)) {} + + Future(const Future &) = delete; + Future &operator=(const Future &) = delete; + + Future(Future &&other) noexcept + : state_(std::move(other.state_)), cancel_(std::move(other.cancel_)) { + other.cancel_ = nullptr; + } + + Future &operator=(Future &&other) noexcept { + if (this != &other) { + cancel(); + state_ = std::move(other.state_); + cancel_ = std::move(other.cancel_); + other.cancel_ = nullptr; + } + return *this; + } + + ~Future() { cancel(); } + + bool valid() const noexcept { return state_ != nullptr; } + + // Take an independent handle before consuming or moving this future. + [[nodiscard]] FutureCancelHandle cancel_handle() const { return FutureCancelHandle(cancel_); } + + // Wait for completion and consume the result, rethrowing any stored error. + decltype(auto) get() { + require_state(); + detail::check_blocking_wait(state_->wait_for(std::chrono::seconds(0)) == + std::future_status::ready); + auto state = std::move(state_); + cancel_ = nullptr; + return state->get(); + } + + // Wait for readiness and keep the result available for get() or then(). + void wait() const { + require_state(); + state_->wait(); + } + + // Wait up to timeout. A nonpositive timeout checks readiness immediately. + template + std::future_status wait_for(const std::chrono::duration &timeout) const { + require_state(); + return state_->wait_for(timeout); + } + + // Consume this future and deliver its result on the worker. The returned token owns cancellation. + [[nodiscard]] FutureContinuation then(Callback callback) && { + require_state(); + if (!callback) { + throw std::invalid_argument("UniFFI future continuation must not be empty"); + } + state_->then(std::move(callback)); + auto cancel = std::move(cancel_); + cancel_ = nullptr; + state_.reset(); + return FutureContinuation(std::move(cancel)); + } + + // Request cancellation and keep the result available for get() or then(). + void cancel() noexcept { + if (cancel_) { + auto cancel = std::move(cancel_); + cancel_ = nullptr; + cancel(); + } + } + + private: + void require_state() const { + if (!state_) { + throw std::future_error(std::future_errc::no_state); + } + } + + std::shared_ptr> state_; + std::function cancel_; +}; diff --git a/cpp-tests/CMakeLists.txt b/cpp-tests/CMakeLists.txt index 513ffc6..40e4d30 100644 --- a/cpp-tests/CMakeLists.txt +++ b/cpp-tests/CMakeLists.txt @@ -58,6 +58,12 @@ function(runtime_test TEST_NAME) endfunction() runtime_test(async_executor_unit tests/async_executor_unit/peer.cpp) +runtime_test(async_futures_unit) +runtime_test(async_exit_from_continuation) +set_tests_properties(async_exit_from_continuation-test PROPERTIES TIMEOUT 15) +if(VALGRIND) + set_tests_properties(async_exit_from_continuation-test-test-memcheck PROPERTIES TIMEOUT 30) +endif() # Add a bindings test case macro(test_case TEST_NAME) 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..d0adeac --- /dev/null +++ b/cpp-tests/tests/async_exit_from_continuation/main.cpp @@ -0,0 +1,16 @@ +#include "async_runtime_test.hpp" + +#include + +int main() { + auto state = std::make_shared>(); + state->complete(uniffi::FutureResult(true)); + auto continuation = uniffi::Future(state, nullptr).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_futures_unit/main.cpp b/cpp-tests/tests/async_futures_unit/main.cpp new file mode 100644 index 0000000..7d66881 --- /dev/null +++ b/cpp-tests/tests/async_futures_unit/main.cpp @@ -0,0 +1,131 @@ +#include "async_runtime_test.hpp" + +using namespace std::chrono_literals; + +namespace { + +using executor_tests::wait_for_future; +using uniffi::AsyncCancelledError; +using uniffi::Future; +using uniffi::FutureResult; +using uniffi::detail::FutureCompletionState; +using uniffi::detail::async_executor; + +// Waits retain a result until get() consumes it, including void and error results. +void test_result_and_waits() { + Future empty; + ASSERT_FALSE(empty.valid()); + EXPECT_EXCEPTION(empty.get(), std::future_error); + + auto value = std::make_shared>(); + Future future(value, nullptr); + ASSERT_EQ(future.wait_for(1ms), std::future_status::timeout); + value->complete(FutureResult(42)); + future.wait(); + ASSERT_EQ(wait_for_future(future), 42); + ASSERT_FALSE(future.valid()); + + auto unit = std::make_shared>(); + unit->complete(FutureResult()); + wait_for_future(Future(unit, nullptr)); + + auto error = std::make_shared>(); + error->complete(FutureResult(std::make_exception_ptr(AsyncCancelledError()))); + EXPECT_EXCEPTION(wait_for_future(Future(error, nullptr)), AsyncCancelledError); +} + +// Both attachment orders deliver the same result on the executor. +void test_continuation_delivery(bool complete_first) { + auto state = std::make_shared>(); + Future future(state, nullptr); + if (complete_first) { + state->complete(FutureResult(42)); + } + + auto delivered = std::make_shared>(); + auto result = delivered->get_future(); + auto token = std::move(future).then([delivered](auto completed) { + ASSERT_TRUE(async_executor().is_worker()); + delivered->set_value(std::move(completed).get()); + }); + ASSERT_FALSE(future.valid()); + if (!complete_first) { + ASSERT_EQ(result.wait_for(0ms), std::future_status::timeout); + state->complete(FutureResult(42)); + } + ASSERT_EQ(wait_for_future(result), 42); +} + +// An unresolved future cannot block the executor or lose ownership on a rejected wait. +void test_worker_wait_rejected() { + std::promise checked; + auto result = checked.get_future(); + ASSERT_TRUE(async_executor().enqueue([&] { + auto state = std::make_shared>(); + Future future(state, nullptr); + EXPECT_EXCEPTION(future.get(), std::logic_error); + EXPECT_EXCEPTION(future.wait(), std::logic_error); + EXPECT_EXCEPTION(future.wait_for(1ms), std::logic_error); + ASSERT_EQ(future.wait_for(0ms), std::future_status::timeout); + state->complete(FutureResult(42)); + ASSERT_EQ(future.get(), 42); + checked.set_value(); + })); + wait_for_future(result); +} + +// Move assignment cancels the old owner and leaves the new result available. +void test_move_ownership() { + unsigned cancellations = 0; + auto old = std::make_shared>(); + Future owned(old, [&] { ++cancellations; }); + auto replacement = std::make_shared>(); + replacement->complete(FutureResult()); + Future ready(replacement, nullptr); + owned = std::move(ready); + ASSERT_FALSE(ready.valid()); + ASSERT_EQ(cancellations, 1u); + wait_for_future(owned); + ASSERT_EQ(cancellations, 1u); + + uniffi::FutureContinuation old_token([&] { ++cancellations; }); + uniffi::FutureContinuation new_token([&] { ++cancellations; }); + old_token = std::move(new_token); + ASSERT_EQ(cancellations, 2u); + new_token.cancel(); + ASSERT_EQ(cancellations, 2u); + old_token.cancel(); + ASSERT_EQ(cancellations, 3u); +} + +// A detached token leaves the result pending until a copied handle cancels from another thread. +void test_detach_and_cancel_handle() { + auto state = std::make_shared>(); + Future future(state, [state] { + state->complete(FutureResult(std::make_exception_ptr(AsyncCancelledError()))); + }); + auto handle = future.cancel_handle(); + auto delivered = std::make_shared>(); + auto result = delivered->get_future(); + std::move(future).then([delivered](auto completed) { + EXPECT_EXCEPTION(std::move(completed).get(), AsyncCancelledError); + delivered->set_value(); + }).detach(); + ASSERT_EQ(state->wait_for(0ms), std::future_status::timeout); + + auto canceller = std::async(std::launch::async, [handle] { handle.cancel(); }); + wait_for_future(canceller); + wait_for_future(result); +} + +} // namespace + +int main() { + test_result_and_waits(); + test_continuation_delivery(true); + test_continuation_delivery(false); + test_worker_wait_rejected(); + test_move_ownership(); + test_detach_and_cancel_handle(); + uniffi::shutdown_async_executor(); +}