From 7eb84159859c6b0433fda5567544ed52c3af91a4 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Tue, 24 Nov 2026 11:30:51 -0800 Subject: [PATCH 1/9] Add C++20 coroutine (co20) backend to the async layer Adds SUBSPACE_CORO_BACKEND_CO20, selected with --config=cpp20 in Bazel and automatically by CMake when CMAKE_CXX_STANDARD >= 20. The build always defines the backend macro, and a link-time symbol check rejects objects built for different backends. common/async gains task.h: async::Task, ASYNC_AWAIT and ASYNC_RETURN let a function that waits be written once for every backend, and SyncWait runs a task from non-coroutine code. Waits, sockets, ByteStream and AsyncRuntime are implemented on co20::Scheduler. A co20 Context holds a co20 coroutine (which suspends) or an AsyncWaiter (which blocks the thread, yielding a stackful co::Coroutine), and falls back to poll(). The client's blocking API now takes const toolbelt::AsyncWaiter* instead of const co::Coroutine*. The co library is patched (patches/co_cpp20_wait_any_and_reap.patch) with a multi-fd Wait, reaping of finished coroutines, a fix for the poll fallback resuming a coroutine twice, non-aggregate ValueTask promises for GCC, destruction of all nested frames when a suspended coroutine is destroyed, and Run() honouring Stop() from a coroutine in epoll mode. The client and server are not yet converted to co20. --- .bazelrc | 7 + BUILD.bazel | 11 +- CMakeLists.txt | 48 +- MODULE.bazel | 6 + MODULE.bazel.lock | 4 +- client/client.cc | 10 +- client/client.h | 68 +-- common/CMakeLists.txt | 5 +- common/async/BUILD.bazel | 19 +- common/async/async_test.cc | 284 ++++++++--- common/async/byte_stream.cc | 252 +++++----- common/async/byte_stream.h | 40 +- common/async/context.h | 87 +++- common/async/mtls_test.cc | 105 ++-- common/async/runtime.h | 86 +++- common/async/socket.cc | 410 ++++++++------- common/async/socket.h | 103 ++-- common/async/task.h | 82 +++ common/async/wait.cc | 187 +++++++ common/async/wait.h | 34 +- docs/asio-backend.md | 8 +- patches/co_cpp20_wait_any_and_reap.patch | 611 +++++++++++++++++++++++ 22 files changed, 1921 insertions(+), 546 deletions(-) create mode 100644 common/async/task.h create mode 100644 patches/co_cpp20_wait_any_and_reap.patch diff --git a/.bazelrc b/.bazelrc index df11ec10..628594b2 100644 --- a/.bazelrc +++ b/.bazelrc @@ -77,6 +77,13 @@ build:macos_x86_64 --extra_execution_platforms=//platform/host:darwin_x86_64 # For all builds, use C++17 build --cxxopt="-std=c++17" + +# C++20 build: the server and the async layer use C++20 stackless coroutines +# (co20) instead of the stackful co library. The backend has to match the +# language mode, so this config sets both. +build:cpp20 --cxxopt="-std=c++20" +build:cpp20 --//:coro_backend=co20 + build --java_runtime_version=remotejdk_17 # Statically link C++ deps into Rust binaries (avoids RPATH issues) diff --git a/BUILD.bazel b/BUILD.bazel index aeb1be09..97bfb381 100644 --- a/BUILD.bazel +++ b/BUILD.bazel @@ -4,15 +4,19 @@ load("@bazel_skylib//rules:common_settings.bzl", "bool_flag", "string_flag") # Build-time selection of the coroutine/networking backend for the server (and # the client paths it relies on). See common/async/context.h. `co` is the -# default; `asio` compiles the server against Boost.Asio. +# default; `asio` compiles the server against Boost.Asio; `co20` uses C++20 +# stackless coroutines and needs -std=c++20, so select it with --config=cpp20 +# (see .bazelrc), which sets both. # # bazelisk build --//:coro_backend=asio //server +# bazelisk build --config=cpp20 //server string_flag( name = "coro_backend", build_setting_default = "co", values = [ "co", "asio", + "co20", ], ) @@ -26,6 +30,11 @@ config_setting( flag_values = {":coro_backend": "asio"}, ) +config_setting( + name = "coro_backend_co20", + flag_values = {":coro_backend": "co20"}, +) + # Mutual TLS for native bridge connections and the tunnel. Off by default, # so a normal build does not depend on BoringSSL. See docs/mtls.md. # diff --git a/CMakeLists.txt b/CMakeLists.txt index bcb99ffe..f5734c87 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -7,8 +7,12 @@ cmake_minimum_required(VERSION 3.15) project(Subspace LANGUAGES CXX ASM) -# Set C++ standard and compiler flags -set(CMAKE_CXX_STANDARD 17) +# Set C++ standard and compiler flags. Configure with +# -DCMAKE_CXX_STANDARD=20 for the C++20 coroutine backend (see +# SUBSPACE_CORO_BACKEND below). +if(NOT DEFINED CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 17) +endif() set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) # Prefer standard C++ set(CMAKE_POSITION_INDEPENDENT_CODE ON) @@ -199,11 +203,15 @@ endif() message(STATUS "Trigger mechanism: ${SUBSPACE_TRIGGER_MECHANISM}") # --- External Dependency: co (using FetchContent for native CMake) --- +set(SUBSPACE_CO_PATCH ${CMAKE_CURRENT_SOURCE_DIR}/patches/co_cpp20_wait_any_and_reap.patch) FetchContent_Declare( co GIT_REPOSITORY https://github.com/dallison/co.git # dallison/co#77 (poll event mask) plus TSan stack-switch fix (c2cbd0f). GIT_TAG c2cbd0f75b1e834090762d584b812a485b8b8ca8 + # Same patch as the Bazel git_override in MODULE.bazel. Skipped when it + # is already applied, so reconfiguring works. + PATCH_COMMAND sh -c "git apply --reverse --check ${SUBSPACE_CO_PATCH} 2>/dev/null || git apply ${SUBSPACE_CO_PATCH}" CMAKE_ARGS -DCMAKE_OSX_ARCHITECTURES="${CMAKE_OSX_ARCHITECTURES}" ) @@ -234,22 +242,40 @@ FetchContent_MakeAvailable(protobuf) # These targets can be used directly without find_package # --- Option: coroutine/networking backend for the server --- -# Mirrors the Bazel //:coro_backend flag. "co" (default) builds against the co -# coroutine library; "asio" builds the server against Boost.Asio. The value is +# Mirrors the Bazel //:coro_backend flag. "co" builds against the co +# coroutine library; "asio" builds the server against Boost.Asio; "co20" uses +# C++20 stackless coroutines and needs CMAKE_CXX_STANDARD 20 or later. "auto" +# (default) picks co20 for C++20 and later, otherwise co. The value is # translated into the SUBSPACE_CORO_BACKEND macro (see common/async/context.h) # and applied globally so every translation unit that includes the async # headers sees a consistent backend. -set(SUBSPACE_CORO_BACKEND "co" CACHE STRING "Server coroutine backend: co or asio") -set_property(CACHE SUBSPACE_CORO_BACKEND PROPERTY STRINGS "co" "asio") +set(SUBSPACE_CORO_BACKEND "auto" CACHE STRING "Server coroutine backend: auto, co, co20 or asio") +set_property(CACHE SUBSPACE_CORO_BACKEND PROPERTY STRINGS "auto" "co" "co20" "asio") + +if(SUBSPACE_CORO_BACKEND STREQUAL "auto") + if(CMAKE_CXX_STANDARD GREATER_EQUAL 20) + set(SUBSPACE_CORO_BACKEND_RESOLVED "co20") + else() + set(SUBSPACE_CORO_BACKEND_RESOLVED "co") + endif() +else() + set(SUBSPACE_CORO_BACKEND_RESOLVED "${SUBSPACE_CORO_BACKEND}") +endif() -if(SUBSPACE_CORO_BACKEND STREQUAL "asio") +if(SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "asio") add_compile_definitions(SUBSPACE_CORO_BACKEND=2) message(STATUS "Subspace coroutine backend: asio (Boost.Asio)") -elseif(SUBSPACE_CORO_BACKEND STREQUAL "co") - # co backend leaves SUBSPACE_CORO_BACKEND unset; context.h defaults to _CO. +elseif(SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "co20") + if(CMAKE_CXX_STANDARD LESS 20) + message(FATAL_ERROR "SUBSPACE_CORO_BACKEND=co20 needs CMAKE_CXX_STANDARD 20 or later") + endif() + add_compile_definitions(SUBSPACE_CORO_BACKEND=3) + message(STATUS "Subspace coroutine backend: co20 (C++20 coroutines)") +elseif(SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "co") + add_compile_definitions(SUBSPACE_CORO_BACKEND=1) message(STATUS "Subspace coroutine backend: co") else() - message(FATAL_ERROR "SUBSPACE_CORO_BACKEND must be 'co' or 'asio'") + message(FATAL_ERROR "SUBSPACE_CORO_BACKEND must be 'auto', 'co', 'co20' or 'asio'") endif() # --- Option: asio_rpc backend (Boost.Asio RPC) --- @@ -269,7 +295,7 @@ if(SUBSPACE_ASIO_RPC AND CMAKE_CROSSCOMPILING) endif() set(SUBSPACE_NEEDS_BOOST OFF) -if(SUBSPACE_CORO_BACKEND STREQUAL "asio" OR SUBSPACE_ASIO_RPC) +if(SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "asio" OR SUBSPACE_ASIO_RPC) set(SUBSPACE_NEEDS_BOOST ON) endif() diff --git a/MODULE.bazel b/MODULE.bazel index 9ac50f54..cf72d473 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -31,9 +31,15 @@ bazel_dep(name = "coroutines", version = "3.4.1") # co20_rpc on macOS (dallison/co#77). c2cbd0f also keeps TSan from corrupting # the shadow stack on a coroutine stack switch with GCC 15 (dallison/co c2cbd0f). # Not released yet. +# +# The patch adds a multi-fd Wait to the C++20 scheduler, frees coroutines when +# they finish, and keeps the poll fallback from resuming a coroutine twice. +# The co20 backend needs all three. Drop it once it is upstream. git_override( module_name = "coroutines", commit = "c2cbd0f75b1e834090762d584b812a485b8b8ca8", + patch_strip = 1, + patches = ["//patches:co_cpp20_wait_any_and_reap.patch"], remote = "https://github.com/dallison/co.git", ) diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index b9e69dc8..649cfb5d 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -601,8 +601,8 @@ }, "@@rules_rust+//crate_universe:extensions.bzl%crate": { "general": { - "bzlTransitiveDigest": "ebJjXa+P6PCjLNy5r9Y6usOlasRE1po9acRzqmcTvxw=", - "usagesDigest": "elCpzqBbH4Uze4bFcJkhufozV4OiThsWRv8J+c9fLvo=", + "bzlTransitiveDigest": "/zNsa7ILQZw4ggprbQZ7KsHdx0WiuK5EEslC/bxQUJw=", + "usagesDigest": "AkSzlYDag/ptRiPH/inccjoRKY8ur3ttcbzIxnSHNwo=", "recordedInputs": [ "ENV:CARGO_BAZEL_DEBUG \\0", "ENV:CARGO_BAZEL_GENERATOR_SHA256 \\0", diff --git a/client/client.cc b/client/client.cc index f7d8ff48..2fcd9e42 100644 --- a/client/client.cc +++ b/client/client.cc @@ -1081,7 +1081,7 @@ void ClientImpl::CancelPublish(PublisherImpl * /*publisher*/) { absl::Status ClientImpl::WaitForReliablePublisher(PublisherImpl *publisher, std::chrono::nanoseconds timeout, - const co::Coroutine *c) { + const toolbelt::AsyncWaiter *c) { if (absl::Status status = CheckConnected(); !status.ok()) { return status; } @@ -1139,7 +1139,7 @@ ClientImpl::WaitForReliablePublisher(PublisherImpl *publisher, const toolbelt::FileDescriptor &fd, std::chrono::nanoseconds timeout, - const co::Coroutine *c) { + const toolbelt::AsyncWaiter *c) { if (absl::Status status = CheckConnected(); !status.ok()) { return status; } @@ -1202,7 +1202,7 @@ ClientImpl::WaitForReliablePublisher(PublisherImpl *publisher, absl::Status ClientImpl::WaitForSubscriber(SubscriberImpl *subscriber, std::chrono::nanoseconds timeout, - const co::Coroutine *c) { + const toolbelt::AsyncWaiter *c) { if (absl::Status status = CheckConnected(); !status.ok()) { return status; } @@ -1250,7 +1250,7 @@ absl::Status ClientImpl::WaitForSubscriber(SubscriberImpl *subscriber, absl::StatusOr ClientImpl::WaitForSubscriber( SubscriberImpl *subscriber, const toolbelt::FileDescriptor &fd, - std::chrono::nanoseconds timeout, const co::Coroutine *c) { + std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c) { if (absl::Status status = CheckConnected(); !status.ok()) { return status; } @@ -1307,7 +1307,7 @@ absl::StatusOr ClientImpl::WaitForSubscriber( #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO // Asio overloads taking an async::Context (yield_context) directly. Unlike the -// co::Coroutine* overloads above, which fall back to the client's stored +// AsyncWaiter overloads above, which fall back to the client's stored // context (SocketContext()), these wait cooperatively on the caller-supplied // context. This lets an Asio caller wait from within an arbitrary coroutine, // mirroring how the co backend accepts a co::Coroutine*. diff --git a/client/client.h b/client/client.h index 55a74c90..0a25d469 100644 --- a/client/client.h +++ b/client/client.h @@ -22,6 +22,7 @@ #include "common/client_buffer.h" #include "proto/subspace.pb.h" +#include "toolbelt/async_waiter.h" #include "toolbelt/fd.h" #include "toolbelt/logging.h" #include "toolbelt/sockets.h" @@ -342,14 +343,15 @@ class ScopedPublisherBufferLease { // https://github.com/dallison/co. class ClientImpl : public std::enable_shared_from_this { public: - // You can pass a Coroutine pointer to the Client and it will run inside - // a CoroutineScheduler, sharing the CPU with all other coroutines in the - // same scheduler. If c is nullptr, the client will not yield to - // other coroutines when talking to the server and will block the CPU. + // You can pass an AsyncWaiter, such as a co::Coroutine, to the Client and + // it will wait through it, so a coroutine shares the CPU with all other + // coroutines in the same scheduler. If c is nullptr, the client will not + // yield to other coroutines when talking to the server and will block the + // CPU. // // These are public so that they can be accessed by std::make_shared. // You shouldn't create these yourself - create a Client instead. - ClientImpl(const co::Coroutine *c = nullptr) : co_(c) {} + ClientImpl(const toolbelt::AsyncWaiter *c = nullptr) : co_(c) {} #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO // Asio-backed client. The yield_context drives all cooperative socket I/O. // The co coroutine pointer API is preserved for source compatibility but is @@ -508,13 +510,13 @@ class ClientImpl : public std::enable_shared_from_this { // client is coroutine-aware, the coroutine will wait. If it's not, // the function will block on a poll until the publisher is triggered. absl::Status WaitForReliablePublisher(details::PublisherImpl *publisher, - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { return WaitForReliablePublisher(publisher, std::chrono::nanoseconds(0), c); } absl::Status WaitForReliablePublisher(details::PublisherImpl *publisher, std::chrono::nanoseconds timeout, - const co::Coroutine *c = nullptr); + const toolbelt::AsyncWaiter *c = nullptr); // Wait until a reliable publisher can try again to send a message. If the // client is coroutine-aware, the coroutine will wait. If it's not, @@ -522,21 +524,21 @@ class ClientImpl : public std::enable_shared_from_this { absl::StatusOr WaitForReliablePublisher(details::PublisherImpl *publisher, const toolbelt::FileDescriptor &fd, - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { return WaitForReliablePublisher(publisher, fd, std::chrono::nanoseconds(0), c); } absl::StatusOr WaitForReliablePublisher( details::PublisherImpl *publisher, const toolbelt::FileDescriptor &fd, - std::chrono::nanoseconds timeout, const co::Coroutine *c = nullptr); + std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c = nullptr); #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO // Asio overloads that take an async::Context (yield_context) directly so an // Asio caller can cooperatively wait on a caller-supplied coroutine context, // exactly as the co backend does with a co::Coroutine*. On the co backend - // async::Context *is* co::Coroutine*, so these would redeclare the overloads - // above; they are therefore only present for the Asio backend. + // async::Context is a co::Coroutine*, which the AsyncWaiter overloads above + // already accept, so these are only present for the Asio backend. absl::Status WaitForReliablePublisher(details::PublisherImpl *publisher, async::Context ctx) { return WaitForReliablePublisher(publisher, std::chrono::nanoseconds(0), @@ -565,13 +567,13 @@ class ClientImpl : public std::enable_shared_from_this { // will wait. If it's not, the function will block on a poll // until the subscriber is triggered. absl::Status WaitForSubscriber(details::SubscriberImpl *subscriber, - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { return WaitForSubscriber(subscriber, std::chrono::nanoseconds(0), c); } absl::Status WaitForSubscriber(details::SubscriberImpl *subscriber, std::chrono::nanoseconds timeout, - const co::Coroutine *c = nullptr); + const toolbelt::AsyncWaiter *c = nullptr); // Wait until there' s a message available to be read by the // subscriber. If the client is coroutine-aware, the coroutine @@ -579,14 +581,14 @@ class ClientImpl : public std::enable_shared_from_this { // until the subscriber is triggered. absl::StatusOr WaitForSubscriber(details::SubscriberImpl *subscriber, const toolbelt::FileDescriptor &fd, - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { return WaitForSubscriber(subscriber, fd, std::chrono::nanoseconds(0), c); } absl::StatusOr WaitForSubscriber(details::SubscriberImpl *subscriber, const toolbelt::FileDescriptor &fd, std::chrono::nanoseconds timeout, - const co::Coroutine *c = nullptr); + const toolbelt::AsyncWaiter *c = nullptr); #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO // Asio async::Context (yield_context) overloads; see the publisher overloads @@ -796,9 +798,9 @@ class ClientImpl : public std::enable_shared_from_this { // The client owns all the publishers and subscribers. absl::flat_hash_set> channels_; - // If this is non-nullptr the client is coroutine aware and will cooperate - // with all other coroutines to share the CPU. - const co::Coroutine *co_; // Does not own the coroutine. + // If this is non-nullptr the client waits through it, so a coroutine + // cooperates with all other coroutines to share the CPU. + const toolbelt::AsyncWaiter *co_; // Does not own the waiter. #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO // On the Asio backend the cooperative context is a yield_context supplied at @@ -817,7 +819,7 @@ class ClientImpl : public std::enable_shared_from_this { // false for a blocking client that uses synchronous socket I/O + poll(). bool IsCooperative() const { return async_ctx_.has_value(); } #else - const co::Coroutine *SocketContext() const { return co_; } + const toolbelt::AsyncWaiter *SocketContext() const { return co_; } #endif // Call this function when the given subscriber detects a dropped message. @@ -1069,12 +1071,12 @@ class Publisher { // Wait until a reliable publisher can try again to send a message. If the // client is coroutine-aware, the coroutine will wait. If it's not, // the function will block on a poll until the publisher is triggered. - absl::Status Wait(const co::Coroutine *c = nullptr) { + absl::Status Wait(const toolbelt::AsyncWaiter *c = nullptr) { return client_->WaitForReliablePublisher(impl_.get(), c); } absl::Status Wait(std::chrono::nanoseconds timeout, - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { return client_->WaitForReliablePublisher(impl_.get(), timeout, c); } @@ -1085,19 +1087,19 @@ class Publisher { // the wait. Returns the integer fd value of the file descriptor that // triggered the wait. absl::StatusOr Wait(const toolbelt::FileDescriptor &fd, - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { return client_->WaitForReliablePublisher(impl_.get(), fd, c); } absl::StatusOr Wait(const toolbelt::FileDescriptor &fd, std::chrono::nanoseconds timeout, - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { return client_->WaitForReliablePublisher(impl_.get(), fd, timeout, c); } #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO // Asio overloads: cooperatively wait on a caller-supplied yield_context, the - // direct analogue of the co::Coroutine* overloads above. + // direct analogue of the AsyncWaiter overloads above. absl::Status Wait(async::Context ctx) { return client_->WaitForReliablePublisher(impl_.get(), ctx); } @@ -1477,12 +1479,12 @@ class Subscriber { // subscriber. If the client is coroutine-aware, the coroutine // will wait. If it's not, the function will block on a poll // until the subscriber is triggered. - absl::Status Wait(const co::Coroutine *c = nullptr) { + absl::Status Wait(const toolbelt::AsyncWaiter *c = nullptr) { return client_->WaitForSubscriber(impl_.get(), c); } absl::Status Wait(std::chrono::nanoseconds timeout, - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { return client_->WaitForSubscriber(impl_.get(), timeout, c); } @@ -1494,19 +1496,19 @@ class Subscriber { // the wait. Returns the integer fd value of the file descriptor that // triggered the wait. absl::StatusOr Wait(const toolbelt::FileDescriptor &fd, - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { return client_->WaitForSubscriber(impl_.get(), fd, c); } absl::StatusOr Wait(const toolbelt::FileDescriptor &fd, std::chrono::nanoseconds timeout, - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { return client_->WaitForSubscriber(impl_.get(), fd, timeout, c); } #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO // Asio overloads: cooperatively wait on a caller-supplied yield_context, the - // direct analogue of the co::Coroutine* overloads above. + // direct analogue of the AsyncWaiter overloads above. absl::Status Wait(async::Context ctx) { return client_->WaitForSubscriber(impl_.get(), ctx); } @@ -1890,7 +1892,7 @@ class Client { static absl::StatusOr> Create(const std::string &server_socket = kDefaultServerSocket, const std::string &client_name = "", - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { auto client = std::make_shared(c); auto status = client->Init(server_socket, client_name); if (!status.ok()) { @@ -1899,7 +1901,7 @@ class Client { return client; } - Client(const co::Coroutine *c = nullptr) + Client(const toolbelt::AsyncWaiter *c = nullptr) : impl_(std::make_shared(c)) {} #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO // Asio-backed client: the yield_context drives cooperative socket I/O. @@ -1994,7 +1996,7 @@ CreatePublisher(const std::string &channel_name, const PublisherOptions &opts = PublisherOptions(), const std::string &server_socket = "/tmp/subspace", const std::string &client_name = "", - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { auto client_or = Client::Create(server_socket, client_name, c); if (!client_or.ok()) { return client_or.status(); @@ -2007,7 +2009,7 @@ CreateSubscriber(const std::string &channel_name, const SubscriberOptions &opts = SubscriberOptions(), const std::string &server_socket = "/tmp/subspace", const std::string &client_name = "", - const co::Coroutine *c = nullptr) { + const toolbelt::AsyncWaiter *c = nullptr) { auto client_or = Client::Create(server_socket, client_name, c); if (!client_or.ok()) { return client_or.status(); diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index c97ab2d8..25bd40f7 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -47,6 +47,7 @@ add_library(subspace_async STATIC async/byte_stream.cc async/socket.h async/socket.cc + async/task.h async/wait.h async/wait.cc ) @@ -64,8 +65,10 @@ if(SUBSPACE_ENABLE_MTLS) else() target_compile_definitions(subspace_async PUBLIC SUBSPACE_ENABLE_MTLS=0) endif() -if(SUBSPACE_CORO_BACKEND STREQUAL "asio") +if(SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "asio") target_link_libraries(subspace_async PUBLIC Boost::asio Boost::coroutine) +elseif(SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "co20") + target_link_libraries(subspace_async PUBLIC co_cpp20) endif() add_executable(async_test async/async_test.cc) diff --git a/common/async/BUILD.bazel b/common/async/BUILD.bazel index c35c880a..5e27a9ff 100644 --- a/common/async/BUILD.bazel +++ b/common/async/BUILD.bazel @@ -3,10 +3,13 @@ package(default_visibility = ["//visibility:public"]) load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") # The async abstraction layer. One macro (SUBSPACE_CORO_BACKEND) selects -# between the `co` coroutine backend (default) and the Boost.Asio backend. -# The macro is propagated to dependents via `defines` because the headers -# (context.h / socket.h) are included by the server and client translation -# units and must see the same backend selection. +# between the `co` coroutine backend (default), the Boost.Asio backend and the +# C++20 coroutine backend (co20). The macro is propagated to dependents via +# `defines` because the headers (context.h / socket.h) are included by the +# server and client translation units and must see the same backend +# selection. It is always set, even for co, because some dependents +# (co20_rpc) compile as C++20 in a C++17 build and context.h would otherwise +# choose co20 for them. cc_library( name = "async", srcs = [ @@ -20,13 +23,14 @@ cc_library( "mtls.h", "runtime.h", "socket.h", + "task.h", "wait.h", ], defines = select({ - # SUBSPACE_CORO_BACKEND_ASIO == 2 (see context.h). + # Values from context.h. "//:coro_backend_asio": ["SUBSPACE_CORO_BACKEND=2"], - # co backend leaves the macro unset; context.h defaults to _CO. - "//conditions:default": [], + "//:coro_backend_co20": ["SUBSPACE_CORO_BACKEND=3"], + "//conditions:default": ["SUBSPACE_CORO_BACKEND=1"], }) + select({ "//:mtls_enabled": ["SUBSPACE_ENABLE_MTLS=1"], "//conditions:default": ["SUBSPACE_ENABLE_MTLS=0"], @@ -44,6 +48,7 @@ cc_library( "@boost.context//:boost.context", "@boost.coroutine//:boost.coroutine", ], + "//:coro_backend_co20": ["@coroutines//co:co_cpp20"], "//conditions:default": [], }) + select({ "//:mtls_enabled": [ diff --git a/common/async/async_test.cc b/common/async/async_test.cc index 509e5f42..50c78196 100644 --- a/common/async/async_test.cc +++ b/common/async/async_test.cc @@ -6,6 +6,7 @@ #include "common/async/runtime.h" #include "common/async/socket.h" +#include "common/async/task.h" #include "common/async/wait.h" #include "common/coroutine_stack.h" @@ -21,12 +22,18 @@ #include #include #include +#elif SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 +#include "co/coroutine.h" #endif +// The coroutine bodies below are written once for every backend with +// ASYNC_AWAIT and ASYNC_RETURN (see task.h). gtest's ASSERT_* macros return, +// which a C++20 coroutine can't do, so the bodies use EXPECT_* instead. + namespace subspace::async { namespace { -// Helper to construct an AsyncRuntime and run it, abstracting over the two +// Helper to construct an AsyncRuntime and run it, abstracting over the // backends so the test bodies are backend-agnostic. #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO struct RuntimeFixture { @@ -34,6 +41,12 @@ struct RuntimeFixture { AsyncRuntime runtime{ioc}; void Run() { ioc.run(); } }; +#elif SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 +struct RuntimeFixture { + co20::Scheduler scheduler; + AsyncRuntime runtime{scheduler}; + void Run() { scheduler.Run(); } +}; #else struct RuntimeFixture { co::CoroutineScheduler scheduler; @@ -61,17 +74,18 @@ TEST(AsyncTest, WaitReadableWakesOnData) { RuntimeFixture fx; bool got_data = false; - fx.runtime.Spawn([&](Context ctx) { - ASSERT_TRUE(WaitReadable(ctx, fds[0]).ok()); + fx.runtime.Spawn([&](Context ctx) -> Task { + absl::Status s = ASYNC_AWAIT(WaitReadable(ctx, fds[0])); + EXPECT_TRUE(s.ok()) << s; char buf[8] = {}; ssize_t n = ::read(fds[0], buf, sizeof(buf)); got_data = (n == 3 && buf[0] == 'a' && buf[1] == 'b' && buf[2] == 'c'); }); // Writer coroutine: sleeps a touch, then writes. - fx.runtime.Spawn([&](Context ctx) { - Sleep(ctx, std::chrono::milliseconds(10)); - ASSERT_EQ(3, ::write(fds[1], "abc", 3)); + fx.runtime.Spawn([&](Context ctx) -> Task { + ASYNC_AWAIT(Sleep(ctx, std::chrono::milliseconds(10))); + EXPECT_EQ(3, ::write(fds[1], "abc", 3)); }); fx.Run(); @@ -87,8 +101,9 @@ TEST(AsyncTest, WaitReadableTimeout) { RuntimeFixture fx; bool timed_out = false; - fx.runtime.Spawn([&](Context ctx) { - absl::Status s = WaitReadable(ctx, fds[0], std::chrono::milliseconds(20)); + fx.runtime.Spawn([&](Context ctx) -> Task { + absl::Status s = ASYNC_AWAIT( + WaitReadable(ctx, fds[0], std::chrono::milliseconds(20))); timed_out = absl::IsDeadlineExceeded(s); }); @@ -148,16 +163,16 @@ TEST(AsyncTest, SecondWaiterOnAnFdReturns) { absl::Status first; absl::Status second; bool second_returned = false; - fx.runtime.Spawn([&](Context ctx) { - first = WaitReadable(ctx, fds[0], std::chrono::seconds(5)); + fx.runtime.Spawn([&](Context ctx) -> Task { + first = ASYNC_AWAIT(WaitReadable(ctx, fds[0], std::chrono::seconds(5))); }); - fx.runtime.Spawn([&](Context ctx) { - second = WaitReadable(ctx, fds[0], std::chrono::seconds(5)); + fx.runtime.Spawn([&](Context ctx) -> Task { + second = ASYNC_AWAIT(WaitReadable(ctx, fds[0], std::chrono::seconds(5))); second_returned = true; }); - fx.runtime.Spawn([&](Context ctx) { - Sleep(ctx, std::chrono::milliseconds(10)); - ASSERT_EQ(1, ::write(fds[1], "x", 1)); + fx.runtime.Spawn([&](Context ctx) -> Task { + ASYNC_AWAIT(Sleep(ctx, std::chrono::milliseconds(10))); + EXPECT_EQ(1, ::write(fds[1], "x", 1)); }); fx.Run(); @@ -180,16 +195,16 @@ TEST(AsyncTest, WaitEitherReturnsReadyFd) { RuntimeFixture fx; int ready = -1; - fx.runtime.Spawn([&](Context ctx) { - absl::StatusOr r = WaitEither(ctx, a[0], b[0]); + fx.runtime.Spawn([&](Context ctx) -> Task { + absl::StatusOr r = ASYNC_AWAIT(WaitEither(ctx, a[0], b[0])); if (r.ok()) { ready = *r; } }); - fx.runtime.Spawn([&](Context ctx) { - Sleep(ctx, std::chrono::milliseconds(10)); - ASSERT_EQ(1, ::write(b[1], "x", 1)); + fx.runtime.Spawn([&](Context ctx) -> Task { + ASYNC_AWAIT(Sleep(ctx, std::chrono::milliseconds(10))); + EXPECT_EQ(1, ::write(b[1], "x", 1)); }); fx.Run(); @@ -208,9 +223,9 @@ TEST(AsyncTest, WaitEitherTimeout) { RuntimeFixture fx; bool timed_out = false; - fx.runtime.Spawn([&](Context ctx) { - absl::StatusOr r = - WaitEither(ctx, a[0], b[0], std::chrono::milliseconds(20)); + fx.runtime.Spawn([&](Context ctx) -> Task { + absl::StatusOr r = ASYNC_AWAIT( + WaitEither(ctx, a[0], b[0], std::chrono::milliseconds(20))); timed_out = absl::IsDeadlineExceeded(r.status()); }); @@ -236,31 +251,32 @@ TEST(AsyncTest, StreamSocketLoopbackMessage) { ASSERT_GT(port, 0); // Server: accept, receive one framed message. - fx.runtime.Spawn([&](Context ctx) { - absl::StatusOr conn = listener.Accept(ctx); + fx.runtime.Spawn([&](Context ctx) -> Task { + absl::StatusOr conn = ASYNC_AWAIT(listener.Accept(ctx)); if (!conn.ok()) { - return; + ASYNC_RETURN; } char buf[256]; - absl::StatusOr n = conn->ReceiveMessage(buf, sizeof(buf), ctx); + absl::StatusOr n = + ASYNC_AWAIT(conn->ReceiveMessage(buf, sizeof(buf), ctx)); if (n.ok() && *n > 0) { received.assign(buf, static_cast(*n)); } }); // Client: connect to loopback, send one framed message. - fx.runtime.Spawn([&, port](Context ctx) { + fx.runtime.Spawn([&, port](Context ctx) -> Task { StreamSocket client; SocketAddress dest(InetAddress("127.0.0.1", port)); if (!client.Connect(dest).ok()) { - return; + ASYNC_RETURN; } char outbuf[64]; const char *payload = "hello-bridge"; size_t len = std::strlen(payload); // SendMessage requires 4 bytes below the payload pointer. std::memcpy(outbuf + sizeof(int32_t), payload, len); - (void)client.SendMessage(outbuf + sizeof(int32_t), len, ctx); + (void)ASYNC_AWAIT(client.SendMessage(outbuf + sizeof(int32_t), len, ctx)); }); fx.Run(); @@ -281,21 +297,22 @@ TEST(AsyncTest, UnixSocketMessageAndFdPassing) { UnixSocket listener; ASSERT_TRUE(listener.Bind(path, /*listen=*/true).ok()); - fx.runtime.Spawn([&](Context ctx) { - absl::StatusOr conn = listener.Accept(ctx); + fx.runtime.Spawn([&](Context ctx) -> Task { + absl::StatusOr conn = ASYNC_AWAIT(listener.Accept(ctx)); if (!conn.ok()) { - return; + ASYNC_RETURN; } absl::StatusOr> msg = - conn->ReceiveVariableLengthMessage(ctx); + ASYNC_AWAIT(conn->ReceiveVariableLengthMessage(ctx)); if (!msg.ok()) { - return; + ASYNC_RETURN; } received_msg.assign(msg->data(), msg->size()); std::vector fds; - if (!conn->ReceiveFds(fds, ctx).ok() || fds.empty()) { - return; + absl::Status s = ASYNC_AWAIT(conn->ReceiveFds(fds, ctx)); + if (!s.ok() || fds.empty()) { + ASYNC_RETURN; } char buf[16] = {}; ssize_t n = ::read(fds[0].Fd(), buf, sizeof(buf)); @@ -304,29 +321,32 @@ TEST(AsyncTest, UnixSocketMessageAndFdPassing) { } }); - fx.runtime.Spawn([&, path](Context ctx) { + fx.runtime.Spawn([&, path](Context ctx) -> Task { UnixSocket client; if (!client.Connect(path).ok()) { - return; + ASYNC_RETURN; } // A pipe whose read end we pass to the peer. int p[2]; if (::pipe(p) != 0) { - return; + ASYNC_RETURN; } - ASSERT_EQ(3, ::write(p[1], "FD!", 3)); + EXPECT_EQ(3, ::write(p[1], "FD!", 3)); ::close(p[1]); char outbuf[64]; const char *payload = "hello-uds"; size_t len = std::strlen(payload); std::memcpy(outbuf + sizeof(int32_t), payload, len); - if (!client.SendMessage(outbuf + sizeof(int32_t), len, ctx).ok()) { - return; + absl::StatusOr sent = + ASYNC_AWAIT(client.SendMessage(outbuf + sizeof(int32_t), len, ctx)); + if (!sent.ok()) { + ::close(p[0]); + ASYNC_RETURN; } std::vector fds; fds.emplace_back(p[0], /*owned=*/false); - (void)client.SendFds(fds, ctx); + (void)ASYNC_AWAIT(client.SendFds(fds, ctx)); ::close(p[0]); }); @@ -344,12 +364,14 @@ TEST(AsyncTest, WaitWritableOnPipe) { RuntimeFixture fx; absl::Status empty_status = absl::UnknownError("not run"); absl::Status full_status = absl::UnknownError("not run"); - fx.runtime.Spawn([&](Context ctx) { - empty_status = WaitWritable(ctx, fds[1], std::chrono::milliseconds(100)); + fx.runtime.Spawn([&](Context ctx) -> Task { + empty_status = ASYNC_AWAIT( + WaitWritable(ctx, fds[1], std::chrono::milliseconds(100))); char buf[4096] = {}; while (::write(fds[1], buf, sizeof(buf)) > 0) { } - full_status = WaitWritable(ctx, fds[1], std::chrono::milliseconds(20)); + full_status = ASYNC_AWAIT( + WaitWritable(ctx, fds[1], std::chrono::milliseconds(20))); }); fx.Run(); EXPECT_TRUE(empty_status.ok()) << empty_status; @@ -369,26 +391,27 @@ TEST(AsyncTest, ConnectStreamLoopback) { RuntimeFixture fx; std::string received; absl::Status connect_status = absl::UnknownError("not run"); - fx.runtime.Spawn([&](Context ctx) { - absl::StatusOr conn = listener->Accept(ctx); + fx.runtime.Spawn([&](Context ctx) -> Task { + absl::StatusOr conn = ASYNC_AWAIT(listener->Accept(ctx)); if (!conn.ok()) { - return; + ASYNC_RETURN; } char buf[4]; - absl::StatusOr n = conn->Receive(buf, sizeof(buf), ctx); + absl::StatusOr n = + ASYNC_AWAIT(conn->Receive(buf, sizeof(buf), ctx)); if (n.ok() && *n > 0) { received.assign(buf, static_cast(*n)); } }); - fx.runtime.Spawn([&, port](Context ctx) { - absl::StatusOr client = ConnectStream( - InetAddress("127.0.0.1", port), std::chrono::seconds(5), ctx); + fx.runtime.Spawn([&, port](Context ctx) -> Task { + absl::StatusOr client = ASYNC_AWAIT(ConnectStream( + InetAddress("127.0.0.1", port), std::chrono::seconds(5), ctx)); connect_status = client.status(); if (!client.ok()) { - return; + ASYNC_RETURN; } EXPECT_GE(StreamSocketFd(*client), 0); - (void)client->Send("ping", 4, ctx); + (void)ASYNC_AWAIT(client->Send("ping", 4, ctx)); }); fx.Run(); EXPECT_TRUE(connect_status.ok()) << connect_status; @@ -406,10 +429,10 @@ TEST(AsyncTest, ConnectStreamRefused) { RuntimeFixture fx; absl::Status status = absl::UnknownError("not run"); - fx.runtime.Spawn([&, port](Context ctx) { - status = ConnectStream(InetAddress("127.0.0.1", port), - std::chrono::seconds(5), ctx) - .status(); + fx.runtime.Spawn([&, port](Context ctx) -> Task { + absl::StatusOr client = ASYNC_AWAIT(ConnectStream( + InetAddress("127.0.0.1", port), std::chrono::seconds(5), ctx)); + status = client.status(); }); fx.Run(); EXPECT_TRUE(absl::IsUnavailable(status)) << status; @@ -441,10 +464,10 @@ TEST(AsyncTest, ConnectStreamTimeout) { RuntimeFixture fx; absl::Status status = absl::UnknownError("not run"); - fx.runtime.Spawn([&](Context ctx) { - status = ConnectStream(InetAddress(bound), std::chrono::milliseconds(200), - ctx) - .status(); + fx.runtime.Spawn([&](Context ctx) -> Task { + absl::StatusOr client = ASYNC_AWAIT(ConnectStream( + InetAddress(bound), std::chrono::milliseconds(200), ctx)); + status = client.status(); }); fx.Run(); EXPECT_TRUE(absl::IsDeadlineExceeded(status)) << status; @@ -455,5 +478,138 @@ TEST(AsyncTest, ConnectStreamTimeout) { } #endif +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + +// A coroutine's interrupt fd ends its wait with CancelledError, which is how +// the server shuts its coroutines down. +TEST(AsyncTest, InterruptFdCancelsWait) { + int fds[2], trigger[2]; + ASSERT_EQ(0, ::pipe(fds)); + ASSERT_EQ(0, ::pipe(trigger)); + + RuntimeFixture fx; + absl::Status status = absl::UnknownError("not run"); + fx.runtime.Spawn( + [&](Context ctx) -> Task { + status = co_await WaitReadable(ctx, fds[0], std::chrono::seconds(5)); + }, + {.name = "waiter", .interrupt_fd = trigger[0]}); + fx.runtime.Spawn([&](Context ctx) -> Task { + co_await Sleep(ctx, std::chrono::milliseconds(10)); + EXPECT_EQ(1, ::write(trigger[1], "x", 1)); + }); + fx.Run(); + EXPECT_TRUE(absl::IsCancelled(status)) << status; + for (int fd : {fds[0], fds[1], trigger[0], trigger[1]}) { + ::close(fd); + } +} + +TEST(AsyncTest, AllCoroutineStringsTracksLiveCoroutines) { + RuntimeFixture fx; + size_t seen_while_running = 0; + fx.runtime.Spawn( + [&](Context ctx) -> Task { + co_await Sleep(ctx, std::chrono::milliseconds(10)); + }, + {.name = "sleeper"}); + fx.runtime.Spawn([&](Context ctx) -> Task { + seen_while_running = fx.runtime.AllCoroutineStrings().size(); + co_return; + }); + fx.Run(); + EXPECT_EQ(seen_while_running, 2u); + EXPECT_TRUE(fx.runtime.AllCoroutineStrings().empty()); +} + +// A coroutine destroyed while suspended no longer shows as live. +TEST(AsyncTest, AllCoroutineStringsDropsDestroyedCoroutines) { + int fds[2]; + ASSERT_EQ(0, ::pipe(fds)); + auto scheduler = std::make_unique(); + AsyncRuntime runtime(*scheduler); + runtime.Spawn( + [&](Context ctx) -> Task { + co_await WaitReadable(ctx, fds[0]); + }, + {.name = "waiter"}); + runtime.Spawn([&](Context ctx) -> Task { + co_await Sleep(ctx, std::chrono::milliseconds(1)); + runtime.Stop(); + }); + runtime.Run(); + EXPECT_EQ(runtime.AllCoroutineStrings(), + std::vector{"waiter"}); + scheduler.reset(); + EXPECT_TRUE(runtime.AllCoroutineStrings().empty()); + ::close(fds[0]); + ::close(fds[1]); +} + +// Outside a coroutine, a task whose Context doesn't suspend runs to the end +// in SyncWait, blocking the thread in poll(). +TEST(AsyncTest, SyncWaitBlocksWithNullContext) { + int fds[2]; + ASSERT_EQ(0, ::pipe(fds)); + absl::Status timeout = SyncWait( + WaitReadable(NullContext(), fds[0], std::chrono::milliseconds(20))); + EXPECT_TRUE(absl::IsDeadlineExceeded(timeout)) << timeout; + ASSERT_EQ(1, ::write(fds[1], "x", 1)); + absl::Status ready = SyncWait( + WaitReadable(NullContext(), fds[0], std::chrono::milliseconds(20))); + EXPECT_TRUE(ready.ok()) << ready; + SyncWait(Sleep(NullContext(), std::chrono::milliseconds(1))); + + // A closed fd is an error rather than a wait that never ends. + int closed[2]; + ASSERT_EQ(0, ::pipe(closed)); + ::close(closed[0]); + absl::Status bad = SyncWait(WaitReadable(NullContext(), closed[0])); + EXPECT_TRUE(absl::IsInternal(bad)) << bad; + ::close(closed[1]); + + int sv[2]; + ASSERT_EQ(0, ::socketpair(AF_UNIX, SOCK_STREAM, 0, sv)); + UnixSocket a(sv[0], /*connected=*/true); + UnixSocket b(sv[1], /*connected=*/true); + char outbuf[16]; + std::memcpy(outbuf + sizeof(int32_t), "sync", 4); + absl::StatusOr sent = + SyncWait(a.SendMessage(outbuf + sizeof(int32_t), 4, NullContext())); + ASSERT_TRUE(sent.ok()) << sent.status(); + char inbuf[16]; + absl::StatusOr got = + SyncWait(b.ReceiveMessage(inbuf, sizeof(inbuf), NullContext())); + ASSERT_TRUE(got.ok()) << got.status(); + EXPECT_EQ(std::string(inbuf, static_cast(*got)), "sync"); + ::close(fds[0]); + ::close(fds[1]); +} + +// With an AsyncWaiter Context the wait goes through the waiter. A stackful +// co::Coroutine yields there, so the writer gets to run while the reader +// waits on the same thread. +TEST(AsyncTest, AsyncWaiterContextYieldsStackfulCoroutine) { + int fds[2]; + ASSERT_EQ(0, ::pipe(fds)); + co::CoroutineScheduler scheduler; + absl::Status status = absl::UnknownError("not run"); + scheduler.Spawn([&](co::Coroutine *c) { + const toolbelt::AsyncWaiter *waiter = c; + status = SyncWait( + WaitReadable(Context(waiter), fds[0], std::chrono::seconds(5))); + }); + scheduler.Spawn([&](co::Coroutine *c) { + c->Millisleep(10); + EXPECT_EQ(1, ::write(fds[1], "x", 1)); + }); + scheduler.Run(); + EXPECT_TRUE(status.ok()) << status; + ::close(fds[0]); + ::close(fds[1]); +} + +#endif + } // namespace } // namespace subspace::async diff --git a/common/async/byte_stream.cc b/common/async/byte_stream.cc index de67a9f2..fb181ba4 100644 --- a/common/async/byte_stream.cc +++ b/common/async/byte_stream.cc @@ -195,8 +195,9 @@ ByteStream::DeadlineFrom(std::chrono::nanoseconds timeout) const { return std::chrono::steady_clock::now() + timeout; } -absl::Status ByteStream::SendRaw(Context ctx, const char *data, size_t length, - std::optional deadline) { +Task ByteStream::SendRaw(Context ctx, const char *data, + size_t length, + std::optional deadline) { const int fd = Fd(); while (length > 0) { ssize_t n = ::send(fd, data, length, kSendFlags); @@ -211,60 +212,63 @@ absl::Status ByteStream::SendRaw(Context ctx, const char *data, size_t length, if (n < 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) { std::optional remaining = Remaining(deadline); if (deadline.has_value() && !remaining.has_value()) { - return absl::DeadlineExceededError("timed out sending mTLS records"); + ASYNC_RETURN absl::DeadlineExceededError( + "timed out sending mTLS records"); } - if (absl::Status s = WaitWritable(ctx, fd, remaining.value_or( - std::chrono::nanoseconds(0))); + if (absl::Status s = ASYNC_AWAIT(WaitWritable( + ctx, fd, remaining.value_or(std::chrono::nanoseconds(0)))); !s.ok()) { - return s; + ASYNC_RETURN s; } continue; } - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("send failed: %s", strerror(errno))); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::StatusOr ByteStream::RecvRaw(Context ctx, char *buffer, - size_t length, - std::optional deadline) { +Task> +ByteStream::RecvRaw(Context ctx, char *buffer, size_t length, + std::optional deadline) { const int fd = Fd(); for (;;) { ssize_t n = ::recv(fd, buffer, length, 0); if (n > 0) { - return n; + ASYNC_RETURN n; } if (n == 0) { - return static_cast(0); + ASYNC_RETURN static_cast(0); } if (errno == EINTR) { continue; } if (errno != EAGAIN && errno != EWOULDBLOCK) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("recv failed: %s", strerror(errno))); } std::optional remaining = Remaining(deadline); if (deadline.has_value() && !remaining.has_value()) { - return absl::DeadlineExceededError("timed out reading mTLS records"); + ASYNC_RETURN absl::DeadlineExceededError( + "timed out reading mTLS records"); } - if (absl::Status s = - WaitReadable(ctx, fd, remaining.value_or(std::chrono::nanoseconds(0))); + if (absl::Status s = ASYNC_AWAIT(WaitReadable( + ctx, fd, remaining.value_or(std::chrono::nanoseconds(0)))); !s.ok()) { - return s; + ASYNC_RETURN s; } } } -absl::Status ByteStream::FlushTls(Context ctx, std::optional deadline) { +Task ByteStream::FlushTls(Context ctx, + std::optional deadline) { #if !SUBSPACE_ENABLE_MTLS (void)ctx; (void)deadline; - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); #else if (tls_ == nullptr || tls_->write_bio == nullptr) { - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } char buf[kTlsRecordBuf]; while (BIO_pending(tls_->write_bio) > 0) { @@ -272,57 +276,66 @@ absl::Status ByteStream::FlushTls(Context ctx, std::optional deadline) if (n <= 0) { break; } - if (absl::Status s = SendRaw(ctx, buf, static_cast(n), deadline); + if (absl::Status s = ASYNC_AWAIT( + SendRaw(ctx, buf, static_cast(n), deadline)); !s.ok()) { - return s; + ASYNC_RETURN s; } } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); #endif } -absl::Status ByteStream::FillTls(Context ctx, std::optional deadline) { +Task ByteStream::FillTls(Context ctx, + std::optional deadline) { #if !SUBSPACE_ENABLE_MTLS (void)ctx; (void)deadline; - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); #else char buf[kTlsRecordBuf]; - absl::StatusOr n = RecvRaw(ctx, buf, sizeof(buf), deadline); + absl::StatusOr n = + ASYNC_AWAIT(RecvRaw(ctx, buf, sizeof(buf), deadline)); if (!n.ok()) { - return n.status(); + ASYNC_RETURN n.status(); } if (*n == 0) { - return PeerClosed(); + ASYNC_RETURN PeerClosed(); + } + // Close() can drop the session while the read waits. + if (tls_ == nullptr) { + ASYNC_RETURN absl::FailedPreconditionError("mTLS session closed"); } int wrote = BIO_write(tls_->read_bio, buf, static_cast(*n)); if (wrote != static_cast(*n)) { - return absl::InternalError(SslErrors("failed to buffer an mTLS record")); + ASYNC_RETURN absl::InternalError( + SslErrors("failed to buffer an mTLS record")); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); #endif } -absl::Status ByteStream::HandshakeTls(const std::shared_ptr &mtls, - bool server_role, Context ctx, - std::chrono::nanoseconds timeout) { +Task ByteStream::HandshakeTls(std::shared_ptr mtls, + bool server_role, Context ctx, + std::chrono::nanoseconds timeout) { #if !SUBSPACE_ENABLE_MTLS (void)mtls; (void)server_role; (void)ctx; (void)timeout; - return absl::UnimplementedError( + ASYNC_RETURN absl::UnimplementedError( "mTLS is not enabled in this build; rebuild with --//:mtls " "(Bazel) or -DSUBSPACE_ENABLE_MTLS=ON (CMake)"); #else if (mtls == nullptr || mtls->state_ == nullptr || mtls->state_->ctx == nullptr) { - return absl::InvalidArgumentError("mTLS handshake without credentials"); + ASYNC_RETURN absl::InvalidArgumentError( + "mTLS handshake without credentials"); } if (tls_ != nullptr) { - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } if (absl::Status s = socket_.SetNonBlocking(); !s.ok()) { - return s; + ASYNC_RETURN s; } SSL *ssl = SSL_new(mtls->state_->ctx); BIO *read_bio = BIO_new(BIO_s_mem()); @@ -334,7 +347,8 @@ absl::Status ByteStream::HandshakeTls(const std::shared_ptr &mtls, BIO_free(read_bio); BIO_free(write_bio); broken_ = true; - return absl::InternalError(SslErrors("failed to create an mTLS session")); + ASYNC_RETURN absl::InternalError( + SslErrors("failed to create an mTLS session")); } // An empty read bio must look like EAGAIN, not a close, so the handshake // waits for the next record. SSL_set_bio takes ownership of both bios. @@ -359,28 +373,28 @@ absl::Status ByteStream::HandshakeTls(const std::shared_ptr &mtls, for (;;) { ERR_clear_error(); int rc = SSL_do_handshake(tls_->ssl); - if (absl::Status s = FlushTls(ctx, deadline); !s.ok()) { + if (absl::Status s = ASYNC_AWAIT(FlushTls(ctx, deadline)); !s.ok()) { broken_ = true; tls_.reset(); - return s; + ASYNC_RETURN s; } if (rc == 1) { long verify = SSL_get_verify_result(tls_->ssl); if (verify != X509_V_OK) { broken_ = true; tls_.reset(); - return absl::UnauthenticatedError(absl::StrFormat( + ASYNC_RETURN absl::UnauthenticatedError(absl::StrFormat( "mTLS peer certificate rejected: %s", X509_verify_cert_error_string(verify))); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } int err = SSL_get_error(tls_->ssl, rc); if (err == SSL_ERROR_WANT_READ) { - if (absl::Status s = FillTls(ctx, deadline); !s.ok()) { + if (absl::Status s = ASYNC_AWAIT(FillTls(ctx, deadline)); !s.ok()) { broken_ = true; tls_.reset(); - return s; + ASYNC_RETURN s; } continue; } @@ -390,15 +404,15 @@ absl::Status ByteStream::HandshakeTls(const std::shared_ptr &mtls, std::string message = SslErrors("mTLS handshake failed"); broken_ = true; tls_.reset(); - return absl::UnauthenticatedError(message); + ASYNC_RETURN absl::UnauthenticatedError(message); } #endif } -absl::StatusOr ByteStream::Send(const char *buffer, size_t length, - Context ctx) { +Task> ByteStream::Send(const char *buffer, + size_t length, Context ctx) { if (broken_) { - return absl::FailedPreconditionError("mTLS handshake failed"); + ASYNC_RETURN absl::FailedPreconditionError("mTLS handshake failed"); } #if SUBSPACE_ENABLE_MTLS if (tls_ != nullptr) { @@ -409,8 +423,8 @@ absl::StatusOr ByteStream::Send(const char *buffer, size_t length, static_cast(std::min( length - off, static_cast(std::numeric_limits::max())))); - if (absl::Status s = FlushTls(ctx, std::nullopt); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(FlushTls(ctx, std::nullopt)); !s.ok()) { + ASYNC_RETURN s; } if (n > 0) { off += static_cast(n); @@ -418,8 +432,9 @@ absl::StatusOr ByteStream::Send(const char *buffer, size_t length, } int err = SSL_get_error(tls_->ssl, n); if (err == SSL_ERROR_WANT_READ) { - if (absl::Status s = FillTls(ctx, std::nullopt); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(FillTls(ctx, std::nullopt)); + !s.ok()) { + ASYNC_RETURN s; } continue; } @@ -427,41 +442,42 @@ absl::StatusOr ByteStream::Send(const char *buffer, size_t length, continue; } if (err == SSL_ERROR_ZERO_RETURN) { - return PeerClosed(); + ASYNC_RETURN PeerClosed(); } - return absl::UnavailableError(SslErrors("mTLS send failed")); + ASYNC_RETURN absl::UnavailableError(SslErrors("mTLS send failed")); } - return static_cast(length); + ASYNC_RETURN static_cast(length); } #endif - return socket_.Send(buffer, length, ctx); + ASYNC_RETURN ASYNC_AWAIT(socket_.Send(buffer, length, ctx)); } -absl::StatusOr ByteStream::Receive(char *buffer, size_t buflen, - Context ctx) { +Task> ByteStream::Receive(char *buffer, size_t buflen, + Context ctx) { if (broken_) { - return absl::FailedPreconditionError("mTLS handshake failed"); + ASYNC_RETURN absl::FailedPreconditionError("mTLS handshake failed"); } #if SUBSPACE_ENABLE_MTLS if (tls_ != nullptr) { if (buflen == 0) { - return static_cast(0); + ASYNC_RETURN static_cast(0); } for (;;) { ERR_clear_error(); int n = SSL_read(tls_->ssl, buffer, static_cast(std::min( buflen, static_cast(std::numeric_limits::max())))); - if (absl::Status s = FlushTls(ctx, std::nullopt); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(FlushTls(ctx, std::nullopt)); !s.ok()) { + ASYNC_RETURN s; } if (n > 0) { - return static_cast(n); + ASYNC_RETURN static_cast(n); } int err = SSL_get_error(tls_->ssl, n); if (err == SSL_ERROR_WANT_READ) { - if (absl::Status s = FillTls(ctx, std::nullopt); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(FillTls(ctx, std::nullopt)); + !s.ok()) { + ASYNC_RETURN s; } continue; } @@ -469,35 +485,37 @@ absl::StatusOr ByteStream::Receive(char *buffer, size_t buflen, continue; } if (err == SSL_ERROR_ZERO_RETURN) { - return static_cast(0); + ASYNC_RETURN static_cast(0); } - return absl::UnavailableError(SslErrors("mTLS receive failed")); + ASYNC_RETURN absl::UnavailableError(SslErrors("mTLS receive failed")); } } #endif - return socket_.Receive(buffer, buflen, ctx); + ASYNC_RETURN ASYNC_AWAIT(socket_.Receive(buffer, buflen, ctx)); } -absl::Status ByteStream::SendAll(const void *data, size_t length, Context ctx) { +Task ByteStream::SendAll(const void *data, size_t length, + Context ctx) { const char *p = static_cast(data); while (length > 0) { - absl::StatusOr n = Send(p, length, ctx); + absl::StatusOr n = ASYNC_AWAIT(Send(p, length, ctx)); if (!n.ok()) { - return n.status(); + ASYNC_RETURN n.status(); } if (*n <= 0) { - return absl::UnavailableError("connection closed while sending"); + ASYNC_RETURN absl::UnavailableError("connection closed while sending"); } p += *n; length -= static_cast(*n); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::Status ByteStream::ReadFully(void *buffer, size_t length, Context ctx, - std::optional deadline) { +Task ByteStream::ReadFully(void *buffer, size_t length, + Context ctx, + std::optional deadline) { if (broken_) { - return absl::FailedPreconditionError("mTLS handshake failed"); + ASYNC_RETURN absl::FailedPreconditionError("mTLS handshake failed"); } char *p = static_cast(buffer); #if SUBSPACE_ENABLE_MTLS @@ -507,12 +525,12 @@ absl::Status ByteStream::ReadFully(void *buffer, size_t length, Context ctx, // Receive waits without a deadline. A deadline has to bound the // ciphertext read inside FillTls, so that path calls SSL_read itself. if (!deadline.has_value()) { - absl::StatusOr got = Receive(p, chunk, ctx); + absl::StatusOr got = ASYNC_AWAIT(Receive(p, chunk, ctx)); if (!got.ok()) { - return got.status(); + ASYNC_RETURN got.status(); } if (*got <= 0) { - return PeerClosed(); + ASYNC_RETURN PeerClosed(); } p += *got; length -= static_cast(*got); @@ -520,8 +538,8 @@ absl::Status ByteStream::ReadFully(void *buffer, size_t length, Context ctx, } ERR_clear_error(); int got = SSL_read(tls_->ssl, p, static_cast(chunk)); - if (absl::Status s = FlushTls(ctx, deadline); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(FlushTls(ctx, deadline)); !s.ok()) { + ASYNC_RETURN s; } if (got > 0) { p += got; @@ -530,8 +548,8 @@ absl::Status ByteStream::ReadFully(void *buffer, size_t length, Context ctx, } int err = SSL_get_error(tls_->ssl, got); if (err == SSL_ERROR_WANT_READ) { - if (absl::Status s = FillTls(ctx, deadline); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(FillTls(ctx, deadline)); !s.ok()) { + ASYNC_RETURN s; } continue; } @@ -539,11 +557,11 @@ absl::Status ByteStream::ReadFully(void *buffer, size_t length, Context ctx, continue; } if (err == SSL_ERROR_ZERO_RETURN) { - return PeerClosed(); + ASYNC_RETURN PeerClosed(); } - return absl::UnavailableError(SslErrors("mTLS receive failed")); + ASYNC_RETURN absl::UnavailableError(SslErrors("mTLS receive failed")); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } #endif if (deadline.has_value()) { @@ -556,85 +574,91 @@ absl::Status ByteStream::ReadFully(void *buffer, size_t length, Context ctx, continue; } if (n == 0) { - return PeerClosed(); + ASYNC_RETURN PeerClosed(); } if (errno == EINTR) { continue; } if (errno != EAGAIN && errno != EWOULDBLOCK) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("recv failed: %s", strerror(errno))); } std::optional remaining = Remaining(deadline); if (!remaining.has_value()) { - return absl::DeadlineExceededError("timed out"); + ASYNC_RETURN absl::DeadlineExceededError("timed out"); } - if (absl::Status s = WaitReadable(ctx, fd, *remaining); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(WaitReadable(ctx, fd, *remaining)); + !s.ok()) { + ASYNC_RETURN s; } } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } while (length > 0) { size_t chunk = std::min(length, kMaxReceiveChunk); - absl::StatusOr n = socket_.Receive(p, chunk, ctx); + absl::StatusOr n = ASYNC_AWAIT(socket_.Receive(p, chunk, ctx)); if (!n.ok()) { - return n.status(); + ASYNC_RETURN n.status(); } if (*n <= 0) { - return PeerClosed(); + ASYNC_RETURN PeerClosed(); } p += *n; length -= static_cast(*n); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::StatusOr ByteStream::SendMessage(char *buffer, size_t length, - Context ctx) { +Task> ByteStream::SendMessage(char *buffer, + size_t length, + Context ctx) { #if SUBSPACE_ENABLE_MTLS if (tls_ != nullptr) { char *start = buffer - sizeof(int32_t); uint32_t net_len = htonl(static_cast(length)); memcpy(start, &net_len, sizeof(net_len)); - if (absl::Status s = SendAll(start, length + sizeof(int32_t), ctx); !s.ok()) { - return s; + if (absl::Status s = + ASYNC_AWAIT(SendAll(start, length + sizeof(int32_t), ctx)); + !s.ok()) { + ASYNC_RETURN s; } - return static_cast(length); + ASYNC_RETURN static_cast(length); } #endif - return socket_.SendMessage(buffer, length, ctx); + ASYNC_RETURN ASYNC_AWAIT(socket_.SendMessage(buffer, length, ctx)); } -absl::StatusOr ByteStream::ReceiveMessage(char *buffer, size_t buflen, - Context ctx) { +Task> ByteStream::ReceiveMessage(char *buffer, + size_t buflen, + Context ctx) { #if SUBSPACE_ENABLE_MTLS if (tls_ != nullptr) { char lenbuf[sizeof(int32_t)]; - absl::Status got = ReadFully(lenbuf, sizeof(lenbuf), ctx); + absl::Status got = ASYNC_AWAIT(ReadFully(lenbuf, sizeof(lenbuf), ctx)); if (!got.ok()) { if (absl::IsAborted(got)) { - return static_cast(0); + ASYNC_RETURN static_cast(0); } - return got; + ASYNC_RETURN got; } uint32_t net_len = 0; memcpy(&net_len, lenbuf, sizeof(net_len)); size_t length = ntohl(net_len); if (length > buflen) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "message length %zu exceeds buffer size %zu", length, buflen)); } if (length == 0) { - return static_cast(0); + ASYNC_RETURN static_cast(0); } - if (absl::Status payload = ReadFully(buffer, length, ctx); !payload.ok()) { - return payload; + if (absl::Status payload = ASYNC_AWAIT(ReadFully(buffer, length, ctx)); + !payload.ok()) { + ASYNC_RETURN payload; } - return static_cast(length); + ASYNC_RETURN static_cast(length); } #endif - return socket_.ReceiveMessage(buffer, buflen, ctx); + ASYNC_RETURN ASYNC_AWAIT(socket_.ReceiveMessage(buffer, buflen, ctx)); } } // namespace subspace::async diff --git a/common/async/byte_stream.h b/common/async/byte_stream.h index f54a3bc7..3f4ad772 100644 --- a/common/async/byte_stream.h +++ b/common/async/byte_stream.h @@ -7,6 +7,7 @@ #include "common/async/mtls.h" #include "common/async/socket.h" +#include "common/async/task.h" #include #include #include @@ -15,7 +16,8 @@ namespace subspace::async { // A connected stream. Without an mTLS handshake it is the socket itself. // After HandshakeTls, Send and Receive carry plaintext and BoringSSL (or -// OpenSSL, in the CMake build) carries the records on the socket. +// OpenSSL, in the CMake build) carries the records on the socket. Under +// co20 the methods that wait return tasks (see task.h). class ByteStream { public: ByteStream(); @@ -35,38 +37,42 @@ class ByteStream { // Client when this side connected, server when this side accepted. // `timeout` of zero waits until the handshake finishes or the peer closes. - absl::Status HandshakeTls(const std::shared_ptr &mtls, - bool server_role, Context ctx, - std::chrono::nanoseconds timeout); + Task HandshakeTls(std::shared_ptr mtls, + bool server_role, Context ctx, + std::chrono::nanoseconds timeout); - absl::StatusOr Send(const char *buffer, size_t length, Context ctx); - absl::StatusOr Receive(char *buffer, size_t buflen, Context ctx); - absl::Status SendAll(const void *data, size_t length, Context ctx); + Task> Send(const char *buffer, size_t length, + Context ctx); + Task> Receive(char *buffer, size_t buflen, + Context ctx); + Task SendAll(const void *data, size_t length, Context ctx); // Reads exactly `length` bytes. A deadline uses the non-blocking // descriptor directly, because the co backend's Receive waits until its // whole buffer is full. - absl::Status ReadFully( + Task ReadFully( void *buffer, size_t length, Context ctx, std::optional deadline = std::nullopt); // Length-delimited framing identical to StreamSocket::SendMessage. // `buffer` must have 4 bytes of writable padding immediately before it. - absl::StatusOr SendMessage(char *buffer, size_t length, Context ctx); + Task> SendMessage(char *buffer, size_t length, + Context ctx); // Returns 0 on a clean close. - absl::StatusOr ReceiveMessage(char *buffer, size_t buflen, - Context ctx); + Task> ReceiveMessage(char *buffer, size_t buflen, + Context ctx); private: struct Tls; using Deadline = std::chrono::steady_clock::time_point; - absl::Status SendRaw(Context ctx, const char *data, size_t length, - std::optional deadline); - absl::StatusOr RecvRaw(Context ctx, char *buffer, size_t length, - std::optional deadline); - absl::Status FlushTls(Context ctx, std::optional deadline); - absl::Status FillTls(Context ctx, std::optional deadline); + Task SendRaw(Context ctx, const char *data, size_t length, + std::optional deadline); + Task> RecvRaw(Context ctx, char *buffer, + size_t length, + std::optional deadline); + Task FlushTls(Context ctx, std::optional deadline); + Task FillTls(Context ctx, std::optional deadline); std::optional DeadlineFrom(std::chrono::nanoseconds timeout) const; StreamSocket socket_; diff --git a/common/async/context.h b/common/async/context.h index 04f12371..361c98ba 100644 --- a/common/async/context.h +++ b/common/async/context.h @@ -9,28 +9,43 @@ // Build-time selection of the coroutine/networking backend used by the // Subspace server (and the client paths it relies on). This mirrors the // SUBSPACE_SHMEM_MODE idiom in common/channel.h: a single macro selects one of -// two fully-compiled-in implementations. +// three fully-compiled-in implementations. // // SUBSPACE_CORO_BACKEND_CO - the existing `co` coroutine library and the // cpp_toolbelt sockets (the default). // SUBSPACE_CORO_BACKEND_ASIO - Boost.Asio stackful coroutines // (yield_context) with an externally-provided // io_context, and Asio TCP/UDP/vsock sockets. +// SUBSPACE_CORO_BACKEND_CO20 - C++20 stackless coroutines (co20::Scheduler). +// Functions that suspend return async::Task +// and are awaited (see common/async/task.h). // // Everything the server/client coroutines touch is expressed in terms of the // `subspace::async` abstraction (Context, AsyncRuntime, WaitReadable/Sleep and -// the StreamSocket/UdpSocket facade). The two backends are selected here. +// the StreamSocket/UdpSocket facade). The backends are selected here. +// +// The build (Bazel or CMake) always defines SUBSPACE_CORO_BACKEND. The +// language mode can differ between translation units (co20_rpc compiles as +// C++20 against a C++17 client library), so the backend must come from the +// build rather than from __cplusplus. The fallback below is only for builds +// that don't define it. #define SUBSPACE_CORO_BACKEND_CO 1 #define SUBSPACE_CORO_BACKEND_ASIO 2 +#define SUBSPACE_CORO_BACKEND_CO20 3 #ifndef SUBSPACE_CORO_BACKEND +#if __cplusplus >= 202002L && defined(__cpp_impl_coroutine) +#define SUBSPACE_CORO_BACKEND SUBSPACE_CORO_BACKEND_CO20 +#else #define SUBSPACE_CORO_BACKEND SUBSPACE_CORO_BACKEND_CO #endif +#endif #if SUBSPACE_CORO_BACKEND != SUBSPACE_CORO_BACKEND_CO && \ - SUBSPACE_CORO_BACKEND != SUBSPACE_CORO_BACKEND_ASIO -#error "SUBSPACE_CORO_BACKEND must be SUBSPACE_CORO_BACKEND_CO or SUBSPACE_CORO_BACKEND_ASIO" + SUBSPACE_CORO_BACKEND != SUBSPACE_CORO_BACKEND_ASIO && \ + SUBSPACE_CORO_BACKEND != SUBSPACE_CORO_BACKEND_CO20 +#error "SUBSPACE_CORO_BACKEND must be SUBSPACE_CORO_BACKEND_CO, SUBSPACE_CORO_BACKEND_ASIO or SUBSPACE_CORO_BACKEND_CO20" #endif #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO @@ -56,6 +71,49 @@ inline Context NullContext() { } // namespace subspace::async +#elif SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + +#if __cplusplus < 202002L +#error "SUBSPACE_CORO_BACKEND_CO20 requires C++20 (-std=c++20)" +#endif + +#include "co/coroutine_cpp20.h" +#include "toolbelt/async_waiter.h" +#include + +#if !CO20_HAVE_COROUTINES +#error "SUBSPACE_CORO_BACKEND_CO20 requires compiler support for C++20 coroutines" +#endif + +namespace subspace::async { + +// Says how code driven by this Context waits for an fd or a timer. With a +// co20 coroutine the wait suspends it, so the function doing the wait must be +// awaited. Otherwise the wait blocks the calling thread: through the +// AsyncWaiter if there is one (a stackful co::Coroutine yields to its own +// scheduler there), or with poll(). A Context that doesn't suspend is what +// SyncWait (task.h) needs. +class Context { +public: + constexpr Context() = default; + constexpr Context(std::nullptr_t) {} + constexpr Context(co20::Coroutine *coroutine) : coroutine_(coroutine) {} + constexpr Context(const toolbelt::AsyncWaiter *waiter) : waiter_(waiter) {} + + co20::Coroutine *Coroutine() const { return coroutine_; } + const toolbelt::AsyncWaiter *Waiter() const { return waiter_; } + bool Suspends() const { return coroutine_ != nullptr; } + +private: + co20::Coroutine *coroutine_ = nullptr; + const toolbelt::AsyncWaiter *waiter_ = nullptr; +}; + +// A Context that blocks with poll(). +inline Context NullContext() { return Context(); } + +} // namespace subspace::async + #else // SUBSPACE_CORO_BACKEND_CO #include "co/coroutine.h" @@ -82,6 +140,27 @@ namespace subspace::async { inline constexpr bool kIsAsioBackend = SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO; +// True when compiled against the C++20 stackless coroutine backend. +inline constexpr bool kIsCo20Backend = + SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20; + } // namespace subspace::async +// The backend changes the layout of Server, Client and the socket types, so +// objects built for different backends must not be linked together. Every +// translation unit that includes this header references a symbol named for +// its backend, and the async library defines only the one it was built for, +// so a mismatch fails at link time. +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO +#define SUBSPACE_CORO_BACKEND_LINK_SYMBOL subspace_coro_backend_asio +#elif SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 +#define SUBSPACE_CORO_BACKEND_LINK_SYMBOL subspace_coro_backend_co20 +#else +#define SUBSPACE_CORO_BACKEND_LINK_SYMBOL subspace_coro_backend_co +#endif + +extern "C" const int SUBSPACE_CORO_BACKEND_LINK_SYMBOL; +[[maybe_unused]] __attribute__((used)) static const int + *const subspace_coro_backend_check = &SUBSPACE_CORO_BACKEND_LINK_SYMBOL; + #endif // _COMMON_ASYNC_CONTEXT_H diff --git a/common/async/mtls_test.cc b/common/async/mtls_test.cc index 4d5761d9..3b7edc3e 100644 --- a/common/async/mtls_test.cc +++ b/common/async/mtls_test.cc @@ -5,6 +5,7 @@ #include "common/async/byte_stream.h" #include "common/async/runtime.h" #include "common/async/socket.h" +#include "common/async/task.h" #include "absl/status/status.h" #include "absl/status/status_matchers.h" @@ -33,6 +34,12 @@ struct RuntimeFixture { AsyncRuntime runtime{ioc}; void Run() { ioc.run(); } }; +#elif SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 +struct RuntimeFixture { + co20::Scheduler scheduler; + AsyncRuntime runtime{scheduler}; + void Run() { scheduler.Run(); } +}; #else struct RuntimeFixture { co::CoroutineScheduler scheduler; @@ -46,41 +53,42 @@ TEST(ByteStream, CleartextBytesArriveIntact) { std::string received; absl::Status status = absl::OkStatus(); - fx.runtime.Spawn([&](Context ctx) { + fx.runtime.Spawn([&](Context ctx) -> Task { absl::StatusOr listener = ListenStream(InetAddress("127.0.0.1", 0)); if (!listener.ok()) { status = listener.status(); - return; + ASYNC_RETURN; } const int port = listener->BoundAddress().Port(); - fx.runtime.Spawn([&, port](Context client_ctx) { - absl::StatusOr connected = ConnectStream( - InetAddress("127.0.0.1", port), std::chrono::seconds(2), client_ctx); + fx.runtime.Spawn([&, port](Context client_ctx) -> Task { + absl::StatusOr connected = ASYNC_AWAIT(ConnectStream( + InetAddress("127.0.0.1", port), std::chrono::seconds(2), client_ctx)); if (!connected.ok()) { status = connected.status(); - return; + ASYNC_RETURN; } ByteStream client(std::move(*connected)); const std::string payload(100000, 'q'); - if (absl::Status s = client.SendAll(payload.data(), payload.size(), - client_ctx); + if (absl::Status s = ASYNC_AWAIT( + client.SendAll(payload.data(), payload.size(), client_ctx)); !s.ok()) { status = s; } }); - absl::StatusOr accepted = listener->Accept(ctx); + absl::StatusOr accepted = ASYNC_AWAIT(listener->Accept(ctx)); if (!accepted.ok()) { status = accepted.status(); - return; + ASYNC_RETURN; } ByteStream server(std::move(*accepted)); if (absl::Status s = server.SetNonBlocking(); !s.ok()) { status = s; - return; + ASYNC_RETURN; } received.resize(100000); - status = server.ReadFully(received.data(), received.size(), ctx); + status = ASYNC_AWAIT( + server.ReadFully(received.data(), received.size(), ctx)); }); fx.Run(); @@ -106,67 +114,69 @@ TEST(ByteStream, MutualTlsExchangesBothWays) { std::string from_server; absl::Status status = absl::OkStatus(); - fx.runtime.Spawn([&](Context ctx) { + fx.runtime.Spawn([&](Context ctx) -> Task { absl::StatusOr listener = ListenStream(InetAddress("127.0.0.1", 0)); if (!listener.ok()) { status = listener.status(); - return; + ASYNC_RETURN; } const int port = listener->BoundAddress().Port(); - fx.runtime.Spawn([&, port](Context client_ctx) { - absl::StatusOr connected = ConnectStream( - InetAddress("127.0.0.1", port), std::chrono::seconds(2), client_ctx); + fx.runtime.Spawn([&, port](Context client_ctx) -> Task { + absl::StatusOr connected = ASYNC_AWAIT(ConnectStream( + InetAddress("127.0.0.1", port), std::chrono::seconds(2), client_ctx)); if (!connected.ok()) { status = connected.status(); - return; + ASYNC_RETURN; } ByteStream client(std::move(*connected)); - if (absl::Status s = client.HandshakeTls(*alpha, /*server_role=*/false, - client_ctx, - std::chrono::seconds(2)); + if (absl::Status s = ASYNC_AWAIT( + client.HandshakeTls(*alpha, /*server_role=*/false, client_ctx, + std::chrono::seconds(2))); !s.ok()) { status = s; - return; + ASYNC_RETURN; } char storage[64] = {}; const std::string payload = "client-to-server"; memcpy(storage + sizeof(int32_t), payload.data(), payload.size()); - if (absl::StatusOr n = client.SendMessage( - storage + sizeof(int32_t), payload.size(), client_ctx); + if (absl::StatusOr n = ASYNC_AWAIT(client.SendMessage( + storage + sizeof(int32_t), payload.size(), client_ctx)); !n.ok()) { status = n.status(); - return; + ASYNC_RETURN; } char reply[32]; if (absl::Status s = - client.ReadFully(reply, 12, client_ctx); !s.ok()) { + ASYNC_AWAIT(client.ReadFully(reply, 12, client_ctx)); + !s.ok()) { status = s; - return; + ASYNC_RETURN; } from_server.assign(reply, 12); }); - absl::StatusOr accepted = listener->Accept(ctx); + absl::StatusOr accepted = ASYNC_AWAIT(listener->Accept(ctx)); if (!accepted.ok()) { status = accepted.status(); - return; + ASYNC_RETURN; } ByteStream server(std::move(*accepted)); - if (absl::Status s = server.HandshakeTls(*beta, /*server_role=*/true, ctx, - std::chrono::seconds(2)); + if (absl::Status s = ASYNC_AWAIT(server.HandshakeTls( + *beta, /*server_role=*/true, ctx, std::chrono::seconds(2))); !s.ok()) { status = s; - return; + ASYNC_RETURN; } char buffer[64]; - absl::StatusOr n = server.ReceiveMessage(buffer, sizeof(buffer), ctx); + absl::StatusOr n = + ASYNC_AWAIT(server.ReceiveMessage(buffer, sizeof(buffer), ctx)); if (!n.ok()) { status = n.status(); - return; + ASYNC_RETURN; } from_client.assign(buffer, static_cast(*n)); - status = server.SendAll("server-reply", 12, ctx); + status = ASYNC_AWAIT(server.SendAll("server-reply", 12, ctx)); }); fx.Run(); @@ -189,33 +199,34 @@ TEST(ByteStream, RejectsACertificateFromAnotherCa) { absl::Status client_status = absl::OkStatus(); absl::Status server_status = absl::OkStatus(); - fx.runtime.Spawn([&](Context ctx) { + fx.runtime.Spawn([&](Context ctx) -> Task { absl::StatusOr listener = ListenStream(InetAddress("127.0.0.1", 0)); if (!listener.ok()) { server_status = listener.status(); - return; + ASYNC_RETURN; } const int port = listener->BoundAddress().Port(); - fx.runtime.Spawn([&, port](Context client_ctx) { - absl::StatusOr connected = ConnectStream( - InetAddress("127.0.0.1", port), std::chrono::seconds(2), client_ctx); + fx.runtime.Spawn([&, port](Context client_ctx) -> Task { + absl::StatusOr connected = ASYNC_AWAIT(ConnectStream( + InetAddress("127.0.0.1", port), std::chrono::seconds(2), client_ctx)); if (!connected.ok()) { client_status = connected.status(); - return; + ASYNC_RETURN; } ByteStream client(std::move(*connected)); - client_status = client.HandshakeTls(*stranger, /*server_role=*/false, - client_ctx, std::chrono::seconds(2)); + client_status = ASYNC_AWAIT(client.HandshakeTls( + *stranger, /*server_role=*/false, client_ctx, + std::chrono::seconds(2))); }); - absl::StatusOr accepted = listener->Accept(ctx); + absl::StatusOr accepted = ASYNC_AWAIT(listener->Accept(ctx)); if (!accepted.ok()) { server_status = accepted.status(); - return; + ASYNC_RETURN; } ByteStream server(std::move(*accepted)); - server_status = server.HandshakeTls(*trusted, /*server_role=*/true, ctx, - std::chrono::seconds(2)); + server_status = ASYNC_AWAIT(server.HandshakeTls( + *trusted, /*server_role=*/true, ctx, std::chrono::seconds(2))); }); fx.Run(); diff --git a/common/async/runtime.h b/common/async/runtime.h index d223a341..39bdb7ea 100644 --- a/common/async/runtime.h +++ b/common/async/runtime.h @@ -7,6 +7,7 @@ #define _COMMON_ASYNC_RUNTIME_H #include "common/async/context.h" +#include "common/async/task.h" #include "common/coroutine_stack.h" #include #include @@ -28,20 +29,30 @@ #include #include #include +#elif SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 +#include +#include #endif namespace subspace::async { // The execution engine an embedder provides to a Server (and to AsyncRuntime). // Under the co backend this is a co::CoroutineScheduler; under Asio it is a -// boost::asio::io_context. Exposed so callers (and tests) can declare an -// engine variable in a backend-agnostic way and pass it to the Server. +// boost::asio::io_context; under co20 it is a co20::Scheduler. Exposed so +// callers (and tests) can declare an engine variable in a backend-agnostic way +// and pass it to the Server. #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO using RuntimeEngine = boost::asio::io_context; +#elif SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 +using RuntimeEngine = co20::Scheduler; #else using RuntimeEngine = co::CoroutineScheduler; #endif +// The function a coroutine runs. Under co20 it is itself a coroutine +// returning a task (see task.h). +using CoroutineFunction = std::function(Context)>; + // Options that mirror the subset of co::CoroutineOptions the server uses when // spawning coroutines. Under Asio `interrupt_fd` and `name` are advisory (Asio // uses cancellation rather than an interrupt fd), but they are kept so the same @@ -306,6 +317,77 @@ class AsyncRuntime { // Drives the periodic re-emit of cancellations during graceful shutdown. std::unique_ptr reemit_timer_; +#elif SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + explicit AsyncRuntime(co20::Scheduler &scheduler) + : scheduler_(scheduler), + live_(std::make_shared>()) {} + + co20::Scheduler &scheduler() { return scheduler_; } + + // Spawn a C++20 coroutine running `fn(ctx)`. Like the co backend, a wait + // in it ends with CancelledError once `opts.interrupt_fd` is readable. + void Spawn(CoroutineFunction fn, SpawnOptions opts = {}) { + auto it = live_->emplace(live_->end(), opts.name); + // The scheduler keeps this callable, and so `fn`, alive until the + // coroutine is freed. The list is shared so a coroutine that outlives + // the runtime can still remove itself. + scheduler_.Spawn( + [fn = std::move(fn), live = live_, + it](co20::Coroutine &c) -> co20::Task { + // Lives in the coroutine frame, so the name is also removed if the + // frame is destroyed before `fn` finishes. + LiveEntry entry(live, it); + co_await fn(Context(&c)); + }, + opts.name, opts.interrupt_fd); + } + + // The co20 scheduler is single-threaded, so there are no strands: these + // behave like the co backend's. + void SpawnOnStrand(CoroutineFunction fn, SpawnOptions opts = {}) { + Spawn(std::move(fn), std::move(opts)); + } + void RunOnStrand(std::function fn) { fn(); } + void SpawnOnNewStrand(CoroutineFunction fn, SpawnOptions opts = {}) { + Spawn(std::move(fn), std::move(opts)); + } + void SpawnOnCurrentStrand(Context /*ctx*/, CoroutineFunction fn, + SpawnOptions opts = {}) { + Spawn(std::move(fn), std::move(opts)); + } + + // The co20 scheduler is single-threaded; num_threads is ignored. + void Run(int /*num_threads*/ = 1) { scheduler_.Run(); } + void Stop() { scheduler_.Stop(); } + // Graceful shutdown goes through per-coroutine interrupt fds, as with co. + void StopGracefully() { scheduler_.Stop(); } + // co20 has no aborts. + void EnableAborts(bool) {} + // The names of the live coroutines spawned through this runtime. + std::vector AllCoroutineStrings() const { + return std::vector(live_->begin(), live_->end()); + } + +private: + using LiveList = std::list; + + // Removes a coroutine's name from the live list when destroyed. + class LiveEntry { + public: + LiveEntry(std::shared_ptr list, LiveList::iterator it) + : list_(std::move(list)), it_(it) {} + LiveEntry(const LiveEntry &) = delete; + LiveEntry &operator=(const LiveEntry &) = delete; + ~LiveEntry() { list_->erase(it_); } + + private: + std::shared_ptr list_; + LiveList::iterator it_; + }; + + co20::Scheduler &scheduler_; + std::shared_ptr live_; + #else // SUBSPACE_CORO_BACKEND_CO explicit AsyncRuntime(co::CoroutineScheduler &scheduler) : scheduler_(scheduler) {} diff --git a/common/async/socket.cc b/common/async/socket.cc index 45840c12..cd94ec68 100644 --- a/common/async/socket.cc +++ b/common/async/socket.cc @@ -6,9 +6,11 @@ #include "common/async/socket.h" -#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO || \ + SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 #include "absl/strings/str_format.h" +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO #include #include #include @@ -16,6 +18,9 @@ #include #include #include +#else +#include "common/async/wait.h" +#endif #include #include @@ -35,6 +40,8 @@ namespace { constexpr bool kSocketDebugEnabled = false; +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO + boost::asio::io_context &IocFromYield(Context yield) { return static_cast( yield.get_executor().context()); @@ -163,6 +170,18 @@ absl::Status WaitFdWritable(Context yield, int fd) { "wait_write"); } +#else // SUBSPACE_CORO_BACKEND_CO20 + +Task WaitFdReadable(Context ctx, int fd) { + return WaitReadable(ctx, fd); +} + +Task WaitFdWritable(Context ctx, int fd) { + return WaitWritable(ctx, fd); +} + +#endif + // Fill a sockaddr_storage from a SocketAddress. Returns the length. absl::StatusOr AddrToSockaddr(const SocketAddress &addr, sockaddr_storage *out, int *family) { @@ -289,28 +308,31 @@ absl::Status StreamSocket::Connect(const SocketAddress &addr) { return absl::OkStatus(); } -absl::StatusOr StreamSocket::Accept(Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("Accept on unbound socket"); +Task> StreamSocket::Accept(Context ctx) { + // Held across waits so a concurrent Close() can't free the fd under us. + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError("Accept on unbound socket"); } for (;;) { sockaddr_storage ss; socklen_t slen = sizeof(ss); - int newfd = ::accept(impl_->fd, reinterpret_cast(&ss), &slen); + int newfd = ::accept(impl->fd, reinterpret_cast(&ss), &slen); if (newfd >= 0) { SetFdNonBlocking(newfd); auto new_impl = std::make_shared(); new_impl->fd = newfd; new_impl->nonblocking = true; - return MakeConnectedStreamSocket(std::move(new_impl)); + ASYNC_RETURN MakeConnectedStreamSocket(std::move(new_impl)); } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - if (absl::Status s = WaitFdReadable(ctx, impl_->fd); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(WaitFdReadable(ctx, impl->fd)); + !s.ok()) { + ASYNC_RETURN s; } continue; } - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("accept() failed: %s", strerror(errno))); } } @@ -328,14 +350,15 @@ absl::Status StreamSocket::SetNonBlocking() { return absl::OkStatus(); } -absl::StatusOr StreamSocket::Send(const char *buffer, size_t length, - Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("Send on closed socket"); +Task> StreamSocket::Send(const char *buffer, + size_t length, Context ctx) { + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError("Send on closed socket"); } size_t sent = 0; while (sent < length) { - ssize_t n = ::send(impl_->fd, buffer + sent, length - sent, MSG_NOSIGNAL); + ssize_t n = ::send(impl->fd, buffer + sent, length - sent, MSG_NOSIGNAL); if (n > 0) { sent += static_cast(n); continue; @@ -344,42 +367,45 @@ absl::StatusOr StreamSocket::Send(const char *buffer, size_t length, break; } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - if (absl::Status s = WaitFdWritable(ctx, impl_->fd); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(WaitFdWritable(ctx, impl->fd)); + !s.ok()) { + ASYNC_RETURN s; } continue; } - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("send() failed: %s", strerror(errno))); } - return static_cast(sent); + ASYNC_RETURN static_cast(sent); } -absl::StatusOr StreamSocket::Receive(char *buffer, size_t buflen, - Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("Receive on closed socket"); +Task> StreamSocket::Receive(char *buffer, size_t buflen, + Context ctx) { + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError("Receive on closed socket"); } for (;;) { - ssize_t n = ::recv(impl_->fd, buffer, buflen, 0); + ssize_t n = ::recv(impl->fd, buffer, buflen, 0); if (n >= 0) { - return n; + ASYNC_RETURN n; } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - if (absl::Status s = WaitFdReadable(ctx, impl_->fd); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(WaitFdReadable(ctx, impl->fd)); + !s.ok()) { + ASYNC_RETURN s; } continue; } - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("recv() failed: %s", strerror(errno))); } } // Read exactly `n` bytes (yielding as needed). Returns the number read, which // is < n only on EOF. -static absl::StatusOr ReadExactly(int fd, Context ctx, char *buffer, - size_t n) { +static Task> ReadExactly(int fd, Context ctx, + char *buffer, size_t n) { size_t got = 0; while (got < n) { ssize_t r = ::recv(fd, buffer + got, n - got, 0); @@ -388,65 +414,70 @@ static absl::StatusOr ReadExactly(int fd, Context ctx, char *buffer, continue; } if (r == 0) { - return got; // EOF + ASYNC_RETURN got; // EOF } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - if (absl::Status s = WaitFdReadable(ctx, fd); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(WaitFdReadable(ctx, fd)); !s.ok()) { + ASYNC_RETURN s; } continue; } - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("recv() failed: %s", strerror(errno))); } - return got; + ASYNC_RETURN got; } -absl::StatusOr StreamSocket::SendMessage(char *buffer, size_t length, - Context ctx) { +Task> +StreamSocket::SendMessage(char *buffer, size_t length, Context ctx) { // toolbelt convention: write the 4-byte big-endian length immediately before // `buffer` and send length+4 bytes from buffer-4 in one logical message. char *start = buffer - sizeof(int32_t); uint32_t net_len = htonl(static_cast(length)); std::memcpy(start, &net_len, sizeof(net_len)); - absl::StatusOr n = Send(start, length + sizeof(int32_t), ctx); + absl::StatusOr n = + ASYNC_AWAIT(Send(start, length + sizeof(int32_t), ctx)); if (!n.ok()) { - return n.status(); + ASYNC_RETURN n.status(); } - return static_cast(length); + ASYNC_RETURN static_cast(length); } -absl::StatusOr StreamSocket::ReceiveMessage(char *buffer, size_t buflen, - Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("ReceiveMessage on closed socket"); +Task> +StreamSocket::ReceiveMessage(char *buffer, size_t buflen, Context ctx) { + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError( + "ReceiveMessage on closed socket"); } char lenbuf[sizeof(int32_t)]; - absl::StatusOr got = ReadExactly(impl_->fd, ctx, lenbuf, sizeof(lenbuf)); + absl::StatusOr got = + ASYNC_AWAIT(ReadExactly(impl->fd, ctx, lenbuf, sizeof(lenbuf))); if (!got.ok()) { - return got.status(); + ASYNC_RETURN got.status(); } if (*got == 0) { - return static_cast(0); // clean EOF + ASYNC_RETURN static_cast(0); // clean EOF } if (*got < sizeof(lenbuf)) { - return absl::InternalError("short read on message length"); + ASYNC_RETURN absl::InternalError("short read on message length"); } uint32_t net_len; std::memcpy(&net_len, lenbuf, sizeof(net_len)); size_t length = ntohl(net_len); if (length > buflen) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "message length %zu exceeds buffer size %zu", length, buflen)); } - absl::StatusOr payload = ReadExactly(impl_->fd, ctx, buffer, length); + absl::StatusOr payload = + ASYNC_AWAIT(ReadExactly(impl->fd, ctx, buffer, length)); if (!payload.ok()) { - return payload.status(); + ASYNC_RETURN payload.status(); } if (*payload < length) { - return absl::InternalError("EOF in the middle of a message"); + ASYNC_RETURN absl::InternalError("EOF in the middle of a message"); } - return static_cast(length); + ASYNC_RETURN static_cast(length); } absl::StatusOr StreamSocket::GetPeerName() const { @@ -536,50 +567,58 @@ absl::Status UDPSocket::SetBroadcast() { return absl::OkStatus(); } -absl::Status UDPSocket::SendTo(const InetAddress &addr, const void *buffer, - size_t length, Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("SendTo on closed socket"); +Task UDPSocket::SendTo(const InetAddress &addr, + const void *buffer, size_t length, + Context ctx) { + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError("SendTo on closed socket"); } - const sockaddr_in &sa = addr.GetAddress(); + // Copied because the caller's address need not outlive a suspension. + const sockaddr_in sa = addr.GetAddress(); for (;;) { - ssize_t n = ::sendto(impl_->fd, buffer, length, 0, + ssize_t n = ::sendto(impl->fd, buffer, length, 0, reinterpret_cast(&sa), sizeof(sa)); if (n >= 0) { - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - if (absl::Status s = WaitFdWritable(ctx, impl_->fd); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(WaitFdWritable(ctx, impl->fd)); + !s.ok()) { + ASYNC_RETURN s; } continue; } - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("sendto() failed: %s", strerror(errno))); } } -absl::StatusOr UDPSocket::ReceiveFrom(InetAddress &sender, void *buffer, - size_t buflen, Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("ReceiveFrom on closed socket"); +Task> UDPSocket::ReceiveFrom(InetAddress &sender, + void *buffer, + size_t buflen, + Context ctx) { + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError("ReceiveFrom on closed socket"); } for (;;) { sockaddr_in from; socklen_t flen = sizeof(from); - ssize_t n = ::recvfrom(impl_->fd, buffer, buflen, 0, - reinterpret_cast(&from), &flen); + ssize_t n = ::recvfrom(impl->fd, buffer, buflen, 0, + reinterpret_cast(&from), &flen); if (n >= 0) { sender = InetAddress(from); - return n; + ASYNC_RETURN n; } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - if (absl::Status s = WaitFdReadable(ctx, impl_->fd); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(WaitFdReadable(ctx, impl->fd)); + !s.ok()) { + ASYNC_RETURN s; } continue; } - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("recvfrom() failed: %s", strerror(errno))); } } @@ -609,8 +648,8 @@ struct sockaddr_un BuildUnixSocketName(const std::string &pathname) { } // Send `length` bytes from `buffer`, yielding the coroutine on EAGAIN. -absl::StatusOr SendAll(int fd, Context ctx, const char *buffer, - size_t length) { +Task> SendAll(int fd, Context ctx, const char *buffer, + size_t length) { size_t sent = 0; while (sent < length) { ssize_t n = ::send(fd, buffer + sent, length - sent, MSG_NOSIGNAL); @@ -622,15 +661,15 @@ absl::StatusOr SendAll(int fd, Context ctx, const char *buffer, break; } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - if (absl::Status s = WaitFdWritable(ctx, fd); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(WaitFdWritable(ctx, fd)); !s.ok()) { + ASYNC_RETURN s; } continue; } - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("send() failed: %s", strerror(errno))); } - return static_cast(sent); + ASYNC_RETURN static_cast(sent); } } // namespace @@ -708,121 +747,134 @@ absl::Status UnixSocket::Connect(const std::string &pathname) { return absl::OkStatus(); } -absl::StatusOr UnixSocket::Accept(Context ctx) const { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("Accept on invalid unix socket"); +Task> UnixSocket::Accept(Context ctx) const { + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError( + "Accept on invalid unix socket"); } for (;;) { struct sockaddr_un sender; socklen_t slen = sizeof(sender); int newfd = - ::accept(impl_->fd, reinterpret_cast(&sender), &slen); + ::accept(impl->fd, reinterpret_cast(&sender), &slen); if (newfd >= 0) { - return UnixSocket(newfd, /*connected=*/true); + ASYNC_RETURN UnixSocket(newfd, /*connected=*/true); } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - if (absl::Status s = WaitFdReadable(ctx, impl_->fd); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(WaitFdReadable(ctx, impl->fd)); + !s.ok()) { + ASYNC_RETURN s; } continue; } - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("accept() failed: %s", strerror(errno))); } } -absl::StatusOr UnixSocket::Send(const char *buffer, size_t length, - Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("Send on closed socket"); +Task> UnixSocket::Send(const char *buffer, + size_t length, Context ctx) { + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError("Send on closed socket"); } - return SendAll(impl_->fd, ctx, buffer, length); + ASYNC_RETURN ASYNC_AWAIT(SendAll(impl->fd, ctx, buffer, length)); } -absl::StatusOr UnixSocket::Receive(char *buffer, size_t buflen, - Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("Receive on closed socket"); +Task> UnixSocket::Receive(char *buffer, size_t buflen, + Context ctx) { + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError("Receive on closed socket"); } for (;;) { - ssize_t n = ::recv(impl_->fd, buffer, buflen, 0); + ssize_t n = ::recv(impl->fd, buffer, buflen, 0); if (n >= 0) { - return n; + ASYNC_RETURN n; } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - if (absl::Status s = WaitFdReadable(ctx, impl_->fd); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(WaitFdReadable(ctx, impl->fd)); + !s.ok()) { + ASYNC_RETURN s; } continue; } - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("recv() failed: %s", strerror(errno))); } } -absl::StatusOr UnixSocket::SendMessage(char *buffer, size_t length, - Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("SendMessage on closed socket"); +Task> UnixSocket::SendMessage(char *buffer, + size_t length, + Context ctx) { + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError("SendMessage on closed socket"); } char *start = buffer - sizeof(int32_t); uint32_t net_len = htonl(static_cast(length)); std::memcpy(start, &net_len, sizeof(net_len)); - absl::StatusOr n = SendAll(impl_->fd, ctx, start, - length + sizeof(int32_t)); + absl::StatusOr n = ASYNC_AWAIT( + SendAll(impl->fd, ctx, start, length + sizeof(int32_t))); if (!n.ok()) { - return n.status(); + ASYNC_RETURN n.status(); } - return static_cast(length); + ASYNC_RETURN static_cast(length); } -absl::StatusOr UnixSocket::ReceiveMessage(char *buffer, size_t buflen, - Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("ReceiveMessage on closed socket"); +Task> UnixSocket::ReceiveMessage(char *buffer, + size_t buflen, + Context ctx) { + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError( + "ReceiveMessage on closed socket"); } char lenbuf[sizeof(int32_t)]; absl::StatusOr got = - ReadExactly(impl_->fd, ctx, lenbuf, sizeof(lenbuf)); + ASYNC_AWAIT(ReadExactly(impl->fd, ctx, lenbuf, sizeof(lenbuf))); if (!got.ok()) { - return got.status(); + ASYNC_RETURN got.status(); } if (*got == 0) { - return static_cast(0); + ASYNC_RETURN static_cast(0); } if (*got < sizeof(lenbuf)) { - return absl::InternalError("short read on message length"); + ASYNC_RETURN absl::InternalError("short read on message length"); } uint32_t net_len; std::memcpy(&net_len, lenbuf, sizeof(net_len)); size_t length = ntohl(net_len); if (length > buflen) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "message length %zu exceeds buffer size %zu", length, buflen)); } - absl::StatusOr payload = ReadExactly(impl_->fd, ctx, buffer, length); + absl::StatusOr payload = + ASYNC_AWAIT(ReadExactly(impl->fd, ctx, buffer, length)); if (!payload.ok()) { - return payload.status(); + ASYNC_RETURN payload.status(); } if (*payload < length) { - return absl::InternalError("EOF in the middle of a message"); + ASYNC_RETURN absl::InternalError("EOF in the middle of a message"); } - return static_cast(length); + ASYNC_RETURN static_cast(length); } -absl::StatusOr> +Task>> UnixSocket::ReceiveVariableLengthMessage(Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("Receive on closed socket"); + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError("Receive on closed socket"); } char lenbuf[sizeof(int32_t)]; absl::StatusOr got = - ReadExactly(impl_->fd, ctx, lenbuf, sizeof(lenbuf)); + ASYNC_AWAIT(ReadExactly(impl->fd, ctx, lenbuf, sizeof(lenbuf))); if (!got.ok()) { - return got.status(); + ASYNC_RETURN got.status(); } if (*got < sizeof(lenbuf)) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("Failed to read length from socket: socket closed")); } uint32_t net_len; @@ -830,21 +882,22 @@ UnixSocket::ReceiveVariableLengthMessage(Context ctx) { size_t length = ntohl(net_len); std::vector buffer(length); absl::StatusOr payload = - ReadExactly(impl_->fd, ctx, buffer.data(), buffer.size()); + ASYNC_AWAIT(ReadExactly(impl->fd, ctx, buffer.data(), buffer.size())); if (!payload.ok()) { - return payload.status(); + ASYNC_RETURN payload.status(); } if (*payload < length) { - return absl::InternalError("EOF in the middle of a message"); + ASYNC_RETURN absl::InternalError("EOF in the middle of a message"); } - return buffer; + ASYNC_RETURN std::move(buffer); } -absl::Status +Task UnixSocket::SendFds(const std::vector &fds, Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("SendFds on closed socket"); + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError("SendFds on closed socket"); } constexpr size_t kMaxFds = 252; std::vector control_buf(CMSG_SPACE(kMaxFds * sizeof(int))); @@ -863,7 +916,7 @@ UnixSocket::SendFds(const std::vector &fds, fprintf(stderr, "SUBSPACE_SHM_DEBUG: SendFds socket=%d total=%zu first=%zu " "count=%zu values=", - impl_->fd, fds.size(), first_fd, fds_to_send); + impl->fd, fds.size(), first_fd, fds_to_send); for (size_t i = first_fd; i < first_fd + fds_to_send; i++) { fprintf(stderr, "%s%d", i == first_fd ? "" : ",", fds[i].Fd()); } @@ -883,29 +936,32 @@ UnixSocket::SendFds(const std::vector &fds, *fdptr++ = fds[i].Fd(); } for (;;) { - ssize_t e = ::sendmsg(impl_->fd, &msg, MSG_NOSIGNAL); + ssize_t e = ::sendmsg(impl->fd, &msg, MSG_NOSIGNAL); if (e >= 0) { break; } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - if (absl::Status s = WaitFdWritable(ctx, impl_->fd); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(WaitFdWritable(ctx, impl->fd)); + !s.ok()) { + ASYNC_RETURN s; } continue; } - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "Failed to write fds to unix socket: %s", strerror(errno))); } remaining_fds -= fds_to_send; first_fd += fds_to_send; } while (remaining_fds > 0); - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::Status UnixSocket::ReceiveFds(std::vector &fds, - Context ctx) { - if (impl_ == nullptr || impl_->fd < 0) { - return absl::FailedPreconditionError("ReceiveFds on closed socket"); +Task +UnixSocket::ReceiveFds(std::vector &fds, + Context ctx) { + std::shared_ptr impl = impl_; + if (impl == nullptr || impl->fd < 0) { + ASYNC_RETURN absl::FailedPreconditionError("ReceiveFds on closed socket"); } constexpr size_t kMaxFds = 252; std::vector control_buf(CMSG_SPACE(kMaxFds * sizeof(int))); @@ -924,31 +980,32 @@ absl::Status UnixSocket::ReceiveFds(std::vector &fds, ssize_t n; for (;;) { - n = ::recvmsg(impl_->fd, &msg, 0); + n = ::recvmsg(impl->fd, &msg, 0); if (n >= 0) { break; } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - if (absl::Status s = WaitFdReadable(ctx, impl_->fd); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(WaitFdReadable(ctx, impl->fd)); + !s.ok()) { + ASYNC_RETURN s; } continue; } - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "Failed to read fds from unix socket: %s", strerror(errno))); } if (n == 0) { - return absl::InternalError("EOF from socket while reading fds"); + ASYNC_RETURN absl::InternalError("EOF from socket while reading fds"); } if constexpr (kSocketDebugEnabled) { fprintf(stderr, "SUBSPACE_SHM_DEBUG: ReceiveFds socket=%d n=%zd total_fds=%d " "msg_flags=0x%x msg_controllen=%zu\n", - impl_->fd, n, total_fds, msg.msg_flags, + impl->fd, n, total_fds, msg.msg_flags, static_cast(msg.msg_controllen)); } if ((msg.msg_flags & MSG_CTRUNC) != 0) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( "Control data was truncated while reading fds from unix socket"); } @@ -967,7 +1024,7 @@ absl::Status UnixSocket::ReceiveFds(std::vector &fds, } saw_rights = true; if (cmsg->cmsg_len < CMSG_LEN(0)) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "Invalid SCM_RIGHTS control length %zu while reading fds", static_cast(cmsg->cmsg_len))); } @@ -979,7 +1036,7 @@ absl::Status UnixSocket::ReceiveFds(std::vector &fds, static_cast(cmsg->cmsg_len), data_len); } if (data_len % sizeof(int) != 0) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "Misaligned SCM_RIGHTS control length %zu while reading fds", static_cast(cmsg->cmsg_len))); } @@ -995,7 +1052,7 @@ absl::Status UnixSocket::ReceiveFds(std::vector &fds, num_fds_received += num_fds; } if (!saw_rights && total_fds > 0) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "Expected %d fds from unix socket but received no SCM_RIGHTS message", total_fds)); } @@ -1003,7 +1060,7 @@ absl::Status UnixSocket::ReceiveFds(std::vector &fds, break; } } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } absl::Status UnixSocket::SetNonBlocking() { @@ -1046,7 +1103,7 @@ void UnixSocket::Close() { } // namespace subspace::async -#endif // SUBSPACE_CORO_BACKEND_ASIO +#endif // SUBSPACE_CORO_BACKEND_ASIO || SUBSPACE_CORO_BACKEND_CO20 #include "absl/strings/str_format.h" #include "common/async/wait.h" @@ -1092,32 +1149,34 @@ absl::Status SetFdFlags(int fd, bool nonblocking) { return absl::OkStatus(); } -absl::StatusOr ConnectTcpFd(const InetAddress &addr, - std::chrono::nanoseconds timeout, - Context ctx) { +// Takes `addr` by value because it is used after the wait. +Task> ConnectTcpFd(InetAddress addr, + std::chrono::nanoseconds timeout, + Context ctx) { FdCloser fd{::socket(AF_INET, SOCK_STREAM, 0)}; if (fd.fd < 0) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("socket() failed: %s", strerror(errno))); } if (absl::Status s = SetFdFlags(fd.fd, /*nonblocking=*/true); !s.ok()) { - return s; + ASYNC_RETURN s; } const sockaddr_in &sa = addr.GetAddress(); if (::connect(fd.fd, reinterpret_cast(&sa), sizeof(sa)) == 0) { - return fd.Release(); + ASYNC_RETURN fd.Release(); } if (errno != EINPROGRESS && errno != EINTR) { - return absl::UnavailableError(absl::StrFormat( + ASYNC_RETURN absl::UnavailableError(absl::StrFormat( "connect to %s failed: %s", addr.ToString(), strerror(errno))); } - if (absl::Status s = WaitWritable(ctx, fd.fd, timeout); !s.ok()) { + if (absl::Status s = ASYNC_AWAIT(WaitWritable(ctx, fd.fd, timeout)); + !s.ok()) { if (absl::IsDeadlineExceeded(s)) { - return absl::DeadlineExceededError( + ASYNC_RETURN absl::DeadlineExceededError( absl::StrFormat("timed out connecting to %s", addr.ToString())); } - return s; + ASYNC_RETURN s; } int err = 0; socklen_t len = sizeof(err); @@ -1125,24 +1184,25 @@ absl::StatusOr ConnectTcpFd(const InetAddress &addr, err = errno; } if (err != 0) { - return absl::UnavailableError(absl::StrFormat( + ASYNC_RETURN absl::UnavailableError(absl::StrFormat( "connect to %s failed: %s", addr.ToString(), strerror(err))); } - return fd.Release(); + ASYNC_RETURN fd.Release(); } } // namespace -#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO || \ + SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 -absl::StatusOr ConnectStream(const InetAddress &addr, - std::chrono::nanoseconds timeout, - Context ctx) { - absl::StatusOr fd = ConnectTcpFd(addr, timeout, ctx); +Task> +ConnectStream(const InetAddress &addr, std::chrono::nanoseconds timeout, + Context ctx) { + absl::StatusOr fd = ASYNC_AWAIT(ConnectTcpFd(addr, timeout, ctx)); if (!fd.ok()) { - return fd.status(); + ASYNC_RETURN fd.status(); } - return StreamSocket::Adopt(*fd); + ASYNC_RETURN StreamSocket::Adopt(*fd); } absl::StatusOr ListenStream(const InetAddress &addr) { diff --git a/common/async/socket.h b/common/async/socket.h index fbb4e8f1..7460b303 100644 --- a/common/async/socket.h +++ b/common/async/socket.h @@ -10,12 +10,13 @@ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/async/context.h" +#include "common/async/task.h" #include "toolbelt/sockets.h" #include // Networking facade used by the server's discovery and bridging paths. The // address types (InetAddress / VirtualAddress / SocketAddress) are pure value -// holders and are shared by both backends, so they are re-exported from +// holders and are shared by all backends, so they are re-exported from // toolbelt unchanged. The socket types differ: // // co backend: StreamSocket/UDPSocket/UnixSocket are thin aliases over the @@ -24,12 +25,14 @@ // call sites pass the Context straight through and behavior is // identical to the pre-existing code. // -// asio backend: StreamSocket/UDPSocket are real wrappers over Boost.Asio. -// TCP and vsock share a single code path via -// boost::asio::generic::stream_protocol with a sockaddr_vm -// endpoint for vsock (Asio has no native vsock type). The -// length-delimited framing of SendMessage/ReceiveMessage -// matches toolbelt exactly so the wire format is unchanged. +// asio and co20 backends: StreamSocket/UDPSocket/UnixSocket are wrappers +// over non-blocking raw fds that wait through the backend +// when an operation would block. TCP and vsock share a +// single code path. The length-delimited framing of +// SendMessage/ReceiveMessage and the fd protocol of +// SendFds/ReceiveFds match toolbelt exactly, so the wire +// format is unchanged. Under co20 the methods that wait +// return tasks (see task.h); a null Context blocks the thread. namespace subspace::async { @@ -39,21 +42,25 @@ using SocketAddress = toolbelt::SocketAddress; } // namespace subspace::async -#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO || \ + SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 #include "toolbelt/fd.h" +#include +#include +#include + +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO #include #include #include #include -#include -#include -#include +#endif namespace subspace::async { -// A stream socket (TCP, vsock or Unix-stream) over Boost.Asio. Mirrors the -// subset of toolbelt::StreamSocket the server uses. +// A stream socket (TCP or vsock) over a raw fd. Mirrors the subset of +// toolbelt::StreamSocket the server uses. class StreamSocket { public: StreamSocket() = default; @@ -69,22 +76,25 @@ class StreamSocket { absl::Status Connect(const SocketAddress &addr); // Accept an incoming connection, yielding the coroutine until one arrives. - absl::StatusOr Accept(Context ctx); + Task> Accept(Context ctx); absl::Status SetNonBlocking(); // Raw send/receive. - absl::StatusOr Send(const char *buffer, size_t length, Context ctx); - absl::StatusOr Receive(char *buffer, size_t buflen, Context ctx); + Task> Send(const char *buffer, size_t length, + Context ctx); + Task> Receive(char *buffer, size_t buflen, + Context ctx); // Length-delimited message framing identical to toolbelt: SendMessage writes // a 4-byte big-endian length immediately before `buffer` (so `buffer` must // point 4 bytes into a length+4 region), then the payload. ReceiveMessage // reads the 4-byte length then that many payload bytes and returns the // payload length (0 on clean EOF). - absl::StatusOr SendMessage(char *buffer, size_t length, Context ctx); - absl::StatusOr ReceiveMessage(char *buffer, size_t buflen, - Context ctx); + Task> SendMessage(char *buffer, size_t length, + Context ctx); + Task> ReceiveMessage(char *buffer, size_t buflen, + Context ctx); SocketAddress BoundAddress() const { return bound_address_; } absl::StatusOr GetPeerName() const; @@ -107,8 +117,7 @@ class StreamSocket { std::shared_ptr impl); }; -// A UDP socket over Boost.Asio (generic datagram protocol so it can support -// IPv4 today and other families later). +// An IPv4 UDP socket over a raw fd. class UDPSocket { public: UDPSocket() = default; @@ -119,10 +128,10 @@ class UDPSocket { absl::Status Bind(const InetAddress &addr); absl::Status SetBroadcast(); - absl::Status SendTo(const InetAddress &addr, const void *buffer, - size_t length, Context ctx); - absl::StatusOr ReceiveFrom(InetAddress &sender, void *buffer, - size_t buflen, Context ctx); + Task SendTo(const InetAddress &addr, const void *buffer, + size_t length, Context ctx); + Task> ReceiveFrom(InetAddress &sender, void *buffer, + size_t buflen, Context ctx); const InetAddress &BoundAddress() const { return bound_address_; } @@ -132,11 +141,11 @@ class UDPSocket { InetAddress bound_address_; }; -// A Unix-domain stream socket over Boost.Asio with SCM_RIGHTS fd passing. -// Mirrors the subset of toolbelt::UnixSocket the client RPC and the server's -// client handler use, and replicates toolbelt's wire framing exactly (4-byte -// big-endian length prefix for messages; the fd protocol of SendFds/ReceiveFds) -// so an Asio client and a co server (or vice versa) interoperate. +// A Unix-domain stream socket with SCM_RIGHTS fd passing. Mirrors the subset +// of toolbelt::UnixSocket the client RPC and the server's client handler use, +// and replicates toolbelt's wire framing exactly (4-byte big-endian length +// prefix for messages; the fd protocol of SendFds/ReceiveFds) so a client and +// server built with different backends interoperate. class UnixSocket { public: // Like toolbelt::UnixSocket, the default constructor creates the underlying @@ -150,7 +159,7 @@ class UnixSocket { absl::Status Bind(const std::string &pathname, bool listen); absl::Status Connect(const std::string &pathname); - absl::StatusOr Accept(Context ctx) const; + Task> Accept(Context ctx) const; // Put the socket in blocking mode. In blocking mode the underlying fd is // left blocking so socket calls never return EAGAIN and therefore never @@ -160,17 +169,21 @@ class UnixSocket { // called before Connect()/Bind(). void SetBlocking(bool blocking); - absl::StatusOr Send(const char *buffer, size_t length, Context ctx); - absl::StatusOr Receive(char *buffer, size_t buflen, Context ctx); - absl::StatusOr SendMessage(char *buffer, size_t length, Context ctx); - absl::StatusOr ReceiveMessage(char *buffer, size_t buflen, - Context ctx); - absl::StatusOr> ReceiveVariableLengthMessage(Context ctx); - - absl::Status SendFds(const std::vector &fds, - Context ctx); - absl::Status ReceiveFds(std::vector &fds, - Context ctx); + Task> Send(const char *buffer, size_t length, + Context ctx); + Task> Receive(char *buffer, size_t buflen, + Context ctx); + Task> SendMessage(char *buffer, size_t length, + Context ctx); + Task> ReceiveMessage(char *buffer, size_t buflen, + Context ctx); + Task>> + ReceiveVariableLengthMessage(Context ctx); + + Task SendFds(const std::vector &fds, + Context ctx); + Task ReceiveFds(std::vector &fds, + Context ctx); absl::Status SetNonBlocking(); absl::Status SetCloseOnExec(); @@ -207,9 +220,9 @@ namespace subspace::async { // Connects a TCP socket to `addr` without blocking the runtime. A non-zero // timeout returns DeadlineExceededError if the connection isn't made in time; // a zero timeout leaves it to the kernel. The socket is non-blocking. -absl::StatusOr ConnectStream(const InetAddress &addr, - std::chrono::nanoseconds timeout, - Context ctx); +Task> +ConnectStream(const InetAddress &addr, std::chrono::nanoseconds timeout, + Context ctx); // Binds a listening TCP socket to `addr` with SO_REUSEADDR set, so a // restarted server can rebind a fixed port while connections from its diff --git a/common/async/task.h b/common/async/task.h new file mode 100644 index 00000000..fabb4e36 --- /dev/null +++ b/common/async/task.h @@ -0,0 +1,82 @@ +// Copyright 2023-2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#ifndef _COMMON_ASYNC_TASK_H +#define _COMMON_ASYNC_TASK_H + +// Lets a function that waits be written once for every backend. +// +// Under the co and Asio backends a coroutine has its own stack, so a function +// that waits is an ordinary function. Under co20 a coroutine can only suspend +// at a co_await in its own body, so every function between a coroutine and a +// wait has to be a coroutine itself, returning an awaitable task. A function +// written as +// +// async::Task Foo(async::Context ctx) { +// absl::Status s = ASYNC_AWAIT(async::WaitReadable(ctx, fd)); +// ASYNC_RETURN s; +// } +// +// is a plain function returning absl::Status under co and Asio, and a C++20 +// coroutine returning co20::ValueTask under co20. Under co20 a +// Task function must contain at least one ASYNC_AWAIT or ASYNC_RETURN, and +// must use ASYNC_RETURN rather than return. +// +// A Task is lazy: it starts when it is awaited. Arguments are only safe to +// pass by reference when the task is awaited in the same full expression that +// creates it, which ASYNC_AWAIT(Foo(...)) always does. + +#include "common/async/context.h" + +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + +#include +#include +#include +#include + +namespace subspace::async { + +template using Task = co20::ValueTask; + +#define ASYNC_AWAIT(expr) (co_await (expr)) +#define ASYNC_RETURN co_return + +// Runs `task` to completion from code that is not a coroutine. Every wait in +// the task must use a Context that doesn't suspend, so the task never +// suspends and is finished when this returns. +template T SyncWait(Task task) { + // Each co_await of a ValueTask points co20::self's handle at the awaiting + // frame. These frames belong to this call, not to co20::self, so hide it. + co20::Coroutine *self = std::exchange(co20::self, nullptr); + task.handle_.resume(); + co20::self = self; + if (!task.handle_.done()) { + std::fprintf(stderr, "async::SyncWait: task suspended; its Context must " + "not hold a coroutine\n"); + std::abort(); + } + if constexpr (!std::is_void_v) { + return std::move(task.handle_.promise().value_); + } +} + +} // namespace subspace::async + +#else + +namespace subspace::async { + +template using Task = T; + +#define ASYNC_AWAIT(expr) (expr) +#define ASYNC_RETURN return + +template T SyncWait(T value) { return value; } + +} // namespace subspace::async + +#endif + +#endif // _COMMON_ASYNC_TASK_H diff --git a/common/async/wait.cc b/common/async/wait.cc index 6d49efe8..c2f4d84f 100644 --- a/common/async/wait.cc +++ b/common/async/wait.cc @@ -8,6 +8,9 @@ #include +// See context.h. +extern "C" const int SUBSPACE_CORO_BACKEND_LINK_SYMBOL = SUBSPACE_CORO_BACKEND; + #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO #include "absl/strings/str_format.h" @@ -470,6 +473,190 @@ void Sleep(Context ctx, std::chrono::nanoseconds duration) { } // namespace subspace::async +#elif SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + +#include "absl/strings/str_format.h" +#include +#include +#include +#include +#include + +namespace subspace::async { + +namespace { + +using Clock = std::chrono::steady_clock; + +enum class WaitResult { kReady, kTimedOut, kInterrupted, kError }; + +uint64_t ToNanos(std::chrono::nanoseconds d) { + return d.count() <= 0 ? 0 : static_cast(d.count()); +} + +// Classifies the value a co20 wait resumed with. It resumes with the fd that +// became ready, the coroutine's interrupt fd, or the fd of its timeout timer. +// -1 means the scheduler could not watch the fd. +WaitResult FromCo20(const co20::Coroutine &c, const std::vector &fds, + int r, int *ready_fd) { + for (int fd : fds) { + if (r == fd) { + *ready_fd = fd; + return WaitResult::kReady; + } + } + if (r == -1) { + return WaitResult::kError; + } + if (c.GetInterruptFd() != -1 && r == c.GetInterruptFd()) { + return WaitResult::kInterrupted; + } + return WaitResult::kTimedOut; +} + +// Classifies the value an AsyncWaiter wait returned: an fd that became ready, +// -1 on timeout, -2 on a poll error, or the interrupt fd of a co::Coroutine. +WaitResult FromWaiter(const std::vector &fds, int r, bool has_timeout, + int *ready_fd) { + for (int fd : fds) { + if (r == fd) { + *ready_fd = fd; + return WaitResult::kReady; + } + } + if (r == -1 && has_timeout) { + return WaitResult::kTimedOut; + } + if (r == -2) { + return WaitResult::kError; + } + return WaitResult::kInterrupted; +} + +// Blocks the thread in poll() until one of `fds` is ready for `events`. An +// error or hangup counts as ready, so the caller's next read or write reports +// it. +WaitResult PollBlocking(const std::vector &fds, short events, + std::chrono::nanoseconds timeout, int *ready_fd) { + const bool has_timeout = timeout.count() > 0; + const Clock::time_point deadline = + has_timeout ? Clock::now() + timeout : Clock::time_point::max(); + std::vector pfds; + pfds.reserve(fds.size()); + for (int fd : fds) { + pfds.push_back({.fd = fd, .events = events, .revents = 0}); + } + for (;;) { + int timeout_ms = -1; + if (has_timeout) { + auto left = std::chrono::duration_cast( + deadline - Clock::now()); + // Round up so a sub-millisecond remainder doesn't spin. + timeout_ms = static_cast( + std::clamp(left.count() + 1, 0, INT_MAX)); + } + int n = ::poll(pfds.data(), static_cast(pfds.size()), timeout_ms); + if (n < 0) { + if (errno == EINTR) { + continue; + } + return WaitResult::kError; + } + for (const struct pollfd &pfd : pfds) { + if ((pfd.revents & POLLNVAL) != 0) { + return WaitResult::kError; + } + if ((pfd.revents & (events | POLLERR | POLLHUP)) != 0) { + *ready_fd = pfd.fd; + return WaitResult::kReady; + } + } + if (has_timeout && Clock::now() >= deadline) { + return WaitResult::kTimedOut; + } + } +} + +// Waits for one of `fds` to be ready for `events`, by the means `ctx` says. +Task WaitFds(Context ctx, std::vector fds, short events, + std::chrono::nanoseconds timeout, int *ready_fd) { + if (co20::Coroutine *c = ctx.Coroutine()) { + int r = -1; + if (fds.size() == 1) { + r = co_await c->Wait(fds[0], events, ToNanos(timeout)); + } else { + r = co_await c->Wait(fds, events, ToNanos(timeout)); + } + co_return FromCo20(*c, fds, r, ready_fd); + } + if (const toolbelt::AsyncWaiter *w = ctx.Waiter()) { + int r = fds.size() == 1 ? w->Wait(fds[0], events, ToNanos(timeout)) + : w->Wait(fds, events, ToNanos(timeout)); + co_return FromWaiter(fds, r, timeout.count() > 0, ready_fd); + } + co_return PollBlocking(fds, events, timeout, ready_fd); +} + +absl::Status ToStatus(WaitResult result, const char *what) { + switch (result) { + case WaitResult::kReady: + return absl::OkStatus(); + case WaitResult::kTimedOut: + return absl::DeadlineExceededError("Timeout waiting for fd"); + case WaitResult::kInterrupted: + return absl::CancelledError(absl::StrFormat("%s: interrupted", what)); + case WaitResult::kError: + break; + } + return absl::InternalError(absl::StrFormat("%s: unable to wait for fd", what)); +} + +} // namespace + +Task WaitReadable(Context ctx, int fd, + std::chrono::nanoseconds timeout) { + int ready_fd = -1; + WaitResult r = co_await WaitFds(ctx, {fd}, POLLIN, timeout, &ready_fd); + co_return ToStatus(r, "WaitReadable"); +} + +Task WaitWritable(Context ctx, int fd, + std::chrono::nanoseconds timeout) { + int ready_fd = -1; + WaitResult r = co_await WaitFds(ctx, {fd}, POLLOUT, timeout, &ready_fd); + co_return ToStatus(r, "WaitWritable"); +} + +Task> WaitEither(Context ctx, int fd1, int fd2, + std::chrono::nanoseconds timeout) { + int ready_fd = -1; + WaitResult r = co_await WaitFds(ctx, {fd1, fd2}, POLLIN, timeout, &ready_fd); + if (r != WaitResult::kReady) { + co_return ToStatus(r, "WaitEither"); + } + co_return ready_fd; +} + +Task Sleep(Context ctx, std::chrono::nanoseconds duration) { + if (co20::Coroutine *c = ctx.Coroutine()) { + co_await c->Sleep(ToNanos(duration)); + co_return; + } + if (const toolbelt::AsyncWaiter *w = ctx.Waiter()) { + w->Nanosleep(ToNanos(duration)); + co_return; + } + if (duration.count() > 0) { + struct timespec ts = { + .tv_sec = static_cast(duration.count() / 1000000000), + .tv_nsec = static_cast(duration.count() % 1000000000)}; + while (::nanosleep(&ts, &ts) != 0 && errno == EINTR) { + } + } +} + +} // namespace subspace::async + #else // SUBSPACE_CORO_BACKEND_CO namespace subspace::async { diff --git a/common/async/wait.h b/common/async/wait.h index ad9add47..859dcf10 100644 --- a/common/async/wait.h +++ b/common/async/wait.h @@ -10,47 +10,51 @@ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "common/async/context.h" +#include "common/async/task.h" #include namespace subspace::async { // FD-readiness and sleep primitives, expressed against the active backend's // Context. These replace the implicit co::self / co::Wait / co::Sleep calls so -// that the same source compiles under either backend. +// that the same source compiles under any backend. Under co20 they return +// tasks that must be awaited (see task.h). // // Under Asio only one coroutine at a time can wait on a given fd. With epoll // (Linux and Android), another coroutine's wait on it fails at once with an // InternalError. With kqueue (macOS), the other wait takes over the fd and -// the first may never return. The co backend has no such limit. Under Asio a wait that is cancelled, as a graceful -// shutdown does, returns CancelledError. +// the first may never return. The co and co20 backends have no such limit. +// Under Asio a wait that is cancelled, as a graceful shutdown does, returns +// CancelledError. Under co20 a wait woken by the coroutine's interrupt fd +// does the same. // Wait until `fd` is readable. A non-zero timeout returns // DeadlineExceededError if the fd is not ready in time; a zero timeout waits // forever. -absl::Status WaitReadable(Context ctx, int fd, - std::chrono::nanoseconds timeout = - std::chrono::nanoseconds(0)); +Task WaitReadable(Context ctx, int fd, + std::chrono::nanoseconds timeout = + std::chrono::nanoseconds(0)); // Wait until `fd` is writable or has an error pending. A non-zero timeout // returns DeadlineExceededError if the fd is not ready in time; a zero timeout // waits forever. Returns an error if the wait is interrupted or cancelled. -absl::Status WaitWritable(Context ctx, int fd, - std::chrono::nanoseconds timeout = - std::chrono::nanoseconds(0)); +Task WaitWritable(Context ctx, int fd, + std::chrono::nanoseconds timeout = + std::chrono::nanoseconds(0)); // Wait until either `fd1` or `fd2` becomes readable. Returns the raw fd that // became ready. A non-zero timeout returns DeadlineExceededError if neither fd // is ready in time; a zero timeout waits forever. -absl::StatusOr WaitEither(Context ctx, int fd1, int fd2, - std::chrono::nanoseconds timeout = - std::chrono::nanoseconds(0)); +Task> WaitEither(Context ctx, int fd1, int fd2, + std::chrono::nanoseconds timeout = + std::chrono::nanoseconds(0)); // Suspend the current coroutine for `duration`. -void Sleep(Context ctx, std::chrono::nanoseconds duration); +Task Sleep(Context ctx, std::chrono::nanoseconds duration); // Convenience overload taking whole seconds. -inline void Sleep(Context ctx, int seconds) { - Sleep(ctx, std::chrono::seconds(seconds)); +inline Task Sleep(Context ctx, int seconds) { + return Sleep(ctx, std::chrono::seconds(seconds)); } } // namespace subspace::async diff --git a/docs/asio-backend.md b/docs/asio-backend.md index 2ecac873..6b631211 100644 --- a/docs/asio-backend.md +++ b/docs/asio-backend.md @@ -32,7 +32,8 @@ bazelisk test //client:bridge_test --//:coro_backend=asio ``` The flag is declared in the root `BUILD.bazel` as `//:coro_backend` with values -`co` and `asio`. +`co`, `asio` and `co20`. `co20` (C++20 stackless coroutines) needs C++20, so +select it with `--config=cpp20`, which sets both. ### CMake @@ -47,8 +48,9 @@ When `asio` is selected, CMake fetches Boost (asio/coroutine/context) via ### Client code is unchanged -The client public API still takes `const co::Coroutine *` where it always did, -so existing applications compile and run unmodified. Most clients are not +The client public API takes a `const toolbelt::AsyncWaiter *` where it used to +take a `const co::Coroutine *`. A `co::Coroutine` is an `AsyncWaiter`, so +existing applications compile and run unmodified. Most clients are not coroutine-driven at all; under the asio backend such a client simply runs in **blocking mode** (its socket is left blocking, so it never needs a `yield_context`). No code change is required to use an asio-backed client. diff --git a/patches/co_cpp20_wait_any_and_reap.patch b/patches/co_cpp20_wait_any_and_reap.patch new file mode 100644 index 00000000..19de912f --- /dev/null +++ b/patches/co_cpp20_wait_any_and_reap.patch @@ -0,0 +1,611 @@ +diff --git a/co/coroutine_cpp20.cc b/co/coroutine_cpp20.cc +index aae0c12..9b68309 100644 +--- a/co/coroutine_cpp20.cc ++++ b/co/coroutine_cpp20.cc +@@ -134,6 +134,48 @@ int Scheduler::PollFd(int fd, uint32_t event_mask) { + return -1; + } + ++int Scheduler::PollFds(const std::vector& fds, uint32_t event_mask) { ++ for (int fd : fds) { ++ if (PollFd(fd, event_mask) == fd) return fd; ++ } ++ return -1; ++} ++ ++void Scheduler::DetachExtraFds(Coroutine* coroutine) { ++ auto extra_it = extra_fds_.find(coroutine); ++ if (extra_it == extra_fds_.end()) return; ++ for (int fd : extra_it->second) { ++ auto waiting_it = waiting_fds_.find(fd); ++ if (waiting_it == waiting_fds_.end()) continue; ++ auto& list = waiting_it->second; ++ list.erase(std::remove(list.begin(), list.end(), coroutine), list.end()); ++ if (list.empty()) { ++ waiting_fds_.erase(waiting_it); ++#if CO_POLL_MODE == CO_POLL_EPOLL ++ if (epoll_fd_ != -1) { ++ epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, nullptr); ++ } ++#endif ++ } ++ } ++ extra_fds_.erase(extra_it); ++} ++ ++void Scheduler::ReapCoroutine(Coroutine* coroutine) { ++ // A coroutine can be queued more than once (a wakeup racing an Abort). ++ ready_queue_.erase( ++ std::remove(ready_queue_.begin(), ready_queue_.end(), coroutine), ++ ready_queue_.end()); ++ auto it = std::find_if( ++ coroutines_.begin(), coroutines_.end(), ++ [coroutine](const std::unique_ptr& c) { ++ return c.get() == coroutine; ++ }); ++ if (it != coroutines_.end()) { ++ coroutines_.erase(it); ++ } ++} ++ + // Remove a coroutine from all waiting data structures and clean up + // any scheduler-owned FDs (timerfds). Called when a coroutine finishes. + void Scheduler::CleanupCoroutine(Coroutine* coroutine) { +@@ -172,6 +214,7 @@ void Scheduler::CleanupCoroutine(Coroutine* coroutine) { + coroutine_fds_.erase(fd_it); + wait_masks_.erase(coroutine); + } ++ DetachExtraFds(coroutine); + + // Also clean up interrupt FD waiting list. + int ifd = coroutine->GetInterruptFd(); +@@ -195,6 +238,61 @@ void Scheduler::CleanupCoroutine(Coroutine* coroutine) { + CleanupTimeoutFd(coroutine); + } + ++void Scheduler::WaitForFds(Coroutine* coroutine, const std::vector& fds, ++ uint32_t event_mask, uint64_t timeout_ns) { ++ if (!coroutine) return; ++ if (fds.empty()) { ++ ScheduleCoroutine(coroutine); ++ return; ++ } ++ int ready = PollFds(fds, event_mask); ++ if (ready != -1) { ++ coroutine->SetWaitResult(ready); ++ coroutine->SetState(Coroutine::State::kReady); ++ ready_queue_.push_back(coroutine); ++ TriggerInterrupt(); ++ return; ++ } ++ ++ // The first fd takes the single-fd path, which also registers the interrupt ++ // fd and the timeout. ++ WaitForFd(coroutine, fds[0], event_mask, timeout_ns); ++ if (coroutine->GetState() != Coroutine::State::kWaiting) { ++ return; ++ } ++ ++ std::vector& extra = extra_fds_[coroutine]; ++ for (size_t i = 1; i < fds.size(); i++) { ++ int fd = fds[i]; ++ if (fd == fds[0] || ++ std::find(extra.begin(), extra.end(), fd) != extra.end()) { ++ continue; ++ } ++ [[maybe_unused]] bool fd_already_tracked = waiting_fds_.count(fd) > 0; ++ auto& wait_list = waiting_fds_[fd]; ++ wait_list.push_back(coroutine); ++ extra.push_back(fd); ++#if CO_POLL_MODE == CO_POLL_EPOLL ++ if (epoll_fd_ != -1) { ++ struct epoll_event ev; ++ ev.data.fd = fd; ++ ev.events = 0; ++ if (event_mask & POLLIN) ev.events |= EPOLLIN | EPOLLRDHUP; ++ if (event_mask & POLLOUT) ev.events |= EPOLLOUT; ++ int ret = epoll_ctl(epoll_fd_, fd_already_tracked ? EPOLL_CTL_MOD ++ : EPOLL_CTL_ADD, ++ fd, &ev); ++ if (ret == -1 && errno == EEXIST) { ++ epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &ev); ++ } ++ } ++#endif ++ } ++ if (extra.empty()) { ++ extra_fds_.erase(coroutine); ++ } ++} ++ + void Scheduler::WaitForFd(Coroutine* coroutine, int fd, uint32_t event_mask, + uint64_t timeout_ns) { + if (!coroutine) return; +@@ -209,6 +307,7 @@ void Scheduler::WaitForFd(Coroutine* coroutine, int fd, uint32_t event_mask, + } + + coroutine->SetState(Coroutine::State::kWaiting); ++ DetachExtraFds(coroutine); + + // If this coroutine was already waiting on a different FD, detach it first. + auto existing_it = coroutine_fds_.find(coroutine); +@@ -535,6 +634,7 @@ void Scheduler::ResumeCoroutine(Coroutine* coroutine, int value) { + coroutine_fds_.erase(it); + wait_masks_.erase(coroutine); + } ++ DetachExtraFds(coroutine); + + // Also detach from interrupt FD waiting list if present. + int ifd = coroutine->GetInterruptFd(); +@@ -649,6 +749,7 @@ void Scheduler::ProcessReadyCoroutines() { + coroutine->GetState() == Coroutine::State::kRunning) { + coroutine->SetState(Coroutine::State::kDead); + CleanupCoroutine(coroutine); ++ ReapCoroutine(coroutine); + } + } + } +@@ -728,6 +829,8 @@ void Scheduler::ProcessEvents() { + // waiters that asked for one of the events that is ready. + std::vector to_resume = coroutines_per_fd[i]; + for (Coroutine* c : to_resume) { ++ // A coroutine waiting on several ready fds was resumed by the first. ++ if (c->GetState() != Coroutine::State::kWaiting) continue; + if (revents & (WaitMaskFor(c, fd) | POLLHUP | POLLERR)) { + ResumeCoroutine(c, fd); + } +@@ -737,9 +840,17 @@ void Scheduler::ProcessEvents() { + + uint32_t Scheduler::WaitMaskFor(Coroutine* coroutine, int fd) const { + auto fd_it = coroutine_fds_.find(coroutine); +- if (fd_it == coroutine_fds_.end() || fd_it->second != fd) { ++ if (fd_it == coroutine_fds_.end()) { + return POLLIN; + } ++ if (fd_it->second != fd) { ++ auto extra_it = extra_fds_.find(coroutine); ++ if (extra_it == extra_fds_.end() || ++ std::find(extra_it->second.begin(), extra_it->second.end(), fd) == ++ extra_it->second.end()) { ++ return POLLIN; ++ } ++ } + auto mask_it = wait_masks_.find(coroutine); + return mask_it == wait_masks_.end() ? POLLIN : mask_it->second; + } +@@ -749,6 +860,9 @@ void Scheduler::Run() { + + while (running_) { + ProcessReadyCoroutines(); ++ // A coroutine may have called Stop(), and the interrupt it raised may ++ // already have been drained by ProcessReadyCoroutines. ++ if (!running_) break; + + if (waiting_fds_.empty() && ready_queue_.empty()) break; + if (!ready_queue_.empty()) continue; +diff --git a/co/coroutine_cpp20.h b/co/coroutine_cpp20.h +index 7ea97fc..6adb1ed 100644 +--- a/co/coroutine_cpp20.h ++++ b/co/coroutine_cpp20.h +@@ -99,6 +99,7 @@ struct AbortException {}; + struct BaseAwaitable; + struct YieldAwaitable; + struct WaitAwaitable; ++struct WaitAnyAwaitable; + struct SleepAwaitable; + template struct ValueTask; + +@@ -118,6 +119,7 @@ public: + friend struct BaseAwaitable; + friend struct YieldAwaitable; + friend struct WaitAwaitable; ++ friend struct WaitAnyAwaitable; + friend struct SleepAwaitable; + friend struct Task; + template friend struct ValueTask; +@@ -130,8 +132,10 @@ public: + if (interrupt_fd_ != -1) { + close(interrupt_fd_); + } +- if (handle_) { +- handle_.destroy(); ++ // The root frame owns the ValueTasks it is awaiting, so destroying it ++ // destroys every nested frame. handle_ may point at an inner frame. ++ if (root_) { ++ root_.destroy(); + } + } + +@@ -142,6 +146,11 @@ public: + + YieldAwaitable Yield(); + WaitAwaitable Wait(int fd, uint32_t event_mask = POLLIN, uint64_t timeout_ns = 0); ++ // Wait until any of `fds` is ready. Resumes with the fd that became ready, ++ // the timeout fd on a timeout, or the interrupt fd if interrupted, like the ++ // single-fd Wait. ++ WaitAnyAwaitable Wait(const std::vector& fds, ++ uint32_t event_mask = POLLIN, uint64_t timeout_ns = 0); + SleepAwaitable Sleep(uint64_t nanoseconds); + + template +@@ -165,7 +174,10 @@ private: + + inline void Resume(int value = 0); + ++ // The frame to resume: the innermost frame suspended in this coroutine. + std::coroutine_handle<> handle_; ++ // The frame of the Task the coroutine was created from. ++ std::coroutine_handle<> root_; + Scheduler& scheduler_; + State state_ = State::kNew; + std::string name_; +@@ -189,6 +201,7 @@ public: + void Run(); + void Stop() { running_ = false; TriggerInterrupt(); } + ++ // The returned Coroutine is freed when it finishes. + template + Coroutine* Spawn(Func&& func, const std::string& name = "", + int interrupt_fd = -1) { +@@ -204,9 +217,13 @@ public: + + void ScheduleCoroutine(Coroutine* coroutine); + void WaitForFd(Coroutine* coroutine, int fd, uint32_t event_mask, uint64_t timeout_ns); ++ void WaitForFds(Coroutine* coroutine, const std::vector& fds, ++ uint32_t event_mask, uint64_t timeout_ns); + void SleepFor(Coroutine* coroutine, uint64_t nanoseconds); + void ResumeCoroutine(Coroutine* coroutine, int value); + int PollFd(int fd, uint32_t event_mask); ++ // The first of `fds` that is ready, or -1. ++ int PollFds(const std::vector& fds, uint32_t event_mask); + int AllocateId() { return next_id_++; } + + private: +@@ -217,6 +234,10 @@ private: + uint32_t WaitMaskFor(Coroutine* coroutine, int fd) const; + void CleanupCoroutine(Coroutine* coroutine); + void CleanupTimeoutFd(Coroutine* coroutine); ++ // Stops waiting on the fds a multi-fd wait added beyond its first. ++ void DetachExtraFds(Coroutine* coroutine); ++ // Frees a coroutine that has finished. ++ void ReapCoroutine(Coroutine* coroutine); + void TriggerInterrupt(); + #if CO_POLL_MODE == CO_POLL_EPOLL + void DispatchEpollEvents(struct epoll_event* events, int count); +@@ -229,6 +250,9 @@ private: + absl::flat_hash_map coroutine_fds_; + // The event mask each coroutine passed to WaitForFd for coroutine_fds_. + absl::flat_hash_map wait_masks_; ++ // The fds after the first of a multi-fd wait. They use the mask in ++ // wait_masks_. ++ absl::flat_hash_map> extra_fds_; + absl::flat_hash_set timerfds_; + + #if CO_TIMER_MODE == CO_TIMER_POSIX +@@ -331,6 +355,50 @@ struct WaitAwaitable : BaseAwaitable { + } + }; + ++struct WaitAnyAwaitable : BaseAwaitable { ++ std::vector fds_; ++ uint32_t event_mask_; ++ uint64_t timeout_ns_; ++ mutable int result_ = -1; ++ ++ WaitAnyAwaitable(Coroutine* coroutine, Scheduler* scheduler, ++ std::vector fds, uint32_t event_mask, ++ uint64_t timeout_ns) ++ : BaseAwaitable(coroutine, scheduler), fds_(std::move(fds)), ++ event_mask_(event_mask), timeout_ns_(timeout_ns) {} ++ ++ bool await_ready() const noexcept { ++ if (coroutine_ && scheduler_) { ++ int result = scheduler_->PollFds(fds_, event_mask_); ++ if (result != -1) { ++ result_ = result; ++ return true; ++ } ++ } ++ return false; ++ } ++ ++ void await_suspend(std::coroutine_handle<> handle) const { ++ BaseAwaitable::await_suspend(handle); ++ if (coroutine_ && scheduler_) { ++ scheduler_->WaitForFds(coroutine_, fds_, event_mask_, timeout_ns_); ++ } ++ } ++ ++ int await_resume() const { ++ if (coroutine_ && coroutine_->IsAborted()) { ++ throw AbortException(); ++ } ++ if (result_ != -1) { ++ return result_; ++ } ++ if (coroutine_) { ++ return coroutine_->GetWaitResult(); ++ } ++ return -1; ++ } ++}; ++ + struct SleepAwaitable : BaseAwaitable { + uint64_t timeout_ns_; + +@@ -386,6 +454,7 @@ inline Coroutine::Coroutine(Scheduler& scheduler, Func&& func, const std::string + }(); + if constexpr (requires { task.handle_; }) { + handle_ = std::coroutine_handle<>(task.handle_); ++ root_ = handle_; + if constexpr (requires { task.handle_.promise().coroutine; }) { + task.handle_.promise().coroutine = this; + } +@@ -406,6 +475,12 @@ inline WaitAwaitable Coroutine::Wait(int fd, uint32_t event_mask, uint64_t timeo + return WaitAwaitable(this, &scheduler_, fd, event_mask, timeout_ns); + } + ++inline WaitAnyAwaitable Coroutine::Wait(const std::vector& fds, ++ uint32_t event_mask, ++ uint64_t timeout_ns) { ++ return WaitAnyAwaitable(this, &scheduler_, fds, event_mask, timeout_ns); ++} ++ + inline SleepAwaitable Coroutine::Sleep(uint64_t nanoseconds) { + return SleepAwaitable(this, &scheduler_, nanoseconds); + } +@@ -482,6 +557,11 @@ struct Task { + template + struct ValueTask { + struct promise_type { ++ // Declared so promise_type is not an aggregate. GCC otherwise tries to ++ // initialize it from the coroutine's arguments, which fails to compile ++ // for a member function whose object T can't be built from. ++ promise_type() {} ++ + T value_{}; + std::coroutine_handle<> continuation_{}; + +@@ -549,6 +629,9 @@ struct ValueTask { + template <> + struct ValueTask { + struct promise_type { ++ // See ValueTask::promise_type. ++ promise_type() {} ++ + std::coroutine_handle<> continuation_{}; + + std::suspend_always initial_suspend() noexcept { return {}; } +@@ -611,9 +694,15 @@ inline void Coroutine::Resume(int value) { + if (handle_ && !handle_.done()) { + wait_result_ = value; + state_ = State::kRunning; ++ // Restored afterwards so self never outlives the coroutine, which the ++ // scheduler frees when it finishes. ++ Coroutine* prev_self = co20::self; ++ Scheduler* prev_scheduler = co20::scheduler; + co20::self = this; + co20::scheduler = &scheduler_; + handle_.resume(); ++ co20::self = prev_self; ++ co20::scheduler = prev_scheduler; + if (handle_.done()) { + state_ = State::kDead; + } +@@ -633,6 +722,12 @@ inline WaitAwaitable Wait(int fd, uint32_t event_mask = POLLIN, + return self->Wait(fd, event_mask, timeout_ns); + } + ++inline WaitAnyAwaitable Wait(const std::vector& fds, ++ uint32_t event_mask = POLLIN, ++ uint64_t timeout_ns = 0) { ++ return self->Wait(fds, event_mask, timeout_ns); ++} ++ + inline SleepAwaitable Sleep(uint64_t nanoseconds) { + return self->Sleep(nanoseconds); + } +diff --git a/co/test_cpp20.cc b/co/test_cpp20.cc +index 40948c2..dd52814 100644 +--- a/co/test_cpp20.cc ++++ b/co/test_cpp20.cc +@@ -271,17 +271,19 @@ TEST(Cpp20, AbortSingle) { + + TEST(Cpp20Free, Self) { + Scheduler sched; +- const Coroutine* captured_self = nullptr; ++ std::string captured_name; + +- sched.Spawn([&captured_self]() -> Task { +- captured_self = co20::self; ++ // The coroutine is freed when it finishes, so read it while it runs. ++ sched.Spawn([&captured_name]() -> Task { ++ if (co20::self != nullptr) { ++ captured_name = co20::self->Name(); ++ } + co_return; + }, "self_test"); + + sched.Run(); + +- ASSERT_NE(nullptr, captured_self); +- EXPECT_EQ("self_test", captured_self->Name()); ++ EXPECT_EQ("self_test", captured_name); + } + + TEST(Cpp20Free, SchedulerAccess) { +@@ -991,6 +993,174 @@ TEST(Cpp20WaitTimeout, DataArrivesDuringWait) { + EXPECT_TRUE(success); + } + ++TEST(Cpp20, WaitAnyReturnsReadyFd) { ++ Scheduler sched; ++ int a[2]; ++ int b[2]; ++ ASSERT_EQ(0, pipe(a)); ++ ASSERT_EQ(0, pipe(b)); ++ ++ int result = -1; ++ sched.Spawn([&](Coroutine& co) -> Task { ++ result = co_await co.Wait(std::vector{a[0], b[0]}, POLLIN); ++ }, "waiter"); ++ sched.Spawn([&](Coroutine& co) -> Task { ++ co_await co.Sleep(std::chrono::milliseconds(10)); ++ char c = 'x'; ++ (void)write(b[1], &c, 1); ++ }, "writer"); ++ ++ sched.Run(); ++ EXPECT_EQ(b[0], result); ++ close(a[0]); ++ close(a[1]); ++ close(b[0]); ++ close(b[1]); ++} ++ ++TEST(Cpp20, WaitAnyTimeout) { ++ Scheduler sched; ++ int a[2]; ++ int b[2]; ++ ASSERT_EQ(0, pipe(a)); ++ ASSERT_EQ(0, pipe(b)); ++ ++ int result = -1; ++ sched.Spawn([&](Coroutine& co) -> Task { ++ result = co_await co.Wait(std::vector{a[0], b[0]}, POLLIN, ++ 20000000ULL); ++ }, "waiter"); ++ ++ sched.Run(); ++ EXPECT_NE(a[0], result); ++ EXPECT_NE(b[0], result); ++ close(a[0]); ++ close(a[1]); ++ close(b[0]); ++ close(b[1]); ++} ++ ++// Both fds become ready in the same poll. The coroutine must be resumed once ++// and must then be able to wait again. ++TEST(Cpp20, WaitAnyBothReadyResumesOnce) { ++ Scheduler sched; ++ int a[2]; ++ int b[2]; ++ ASSERT_EQ(0, pipe(a)); ++ ASSERT_EQ(0, pipe(b)); ++ ++ int wakes = 0; ++ bool second_wait_done = false; ++ sched.Spawn([&](Coroutine& co) -> Task { ++ co_await co.Wait(std::vector{a[0], b[0]}, POLLIN); ++ wakes++; ++ char c; ++ (void)read(a[0], &c, 1); ++ (void)read(b[0], &c, 1); ++ co_await co.Sleep(std::chrono::milliseconds(20)); ++ second_wait_done = true; ++ }, "waiter"); ++ sched.Spawn([&](Coroutine& co) -> Task { ++ co_await co.Sleep(std::chrono::milliseconds(10)); ++ char c = 'x'; ++ (void)write(a[1], &c, 1); ++ (void)write(b[1], &c, 1); ++ }, "writer"); ++ ++ sched.Run(); ++ EXPECT_EQ(1, wakes); ++ EXPECT_TRUE(second_wait_done); ++ close(a[0]); ++ close(a[1]); ++ close(b[0]); ++ close(b[1]); ++} ++ ++// Fails to compile if a promise holding it is built from the coroutine's ++// arguments instead of being default constructed. ++struct FromAnything { ++ FromAnything() = default; ++ template ++ FromAnything(U&&) { ++ static_assert(!std::is_same_v, "promise built from an argument"); ++ } ++}; ++ ++struct MemberCoroutines { ++ int value = 7; ++ ValueTask Make() { co_return FromAnything(); } ++ ValueTask Get() { co_return value; } ++ ValueTask Nothing() { co_return; } ++}; ++ ++TEST(Cpp20, MemberFunctionValueTasks) { ++ Scheduler sched; ++ MemberCoroutines m; ++ int got = 0; ++ sched.Spawn([&](Coroutine& co) -> Task { ++ (void)co_await m.Make(); ++ co_await m.Nothing(); ++ got = co_await m.Get(); ++ }); ++ sched.Run(); ++ EXPECT_EQ(7, got); ++} ++ ++// Counts its live instances. ++struct FrameLocal { ++ explicit FrameLocal(int& live) : live_(live) { ++live_; } ++ ~FrameLocal() { --live_; } ++ int& live_; ++}; ++ ++ValueTask WaitInner(Coroutine& co, int fd, int& live) { ++ FrameLocal local(live); ++ co_await co.Wait(fd, POLLIN); ++} ++ ++ValueTask WaitOuter(Coroutine& co, int fd, int& live) { ++ FrameLocal local(live); ++ co_await WaitInner(co, fd, live); ++ co_return 1; ++} ++ ++// Destroying a coroutine suspended inside nested ValueTasks destroys every ++// frame, not just the innermost one. Also checks that Stop() from a ++// coroutine ends Run() while another coroutine waits on an fd. ++TEST(Cpp20, DestroyedCoroutineFreesNestedFrames) { ++ int fds[2]; ++ ASSERT_EQ(0, pipe(fds)); ++ int live = 0; ++ { ++ Scheduler sched; ++ sched.Spawn([&](Coroutine& co) -> Task { ++ FrameLocal local(live); ++ (void)co_await WaitOuter(co, fds[0], live); ++ }); ++ sched.Spawn([&](Coroutine& co) -> Task { ++ co_await co.Sleep(std::chrono::milliseconds(1)); ++ sched.Stop(); ++ }); ++ sched.Run(); ++ EXPECT_EQ(3, live); ++ } ++ EXPECT_EQ(0, live); ++ close(fds[0]); ++ close(fds[1]); ++} ++ ++// A finished coroutine is freed, along with the callable that made it. ++TEST(Cpp20, FinishedCoroutineReleasesCallable) { ++ Scheduler sched; ++ auto token = std::make_shared(0); ++ sched.Spawn([token](Coroutine& co) -> Task { ++ co_await co.Yield(); ++ }, "holder"); ++ EXPECT_EQ(2, token.use_count()); ++ sched.Run(); ++ EXPECT_EQ(1, token.use_count()); ++} ++ + } // namespace co20 + + #endif // CO20_HAVE_COROUTINES From 8c88842a0b93bb6fd10d4f2d9cb3c9075797f8cb Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Tue, 24 Nov 2026 12:02:31 -0800 Subject: [PATCH 2/9] Adapt co20 wait and SyncWait to co 3.5.2 co 3.5.2 stores a ValueTask result in a std::optional and keeps an exception in exception_ptr, rather than storing a bare value and swallowing exceptions. SyncWait now rethrows a stored exception, as the other backends do, and unwraps the optional result. Under co20, Wait returns -1 on timeout as well as for a closed fd. Only a closed fd is an error, so a timed wait that expires is reported as DeadlineExceeded again. --- common/async/task.h | 6 +++++- common/async/wait.cc | 18 +++++++++++++----- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/common/async/task.h b/common/async/task.h index fabb4e36..133f95ce 100644 --- a/common/async/task.h +++ b/common/async/task.h @@ -57,8 +57,12 @@ template T SyncWait(Task task) { "not hold a coroutine\n"); std::abort(); } + auto &promise = task.handle_.promise(); + if (promise.exception_) { + std::rethrow_exception(promise.exception_); + } if constexpr (!std::is_void_v) { - return std::move(task.handle_.promise().value_); + return std::move(*promise.value_); } } diff --git a/common/async/wait.cc b/common/async/wait.cc index c2f4d84f..7909607d 100644 --- a/common/async/wait.cc +++ b/common/async/wait.cc @@ -480,6 +480,7 @@ void Sleep(Context ctx, std::chrono::nanoseconds duration) { #include #include #include +#include #include namespace subspace::async { @@ -495,10 +496,10 @@ uint64_t ToNanos(std::chrono::nanoseconds d) { } // Classifies the value a co20 wait resumed with. It resumes with the fd that -// became ready, the coroutine's interrupt fd, or the fd of its timeout timer. -// -1 means the scheduler could not watch the fd. +// became ready, the coroutine's interrupt fd, or -1 on timeout or when the +// scheduler could not watch a closed fd. WaitResult FromCo20(const co20::Coroutine &c, const std::vector &fds, - int r, int *ready_fd) { + bool has_timeout, int r, int *ready_fd) { for (int fd : fds) { if (r == fd) { *ready_fd = fd; @@ -506,7 +507,14 @@ WaitResult FromCo20(const co20::Coroutine &c, const std::vector &fds, } } if (r == -1) { - return WaitResult::kError; + // -1 is a timeout, or a closed fd that the scheduler could not watch. + // Only the closed fd is an error. + for (int fd : fds) { + if (::fcntl(fd, F_GETFD) == -1 && errno == EBADF) { + return WaitResult::kError; + } + } + return has_timeout ? WaitResult::kTimedOut : WaitResult::kError; } if (c.GetInterruptFd() != -1 && r == c.GetInterruptFd()) { return WaitResult::kInterrupted; @@ -587,7 +595,7 @@ Task WaitFds(Context ctx, std::vector fds, short events, } else { r = co_await c->Wait(fds, events, ToNanos(timeout)); } - co_return FromCo20(*c, fds, r, ready_fd); + co_return FromCo20(*c, fds, timeout.count() > 0, r, ready_fd); } if (const toolbelt::AsyncWaiter *w = ctx.Waiter()) { int r = fds.size() == 1 ? w->Wait(fds[0], events, ToNanos(timeout)) From 4ba073ae8a30c95c786167a0720b480ac98725db Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Tue, 24 Nov 2026 12:02:31 -0800 Subject: [PATCH 3/9] Use co20-subspace-support in ~/co instead of a patch The co20 fixes that were in patches/co_cpp20_wait_any_and_reap.patch are now a branch in ~/co (co 3.5.2, co20-subspace-support, commit fe00d44). Pin coroutines to that commit through a file:// remote in MODULE.bazel and in the CMake FetchContent, and delete the patch and its PATCH_COMMAND. The file:// pin only resolves on this machine until the branch is pushed to dallison/co. --- CMakeLists.txt | 11 +- MODULE.bazel | 24 +- patches/co_cpp20_wait_any_and_reap.patch | 611 ----------------------- 3 files changed, 13 insertions(+), 633 deletions(-) delete mode 100644 patches/co_cpp20_wait_any_and_reap.patch diff --git a/CMakeLists.txt b/CMakeLists.txt index f5734c87..c8f9a69d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -203,15 +203,12 @@ endif() message(STATUS "Trigger mechanism: ${SUBSPACE_TRIGGER_MECHANISM}") # --- External Dependency: co (using FetchContent for native CMake) --- -set(SUBSPACE_CO_PATCH ${CMAKE_CURRENT_SOURCE_DIR}/patches/co_cpp20_wait_any_and_reap.patch) +# Same commit as the Bazel git_override in MODULE.bazel (co 3.5.2 on the +# co20-subspace-support branch in ~/co). Local file remote until it is pushed. FetchContent_Declare( co - GIT_REPOSITORY https://github.com/dallison/co.git - # dallison/co#77 (poll event mask) plus TSan stack-switch fix (c2cbd0f). - GIT_TAG c2cbd0f75b1e834090762d584b812a485b8b8ca8 - # Same patch as the Bazel git_override in MODULE.bazel. Skipped when it - # is already applied, so reconfiguring works. - PATCH_COMMAND sh -c "git apply --reverse --check ${SUBSPACE_CO_PATCH} 2>/dev/null || git apply ${SUBSPACE_CO_PATCH}" + GIT_REPOSITORY file:///Users/FZDSZZ/co + GIT_TAG fe00d446d24fd4047414be4f946dd59320d48bb7 CMAKE_ARGS -DCMAKE_OSX_ARCHITECTURES="${CMAKE_OSX_ARCHITECTURES}" ) diff --git a/MODULE.bazel b/MODULE.bazel index cf72d473..b207c321 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -24,23 +24,17 @@ bazel_dep(name = "rules_java", version = "9.1.0") bazel_dep(name = "rules_pkg", version = "1.0.1") bazel_dep(name = "rules_android_ndk", version = "0.1.5") bazel_dep(name = "zlib", version = "1.3.1.bcr.5") -bazel_dep(name = "coroutines", version = "3.4.1") - -# The cpp20 poll fallback must resume a waiter only for events it asked for. -# A socketpair is always writable, so waking every waiter on POLLOUT hangs -# co20_rpc on macOS (dallison/co#77). c2cbd0f also keeps TSan from corrupting -# the shadow stack on a coroutine stack switch with GCC 15 (dallison/co c2cbd0f). -# Not released yet. -# -# The patch adds a multi-fd Wait to the C++20 scheduler, frees coroutines when -# they finish, and keeps the poll fallback from resuming a coroutine twice. -# The co20 backend needs all three. Drop it once it is upstream. +bazel_dep(name = "coroutines", version = "3.5.2") + +# The co20 backend needs the C++20 scheduler fixes on dallison/co +# co20-subspace-support (3.5.2): multi-fd Wait, the poll fallback event mask, +# TSan across stack switches, and non-aggregate ValueTask promises for GCC. +# The branch is local to ~/co and not pushed yet, so this pin only resolves on +# this machine. Point it at the GitHub remote once the branch is pushed. git_override( module_name = "coroutines", - commit = "c2cbd0f75b1e834090762d584b812a485b8b8ca8", - patch_strip = 1, - patches = ["//patches:co_cpp20_wait_any_and_reap.patch"], - remote = "https://github.com/dallison/co.git", + commit = "fe00d446d24fd4047414be4f946dd59320d48bb7", + remote = "file:///Users/FZDSZZ/co", ) bazel_dep(name = "cpp_toolbelt", version = "2.1.6") diff --git a/patches/co_cpp20_wait_any_and_reap.patch b/patches/co_cpp20_wait_any_and_reap.patch deleted file mode 100644 index 19de912f..00000000 --- a/patches/co_cpp20_wait_any_and_reap.patch +++ /dev/null @@ -1,611 +0,0 @@ -diff --git a/co/coroutine_cpp20.cc b/co/coroutine_cpp20.cc -index aae0c12..9b68309 100644 ---- a/co/coroutine_cpp20.cc -+++ b/co/coroutine_cpp20.cc -@@ -134,6 +134,48 @@ int Scheduler::PollFd(int fd, uint32_t event_mask) { - return -1; - } - -+int Scheduler::PollFds(const std::vector& fds, uint32_t event_mask) { -+ for (int fd : fds) { -+ if (PollFd(fd, event_mask) == fd) return fd; -+ } -+ return -1; -+} -+ -+void Scheduler::DetachExtraFds(Coroutine* coroutine) { -+ auto extra_it = extra_fds_.find(coroutine); -+ if (extra_it == extra_fds_.end()) return; -+ for (int fd : extra_it->second) { -+ auto waiting_it = waiting_fds_.find(fd); -+ if (waiting_it == waiting_fds_.end()) continue; -+ auto& list = waiting_it->second; -+ list.erase(std::remove(list.begin(), list.end(), coroutine), list.end()); -+ if (list.empty()) { -+ waiting_fds_.erase(waiting_it); -+#if CO_POLL_MODE == CO_POLL_EPOLL -+ if (epoll_fd_ != -1) { -+ epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, nullptr); -+ } -+#endif -+ } -+ } -+ extra_fds_.erase(extra_it); -+} -+ -+void Scheduler::ReapCoroutine(Coroutine* coroutine) { -+ // A coroutine can be queued more than once (a wakeup racing an Abort). -+ ready_queue_.erase( -+ std::remove(ready_queue_.begin(), ready_queue_.end(), coroutine), -+ ready_queue_.end()); -+ auto it = std::find_if( -+ coroutines_.begin(), coroutines_.end(), -+ [coroutine](const std::unique_ptr& c) { -+ return c.get() == coroutine; -+ }); -+ if (it != coroutines_.end()) { -+ coroutines_.erase(it); -+ } -+} -+ - // Remove a coroutine from all waiting data structures and clean up - // any scheduler-owned FDs (timerfds). Called when a coroutine finishes. - void Scheduler::CleanupCoroutine(Coroutine* coroutine) { -@@ -172,6 +214,7 @@ void Scheduler::CleanupCoroutine(Coroutine* coroutine) { - coroutine_fds_.erase(fd_it); - wait_masks_.erase(coroutine); - } -+ DetachExtraFds(coroutine); - - // Also clean up interrupt FD waiting list. - int ifd = coroutine->GetInterruptFd(); -@@ -195,6 +238,61 @@ void Scheduler::CleanupCoroutine(Coroutine* coroutine) { - CleanupTimeoutFd(coroutine); - } - -+void Scheduler::WaitForFds(Coroutine* coroutine, const std::vector& fds, -+ uint32_t event_mask, uint64_t timeout_ns) { -+ if (!coroutine) return; -+ if (fds.empty()) { -+ ScheduleCoroutine(coroutine); -+ return; -+ } -+ int ready = PollFds(fds, event_mask); -+ if (ready != -1) { -+ coroutine->SetWaitResult(ready); -+ coroutine->SetState(Coroutine::State::kReady); -+ ready_queue_.push_back(coroutine); -+ TriggerInterrupt(); -+ return; -+ } -+ -+ // The first fd takes the single-fd path, which also registers the interrupt -+ // fd and the timeout. -+ WaitForFd(coroutine, fds[0], event_mask, timeout_ns); -+ if (coroutine->GetState() != Coroutine::State::kWaiting) { -+ return; -+ } -+ -+ std::vector& extra = extra_fds_[coroutine]; -+ for (size_t i = 1; i < fds.size(); i++) { -+ int fd = fds[i]; -+ if (fd == fds[0] || -+ std::find(extra.begin(), extra.end(), fd) != extra.end()) { -+ continue; -+ } -+ [[maybe_unused]] bool fd_already_tracked = waiting_fds_.count(fd) > 0; -+ auto& wait_list = waiting_fds_[fd]; -+ wait_list.push_back(coroutine); -+ extra.push_back(fd); -+#if CO_POLL_MODE == CO_POLL_EPOLL -+ if (epoll_fd_ != -1) { -+ struct epoll_event ev; -+ ev.data.fd = fd; -+ ev.events = 0; -+ if (event_mask & POLLIN) ev.events |= EPOLLIN | EPOLLRDHUP; -+ if (event_mask & POLLOUT) ev.events |= EPOLLOUT; -+ int ret = epoll_ctl(epoll_fd_, fd_already_tracked ? EPOLL_CTL_MOD -+ : EPOLL_CTL_ADD, -+ fd, &ev); -+ if (ret == -1 && errno == EEXIST) { -+ epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &ev); -+ } -+ } -+#endif -+ } -+ if (extra.empty()) { -+ extra_fds_.erase(coroutine); -+ } -+} -+ - void Scheduler::WaitForFd(Coroutine* coroutine, int fd, uint32_t event_mask, - uint64_t timeout_ns) { - if (!coroutine) return; -@@ -209,6 +307,7 @@ void Scheduler::WaitForFd(Coroutine* coroutine, int fd, uint32_t event_mask, - } - - coroutine->SetState(Coroutine::State::kWaiting); -+ DetachExtraFds(coroutine); - - // If this coroutine was already waiting on a different FD, detach it first. - auto existing_it = coroutine_fds_.find(coroutine); -@@ -535,6 +634,7 @@ void Scheduler::ResumeCoroutine(Coroutine* coroutine, int value) { - coroutine_fds_.erase(it); - wait_masks_.erase(coroutine); - } -+ DetachExtraFds(coroutine); - - // Also detach from interrupt FD waiting list if present. - int ifd = coroutine->GetInterruptFd(); -@@ -649,6 +749,7 @@ void Scheduler::ProcessReadyCoroutines() { - coroutine->GetState() == Coroutine::State::kRunning) { - coroutine->SetState(Coroutine::State::kDead); - CleanupCoroutine(coroutine); -+ ReapCoroutine(coroutine); - } - } - } -@@ -728,6 +829,8 @@ void Scheduler::ProcessEvents() { - // waiters that asked for one of the events that is ready. - std::vector to_resume = coroutines_per_fd[i]; - for (Coroutine* c : to_resume) { -+ // A coroutine waiting on several ready fds was resumed by the first. -+ if (c->GetState() != Coroutine::State::kWaiting) continue; - if (revents & (WaitMaskFor(c, fd) | POLLHUP | POLLERR)) { - ResumeCoroutine(c, fd); - } -@@ -737,9 +840,17 @@ void Scheduler::ProcessEvents() { - - uint32_t Scheduler::WaitMaskFor(Coroutine* coroutine, int fd) const { - auto fd_it = coroutine_fds_.find(coroutine); -- if (fd_it == coroutine_fds_.end() || fd_it->second != fd) { -+ if (fd_it == coroutine_fds_.end()) { - return POLLIN; - } -+ if (fd_it->second != fd) { -+ auto extra_it = extra_fds_.find(coroutine); -+ if (extra_it == extra_fds_.end() || -+ std::find(extra_it->second.begin(), extra_it->second.end(), fd) == -+ extra_it->second.end()) { -+ return POLLIN; -+ } -+ } - auto mask_it = wait_masks_.find(coroutine); - return mask_it == wait_masks_.end() ? POLLIN : mask_it->second; - } -@@ -749,6 +860,9 @@ void Scheduler::Run() { - - while (running_) { - ProcessReadyCoroutines(); -+ // A coroutine may have called Stop(), and the interrupt it raised may -+ // already have been drained by ProcessReadyCoroutines. -+ if (!running_) break; - - if (waiting_fds_.empty() && ready_queue_.empty()) break; - if (!ready_queue_.empty()) continue; -diff --git a/co/coroutine_cpp20.h b/co/coroutine_cpp20.h -index 7ea97fc..6adb1ed 100644 ---- a/co/coroutine_cpp20.h -+++ b/co/coroutine_cpp20.h -@@ -99,6 +99,7 @@ struct AbortException {}; - struct BaseAwaitable; - struct YieldAwaitable; - struct WaitAwaitable; -+struct WaitAnyAwaitable; - struct SleepAwaitable; - template struct ValueTask; - -@@ -118,6 +119,7 @@ public: - friend struct BaseAwaitable; - friend struct YieldAwaitable; - friend struct WaitAwaitable; -+ friend struct WaitAnyAwaitable; - friend struct SleepAwaitable; - friend struct Task; - template friend struct ValueTask; -@@ -130,8 +132,10 @@ public: - if (interrupt_fd_ != -1) { - close(interrupt_fd_); - } -- if (handle_) { -- handle_.destroy(); -+ // The root frame owns the ValueTasks it is awaiting, so destroying it -+ // destroys every nested frame. handle_ may point at an inner frame. -+ if (root_) { -+ root_.destroy(); - } - } - -@@ -142,6 +146,11 @@ public: - - YieldAwaitable Yield(); - WaitAwaitable Wait(int fd, uint32_t event_mask = POLLIN, uint64_t timeout_ns = 0); -+ // Wait until any of `fds` is ready. Resumes with the fd that became ready, -+ // the timeout fd on a timeout, or the interrupt fd if interrupted, like the -+ // single-fd Wait. -+ WaitAnyAwaitable Wait(const std::vector& fds, -+ uint32_t event_mask = POLLIN, uint64_t timeout_ns = 0); - SleepAwaitable Sleep(uint64_t nanoseconds); - - template -@@ -165,7 +174,10 @@ private: - - inline void Resume(int value = 0); - -+ // The frame to resume: the innermost frame suspended in this coroutine. - std::coroutine_handle<> handle_; -+ // The frame of the Task the coroutine was created from. -+ std::coroutine_handle<> root_; - Scheduler& scheduler_; - State state_ = State::kNew; - std::string name_; -@@ -189,6 +201,7 @@ public: - void Run(); - void Stop() { running_ = false; TriggerInterrupt(); } - -+ // The returned Coroutine is freed when it finishes. - template - Coroutine* Spawn(Func&& func, const std::string& name = "", - int interrupt_fd = -1) { -@@ -204,9 +217,13 @@ public: - - void ScheduleCoroutine(Coroutine* coroutine); - void WaitForFd(Coroutine* coroutine, int fd, uint32_t event_mask, uint64_t timeout_ns); -+ void WaitForFds(Coroutine* coroutine, const std::vector& fds, -+ uint32_t event_mask, uint64_t timeout_ns); - void SleepFor(Coroutine* coroutine, uint64_t nanoseconds); - void ResumeCoroutine(Coroutine* coroutine, int value); - int PollFd(int fd, uint32_t event_mask); -+ // The first of `fds` that is ready, or -1. -+ int PollFds(const std::vector& fds, uint32_t event_mask); - int AllocateId() { return next_id_++; } - - private: -@@ -217,6 +234,10 @@ private: - uint32_t WaitMaskFor(Coroutine* coroutine, int fd) const; - void CleanupCoroutine(Coroutine* coroutine); - void CleanupTimeoutFd(Coroutine* coroutine); -+ // Stops waiting on the fds a multi-fd wait added beyond its first. -+ void DetachExtraFds(Coroutine* coroutine); -+ // Frees a coroutine that has finished. -+ void ReapCoroutine(Coroutine* coroutine); - void TriggerInterrupt(); - #if CO_POLL_MODE == CO_POLL_EPOLL - void DispatchEpollEvents(struct epoll_event* events, int count); -@@ -229,6 +250,9 @@ private: - absl::flat_hash_map coroutine_fds_; - // The event mask each coroutine passed to WaitForFd for coroutine_fds_. - absl::flat_hash_map wait_masks_; -+ // The fds after the first of a multi-fd wait. They use the mask in -+ // wait_masks_. -+ absl::flat_hash_map> extra_fds_; - absl::flat_hash_set timerfds_; - - #if CO_TIMER_MODE == CO_TIMER_POSIX -@@ -331,6 +355,50 @@ struct WaitAwaitable : BaseAwaitable { - } - }; - -+struct WaitAnyAwaitable : BaseAwaitable { -+ std::vector fds_; -+ uint32_t event_mask_; -+ uint64_t timeout_ns_; -+ mutable int result_ = -1; -+ -+ WaitAnyAwaitable(Coroutine* coroutine, Scheduler* scheduler, -+ std::vector fds, uint32_t event_mask, -+ uint64_t timeout_ns) -+ : BaseAwaitable(coroutine, scheduler), fds_(std::move(fds)), -+ event_mask_(event_mask), timeout_ns_(timeout_ns) {} -+ -+ bool await_ready() const noexcept { -+ if (coroutine_ && scheduler_) { -+ int result = scheduler_->PollFds(fds_, event_mask_); -+ if (result != -1) { -+ result_ = result; -+ return true; -+ } -+ } -+ return false; -+ } -+ -+ void await_suspend(std::coroutine_handle<> handle) const { -+ BaseAwaitable::await_suspend(handle); -+ if (coroutine_ && scheduler_) { -+ scheduler_->WaitForFds(coroutine_, fds_, event_mask_, timeout_ns_); -+ } -+ } -+ -+ int await_resume() const { -+ if (coroutine_ && coroutine_->IsAborted()) { -+ throw AbortException(); -+ } -+ if (result_ != -1) { -+ return result_; -+ } -+ if (coroutine_) { -+ return coroutine_->GetWaitResult(); -+ } -+ return -1; -+ } -+}; -+ - struct SleepAwaitable : BaseAwaitable { - uint64_t timeout_ns_; - -@@ -386,6 +454,7 @@ inline Coroutine::Coroutine(Scheduler& scheduler, Func&& func, const std::string - }(); - if constexpr (requires { task.handle_; }) { - handle_ = std::coroutine_handle<>(task.handle_); -+ root_ = handle_; - if constexpr (requires { task.handle_.promise().coroutine; }) { - task.handle_.promise().coroutine = this; - } -@@ -406,6 +475,12 @@ inline WaitAwaitable Coroutine::Wait(int fd, uint32_t event_mask, uint64_t timeo - return WaitAwaitable(this, &scheduler_, fd, event_mask, timeout_ns); - } - -+inline WaitAnyAwaitable Coroutine::Wait(const std::vector& fds, -+ uint32_t event_mask, -+ uint64_t timeout_ns) { -+ return WaitAnyAwaitable(this, &scheduler_, fds, event_mask, timeout_ns); -+} -+ - inline SleepAwaitable Coroutine::Sleep(uint64_t nanoseconds) { - return SleepAwaitable(this, &scheduler_, nanoseconds); - } -@@ -482,6 +557,11 @@ struct Task { - template - struct ValueTask { - struct promise_type { -+ // Declared so promise_type is not an aggregate. GCC otherwise tries to -+ // initialize it from the coroutine's arguments, which fails to compile -+ // for a member function whose object T can't be built from. -+ promise_type() {} -+ - T value_{}; - std::coroutine_handle<> continuation_{}; - -@@ -549,6 +629,9 @@ struct ValueTask { - template <> - struct ValueTask { - struct promise_type { -+ // See ValueTask::promise_type. -+ promise_type() {} -+ - std::coroutine_handle<> continuation_{}; - - std::suspend_always initial_suspend() noexcept { return {}; } -@@ -611,9 +694,15 @@ inline void Coroutine::Resume(int value) { - if (handle_ && !handle_.done()) { - wait_result_ = value; - state_ = State::kRunning; -+ // Restored afterwards so self never outlives the coroutine, which the -+ // scheduler frees when it finishes. -+ Coroutine* prev_self = co20::self; -+ Scheduler* prev_scheduler = co20::scheduler; - co20::self = this; - co20::scheduler = &scheduler_; - handle_.resume(); -+ co20::self = prev_self; -+ co20::scheduler = prev_scheduler; - if (handle_.done()) { - state_ = State::kDead; - } -@@ -633,6 +722,12 @@ inline WaitAwaitable Wait(int fd, uint32_t event_mask = POLLIN, - return self->Wait(fd, event_mask, timeout_ns); - } - -+inline WaitAnyAwaitable Wait(const std::vector& fds, -+ uint32_t event_mask = POLLIN, -+ uint64_t timeout_ns = 0) { -+ return self->Wait(fds, event_mask, timeout_ns); -+} -+ - inline SleepAwaitable Sleep(uint64_t nanoseconds) { - return self->Sleep(nanoseconds); - } -diff --git a/co/test_cpp20.cc b/co/test_cpp20.cc -index 40948c2..dd52814 100644 ---- a/co/test_cpp20.cc -+++ b/co/test_cpp20.cc -@@ -271,17 +271,19 @@ TEST(Cpp20, AbortSingle) { - - TEST(Cpp20Free, Self) { - Scheduler sched; -- const Coroutine* captured_self = nullptr; -+ std::string captured_name; - -- sched.Spawn([&captured_self]() -> Task { -- captured_self = co20::self; -+ // The coroutine is freed when it finishes, so read it while it runs. -+ sched.Spawn([&captured_name]() -> Task { -+ if (co20::self != nullptr) { -+ captured_name = co20::self->Name(); -+ } - co_return; - }, "self_test"); - - sched.Run(); - -- ASSERT_NE(nullptr, captured_self); -- EXPECT_EQ("self_test", captured_self->Name()); -+ EXPECT_EQ("self_test", captured_name); - } - - TEST(Cpp20Free, SchedulerAccess) { -@@ -991,6 +993,174 @@ TEST(Cpp20WaitTimeout, DataArrivesDuringWait) { - EXPECT_TRUE(success); - } - -+TEST(Cpp20, WaitAnyReturnsReadyFd) { -+ Scheduler sched; -+ int a[2]; -+ int b[2]; -+ ASSERT_EQ(0, pipe(a)); -+ ASSERT_EQ(0, pipe(b)); -+ -+ int result = -1; -+ sched.Spawn([&](Coroutine& co) -> Task { -+ result = co_await co.Wait(std::vector{a[0], b[0]}, POLLIN); -+ }, "waiter"); -+ sched.Spawn([&](Coroutine& co) -> Task { -+ co_await co.Sleep(std::chrono::milliseconds(10)); -+ char c = 'x'; -+ (void)write(b[1], &c, 1); -+ }, "writer"); -+ -+ sched.Run(); -+ EXPECT_EQ(b[0], result); -+ close(a[0]); -+ close(a[1]); -+ close(b[0]); -+ close(b[1]); -+} -+ -+TEST(Cpp20, WaitAnyTimeout) { -+ Scheduler sched; -+ int a[2]; -+ int b[2]; -+ ASSERT_EQ(0, pipe(a)); -+ ASSERT_EQ(0, pipe(b)); -+ -+ int result = -1; -+ sched.Spawn([&](Coroutine& co) -> Task { -+ result = co_await co.Wait(std::vector{a[0], b[0]}, POLLIN, -+ 20000000ULL); -+ }, "waiter"); -+ -+ sched.Run(); -+ EXPECT_NE(a[0], result); -+ EXPECT_NE(b[0], result); -+ close(a[0]); -+ close(a[1]); -+ close(b[0]); -+ close(b[1]); -+} -+ -+// Both fds become ready in the same poll. The coroutine must be resumed once -+// and must then be able to wait again. -+TEST(Cpp20, WaitAnyBothReadyResumesOnce) { -+ Scheduler sched; -+ int a[2]; -+ int b[2]; -+ ASSERT_EQ(0, pipe(a)); -+ ASSERT_EQ(0, pipe(b)); -+ -+ int wakes = 0; -+ bool second_wait_done = false; -+ sched.Spawn([&](Coroutine& co) -> Task { -+ co_await co.Wait(std::vector{a[0], b[0]}, POLLIN); -+ wakes++; -+ char c; -+ (void)read(a[0], &c, 1); -+ (void)read(b[0], &c, 1); -+ co_await co.Sleep(std::chrono::milliseconds(20)); -+ second_wait_done = true; -+ }, "waiter"); -+ sched.Spawn([&](Coroutine& co) -> Task { -+ co_await co.Sleep(std::chrono::milliseconds(10)); -+ char c = 'x'; -+ (void)write(a[1], &c, 1); -+ (void)write(b[1], &c, 1); -+ }, "writer"); -+ -+ sched.Run(); -+ EXPECT_EQ(1, wakes); -+ EXPECT_TRUE(second_wait_done); -+ close(a[0]); -+ close(a[1]); -+ close(b[0]); -+ close(b[1]); -+} -+ -+// Fails to compile if a promise holding it is built from the coroutine's -+// arguments instead of being default constructed. -+struct FromAnything { -+ FromAnything() = default; -+ template -+ FromAnything(U&&) { -+ static_assert(!std::is_same_v, "promise built from an argument"); -+ } -+}; -+ -+struct MemberCoroutines { -+ int value = 7; -+ ValueTask Make() { co_return FromAnything(); } -+ ValueTask Get() { co_return value; } -+ ValueTask Nothing() { co_return; } -+}; -+ -+TEST(Cpp20, MemberFunctionValueTasks) { -+ Scheduler sched; -+ MemberCoroutines m; -+ int got = 0; -+ sched.Spawn([&](Coroutine& co) -> Task { -+ (void)co_await m.Make(); -+ co_await m.Nothing(); -+ got = co_await m.Get(); -+ }); -+ sched.Run(); -+ EXPECT_EQ(7, got); -+} -+ -+// Counts its live instances. -+struct FrameLocal { -+ explicit FrameLocal(int& live) : live_(live) { ++live_; } -+ ~FrameLocal() { --live_; } -+ int& live_; -+}; -+ -+ValueTask WaitInner(Coroutine& co, int fd, int& live) { -+ FrameLocal local(live); -+ co_await co.Wait(fd, POLLIN); -+} -+ -+ValueTask WaitOuter(Coroutine& co, int fd, int& live) { -+ FrameLocal local(live); -+ co_await WaitInner(co, fd, live); -+ co_return 1; -+} -+ -+// Destroying a coroutine suspended inside nested ValueTasks destroys every -+// frame, not just the innermost one. Also checks that Stop() from a -+// coroutine ends Run() while another coroutine waits on an fd. -+TEST(Cpp20, DestroyedCoroutineFreesNestedFrames) { -+ int fds[2]; -+ ASSERT_EQ(0, pipe(fds)); -+ int live = 0; -+ { -+ Scheduler sched; -+ sched.Spawn([&](Coroutine& co) -> Task { -+ FrameLocal local(live); -+ (void)co_await WaitOuter(co, fds[0], live); -+ }); -+ sched.Spawn([&](Coroutine& co) -> Task { -+ co_await co.Sleep(std::chrono::milliseconds(1)); -+ sched.Stop(); -+ }); -+ sched.Run(); -+ EXPECT_EQ(3, live); -+ } -+ EXPECT_EQ(0, live); -+ close(fds[0]); -+ close(fds[1]); -+} -+ -+// A finished coroutine is freed, along with the callable that made it. -+TEST(Cpp20, FinishedCoroutineReleasesCallable) { -+ Scheduler sched; -+ auto token = std::make_shared(0); -+ sched.Spawn([token](Coroutine& co) -> Task { -+ co_await co.Yield(); -+ }, "holder"); -+ EXPECT_EQ(2, token.use_count()); -+ sched.Run(); -+ EXPECT_EQ(1, token.use_count()); -+} -+ - } // namespace co20 - - #endif // CO20_HAVE_COROUTINES From 5225cda5b47197ef0459e9f4759030aebafba5f7 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Tue, 24 Nov 2026 12:41:31 -0800 Subject: [PATCH 4/9] Pin coroutines to co 3.5.2 on dallison/co main The co20 changes were merged upstream as dallison/co#82 (db9ecf4), so the pin moves from the local ~/co branch to the GitHub remote. --- CMakeLists.txt | 7 +++---- MODULE.bazel | 13 ++++++------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c8f9a69d..90ddc316 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -203,12 +203,11 @@ endif() message(STATUS "Trigger mechanism: ${SUBSPACE_TRIGGER_MECHANISM}") # --- External Dependency: co (using FetchContent for native CMake) --- -# Same commit as the Bazel git_override in MODULE.bazel (co 3.5.2 on the -# co20-subspace-support branch in ~/co). Local file remote until it is pushed. +# Same commit as the Bazel git_override in MODULE.bazel (co 3.5.2, #82). FetchContent_Declare( co - GIT_REPOSITORY file:///Users/FZDSZZ/co - GIT_TAG fe00d446d24fd4047414be4f946dd59320d48bb7 + GIT_REPOSITORY https://github.com/dallison/co.git + GIT_TAG db9ecf4c6a7396bcd409addfffac3be6f00c2b59 CMAKE_ARGS -DCMAKE_OSX_ARCHITECTURES="${CMAKE_OSX_ARCHITECTURES}" ) diff --git a/MODULE.bazel b/MODULE.bazel index b207c321..e47a39e6 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -26,15 +26,14 @@ bazel_dep(name = "rules_android_ndk", version = "0.1.5") bazel_dep(name = "zlib", version = "1.3.1.bcr.5") bazel_dep(name = "coroutines", version = "3.5.2") -# The co20 backend needs the C++20 scheduler fixes on dallison/co -# co20-subspace-support (3.5.2): multi-fd Wait, the poll fallback event mask, -# TSan across stack switches, and non-aggregate ValueTask promises for GCC. -# The branch is local to ~/co and not pushed yet, so this pin only resolves on -# this machine. Point it at the GitHub remote once the branch is pushed. +# The co20 backend needs the C++20 scheduler changes in co 3.5.2 (dallison/co +# #82): multi-fd Wait, the poll fallback event mask, TSan across stack +# switches, non-aggregate ValueTask promises for GCC and an atomic Stop. +# Not in the BCR yet. git_override( module_name = "coroutines", - commit = "fe00d446d24fd4047414be4f946dd59320d48bb7", - remote = "file:///Users/FZDSZZ/co", + commit = "db9ecf4c6a7396bcd409addfffac3be6f00c2b59", + remote = "https://github.com/dallison/co.git", ) bazel_dep(name = "cpp_toolbelt", version = "2.1.6") From 195230840c9aca44e7721bac91ed3bf40dc4f578 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Tue, 24 Nov 2026 15:40:57 -0800 Subject: [PATCH 5/9] Convert client and server to support the C++20 coroutine (co20) backend - Convert ClientImpl server round-trips, buffer attachment/unmapping, split-buffer registration/lookup, channel reload callbacks, and publisher/subscriber slot search paths to return async::Task using ASYNC_AWAIT / ASYNC_RETURN, keeping the synchronous public Client, Publisher, and Subscriber APIs unchanged via ASYNC_BLOCK (SyncWait). - Add Async variants (including CloseAsync) on Client, Publisher, and Subscriber for coroutines running on a co20::Scheduler, rejecting thread-safe clients with FailedPrecondition. - Convert Server, ClientHandler, TunnelManager, FFI, Python server wrapper, and plugin entry points to async::Task and RuntimeEngine, using SERVER_CLIENT_CALL / SERVER_CLIENT_CLOSE for in-process clients running on the server scheduler thread. - Route ASYNC_AWAIT through FastAwait so ValueTasks that complete without parking on the scheduler unwind in place instead of relying on compiler symmetric-transfer TCO (avoiding C stack overflow under GCC -O0 and AddressSanitizer), and guard hot-path reload/update checks. - Prevent ShouldReconnect from blocking in connect() when a co20 coroutine's interrupt fd is already signaled during server shutdown, and yield instead of sleeping in ListenerCoroutine's shutdown drain. - Gate co-only and zero-allocation tests under //:coro_backend_co20, add the cpp20 CI workflow job, and document the co20 backend in docs/cpp20-coroutines.md and CHANGELOG.md. --- .github/workflows/ci.yml | 34 + CHANGELOG.md | 19 + c_client/BUILD.bazel | 6 + client/BUILD.bazel | 6 + client/client.cc | 941 ++++++++++++++++------------ client/client.h | 692 ++++++++++++++++---- client/client_channel.cc | 193 +++--- client/client_channel.h | 53 +- client/publisher.cc | 77 ++- client/publisher.h | 17 +- client/subscriber.cc | 51 +- client/subscriber.h | 30 +- common/BUILD.bazel | 1 + common/async/task.h | 69 +- common/channel.cc | 2 +- common/channel.h | 16 +- docs/cpp20-coroutines.md | 167 +++++ plugins/nop_plugin.cc | 40 +- rpc/client/BUILD.bazel | 6 + rpc/server/BUILD.bazel | 6 + rpc/test/BUILD.bazel | 6 + server/client_handler.cc | 28 +- server/client_handler.h | 2 +- server/main.cc | 6 +- server/plugin.h | 9 +- server/python/server.cc | 4 +- server/server.cc | 93 +-- server/server.h | 70 ++- server/server_bridge_receiver.cc | 205 +++--- server/server_bridge_transmitter.cc | 112 ++-- server/server_channels.cc | 80 ++- server/server_discovery.cc | 92 +-- server/server_ffi.cc | 4 +- server/server_telemetry.cc | 68 +- server/tunnel.cc | 295 +++++---- server/tunnel.h | 36 +- shadow/BUILD.bazel | 6 + 37 files changed, 2336 insertions(+), 1206 deletions(-) create mode 100644 docs/cpp20-coroutines.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f671f08..fff0b813 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -139,6 +139,40 @@ jobs: --test_output=errors \ ${{ matrix.bazel_flags }} + # Builds and tests the whole tree with the C++20 coroutine backend (co20, + # --config=cpp20). Targets that depend on the stackful co API or on + # zero-allocation hot paths are gated off under co20 and are skipped. See + # docs/cpp20-coroutines.md. + cpp20: + name: cpp20 (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + timeout-minutes: 90 + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + bazel_flags: + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Install Bazel + uses: bazel-contrib/setup-bazel@0.18.0 + with: + bazelisk-cache: true + disk-cache: ${{ github.workflow }}-${{ matrix.os }}-cpp20 + repository-cache: true + + - name: Build and test all targets with co20 + run: | + bazelisk test \ + --config=cpp20 \ + --test_output=errors \ + ${{ matrix.bazel_flags }} \ + //... + # Exercises the anonymous memfd_create shared-memory backend on Linux # (--config=linux_memfd, i.e. SUBSPACE_SHMEM_MODE_MEMFD). This is the same # mechanism Android always uses; running it on native Linux guards against diff --git a/CHANGELOG.md b/CHANGELOG.md index 57f8512f..a6adb424 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,25 @@ ## Unreleased +### C++20 Coroutine Backend (co20) +- The server and client internals can run on C++20 stackless coroutines + instead of the stackful `co` library. Build with `--config=cpp20` (Bazel) or + `-DCMAKE_CXX_STANDARD=20` (CMake, where `SUBSPACE_CORO_BACKEND=auto` selects + it). The blocking client API and the wire protocol do not change. See + `docs/cpp20-coroutines.md`. +- Every client method that can wait on the server has an `...Async` form that + returns `async::Task` (for example `CreatePublisherAsync`, + `PublishMessageAsync`, `ReadMessageAsync`, `CloseAsync`). Code that runs on + the server's scheduler thread must use it, because a blocking client call + from a server coroutine deadlocks. +- The reload callback type changed to `std::function(Channel *)>` + and `Channel::CheckReload` is awaitable. Plugins and code that install reload + callbacks must match this under co20. The default build is unchanged. +- `//client:alloc_test`, `//c_client:client_test`, `//rpc/client:client_test`, + `//rpc/server:server_test`, `//rpc/test:rpc_test` and `//shadow:shadow_test` + are skipped under `--config=cpp20`. They depend on the stackful `co` API or on + zero-allocation hot paths. + ### Subscriber Queues Keep Per-Publisher Order - A subscriber with an explicit queue size could read a message that had overflowed its queue after newer messages from the same publisher. The diff --git a/c_client/BUILD.bazel b/c_client/BUILD.bazel index aa2b7182..6ad6ee10 100644 --- a/c_client/BUILD.bazel +++ b/c_client/BUILD.bazel @@ -17,6 +17,12 @@ cc_library( cc_test( name = "client_test", + # Co-only: these use the stackful co API directly (or, for alloc_test, assert + # zero allocations on the hot path, which co20 coroutine frames violate). + target_compatible_with = select({ + "//:coro_backend_co20": ["@platforms//:incompatible"], + "//conditions:default": [], + }), size = "small", srcs = ["client_test.cc"], data = [ diff --git a/client/BUILD.bazel b/client/BUILD.bazel index 1d5b9e90..ba16b866 100644 --- a/client/BUILD.bazel +++ b/client/BUILD.bazel @@ -60,6 +60,12 @@ cc_library( cc_test( name = "alloc_test", + # Co-only: these use the stackful co API directly (or, for alloc_test, assert + # zero allocations on the hot path, which co20 coroutine frames violate). + target_compatible_with = select({ + "//:coro_backend_co20": ["@platforms//:incompatible"], + "//conditions:default": [], + }), size = "small", srcs = ["alloc_test.cc"], copts = [ diff --git a/client/client.cc b/client/client.cc index 2fcd9e42..d3389858 100644 --- a/client/client.cc +++ b/client/client.cc @@ -226,14 +226,15 @@ absl::Status ClientImpl::CheckConnected() const { return absl::OkStatus(); } -absl::Status ClientImpl::Init(const std::string &server_socket, +async::Task +ClientImpl::Init(const std::string &server_socket, const std::string &client_name) { #if defined(__QNX__) || defined(__QNXNTO__) ConfigureQnxClockPeriod(); #endif ClientLockGuard guard(this); if (socket_.Connected()) { - return absl::InternalError("Client is already connected to the server; " + ASYNC_RETURN absl::InternalError("Client is already connected to the server; " "Init() called twice perhaps?"); } #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO @@ -243,7 +244,7 @@ absl::Status ClientImpl::Init(const std::string &server_socket, #endif absl::Status status = socket_.Connect(server_socket); if (!status.ok()) { - return status; + ASYNC_RETURN status; } name_ = client_name; @@ -253,24 +254,24 @@ absl::Status ClientImpl::Init(const std::string &server_socket, Response resp; std::vector fds; fds.reserve(100); - status = SendRequestReceiveResponse(req, resp, fds); + status = ASYNC_AWAIT(SendRequestReceiveResponse(req, resp, fds)); if (!status.ok()) { - return status; + ASYNC_RETURN status; } if (!resp.init().error().empty()) { - return absl::InternalError(resp.init().error()); + ASYNC_RETURN absl::InternalError(resp.init().error()); } if (absl::Status fd_status = CheckFdIndex(fds, resp.init().scb_fd_index(), "scb_fd", "InitResponse"); !fd_status.ok()) { - return fd_status; + ASYNC_RETURN fd_status; } scb_fd_ = std::move(fds[resp.init().scb_fd_index()]); session_id_ = resp.init().session_id(); server_user_id_ = resp.init().user_id(); server_group_id_ = resp.init().group_id(); was_connected_ = true; - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } absl::Status ClientImpl::RegisterDroppedMessageCallback( @@ -380,14 +381,15 @@ absl::Status ClientImpl::UnregisterResizeCallback(PublisherImpl *publisher) { return absl::OkStatus(); } -absl::Status ClientImpl::ProcessAllMessages(details::SubscriberImpl *subscriber, +async::Task +ClientImpl::ProcessAllMessages(details::SubscriberImpl *subscriber, ReadMode mode) { std::function callback; { ClientLockGuard guard(this); auto it = message_callbacks_.find(subscriber); if (it == message_callbacks_.end()) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "No message callback has been registered for channel %s\n", subscriber->Name())); } @@ -395,25 +397,25 @@ absl::Status ClientImpl::ProcessAllMessages(details::SubscriberImpl *subscriber, } for (;;) { - absl::StatusOr msg = ReadMessage(subscriber, mode); + absl::StatusOr msg = ASYNC_AWAIT(ReadMessage(subscriber, mode)); if (!msg.ok()) { - return msg.status(); + ASYNC_RETURN msg.status(); } if (msg->length == 0) { break; } callback(subscriber, std::move(*msg)); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::StatusOr> +async::Task>> ClientImpl::GetAllMessages(details::SubscriberImpl *subscriber, ReadMode mode) { std::vector r; for (;;) { - absl::StatusOr msg = ReadMessage(subscriber, mode); + absl::StatusOr msg = ASYNC_AWAIT(ReadMessage(subscriber, mode)); if (!msg.ok()) { - return msg.status(); + ASYNC_RETURN msg.status(); } if (msg->length == 0) { break; @@ -426,33 +428,50 @@ ClientImpl::GetAllMessages(details::SubscriberImpl *subscriber, ReadMode mode) { // std::cerr << "read {} messages, untriggering subscriber\n"_format( // subscriber->numActiveMessages()); subscriber->Untrigger(); - return r; + ASYNC_RETURN r; } if (!r.empty()) { subscriber->Trigger(); } - return r; + ASYNC_RETURN r; +} + +// Tells the server to drop a publisher it created for us when the client +// can't finish setting it up. Best effort: the original failure is what the +// caller needs to see. +async::Task ClientImpl::RemoveServerPublisher( + const std::string &channel_name, int32_t publisher_id) { + Request remove_req; + auto *cmd = remove_req.mutable_remove_publisher(); + cmd->set_channel_name(channel_name); + cmd->set_publisher_id(publisher_id); + + Response remove_resp; + std::vector remove_fds; + (void)ASYNC_AWAIT( + SendRequestReceiveResponse(remove_req, remove_resp, remove_fds)); + ASYNC_RETURN; } -absl::StatusOr +async::Task> ClientImpl::CreatePublisher(const std::string &channel_name, const PublisherOptions &opts) { ClientLockGuard guard(this); if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } if (opts.MaxOutstandingSlotLeases() < 1 || opts.MaxOutstandingSlotLeases() > opts.NumSlots()) { - return absl::InvalidArgumentError( + ASYNC_RETURN absl::InvalidArgumentError( "MaxOutstandingSlotLeases must be between 1 and NumSlots"); } if (opts.max_slot_size < 0) { - return absl::InvalidArgumentError(absl::StrFormat( + ASYNC_RETURN absl::InvalidArgumentError(absl::StrFormat( "MaxSlotSize must be non-negative, not %d", opts.max_slot_size)); } if (opts.max_slot_size > 0 && opts.slot_size > opts.max_slot_size) { - return absl::InvalidArgumentError(absl::StrFormat( + ASYNC_RETURN absl::InvalidArgumentError(absl::StrFormat( "Slot size %d for channel %s exceeds its maximum slot size of %d bytes", opts.slot_size, channel_name, opts.max_slot_size)); } @@ -464,25 +483,14 @@ ClientImpl::CreatePublisher(const std::string &channel_name, Response resp; std::vector fds; fds.reserve(100); - if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, resp, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } auto &pub_resp = resp.create_publisher(); if (!pub_resp.error().empty()) { - return absl::InternalError(pub_resp.error()); + ASYNC_RETURN absl::InternalError(pub_resp.error()); } - auto remove_server_publisher = [&]() { - Request remove_req; - auto *cmd = remove_req.mutable_remove_publisher(); - cmd->set_channel_name(channel_name); - cmd->set_publisher_id(pub_resp.publisher_id()); - - Response remove_resp; - std::vector remove_fds; - (void)SendRequestReceiveResponse(remove_req, remove_resp, remove_fds); - }; - // A publisher may join an existing channel with fewer slots than it has. // The CCB layout is sized by the channel's slot count, so map with that and // keep it in the options so that reregistration asks for the same count. @@ -496,24 +504,29 @@ ClientImpl::CreatePublisher(const std::string &channel_name, pub_resp.subscriber_queue_arena_size(), pub_resp.channel_id(), pub_resp.publisher_id(), pub_resp.vchan_id(), session_id_, pub_resp.type(), channel_opts, - [this](Channel *c) { - return CheckReload(static_cast(c)); + [this](Channel *c) -> async::Task { + ASYNC_RETURN ASYNC_AWAIT(CheckReload(static_cast(c))); }, server_user_id_, server_group_id_); + // The channel awaits these, so they run on the caller's coroutine. channel->SetClientBufferRegistrationCallback( [this](const ClientBufferHandleMetadata &metadata, - const toolbelt::FileDescriptor *fd) { - return RegisterClientBuffer(metadata, fd); + const toolbelt::FileDescriptor *fd) + -> async::Task { + ASYNC_RETURN ASYNC_AWAIT(RegisterClientBuffer(metadata, fd)); + }); + channel->SetClientBufferLookupCallback( + [this](const std::string &channel_name, uint64_t session_id, + uint32_t buffer_index) + -> async::Task>> { + ASYNC_RETURN ASYNC_AWAIT( + GetClientBuffers(channel_name, session_id, buffer_index)); }); - channel->SetClientBufferLookupCallback([this](const std::string &channel_name, - uint64_t session_id, - uint32_t buffer_index) { - return GetClientBuffers(channel_name, session_id, buffer_index); - }); channel->SetClientBufferUnregistrationCallback( [this](const std::string &channel_name, uint64_t session_id, - uint32_t buffer_index) { - return UnregisterClientBuffer(channel_name, session_id, buffer_index); + uint32_t buffer_index) -> async::Task { + ASYNC_RETURN ASYNC_AWAIT( + UnregisterClientBuffer(channel_name, session_id, buffer_index)); }); int32_t cs = opts.ChecksumSize() > 0 ? opts.ChecksumSize() : 4; int32_t ms = opts.MetadataSize() > 0 ? opts.MetadataSize() : 0; @@ -524,89 +537,89 @@ ClientImpl::CreatePublisher(const std::string &channel_name, if (absl::Status fd_status = CheckFdIndex( fds, pub_resp.ccb_fd_index(), "ccb_fd", "CreatePublisherResponse"); !fd_status.ok()) { - remove_server_publisher(); - return fd_status; + ASYNC_AWAIT(RemoveServerPublisher(channel_name, pub_resp.publisher_id())); + ASYNC_RETURN fd_status; } if (absl::Status fd_status = CheckFdIndex( fds, pub_resp.bcb_fd_index(), "bcb_fd", "CreatePublisherResponse"); !fd_status.ok()) { - remove_server_publisher(); - return fd_status; + ASYNC_AWAIT(RemoveServerPublisher(channel_name, pub_resp.publisher_id())); + ASYNC_RETURN fd_status; } SharedMemoryFds channel_fds(std::move(fds[pub_resp.ccb_fd_index()]), std::move(fds[pub_resp.bcb_fd_index()])); if (absl::Status status = channel->Map(std::move(channel_fds), scb_fd_); !status.ok()) { - remove_server_publisher(); - return status; + ASYNC_AWAIT(RemoveServerPublisher(channel_name, pub_resp.publisher_id())); + ASYNC_RETURN status; } if (absl::Status status = - channel->CreateOrAttachBuffers(Aligned(opts.slot_size)); + ASYNC_AWAIT(channel->CreateOrAttachBuffers(Aligned(opts.slot_size))); !status.ok()) { - remove_server_publisher(); - return status; + ASYNC_AWAIT(RemoveServerPublisher(channel_name, pub_resp.publisher_id())); + ASYNC_RETURN status; } ApplyPublisherResponseFds(channel.get(), pub_resp, fds); if (!opts.IsReliable()) { MessageSlot *slot = - channel->FindFreeSlotUnreliable(channel->GetPublisherId()); + ASYNC_AWAIT(channel->FindFreeSlotUnreliable(channel->GetPublisherId())); if (slot == nullptr) { - remove_server_publisher(); - return absl::InternalError("No slot available for publisher"); + ASYNC_AWAIT(RemoveServerPublisher(channel_name, pub_resp.publisher_id())); + ASYNC_RETURN absl::InternalError("No slot available for publisher"); } channel->SetSlot(slot); if (!opts.IsBridge() && opts.Activate()) { - if (absl::Status status = ActivateChannel(channel.get()); !status.ok()) { - remove_server_publisher(); - return status; + if (absl::Status status = ASYNC_AWAIT(ActivateChannel(channel.get())); !status.ok()) { + ASYNC_AWAIT(RemoveServerPublisher(channel_name, pub_resp.publisher_id())); + ASYNC_RETURN status; } } } else if (!opts.IsBridge() && !opts.ForTunnel()) { // Send a single activation message to the channel. Don't activate if // this is a tunnel publisher because there will already be an existing // reliable publisher that has been activated. - absl::Status status = ActivateReliableChannel(channel.get()); + absl::Status status = ASYNC_AWAIT(ActivateReliableChannel(channel.get())); if (!status.ok()) { - remove_server_publisher(); - return status; + ASYNC_AWAIT(RemoveServerPublisher(channel_name, pub_resp.publisher_id())); + ASYNC_RETURN status; } } channel->TriggerSubscribers(); - if (absl::Status status = channel->UnmapUnusedBuffers(); !status.ok()) { - remove_server_publisher(); - return status; + if (absl::Status status = ASYNC_AWAIT(channel->UnmapUnusedBuffers()); !status.ok()) { + ASYNC_AWAIT(RemoveServerPublisher(channel_name, pub_resp.publisher_id())); + ASYNC_RETURN status; } channels_.insert(channel); - return Publisher(shared_from_this(), channel); + ASYNC_RETURN Publisher(shared_from_this(), channel); } -absl::StatusOr +async::Task> ClientImpl::CreatePublisher(const std::string &channel_name, int64_t slot_size, int num_slots, const PublisherOptions &opts) { PublisherOptions options = opts; options.slot_size = slot_size; options.num_slots = num_slots; - return CreatePublisher(channel_name, options); + ASYNC_RETURN ASYNC_AWAIT(CreatePublisher(channel_name, options)); } -absl::StatusOr +async::Task> ClientImpl::CreateSubscriber(const std::string &channel_name, const SubscriberOptions &opts) { ClientLockGuard guard(this); if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } if (opts.MaxActiveMessages() < 1) { - return absl::InvalidArgumentError( + ASYNC_RETURN absl::InvalidArgumentError( "MaxActiveMessages must be at least 1 for a subscriber"); } if (!std::isfinite(opts.StuckWarningGracePeriod()) || opts.StuckWarningGracePeriod() < 0) { - return absl::InvalidArgumentError(absl::StrFormat( + ASYNC_RETURN absl::InvalidArgumentError(absl::StrFormat( "StuckWarningGracePeriod must be a finite number of seconds that is " "at least 0, not %g", opts.StuckWarningGracePeriod())); @@ -619,14 +632,14 @@ ClientImpl::CreateSubscriber(const std::string &channel_name, Response resp; std::vector fds; fds.reserve(100); - if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, resp, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } auto &sub_resp = resp.create_subscriber(); if (!sub_resp.error().empty()) { - return absl::InternalError(sub_resp.error()); + ASYNC_RETURN absl::InternalError(sub_resp.error()); } SubscriberOptions subscriber_options = opts; @@ -645,16 +658,18 @@ ClientImpl::CreateSubscriber(const std::string &channel_name, sub_resp.subscriber_queue_size(), sub_resp.channel_id(), sub_resp.subscriber_id(), sub_resp.vchan_id(), session_id_, sub_resp.type(), subscriber_options, - [this](Channel *c) { - return CheckReload(static_cast(c)); + [this](Channel *c) -> async::Task { + ASYNC_RETURN ASYNC_AWAIT(CheckReload(static_cast(c))); }, server_user_id_, server_group_id_); channel->SetRequestName(channel_name); - channel->SetClientBufferLookupCallback([this](const std::string &channel_name, - uint64_t session_id, - uint32_t buffer_index) { - return GetClientBuffers(channel_name, session_id, buffer_index); - }); + channel->SetClientBufferLookupCallback( + [this](const std::string &channel_name, uint64_t session_id, + uint32_t buffer_index) + -> async::Task>> { + ASYNC_RETURN ASYNC_AWAIT( + GetClientBuffers(channel_name, session_id, buffer_index)); + }); channel->SetNumSlots(sub_resp.num_slots()); channel->SetEffectiveSubscriberQueueSize(sub_resp.subscriber_queue_size()); @@ -670,24 +685,24 @@ ClientImpl::CreateSubscriber(const std::string &channel_name, if (absl::Status fd_status = CheckFdIndex( fds, sub_resp.ccb_fd_index(), "ccb_fd", "CreateSubscriberResponse"); !fd_status.ok()) { - return fd_status; + ASYNC_RETURN fd_status; } if (absl::Status fd_status = CheckFdIndex( fds, sub_resp.bcb_fd_index(), "bcb_fd", "CreateSubscriberResponse"); !fd_status.ok()) { - return fd_status; + ASYNC_RETURN fd_status; } SharedMemoryFds channel_fds(std::move(fds[sub_resp.ccb_fd_index()]), std::move(fds[sub_resp.bcb_fd_index()])); if (absl::Status status = channel->Map(std::move(channel_fds), scb_fd_); !status.ok()) { - return status; + ASYNC_RETURN status; } channel->InitActiveMessages(); - if (absl::Status status = channel->AttachBuffers(); !status.ok()) { - return status; + if (absl::Status status = ASYNC_AWAIT(channel->AttachBuffers()); !status.ok()) { + ASYNC_RETURN status; } channel->RememberPublishedOrdinals(); @@ -696,7 +711,7 @@ ClientImpl::CreateSubscriber(const std::string &channel_name, channel->Trigger(); channels_.insert(channel); - return Subscriber(shared_from_this(), channel); + ASYNC_RETURN Subscriber(shared_from_this(), channel); } static uint64_t ExpandSlotSize(uint64_t slotSize) { @@ -720,20 +735,7 @@ static uint64_t ExpandSlotSize(uint64_t slotSize) { return Aligned(uint64_t(double(slotSize) * multipliers[i])); } -absl::StatusOr ClientImpl::GetMessageBuffer(PublisherImpl *publisher, - int64_t max_size, - bool lock) { - auto span_or_status = GetMessageBufferSpan(publisher, max_size, lock); - if (!span_or_status.ok()) { - return span_or_status.status(); - } - if (absl::Span span = span_or_status.value(); !span.empty()) { - return span.data(); - } - return nullptr; -} - -absl::StatusOr> +async::Task>> ClientImpl::GetMessageBufferSpan(PublisherImpl *publisher, int64_t max_size, bool lock) { // If the current thread is calling this while it already owns the mutex we @@ -750,7 +752,7 @@ ClientImpl::GetMessageBufferSpan(PublisherImpl *publisher, int64_t max_size, if (max_size != -1 && max_size > slot_size) { const int64_t max_slot_size = publisher->MaxSlotSize(); if (max_slot_size != 0 && max_size > max_slot_size) { - return absl::InvalidArgumentError(absl::StrFormat( + ASYNC_RETURN absl::InvalidArgumentError(absl::StrFormat( "Requested buffer of %d bytes on channel %s exceeds its maximum slot " "size of %d bytes", max_size, publisher->Name(), max_slot_size)); @@ -768,16 +770,19 @@ ClientImpl::GetMessageBufferSpan(PublisherImpl *publisher, int64_t max_size, } span_size = size_t(new_slot_size); - if (absl::Status status = ResizeChannel(publisher, new_slot_size); + if (absl::Status status = ASYNC_AWAIT(ResizeChannel(publisher, new_slot_size)); !status.ok()) { - return status; + ASYNC_RETURN status; } publisher->SetSlotToBiggestBuffer(publisher->CurrentSlot()); } - if (absl::Status status = ReloadSubscribersIfNecessary(publisher); - !status.ok()) { - return status; + if (SubscribersChanged(publisher)) { + if (absl::Status status = + ASYNC_AWAIT(ReloadSubscribersIfNecessary(publisher)); + !status.ok()) { + ASYNC_RETURN status; + } } if (publisher->IsReliable() && publisher->CurrentSlot() == nullptr) { @@ -791,19 +796,19 @@ ClientImpl::GetMessageBufferSpan(PublisherImpl *publisher, int64_t max_size, // to stop the publisher taking all the slots. An incoming subscriber // would miss all those messages and that's not reliable. if (publisher->NumSubscribers(publisher->VirtualChannelId()) == 0) { - return absl::Span(); + ASYNC_RETURN absl::Span(); } MessageSlot *slot = - publisher->FindFreeSlotReliable(publisher->GetPublisherId()); + ASYNC_AWAIT(publisher->FindFreeSlotReliable(publisher->GetPublisherId())); if (slot == nullptr) { - return absl::Span(); + ASYNC_RETURN absl::Span(); } publisher->SetSlot(slot); } void *buffer = publisher->GetCurrentBufferAddress(); if (buffer == nullptr) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("Channel %s has no buffer. This should never happen.", publisher->Name())); } @@ -812,19 +817,22 @@ ClientImpl::GetMessageBufferSpan(PublisherImpl *publisher, int64_t max_size, if (span_size > 0) { guard.CommitLock(); } - return absl::Span(reinterpret_cast(buffer), + ASYNC_RETURN absl::Span(reinterpret_cast(buffer), span_size); } -absl::StatusOr +async::Task> ClientImpl::AcquirePublisherBuffer(PublisherImpl *publisher) { ClientLockGuard guard(this); if (publisher->NumLeases() >= size_t(publisher->MaxOutstandingSlotLeases())) { - return PublisherBufferLease{}; + ASYNC_RETURN PublisherBufferLease{}; } - if (absl::Status status = ReloadSubscribersIfNecessary(publisher); - !status.ok()) { - return status; + if (SubscribersChanged(publisher)) { + if (absl::Status status = + ASYNC_AWAIT(ReloadSubscribersIfNecessary(publisher)); + !status.ok()) { + ASYNC_RETURN status; + } } MessageSlot *slot = publisher->CurrentSlot(); @@ -833,17 +841,17 @@ ClientImpl::AcquirePublisherBuffer(PublisherImpl *publisher) { } else { if (publisher->IsReliable() && publisher->NumSubscribers(publisher->VirtualChannelId()) == 0) { - return PublisherBufferLease{}; + ASYNC_RETURN PublisherBufferLease{}; } slot = publisher->IsReliable() - ? publisher->FindFreeSlotReliable(publisher->GetPublisherId()) - : publisher->FindFreeSlotUnreliable(publisher->GetPublisherId()); + ? ASYNC_AWAIT(publisher->FindFreeSlotReliable(publisher->GetPublisherId())) + : ASYNC_AWAIT(publisher->FindFreeSlotUnreliable(publisher->GetPublisherId())); } if (slot == nullptr) { - return PublisherBufferLease{}; + ASYNC_RETURN PublisherBufferLease{}; } uint64_t lease_id = publisher->RegisterLease(slot); - return PublisherBufferLease{ + ASYNC_RETURN PublisherBufferLease{ .buffer = publisher->GetBufferAddress(slot), .buffer_size = size_t(publisher->SlotSize(slot)), .slot_id = slot->id, @@ -851,22 +859,25 @@ ClientImpl::AcquirePublisherBuffer(PublisherImpl *publisher) { }; } -absl::StatusOr +async::Task> ClientImpl::ReclaimPublisherBuffer(PublisherImpl *publisher, int32_t slot_id) { ClientLockGuard guard(this); if (publisher->NumLeases() >= size_t(publisher->MaxOutstandingSlotLeases())) { - return PublisherBufferLease{}; + ASYNC_RETURN PublisherBufferLease{}; } - if (absl::Status status = ReloadSubscribersIfNecessary(publisher); - !status.ok()) { - return status; + if (SubscribersChanged(publisher)) { + if (absl::Status status = + ASYNC_AWAIT(ReloadSubscribersIfNecessary(publisher)); + !status.ok()) { + ASYNC_RETURN status; + } } MessageSlot *slot = publisher->ClaimRetiredSlot(slot_id); if (slot == nullptr) { - return PublisherBufferLease{}; + ASYNC_RETURN PublisherBufferLease{}; } uint64_t lease_id = publisher->RegisterLease(slot); - return PublisherBufferLease{ + ASYNC_RETURN PublisherBufferLease{ .buffer = publisher->GetBufferAddress(slot), .buffer_size = size_t(publisher->SlotSize(slot)), .slot_id = slot->id, @@ -874,23 +885,26 @@ ClientImpl::ReclaimPublisherBuffer(PublisherImpl *publisher, int32_t slot_id) { }; } -absl::StatusOr +async::Task> ClientImpl::ReclaimAnyPublisherBuffer(PublisherImpl *publisher) { ClientLockGuard guard(this); if (publisher->NumLeases() >= size_t(publisher->MaxOutstandingSlotLeases())) { - return PublisherBufferLease{}; + ASYNC_RETURN PublisherBufferLease{}; } - if (absl::Status status = ReloadSubscribersIfNecessary(publisher); - !status.ok()) { - return status; + if (SubscribersChanged(publisher)) { + if (absl::Status status = + ASYNC_AWAIT(ReloadSubscribersIfNecessary(publisher)); + !status.ok()) { + ASYNC_RETURN status; + } } MessageSlot *slot = publisher->ClaimAnyRetiredSlot(); if (slot == nullptr) { - return PublisherBufferLease{}; + ASYNC_RETURN PublisherBufferLease{}; } uint64_t lease_id = publisher->RegisterLease(slot); - return PublisherBufferLease{ + ASYNC_RETURN PublisherBufferLease{ .buffer = publisher->GetBufferAddress(slot), .buffer_size = size_t(publisher->SlotSize(slot)), .slot_id = slot->id, @@ -898,40 +912,44 @@ ClientImpl::ReclaimAnyPublisherBuffer(PublisherImpl *publisher) { }; } -absl::StatusOr +async::Task> ClientImpl::PublishPublisherBuffer(PublisherImpl *publisher, const PublisherBufferLease &lease, int64_t message_size) { ClientLockGuard guard(this); - return PublishPublisherBufferInternal(publisher, lease, message_size, - /*payload=*/nullptr); + ASYNC_RETURN ASYNC_AWAIT(PublishPublisherBufferInternal(publisher, lease, message_size, + /*payload=*/nullptr)); } -absl::StatusOr +async::Task> ClientImpl::PublishPublisherBufferCopy(PublisherImpl *publisher, const PublisherBufferLease &lease, absl::Span payload) { ClientLockGuard guard(this); - return PublishPublisherBufferInternal( - publisher, lease, static_cast(payload.size()), payload.data()); + ASYNC_RETURN ASYNC_AWAIT(PublishPublisherBufferInternal( + publisher, lease, static_cast(payload.size()), payload.data())); } -absl::StatusOr ClientImpl::PublishPublisherBufferInternal( +async::Task> +ClientImpl::PublishPublisherBufferInternal( PublisherImpl *publisher, const PublisherBufferLease &lease, int64_t message_size, const std::byte *payload) { if (message_size <= 0) { - return absl::InvalidArgumentError("Message size must be greater than 0"); + ASYNC_RETURN absl::InvalidArgumentError("Message size must be greater than 0"); } MessageSlot *slot = publisher->FindLease(lease.slot_id, lease.lease_id); if (slot == nullptr) { - return absl::FailedPreconditionError("Invalid or stale publisher lease"); + ASYNC_RETURN absl::FailedPreconditionError("Invalid or stale publisher lease"); } if (message_size > publisher->SlotSize(slot)) { - return absl::InvalidArgumentError("Message size exceeds leased slot size"); + ASYNC_RETURN absl::InvalidArgumentError("Message size exceeds leased slot size"); } - if (absl::Status status = ReloadSubscribersIfNecessary(publisher); - !status.ok()) { - return status; + if (SubscribersChanged(publisher)) { + if (absl::Status status = + ASYNC_AWAIT(ReloadSubscribersIfNecessary(publisher)); + !status.ok()) { + ASYNC_RETURN status; + } } if (payload != nullptr) { std::memmove(publisher->GetBufferAddress(slot), payload, @@ -941,25 +959,25 @@ absl::StatusOr ClientImpl::PublishPublisherBufferInternal( absl::StatusOr status_or_size = publisher->on_send_callback_( publisher->GetBufferAddress(slot), message_size); if (!status_or_size.ok()) { - return status_or_size.status(); + ASYNC_RETURN status_or_size.status(); } message_size = status_or_size.value(); } slot->message_size = message_size; - Channel::PublishedMessage msg = publisher->ActivateSlotAndGetAnother( + Channel::PublishedMessage msg = ASYNC_AWAIT(publisher->ActivateSlotAndGetAnother( slot, publisher->IsReliable(), /*is_activation=*/false, publisher->GetPublisherId(), /*omit_prefix=*/false, /*use_prefix_slot_id=*/false, publisher->ForTunnel(), - /*acquire_next=*/false); + /*acquire_next=*/false)); publisher->RemoveLease(lease.slot_id); publisher->TriggerSubscribers(); if (publisher->NumSubscribers(publisher->VirtualChannelId()) == 0) { publisher->RetirePublishedSlotImmediately(slot); } - if (absl::Status status = publisher->UnmapUnusedBuffers(); !status.ok()) { - return status; + if (absl::Status status = ASYNC_AWAIT(publisher->UnmapUnusedBuffers()); !status.ok()) { + ASYNC_RETURN status; } - return Message(message_size, nullptr, msg.ordinal, msg.timestamp, + ASYNC_RETURN Message(message_size, nullptr, msg.ordinal, msg.timestamp, publisher->VirtualChannelId(), false, lease.slot_id, false); } @@ -986,7 +1004,7 @@ ClientImpl::GetPublisherBufferMetadata(PublisherImpl *publisher, return publisher->GetMetadata(slot); } -absl::StatusOr +async::Task> ClientImpl::PublishMessage(PublisherImpl *publisher, int64_t message_size, bool notify_subscribers) { return PublishMessageInternal(publisher, message_size, /*omit_prefix=*/false, @@ -999,7 +1017,7 @@ void ClientImpl::NotifySubscribers(PublisherImpl *publisher) { publisher->TriggerSubscribers(); } -absl::StatusOr +async::Task> ClientImpl::PublishMessageInternal(PublisherImpl *publisher, int64_t message_size, bool omit_prefix, bool use_prefix_slot_id, @@ -1010,13 +1028,16 @@ ClientImpl::PublishMessageInternal(PublisherImpl *publisher, ClientLockGuard guard(this, LockMode::kMaybeLocked); // Check if there are any new subscribers and if so, load their trigger fds. - if (absl::Status status = ReloadSubscribersIfNecessary(publisher); - !status.ok()) { - return status; + if (SubscribersChanged(publisher)) { + if (absl::Status status = + ASYNC_AWAIT(ReloadSubscribersIfNecessary(publisher)); + !status.ok()) { + ASYNC_RETURN status; + } } if (message_size == 0) { - return absl::InternalError("Message size must be greater than 0"); + ASYNC_RETURN absl::InternalError("Message size must be greater than 0"); } int32_t old_slot_id = publisher->CurrentSlotId(); @@ -1025,7 +1046,7 @@ ClientImpl::PublishMessageInternal(PublisherImpl *publisher, absl::StatusOr status_or_size = publisher->on_send_callback_( publisher->GetCurrentBufferAddress(), message_size); if (!status_or_size.ok()) { - return status_or_size.status(); + ASYNC_RETURN status_or_size.status(); } message_size = status_or_size.value(); } @@ -1038,9 +1059,9 @@ ClientImpl::PublishMessageInternal(PublisherImpl *publisher, } } - Channel::PublishedMessage msg = publisher->ActivateSlotAndGetAnother( + Channel::PublishedMessage msg = ASYNC_AWAIT(publisher->ActivateSlotAndGetAnother( publisher->IsReliable(), /*is_activation=*/false, omit_prefix, - use_prefix_slot_id, publisher->ForTunnel(), use_prefix_vchan_id); + use_prefix_slot_id, publisher->ForTunnel(), use_prefix_vchan_id)); // Prevent use of old_slot. old_slot = nullptr; @@ -1050,17 +1071,17 @@ ClientImpl::PublishMessageInternal(PublisherImpl *publisher, if (notify_subscribers) { publisher->TriggerSubscribers(); } - if (absl::Status status = publisher->UnmapUnusedBuffers(); !status.ok()) { - return status; + if (absl::Status status = ASYNC_AWAIT(publisher->UnmapUnusedBuffers()); !status.ok()) { + ASYNC_RETURN status; } if (msg.new_slot == nullptr) { if (publisher->IsReliable()) { // Reliable publishers don't get a slot until it's asked for. - return Message(message_size, nullptr, msg.ordinal, msg.timestamp, + ASYNC_RETURN Message(message_size, nullptr, msg.ordinal, msg.timestamp, publisher->VirtualChannelId(), false, -1, false); } - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("Out of slots for channel %s", publisher->Name())); } @@ -1069,7 +1090,7 @@ ClientImpl::PublishMessageInternal(PublisherImpl *publisher, msg.new_slot->ordinal.load(std::memory_order_relaxed)); } - return Message(message_size, nullptr, msg.ordinal, msg.timestamp, + ASYNC_RETURN Message(message_size, nullptr, msg.ordinal, msg.timestamp, publisher->VirtualChannelId(), false, old_slot_id, false); } @@ -1078,20 +1099,23 @@ void ClientImpl::CancelPublish(PublisherImpl * /*publisher*/) { ClientLockGuard guard(this, LockMode::kMaybeLocked); } -absl::Status +async::Task ClientImpl::WaitForReliablePublisher(PublisherImpl *publisher, std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c) { if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } if (!publisher->IsReliable()) { - return absl::InternalError("Unreliable publishers can't wait"); + ASYNC_RETURN absl::InternalError("Unreliable publishers can't wait"); } // Check if there are any new subscribers and if so, load their trigger fds. - if (absl::Status status = ReloadSubscribersIfNecessary(publisher); - !status.ok()) { - return status; + if (SubscribersChanged(publisher)) { + if (absl::Status status = + ASYNC_AWAIT(ReloadSubscribersIfNecessary(publisher)); + !status.ok()) { + ASYNC_RETURN status; + } } uint64_t timeout_ns = timeout.count(); #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO @@ -1100,9 +1124,21 @@ ClientImpl::WaitForReliablePublisher(PublisherImpl *publisher, async::WaitReadable(SocketContext(), publisher->GetPollFd().Fd(), std::chrono::nanoseconds(timeout_ns)); if (absl::IsDeadlineExceeded(s)) { - return absl::InternalError("Timeout waiting for reliable publisher"); + ASYNC_RETURN absl::InternalError("Timeout waiting for reliable publisher"); + } + ASYNC_RETURN s; + } +#endif +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // Called from an Async API: suspend this coroutine rather than blocking. + if (c == nullptr && SocketContext().Suspends()) { + absl::Status s = ASYNC_AWAIT( + async::WaitReadable(SocketContext(), publisher->GetPollFd().Fd(), + std::chrono::nanoseconds(timeout_ns))); + if (absl::IsDeadlineExceeded(s)) { + ASYNC_RETURN absl::InternalError("Timeout waiting for reliable publisher"); } - return s; + ASYNC_RETURN s; } #endif int result = -1; @@ -1121,7 +1157,7 @@ ClientImpl::WaitForReliablePublisher(PublisherImpl *publisher, if (timeout_ns != 0 && e == 0) { result = -1; } else if (e != 1) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("Error from poll waiting for reliable publisher: %s", strerror(errno))); } else { @@ -1129,27 +1165,30 @@ ClientImpl::WaitForReliablePublisher(PublisherImpl *publisher, } } if (result == -1) { - return absl::InternalError("Timeout waiting for reliable publisher"); + ASYNC_RETURN absl::InternalError("Timeout waiting for reliable publisher"); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::StatusOr +async::Task> ClientImpl::WaitForReliablePublisher(PublisherImpl *publisher, const toolbelt::FileDescriptor &fd, std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c) { if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } if (!publisher->IsReliable()) { - return absl::InternalError("Unreliable publishers can't wait"); + ASYNC_RETURN absl::InternalError("Unreliable publishers can't wait"); } // Check if there are any new subscribers and if so, load their trigger fds. - if (absl::Status status = ReloadSubscribersIfNecessary(publisher); - !status.ok()) { - return status; + if (SubscribersChanged(publisher)) { + if (absl::Status status = + ASYNC_AWAIT(ReloadSubscribersIfNecessary(publisher)); + !status.ok()) { + ASYNC_RETURN status; + } } int result = -1; uint64_t timeout_ns = timeout.count(); @@ -1158,12 +1197,26 @@ ClientImpl::WaitForReliablePublisher(PublisherImpl *publisher, absl::StatusOr r = async::WaitEither( SocketContext(), publisher->GetPollFd().Fd(), fd.Fd(), timeout); if (absl::IsDeadlineExceeded(r.status())) { - return absl::InternalError("Timeout waiting for reliable publisher"); + ASYNC_RETURN absl::InternalError("Timeout waiting for reliable publisher"); } if (!r.ok()) { - return r.status(); + ASYNC_RETURN r.status(); } - return *r; + ASYNC_RETURN *r; + } +#endif +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // Called from an Async API: suspend this coroutine rather than blocking. + if (c == nullptr && SocketContext().Suspends()) { + absl::StatusOr r = ASYNC_AWAIT(async::WaitEither( + SocketContext(), publisher->GetPollFd().Fd(), fd.Fd(), timeout)); + if (absl::IsDeadlineExceeded(r.status())) { + ASYNC_RETURN absl::InternalError("Timeout waiting for reliable publisher"); + } + if (!r.ok()) { + ASYNC_RETURN r.status(); + } + ASYNC_RETURN *r; } #endif if (c != nullptr) { @@ -1180,10 +1233,10 @@ ClientImpl::WaitForReliablePublisher(PublisherImpl *publisher, int e = GetSyscallShim().poll_fn( fds, 2, timeout_ns == 0 ? -1 : timeout_ns / 1000000); if (timeout_ns != 0 && e == 0) { - return absl::InternalError("Timeout waiting for reliable publisher"); + ASYNC_RETURN absl::InternalError("Timeout waiting for reliable publisher"); } if (e < 0) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("Error from poll waiting for reliable publisher: %s", strerror(errno))); } @@ -1192,19 +1245,20 @@ ClientImpl::WaitForReliablePublisher(PublisherImpl *publisher, } else if (fds[1].revents & (POLLIN | POLLHUP)) { result = fds[1].fd; // The passed in fd triggered. } else { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( "Unexpected poll result, neither publisher nor passed in fd " "triggered"); } } - return result; + ASYNC_RETURN result; } -absl::Status ClientImpl::WaitForSubscriber(SubscriberImpl *subscriber, +async::Task +ClientImpl::WaitForSubscriber(SubscriberImpl *subscriber, std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c) { if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } uint64_t timeout_ns = timeout.count(); @@ -1214,9 +1268,21 @@ absl::Status ClientImpl::WaitForSubscriber(SubscriberImpl *subscriber, async::WaitReadable(SocketContext(), subscriber->GetPollFd().Fd(), std::chrono::nanoseconds(timeout_ns)); if (absl::IsDeadlineExceeded(s)) { - return absl::InternalError("Timeout waiting for subscriber"); + ASYNC_RETURN absl::InternalError("Timeout waiting for subscriber"); + } + ASYNC_RETURN s; + } +#endif +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // Called from an Async API: suspend this coroutine rather than blocking. + if (c == nullptr && SocketContext().Suspends()) { + absl::Status s = ASYNC_AWAIT( + async::WaitReadable(SocketContext(), subscriber->GetPollFd().Fd(), + std::chrono::nanoseconds(timeout_ns))); + if (absl::IsDeadlineExceeded(s)) { + ASYNC_RETURN absl::InternalError("Timeout waiting for subscriber"); } - return s; + ASYNC_RETURN s; } #endif int result = -1; @@ -1236,23 +1302,24 @@ absl::Status ClientImpl::WaitForSubscriber(SubscriberImpl *subscriber, if (timeout_ns != 0 && e == 0) { result = -1; } else if (e != 1) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "Error from poll waiting for subscriber: %s", strerror(errno))); } else { result = fd.fd; } } if (result == -1) { - return absl::InternalError("Timeout waiting for subscriber"); + ASYNC_RETURN absl::InternalError("Timeout waiting for subscriber"); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::StatusOr ClientImpl::WaitForSubscriber( +async::Task> +ClientImpl::WaitForSubscriber( SubscriberImpl *subscriber, const toolbelt::FileDescriptor &fd, std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c) { if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } int result = -1; uint64_t timeout_ns = timeout.count(); @@ -1261,12 +1328,26 @@ absl::StatusOr ClientImpl::WaitForSubscriber( absl::StatusOr r = async::WaitEither( SocketContext(), subscriber->GetPollFd().Fd(), fd.Fd(), timeout); if (absl::IsDeadlineExceeded(r.status())) { - return absl::InternalError("Timeout waiting for subscriber"); + ASYNC_RETURN absl::InternalError("Timeout waiting for subscriber"); + } + if (!r.ok()) { + ASYNC_RETURN r.status(); + } + ASYNC_RETURN *r; + } +#endif +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // Called from an Async API: suspend this coroutine rather than blocking. + if (c == nullptr && SocketContext().Suspends()) { + absl::StatusOr r = ASYNC_AWAIT(async::WaitEither( + SocketContext(), subscriber->GetPollFd().Fd(), fd.Fd(), timeout)); + if (absl::IsDeadlineExceeded(r.status())) { + ASYNC_RETURN absl::InternalError("Timeout waiting for subscriber"); } if (!r.ok()) { - return r.status(); + ASYNC_RETURN r.status(); } - return *r; + ASYNC_RETURN *r; } #endif if (c != nullptr) { @@ -1284,25 +1365,25 @@ absl::StatusOr ClientImpl::WaitForSubscriber( int e = GetSyscallShim().poll_fn( fds, 2, timeout_ns == 0 ? -1 : timeout_ns / 1000000); if (timeout_ns != 0 && e == 0) { - return absl::InternalError("Timeout waiting for subscriber"); + ASYNC_RETURN absl::InternalError("Timeout waiting for subscriber"); } if (e < 0) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "Error from poll waiting for subscriber: %s", strerror(errno))); } if (fds[0].revents & (POLLIN | POLLHUP)) { // The subscriber's poll fd triggered. - return fds[0].fd; + ASYNC_RETURN fds[0].fd; } else if (fds[1].revents & (POLLIN | POLLHUP)) { // The passed in fd triggered. - return fds[1].fd; + ASYNC_RETURN fds[1].fd; } else { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( "Unexpected poll result, neither subscriber nor passed in fd " "triggered"); } } - return result; + ASYNC_RETURN result; } #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO @@ -1385,7 +1466,7 @@ absl::StatusOr ClientImpl::WaitForSubscriber( } #endif -absl::StatusOr +async::Task> ClientImpl::ReadMessageInternal(SubscriberImpl *subscriber, ReadMode mode, bool pass_activation, bool clear_trigger) { if (clear_trigger) { @@ -1402,10 +1483,10 @@ ClientImpl::ReadMessageInternal(SubscriberImpl *subscriber, ReadMode mode, switch (mode) { case ReadMode::kReadNext: - new_slot = subscriber->NextSlot(); + new_slot = ASYNC_AWAIT(subscriber->NextSlot()); break; case ReadMode::kReadNewest: - new_slot = subscriber->LastSlot(); + new_slot = ASYNC_AWAIT(subscriber->LastSlot()); break; } @@ -1418,10 +1499,10 @@ ClientImpl::ReadMessageInternal(SubscriberImpl *subscriber, ReadMode mode, // I'm out of messages to read, trigger the publishers to give me // some more. This is only for reliable publishers. subscriber->TriggerReliablePublishers(); - if (absl::Status status = subscriber->UnmapUnusedBuffers(); !status.ok()) { - return status; + if (absl::Status status = ASYNC_AWAIT(subscriber->UnmapUnusedBuffers()); !status.ok()) { + ASYNC_RETURN status; } - return Message(); + ASYNC_RETURN Message(); } subscriber->SetSlot(new_slot); int64_t delivered_message_size = @@ -1455,9 +1536,9 @@ ClientImpl::ReadMessageInternal(SubscriberImpl *subscriber, ReadMode mode, if (subscriber->IsReliable()) { subscriber->TriggerReliablePublishers(); } - return ReadMessageInternal(subscriber, mode, + ASYNC_RETURN ASYNC_AWAIT(ReadMessageInternal(subscriber, mode, /* pass_activation=*/false, - /* clear_trigger=*/false); + /* clear_trigger=*/false)); } } } @@ -1468,14 +1549,14 @@ ClientImpl::ReadMessageInternal(SubscriberImpl *subscriber, ReadMode mode, if (!status_or_size.ok()) { subscriber->UnreadSlot(new_slot); subscriber->SetSlot(nullptr); - return status_or_size.status(); + ASYNC_RETURN status_or_size.status(); } delivered_message_size = status_or_size.value(); } if (delivered_message_size <= 0) { subscriber->UnreadSlot(new_slot); subscriber->SetSlot(nullptr); - return Message(); + ASYNC_RETURN Message(); } // A FindMessage may already hold this slot. Share that hold instead of // counting the message twice; the read takes over releasing its delivery @@ -1489,7 +1570,7 @@ ClientImpl::ReadMessageInternal(SubscriberImpl *subscriber, ReadMode mode, // read picks the message up. subscriber->UnreadSlot(new_slot); subscriber->SetSlot(nullptr); - return Message(); + ASYNC_RETURN Message(); } if (shared) { subscriber->RetainActiveMessage(msg); @@ -1514,7 +1595,7 @@ ClientImpl::ReadMessageInternal(SubscriberImpl *subscriber, ReadMode mode, // would keep an extra reference after the ActiveMessage becomes valid // and prevent its active-message count from being released. ReportIfSubscriberStuck(subscriber); - return Message(); + ASYNC_RETURN Message(); } } subscriber->NoteUnstuck(); @@ -1567,14 +1648,15 @@ ClientImpl::ReadMessageInternal(SubscriberImpl *subscriber, ReadMode mode, subscriber->ClearActiveMessage(); } if (checksum_error && !subscriber->PassChecksumErrors()) { - return absl::InternalError("Checksum verification failed"); + ASYNC_RETURN absl::InternalError("Checksum verification failed"); } // A checksum error that is ignored results in a valid message with the // checksum_error flag set. - return ret_msg; + ASYNC_RETURN ret_msg; } -absl::StatusOr ClientImpl::ReadMessage(SubscriberImpl *subscriber, +async::Task> +ClientImpl::ReadMessage(SubscriberImpl *subscriber, ReadMode mode, ClearTrigger clear_trigger) { @@ -1594,26 +1676,29 @@ absl::StatusOr ClientImpl::ReadMessage(SubscriberImpl *subscriber, if (should_clear_trigger) { subscriber->ClearPollFd(); } - absl::Status status = ReloadSubscriber(subscriber); + absl::Status status = ASYNC_AWAIT(ReloadSubscriber(subscriber)); if (placeholder_check_hook_ != nullptr) { placeholder_check_hook_(); } if (!status.ok() || subscriber->IsPlaceholder()) { - return Message(); + ASYNC_RETURN Message(); } subscriber->TriggerReliablePublishers(); } // Check if there are any new reliable publishers and if so, load their // trigger fds. - absl::Status status = ReloadReliablePublishersIfNecessary(subscriber); - if (!status.ok()) { - return status; + if (PublishersChanged(subscriber)) { + if (absl::Status status = + ASYNC_AWAIT(ReloadReliablePublishersIfNecessary(subscriber)); + !status.ok()) { + ASYNC_RETURN status; + } } - return ReadMessageInternal(subscriber, mode, + ASYNC_RETURN ASYNC_AWAIT(ReadMessageInternal(subscriber, mode, subscriber->options_.pass_activation, - should_clear_trigger); + should_clear_trigger)); } absl::StatusOr> @@ -1662,21 +1747,21 @@ void ClientImpl::ReportIfSubscriberStuck(SubscriberImpl *subscriber) { : ""); } -absl::StatusOr +async::Task> ClientImpl::ReadMessageFromBatch(SubscriberImpl *subscriber, ReadMode mode) { ClientLockGuard guard(this); - return ReadMessageInternal(subscriber, mode, + ASYNC_RETURN ASYNC_AWAIT(ReadMessageInternal(subscriber, mode, subscriber->options_.pass_activation, - /*clear_trigger=*/false); + /*clear_trigger=*/false)); } -absl::StatusOr +async::Task> ClientImpl::FindMessageInternal(SubscriberImpl *subscriber, uint64_t timestamp) { - MessageSlot *new_slot = subscriber->FindMessage(timestamp); + MessageSlot *new_slot = ASYNC_AWAIT(subscriber->FindMessage(timestamp)); if (new_slot == nullptr) { // Not found. - return Message(); + ASYNC_RETURN Message(); } // FindMessage pinned the slot. The returned Message owns that pin and // releases it when dropped, without consuming the delivery obligation, so a @@ -1686,23 +1771,24 @@ ClientImpl::FindMessageInternal(SubscriberImpl *subscriber, &rejected)) { Message msg(held); held->DecRef(); - return msg; + ASYNC_RETURN msg; } if (rejected) { subscriber->DropLookupPin(new_slot); subscriber->SetSlot(nullptr); - return Message(); + ASYNC_RETURN Message(); } auto msg = subscriber->ActivateLookup(new_slot); if (msg == nullptr) { ReportIfSubscriberStuck(subscriber); - return Message(); + ASYNC_RETURN Message(); } subscriber->NoteUnstuck(); - return Message(msg); + ASYNC_RETURN Message(msg); } -absl::StatusOr ClientImpl::FindMessage(SubscriberImpl *subscriber, +async::Task> +ClientImpl::FindMessage(SubscriberImpl *subscriber, uint64_t timestamp) { ClientLockGuard guard(this); @@ -1715,23 +1801,26 @@ absl::StatusOr ClientImpl::FindMessage(SubscriberImpl *subscriber, // As in ReadMessage, clear before the check so a publisher arriving after // it leaves the poll fd triggered. subscriber->ClearPollFd(); - absl::Status status = ReloadSubscriber(subscriber); + absl::Status status = ASYNC_AWAIT(ReloadSubscriber(subscriber)); if (placeholder_check_hook_ != nullptr) { placeholder_check_hook_(); } if (!status.ok() || subscriber->IsPlaceholder()) { - return Message(); + ASYNC_RETURN Message(); } } // Check if there are any new reliable publishers and if so, load their // trigger fds. - absl::Status status = ReloadReliablePublishersIfNecessary(subscriber); - if (!status.ok()) { - return status; + if (PublishersChanged(subscriber)) { + if (absl::Status status = + ASYNC_AWAIT(ReloadReliablePublishersIfNecessary(subscriber)); + !status.ok()) { + ASYNC_RETURN status; + } } - return FindMessageInternal(subscriber, timestamp); + ASYNC_RETURN ASYNC_AWAIT(FindMessageInternal(subscriber, timestamp)); } struct pollfd ClientImpl::GetPollFd(SubscriberImpl *subscriber) const { @@ -1770,39 +1859,40 @@ int64_t ClientImpl::GetCurrentOrdinal(SubscriberImpl *sub) { return slot->ordinal.load(std::memory_order_relaxed); } -bool ClientImpl::CheckReload(ClientChannel *channel) { - auto reloaded = ReloadBuffersIfNecessary(channel); +async::Task ClientImpl::CheckReload(ClientChannel *channel) { + auto reloaded = ASYNC_AWAIT(ReloadBuffersIfNecessary(channel)); if (!reloaded.ok()) { - return false; + ASYNC_RETURN false; } - return *reloaded; + ASYNC_RETURN *reloaded; } -absl::StatusOr +async::Task> ClientImpl::ReloadBuffersIfNecessary(ClientChannel *channel) { if (!channel->BuffersChanged()) { - return false; + ASYNC_RETURN false; } if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } - if (absl::Status status = channel->AttachBuffers(); !status.ok()) { - return status; + if (absl::Status status = ASYNC_AWAIT(channel->AttachBuffers()); !status.ok()) { + ASYNC_RETURN status; } - return true; + ASYNC_RETURN true; } -absl::Status ClientImpl::ReloadSubscriber(SubscriberImpl *subscriber) { +async::Task +ClientImpl::ReloadSubscriber(SubscriberImpl *subscriber) { // Check if there are any updates to the publishers // since that last time we checked. SystemControlBlock *scb = subscriber->GetScb(); int updates = scb->counters[subscriber->GetChannelId()].num_pub_updates; if (subscriber->NumUpdates() == updates) { - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } Request req; FillCreateSubscriberRequest(req.mutable_create_subscriber(), @@ -1813,14 +1903,14 @@ absl::Status ClientImpl::ReloadSubscriber(SubscriberImpl *subscriber) { Response resp; std::vector fds; fds.reserve(100); - if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, resp, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } auto &sub_resp = resp.create_subscriber(); if (!sub_resp.error().empty()) { - return absl::InternalError(sub_resp.error()); + ASYNC_RETURN absl::InternalError(sub_resp.error()); } // A subscriber-created placeholder is the only case where the server @@ -1831,7 +1921,7 @@ absl::Status ClientImpl::ReloadSubscriber(SubscriberImpl *subscriber) { subscriber->ResetDeliveryState(); // Leave the system control block mapped. Its counters are read from // other threads, and every channel in this client shares the mapping. - subscriber->UnmapForReload(); + ASYNC_AWAIT(subscriber->UnmapForReload()); } if (!sub_resp.type().empty()) { @@ -1859,13 +1949,13 @@ absl::Status ClientImpl::ReloadSubscriber(SubscriberImpl *subscriber) { std::move(fds[sub_resp.bcb_fd_index()])); if (absl::Status status = subscriber->Map(std::move(channel_fds), scb_fd_); !status.ok()) { - return status; + ASYNC_RETURN status; } subscriber->InitActiveMessages(); } - if (absl::Status status = subscriber->AttachBuffers(); !status.ok()) { - return status; + if (absl::Status status = ASYNC_AWAIT(subscriber->AttachBuffers()); !status.ok()) { + ASYNC_RETURN status; } subscriber->SetTriggerFd(fds[sub_resp.trigger_fd_index()]); subscriber->SetPollFd(fds[sub_resp.poll_fd_index()]); @@ -1884,19 +1974,19 @@ absl::Status ClientImpl::ReloadSubscriber(SubscriberImpl *subscriber) { subscriber->SetNumUpdates(updates); // subscriber->Dump(); - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::Status +async::Task ClientImpl::ReloadSubscribersIfNecessary(PublisherImpl *publisher) { SystemControlBlock *scb = publisher->GetScb(); int updates = scb->counters[publisher->GetChannelId()].num_sub_updates; if (publisher->NumUpdates() == updates) { - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } publisher->SetNumUpdates(updates); if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } // We do have updates, get a new list of subscriber for @@ -1909,9 +1999,9 @@ ClientImpl::ReloadSubscribersIfNecessary(PublisherImpl *publisher) { Response resp; std::vector fds; fds.reserve(100); - if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, resp, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } auto &sub_resp = resp.get_triggers(); @@ -1925,22 +2015,22 @@ ClientImpl::ReloadSubscribersIfNecessary(PublisherImpl *publisher) { for (auto index : sub_resp.retirement_fd_indexes()) { publisher->AddRetirementTrigger(fds[size_t(index)]); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::Status +async::Task ClientImpl::ReloadReliablePublishersIfNecessary(SubscriberImpl *subscriber) { // Check if there are any updates to the publishers // since that last time we checked. SystemControlBlock *scb = subscriber->GetScb(); int updates = scb->counters[subscriber->GetChannelId()].num_pub_updates; if (subscriber->NumUpdates() == updates) { - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } subscriber->SetNumUpdates(updates); if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } // We do have updates, get a new list of subscriber for // the channel. @@ -1952,9 +2042,9 @@ ClientImpl::ReloadReliablePublishersIfNecessary(SubscriberImpl *subscriber) { Response resp; std::vector fds; fds.reserve(100); - if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, resp, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } auto &sub_resp = resp.get_triggers(); @@ -1969,59 +2059,59 @@ ClientImpl::ReloadReliablePublishersIfNecessary(SubscriberImpl *subscriber) { subscriber->AddRetirementTrigger(fds[size_t(index)]); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } // A reliable publisher always sends a single activation message when it // is created. This is to ensure that the reliable subscribers see // on message and thus keep a reference to it. -absl::Status ClientImpl::ActivateReliableChannel(PublisherImpl *publisher) { +async::Task ClientImpl::ActivateReliableChannel(PublisherImpl *publisher) { MessageSlot *slot = - publisher->FindFreeSlotReliable(publisher->GetPublisherId()); + ASYNC_AWAIT(publisher->FindFreeSlotReliable(publisher->GetPublisherId())); if (slot == nullptr) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("Channel %s has no free slots", publisher->Name())); } publisher->SetSlot(slot); void *buffer = publisher->GetCurrentBufferAddress(); if (buffer == nullptr) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("Channel %s has no buffer", publisher->Name())); } slot->message_size.store(1, std::memory_order_relaxed); - publisher->ActivateSlotAndGetAnother( + ASYNC_AWAIT(publisher->ActivateSlotAndGetAnother( /*reliable=*/true, /*is_activation=*/true, - /*omit_prefix=*/false, /*use_prefix_slot_id=*/false); + /*omit_prefix=*/false, /*use_prefix_slot_id=*/false)); publisher->SetSlot(nullptr); publisher->TriggerSubscribers(); - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::Status ClientImpl::ActivateChannel(PublisherImpl *publisher) { +async::Task ClientImpl::ActivateChannel(PublisherImpl *publisher) { if (publisher->IsActivated(publisher->VirtualChannelId())) { - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } void *buffer = publisher->GetCurrentBufferAddress(); if (buffer == nullptr) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("3 Channel %s has no buffer", publisher->Name())); } MessageSlot *slot = publisher->CurrentSlot(); slot->message_size.store(1, std::memory_order_relaxed); - Channel::PublishedMessage msg = publisher->ActivateSlotAndGetAnother( + Channel::PublishedMessage msg = ASYNC_AWAIT(publisher->ActivateSlotAndGetAnother( /*reliable=*/false, /*is_activation=*/true, - /*omit_prefix=*/false, /*use_prefix_slot_id=*/false); + /*omit_prefix=*/false, /*use_prefix_slot_id=*/false)); publisher->SetSlot(msg.new_slot); publisher->TriggerSubscribers(); - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } absl::Status ClientImpl::RemoveChannel(ClientChannel *channel) { @@ -2033,10 +2123,11 @@ absl::Status ClientImpl::RemoveChannel(ClientChannel *channel) { return absl::OkStatus(); } -absl::Status ClientImpl::RemovePublisher(PublisherImpl *publisher) { +async::Task +ClientImpl::RemovePublisher(PublisherImpl *publisher) { ClientLockGuard guard(this); if (!socket_.Connected()) { - return RemoveChannel(publisher); + ASYNC_RETURN RemoveChannel(publisher); } Request req; auto *cmd = req.mutable_remove_publisher(); @@ -2047,22 +2138,23 @@ absl::Status ClientImpl::RemovePublisher(PublisherImpl *publisher) { Response response; std::vector fds; fds.reserve(100); - if (absl::Status status = SendRequestReceiveResponse(req, response, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, response, fds)); !status.ok()) { - return RemoveChannel(publisher); + ASYNC_RETURN RemoveChannel(publisher); } auto &resp = response.remove_publisher(); if (!resp.error().empty()) { - return absl::InternalError(resp.error()); + ASYNC_RETURN absl::InternalError(resp.error()); } - return RemoveChannel(publisher); + ASYNC_RETURN RemoveChannel(publisher); } -absl::Status ClientImpl::RemoveSubscriber(SubscriberImpl *subscriber) { +async::Task +ClientImpl::RemoveSubscriber(SubscriberImpl *subscriber) { ClientLockGuard guard(this); if (!socket_.Connected()) { - return RemoveChannel(subscriber); + ASYNC_RETURN RemoveChannel(subscriber); } Request req; auto *cmd = req.mutable_remove_subscriber(); @@ -2074,16 +2166,16 @@ absl::Status ClientImpl::RemoveSubscriber(SubscriberImpl *subscriber) { Response response; std::vector fds; fds.reserve(100); - if (absl::Status status = SendRequestReceiveResponse(req, response, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, response, fds)); !status.ok()) { - return RemoveChannel(subscriber); + ASYNC_RETURN RemoveChannel(subscriber); } auto &resp = response.remove_subscriber(); if (!resp.error().empty()) { - return absl::InternalError(resp.error()); + ASYNC_RETURN absl::InternalError(resp.error()); } - return RemoveChannel(subscriber); + ASYNC_RETURN RemoveChannel(subscriber); } absl::StatusOr @@ -2102,10 +2194,10 @@ const ChannelCounters &ClientImpl::GetChannelCounters(ClientChannel *channel) { return channel->GetCounters(); } -absl::StatusOr +async::Task> ClientImpl::GetChannelInfo(const std::string &channel) { if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } Request req; auto *cmd = req.mutable_get_channel_info(); @@ -2114,18 +2206,18 @@ ClientImpl::GetChannelInfo(const std::string &channel) { // Send request to server and wait for response. Response response; std::vector fds; - if (absl::Status status = SendRequestReceiveResponse(req, response, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, response, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } auto &resp = response.get_channel_info(); if (!resp.error().empty()) { - return absl::InternalError(resp.error()); + ASYNC_RETURN absl::InternalError(resp.error()); } // There will be one channel information in the response. if (resp.channels_size() != 1) { - return absl::InternalError("Invalid response for getChannelInfo"); + ASYNC_RETURN absl::InternalError("Invalid response for getChannelInfo"); } ChannelInfo result; const ChannelInfoProto &info = resp.channels()[0]; @@ -2144,13 +2236,14 @@ ClientImpl::GetChannelInfo(const std::string &channel) { result.subscriber_queue_arena_size = info.subscriber_queue_arena_size(); result.is_local = info.is_local(); - return result; + ASYNC_RETURN result; } -absl::StatusOr> ClientImpl::GetChannelInfo() { +async::Task>> +ClientImpl::GetChannelInfo() { ClientLockGuard guard(this); if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } Request req; [[maybe_unused]] auto cmd = req.mutable_get_channel_info(); @@ -2158,13 +2251,13 @@ absl::StatusOr> ClientImpl::GetChannelInfo() { // Send request to server and wait for response. Response response; std::vector fds; - if (absl::Status status = SendRequestReceiveResponse(req, response, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, response, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } auto &resp = response.get_channel_info(); if (!resp.error().empty()) { - return absl::InternalError(resp.error()); + ASYNC_RETURN absl::InternalError(resp.error()); } std::vector r; for (auto &info : resp.channels()) { @@ -2186,23 +2279,24 @@ absl::StatusOr> ClientImpl::GetChannelInfo() { result.is_local = info.is_local(); r.push_back(result); } - return r; + ASYNC_RETURN r; } -absl::StatusOr ClientImpl::ChannelExists(const std::string &channelName) { +async::Task> +ClientImpl::ChannelExists(const std::string &channelName) { ClientLockGuard guard(this); if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } - absl::StatusOr info = GetChannelInfo(channelName); - return info.ok(); + absl::StatusOr info = ASYNC_AWAIT(GetChannelInfo(channelName)); + ASYNC_RETURN info.ok(); } -absl::StatusOr +async::Task> ClientImpl::GetChannelStats(const std::string &channel) { ClientLockGuard guard(this); if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } Request req; auto *cmd = req.mutable_get_channel_stats(); @@ -2211,17 +2305,17 @@ ClientImpl::GetChannelStats(const std::string &channel) { // Send request to server and wait for response. Response response; std::vector fds; - if (absl::Status status = SendRequestReceiveResponse(req, response, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, response, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } auto &resp = response.get_channel_stats(); if (!resp.error().empty()) { - return absl::InternalError(resp.error()); + ASYNC_RETURN absl::InternalError(resp.error()); } // There will be one channel information in the response. if (resp.channels_size() != 1) { - return absl::InternalError("Invalid response for getChannelStats"); + ASYNC_RETURN absl::InternalError("Invalid response for getChannelStats"); } ChannelStats result; const ChannelStatsProto &stats = resp.channels()[0]; @@ -2230,13 +2324,14 @@ ClientImpl::GetChannelStats(const std::string &channel) { result.total_messages = stats.total_messages(); result.max_message_size = stats.max_message_size(); result.is_local = stats.is_local(); - return result; + ASYNC_RETURN result; } -absl::StatusOr> ClientImpl::GetChannelStats() { +async::Task>> +ClientImpl::GetChannelStats() { ClientLockGuard guard(this); if (absl::Status status = CheckConnected(); !status.ok()) { - return status; + ASYNC_RETURN status; } Request req; @@ -2245,13 +2340,13 @@ absl::StatusOr> ClientImpl::GetChannelStats() { // Send request to server and wait for response. Response response; std::vector fds; - if (absl::Status status = SendRequestReceiveResponse(req, response, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, response, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } auto &resp = response.get_channel_stats(); if (!resp.error().empty()) { - return absl::InternalError(resp.error()); + ASYNC_RETURN absl::InternalError(resp.error()); } std::vector r; for (auto &stats : resp.channels()) { @@ -2263,19 +2358,20 @@ absl::StatusOr> ClientImpl::GetChannelStats() { result.is_local = stats.is_local(); r.push_back(result); } - return r; + ASYNC_RETURN r; } -absl::Status ClientImpl::ResizeChannel(PublisherImpl *publisher, +async::Task +ClientImpl::ResizeChannel(PublisherImpl *publisher, int64_t new_slot_size) { if (publisher->IsFixedSize()) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "Channel %s is fixed size at %d bytes; can't increase it to %d bytes", publisher->Name(), publisher->SlotSize(), new_slot_size)); } if (int64_t max_slot_size = publisher->MaxSlotSize(); max_slot_size != 0 && new_slot_size > max_slot_size) { - return absl::InvalidArgumentError(absl::StrFormat( + ASYNC_RETURN absl::InvalidArgumentError(absl::StrFormat( "Channel %s has a maximum slot size of %d bytes; can't increase it to " "%d bytes", publisher->Name(), max_slot_size, new_slot_size)); @@ -2288,11 +2384,11 @@ absl::Status ClientImpl::ResizeChannel(PublisherImpl *publisher, if (absl::Status s = it->second(publisher, publisher->SlotSize(), new_slot_size); !s.ok()) { - return s; + ASYNC_RETURN s; } } - return publisher->CreateOrAttachBuffers(Aligned(new_slot_size)); + ASYNC_RETURN ASYNC_AWAIT(publisher->CreateOrAttachBuffers(Aligned(new_slot_size))); } void ClientImpl::FillCreatePublisherRequest(CreatePublisherRequest *cmd, @@ -2389,7 +2485,8 @@ void ClientImpl::ApplySubscriberResponseFds( subscriber->SetNumUpdates(resp.num_pub_updates()); } -absl::Status ClientImpl::Reconnect() { +async::Task +ClientImpl::Reconnect() { reconnecting_ = true; auto cleanup = [this]() { reconnecting_ = false; }; @@ -2402,7 +2499,7 @@ absl::Status ClientImpl::Reconnect() { absl::Status status = socket_.Connect(socket_name_); if (!status.ok()) { cleanup(); - return status; + ASYNC_RETURN status; } Request init_req; @@ -2410,14 +2507,14 @@ absl::Status ClientImpl::Reconnect() { Response init_resp; std::vector init_fds; init_fds.reserve(100); - status = SendRequestReceiveResponse(init_req, init_resp, init_fds); + status = ASYNC_AWAIT(SendRequestReceiveResponse(init_req, init_resp, init_fds)); if (!status.ok()) { cleanup(); - return status; + ASYNC_RETURN status; } if (!init_resp.init().error().empty()) { cleanup(); - return absl::InternalError(init_resp.init().error()); + ASYNC_RETURN absl::InternalError(init_resp.init().error()); } scb_fd_ = std::move(init_fds[init_resp.init().scb_fd_index()]); session_id_ = init_resp.init().session_id(); @@ -2426,22 +2523,22 @@ absl::Status ClientImpl::Reconnect() { for (auto &channel : channels_) { if (auto *pub = dynamic_cast(channel.get())) { - status = ReregisterPublisher(pub); + status = ASYNC_AWAIT(ReregisterPublisher(pub)); if (!status.ok()) { cleanup(); - return status; + ASYNC_RETURN status; } } else if (auto *sub = dynamic_cast(channel.get())) { - status = ReregisterSubscriber(sub); + status = ASYNC_AWAIT(ReregisterSubscriber(sub)); if (!status.ok()) { cleanup(); - return status; + ASYNC_RETURN status; } } } cleanup(); - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } bool ClientImpl::ShouldReconnect(const absl::Status &failure) const { @@ -2449,10 +2546,31 @@ bool ClientImpl::ShouldReconnect(const absl::Status &failure) const { // stopped, not that the server has gone. Reconnecting then can block in // connect() for good if the server has stopped accepting connections, as it // does while it shuts down. - return was_connected_ && !reconnecting_ && !absl::IsCancelled(failure); + if (!was_connected_ || reconnecting_ || absl::IsCancelled(failure)) { + return false; + } +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // send()/recv() can fail synchronously (for example EPIPE when the server's + // client handler exited on shutdown first) without reaching a wait that sees + // the coroutine's interrupt fd. Check the interrupt fd directly too. + if (co20::Coroutine *co = SocketContext().Coroutine(); co != nullptr) { + if (co->IsAborted()) { + return false; + } + if (int ifd = co->GetInterruptFd(); ifd != -1) { + struct pollfd pfd = {.fd = ifd, .events = POLLIN, .revents = 0}; + if (GetSyscallShim().poll_fn(&pfd, 1, 0) > 0 && + (pfd.revents & (POLLIN | POLLHUP | POLLERR)) != 0) { + return false; + } + } + } +#endif + return true; } -absl::Status ClientImpl::ReregisterPublisher(PublisherImpl *publisher) { +async::Task +ClientImpl::ReregisterPublisher(PublisherImpl *publisher) { Request req; FillCreatePublisherRequest(req.mutable_create_publisher(), publisher->Name(), publisher->options_, @@ -2463,20 +2581,21 @@ absl::Status ClientImpl::ReregisterPublisher(PublisherImpl *publisher) { Response resp; std::vector fds; fds.reserve(100); - if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, resp, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } auto &pub_resp = resp.create_publisher(); if (!pub_resp.error().empty()) { - return absl::InternalError(pub_resp.error()); + ASYNC_RETURN absl::InternalError(pub_resp.error()); } ApplyPublisherResponseFds(publisher, pub_resp, fds); - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::Status ClientImpl::ReregisterSubscriber(SubscriberImpl *subscriber) { +async::Task +ClientImpl::ReregisterSubscriber(SubscriberImpl *subscriber) { Request req; FillCreateSubscriberRequest(req.mutable_create_subscriber(), subscriber->Name(), subscriber->options_, @@ -2485,20 +2604,21 @@ absl::Status ClientImpl::ReregisterSubscriber(SubscriberImpl *subscriber) { Response resp; std::vector fds; fds.reserve(100); - if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, resp, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } auto &sub_resp = resp.create_subscriber(); if (!sub_resp.error().empty()) { - return absl::InternalError(sub_resp.error()); + ASYNC_RETURN absl::InternalError(sub_resp.error()); } ApplySubscriberResponseFds(subscriber, sub_resp, fds); - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::Status ClientImpl::SendRequestReceiveResponse( +async::Task +ClientImpl::SendRequestReceiveResponse( const Request &req, Response &response, std::vector &fds, const std::vector &send_fds) { @@ -2509,92 +2629,94 @@ absl::Status ClientImpl::SendRequestReceiveResponse( char *sendbuf = send_msg.data() + sizeof(int32_t); if (!req.SerializeToArray(sendbuf, msg_len)) { - return absl::InternalError("Failed to serialize request"); + ASYNC_RETURN absl::InternalError("Failed to serialize request"); } absl::StatusOr n = - socket_.SendMessage(sendbuf, msg_len, SocketContext()); + ASYNC_AWAIT(socket_.SendMessage(sendbuf, msg_len, SocketContext())); if (!n.ok()) { socket_.Close(); if (ShouldReconnect(n.status())) { - if (absl::Status rs = Reconnect(); rs.ok()) { - return SendRequestReceiveResponse(req, response, fds, send_fds); + if (absl::Status rs = ASYNC_AWAIT(Reconnect()); rs.ok()) { + ASYNC_RETURN ASYNC_AWAIT(SendRequestReceiveResponse(req, response, fds, send_fds)); } else { - return rs; + ASYNC_RETURN rs; } } - return n.status(); + ASYNC_RETURN n.status(); } if (!send_fds.empty()) { - absl::Status status = socket_.SendFds(send_fds, SocketContext()); + absl::Status status = + ASYNC_AWAIT(socket_.SendFds(send_fds, SocketContext())); if (!status.ok()) { socket_.Close(); - return status; + ASYNC_RETURN status; } } } absl::StatusOr> recv_msg = - socket_.ReceiveVariableLengthMessage(SocketContext()); + ASYNC_AWAIT(socket_.ReceiveVariableLengthMessage(SocketContext())); if (!recv_msg.ok()) { socket_.Close(); if (ShouldReconnect(recv_msg.status())) { - if (absl::Status rs = Reconnect(); rs.ok()) { - return SendRequestReceiveResponse(req, response, fds, send_fds); + if (absl::Status rs = ASYNC_AWAIT(Reconnect()); rs.ok()) { + ASYNC_RETURN ASYNC_AWAIT(SendRequestReceiveResponse(req, response, fds, send_fds)); } else { - return rs; + ASYNC_RETURN rs; } } - return recv_msg.status(); + ASYNC_RETURN recv_msg.status(); } if (!response.ParseFromArray(recv_msg->data(), static_cast(recv_msg->size()))) { socket_.Close(); - return absl::InternalError("Failed to parse response"); + ASYNC_RETURN absl::InternalError("Failed to parse response"); } - absl::Status s = socket_.ReceiveFds(fds, SocketContext()); + absl::Status s = ASYNC_AWAIT(socket_.ReceiveFds(fds, SocketContext())); if (!s.ok()) { socket_.Close(); } - return s; + ASYNC_RETURN s; } -absl::Status ClientImpl::SendOneWayRequest( +async::Task +ClientImpl::SendOneWayRequest( const Request &req, const std::vector &fds) { size_t msg_len = req.ByteSizeLong(); std::vector send_msg(sizeof(int32_t) + msg_len); char *sendbuf = send_msg.data() + sizeof(int32_t); if (!req.SerializeToArray(sendbuf, msg_len)) { - return absl::InternalError("Failed to serialize one-way request"); + ASYNC_RETURN absl::InternalError("Failed to serialize one-way request"); } absl::StatusOr n = - socket_.SendMessage(sendbuf, msg_len, SocketContext()); + ASYNC_AWAIT(socket_.SendMessage(sendbuf, msg_len, SocketContext())); if (!n.ok()) { socket_.Close(); if (ShouldReconnect(n.status())) { - if (absl::Status rs = Reconnect(); rs.ok()) { - return SendOneWayRequest(req, fds); + if (absl::Status rs = ASYNC_AWAIT(Reconnect()); rs.ok()) { + ASYNC_RETURN ASYNC_AWAIT(SendOneWayRequest(req, fds)); } else { - return rs; + ASYNC_RETURN rs; } } - return n.status(); + ASYNC_RETURN n.status(); } if (!fds.empty()) { - absl::Status status = socket_.SendFds(fds, SocketContext()); + absl::Status status = ASYNC_AWAIT(socket_.SendFds(fds, SocketContext())); if (!status.ok()) { socket_.Close(); - return status; + ASYNC_RETURN status; } } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::Status +async::Task ClientImpl::RegisterClientBuffer(const ClientBufferHandleMetadata &metadata, const toolbelt::FileDescriptor *fd) { Request req; @@ -2609,17 +2731,17 @@ ClientImpl::RegisterClientBuffer(const ClientBufferHandleMetadata &metadata, Response response; std::vector response_fds; if (absl::Status status = - SendRequestReceiveResponse(req, response, response_fds, fds); + ASYNC_AWAIT(SendRequestReceiveResponse(req, response, response_fds, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } if (!response.register_client_buffer().error().empty()) { - return absl::InternalError(response.register_client_buffer().error()); + ASYNC_RETURN absl::InternalError(response.register_client_buffer().error()); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::StatusOr> +async::Task>> ClientImpl::GetClientBuffers(const std::string &channel_name, uint64_t session_id, uint32_t buffer_index) { Request req; @@ -2630,16 +2752,16 @@ ClientImpl::GetClientBuffers(const std::string &channel_name, Response response; std::vector fds; - if (absl::Status status = SendRequestReceiveResponse(req, response, fds); + if (absl::Status status = ASYNC_AWAIT(SendRequestReceiveResponse(req, response, fds)); !status.ok()) { - return status; + ASYNC_RETURN status; } const auto &get_resp = response.get_client_buffers(); if (!get_resp.error().empty()) { - return absl::InternalError(get_resp.error()); + ASYNC_RETURN absl::InternalError(get_resp.error()); } if (get_resp.metadata_size() != get_resp.fd_indexes_size()) { - return absl::InternalError("Malformed client buffer response"); + ASYNC_RETURN absl::InternalError("Malformed client buffer response"); } std::vector result; result.reserve(get_resp.metadata_size()); @@ -2653,10 +2775,11 @@ ClientImpl::GetClientBuffers(const std::string &channel_name, } result.push_back(std::move(buffer)); } - return result; + ASYNC_RETURN result; } -absl::Status ClientImpl::UnregisterClientBuffer(const std::string &channel_name, +async::Task +ClientImpl::UnregisterClientBuffer(const std::string &channel_name, uint64_t session_id, uint32_t buffer_index) { Request req; @@ -2664,7 +2787,7 @@ absl::Status ClientImpl::UnregisterClientBuffer(const std::string &channel_name, unregister->set_channel_name(channel_name); unregister->set_session_id(session_id); unregister->set_buffer_index(buffer_index); - return SendOneWayRequest(req); + ASYNC_RETURN ASYNC_AWAIT(SendOneWayRequest(req)); } } // namespace subspace diff --git a/client/client.h b/client/client.h index 0a25d469..1a41a701 100644 --- a/client/client.h +++ b/client/client.h @@ -17,6 +17,7 @@ #include "co/coroutine.h" #include "common/async/context.h" #include "common/async/socket.h" +#include "common/async/task.h" #include "common/async/wait.h" #include "common/channel.h" #include "common/client_buffer.h" @@ -402,26 +403,29 @@ class ClientImpl : public std::enable_shared_from_this { const std::string &GetName() const { return name_; } // Initialize the client by connecting to the server. - absl::Status Init(const std::string &server_socket = kDefaultServerSocket, + async::Task + Init(const std::string &server_socket = kDefaultServerSocket, const std::string &client_name = ""); // Create a publisher for the given channel. If the channel doesn't exit // it will be created with num_slots slots, each of which is slot_size // bytes long. - absl::StatusOr + async::Task> CreatePublisher(const std::string &channel_name, int64_t slot_size, int num_slots, const PublisherOptions &opts = PublisherOptions()); // Create a publisher with the slot size and number of slots set in the // options. - absl::StatusOr + async::Task> CreatePublisher(const std::string &channel_name, const PublisherOptions &opts = PublisherOptions()); + async::Task RemoveServerPublisher(const std::string &channel_name, + int32_t publisher_id); // Create a subscriber for the given channel. This can be done before there // are any publishers on the channel. - absl::StatusOr + async::Task> CreateSubscriber(const std::string &channel_name, const SubscriberOptions &opts = SubscriberOptions()); @@ -438,19 +442,24 @@ class ClientImpl : public std::enable_shared_from_this { absl::StatusOr GetChannelCounters(const std::string &channel_name) const; - absl::StatusOr + async::Task> GetChannelInfo(const std::string &channelName); - absl::StatusOr> GetChannelInfo(); + async::Task>> + GetChannelInfo(); - absl::StatusOr + async::Task> GetChannelStats(const std::string &channelName); - absl::StatusOr> GetChannelStats(); + async::Task>> + GetChannelStats(); - absl::StatusOr ChannelExists(const std::string &channelName); + async::Task> + ChannelExists(const std::string &channelName); // Remove publisher and subscriber. - absl::Status RemovePublisher(details::PublisherImpl *publisher); - absl::Status RemoveSubscriber(details::SubscriberImpl *subscriber); + async::Task + RemovePublisher(details::PublisherImpl *publisher); + async::Task + RemoveSubscriber(details::SubscriberImpl *subscriber); // Get a pointer to the message buffer for the publisher. The publisher // will own this buffer until you call PublishMessage. The idea is that @@ -462,11 +471,11 @@ class ClientImpl : public std::enable_shared_from_this { // detect when another attempt can be made to get a buffer. // If max_size is greater than the current buffer size, the buffers // will be resized. - absl::StatusOr GetMessageBuffer(details::PublisherImpl *publisher, - int64_t max_size, bool lock); + // (Publisher::GetMessageBuffer is GetMessageBufferSpan plus a conversion, so + // it needs no coroutine frame of its own.) // Get the messsage buffer as a span. Returns an empty span if there is no // buffer available - absl::StatusOr> + async::Task>> GetMessageBufferSpan(details::PublisherImpl *publisher, int64_t max_size, bool lock); @@ -474,26 +483,27 @@ class ClientImpl : public std::enable_shared_from_this { // argument specifies the actual size of the message to send. Returns the // information about the message sent with buffer set to nullptr since // the publisher cannot access the message once it's been published. - absl::StatusOr + async::Task> PublishMessage(details::PublisherImpl *publisher, int64_t message_size, bool notify_subscribers); void NotifySubscribers(details::PublisherImpl *publisher); - absl::StatusOr + async::Task> AcquirePublisherBuffer(details::PublisherImpl *publisher); - absl::StatusOr + async::Task> ReclaimPublisherBuffer(details::PublisherImpl *publisher, int32_t slot_id); - absl::StatusOr + async::Task> ReclaimAnyPublisherBuffer(details::PublisherImpl *publisher); - absl::StatusOr + async::Task> PublishPublisherBuffer(details::PublisherImpl *publisher, const PublisherBufferLease &lease, int64_t message_size); - absl::StatusOr + async::Task> PublishPublisherBufferCopy(details::PublisherImpl *publisher, const PublisherBufferLease &lease, absl::Span payload); - absl::StatusOr PublishPublisherBufferInternal( + async::Task> + PublishPublisherBufferInternal( details::PublisherImpl *publisher, const PublisherBufferLease &lease, int64_t message_size, const std::byte *payload); absl::Status ReleasePublisherBuffer(details::PublisherImpl *publisher, @@ -509,19 +519,21 @@ class ClientImpl : public std::enable_shared_from_this { // Wait until a reliable publisher can try again to send a message. If the // client is coroutine-aware, the coroutine will wait. If it's not, // the function will block on a poll until the publisher is triggered. - absl::Status WaitForReliablePublisher(details::PublisherImpl *publisher, - const toolbelt::AsyncWaiter *c = nullptr) { + async::Task + WaitForReliablePublisher(details::PublisherImpl *publisher, + const toolbelt::AsyncWaiter *c = nullptr) { return WaitForReliablePublisher(publisher, std::chrono::nanoseconds(0), c); } - absl::Status WaitForReliablePublisher(details::PublisherImpl *publisher, + async::Task + WaitForReliablePublisher(details::PublisherImpl *publisher, std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c = nullptr); // Wait until a reliable publisher can try again to send a message. If the // client is coroutine-aware, the coroutine will wait. If it's not, // the function will block on a poll until the publisher is triggered. - absl::StatusOr + async::Task> WaitForReliablePublisher(details::PublisherImpl *publisher, const toolbelt::FileDescriptor &fd, const toolbelt::AsyncWaiter *c = nullptr) { @@ -529,7 +541,8 @@ class ClientImpl : public std::enable_shared_from_this { c); } - absl::StatusOr WaitForReliablePublisher( + async::Task> + WaitForReliablePublisher( details::PublisherImpl *publisher, const toolbelt::FileDescriptor &fd, std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c = nullptr); @@ -566,12 +579,14 @@ class ClientImpl : public std::enable_shared_from_this { // subscriber. If the client is coroutine-aware, the coroutine // will wait. If it's not, the function will block on a poll // until the subscriber is triggered. - absl::Status WaitForSubscriber(details::SubscriberImpl *subscriber, - const toolbelt::AsyncWaiter *c = nullptr) { + async::Task + WaitForSubscriber(details::SubscriberImpl *subscriber, + const toolbelt::AsyncWaiter *c = nullptr) { return WaitForSubscriber(subscriber, std::chrono::nanoseconds(0), c); } - absl::Status WaitForSubscriber(details::SubscriberImpl *subscriber, + async::Task + WaitForSubscriber(details::SubscriberImpl *subscriber, std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c = nullptr); @@ -579,13 +594,15 @@ class ClientImpl : public std::enable_shared_from_this { // subscriber. If the client is coroutine-aware, the coroutine // will wait. If it's not, the function will block on a poll // until the subscriber is triggered. - absl::StatusOr WaitForSubscriber(details::SubscriberImpl *subscriber, - const toolbelt::FileDescriptor &fd, - const toolbelt::AsyncWaiter *c = nullptr) { + async::Task> + WaitForSubscriber(details::SubscriberImpl *subscriber, + const toolbelt::FileDescriptor &fd, + const toolbelt::AsyncWaiter *c = nullptr) { return WaitForSubscriber(subscriber, fd, std::chrono::nanoseconds(0), c); } - absl::StatusOr WaitForSubscriber(details::SubscriberImpl *subscriber, + async::Task> + WaitForSubscriber(details::SubscriberImpl *subscriber, const toolbelt::FileDescriptor &fd, std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c = nullptr); @@ -622,30 +639,32 @@ class ClientImpl : public std::enable_shared_from_this { // PollFd is only triggered when a new message is published. // Pass ClearTrigger::kNoClearTrigger to leave the subscriber trigger fd // unread. - absl::StatusOr ReadMessage( + async::Task> + ReadMessage( details::SubscriberImpl *subscriber, ReadMode mode = ReadMode::kReadNext, ClearTrigger clear_trigger = ClearTrigger::kClearTrigger); // Continue draining a batch after ReadMessage has cleared the poll fd and // refreshed publisher state. This avoids repeating that work per message. - absl::StatusOr + async::Task> ReadMessageFromBatch(details::SubscriberImpl *subscriber, ReadMode mode = ReadMode::kReadNext); // As ReadMessage above but returns a shared_ptr to the typed message. // NOTE: this is subspace::shared_ptr, not std::shared_ptr. template - absl::StatusOr> + async::Task>> ReadMessage(details::SubscriberImpl *subscriber, ReadMode mode = ReadMode::kReadNext, ClearTrigger clear_trigger = ClearTrigger::kClearTrigger); // Find a message given a timestamp. - absl::StatusOr FindMessage(details::SubscriberImpl *subscriber, + async::Task> + FindMessage(details::SubscriberImpl *subscriber, uint64_t timestamp); // AsFindMessage above but returns a shared_ptr to the typed message. // NOTE: this is subspace::shared_ptr, not std::shared_ptr. template - absl::StatusOr> + async::Task>> FindMessage(details::SubscriberImpl *subscriber, uint64_t timestamp); // Gets the PollFd for a publisher and subscriber. PollFds are only @@ -709,10 +728,11 @@ class ClientImpl : public std::enable_shared_from_this { // Call the message callback function for all available messages. You must // have registered a callback function with RegisterMessageCallback for this // to work. - absl::Status ProcessAllMessages(details::SubscriberImpl *subscriber, + async::Task + ProcessAllMessages(details::SubscriberImpl *subscriber, ReadMode mode = ReadMode::kReadNext); - absl::StatusOr> + async::Task>> GetAllMessages(details::SubscriberImpl *subscriber, ReadMode mode = ReadMode::kReadNext); @@ -720,28 +740,33 @@ class ClientImpl : public std::enable_shared_from_this { int64_t GetCurrentOrdinal(details::SubscriberImpl *sub); absl::Status CheckConnected() const; - absl::Status SendRequestReceiveResponse( + async::Task + SendRequestReceiveResponse( const Request &req, Response &response, std::vector &fds, const std::vector &send_fds = {}); - absl::Status + async::Task SendOneWayRequest(const Request &req, const std::vector &fds = {}); - absl::Status + async::Task RegisterClientBuffer(const ClientBufferHandleMetadata &metadata, const toolbelt::FileDescriptor *fd = nullptr); - absl::StatusOr> + async::Task>> GetClientBuffers(const std::string &channel_name, uint64_t session_id, uint32_t buffer_index); - absl::Status UnregisterClientBuffer(const std::string &channel_name, + async::Task + UnregisterClientBuffer(const std::string &channel_name, uint64_t session_id, uint32_t buffer_index); - absl::Status Reconnect(); + async::Task + Reconnect(); // Whether a request that failed with `failure` should reconnect and retry. bool ShouldReconnect(const absl::Status &failure) const; - absl::Status ReregisterPublisher(details::PublisherImpl *publisher); - absl::Status ReregisterSubscriber(details::SubscriberImpl *subscriber); + async::Task + ReregisterPublisher(details::PublisherImpl *publisher); + async::Task + ReregisterSubscriber(details::SubscriberImpl *subscriber); static void FillCreatePublisherRequest(CreatePublisherRequest *cmd, const std::string &channel_name, @@ -758,29 +783,60 @@ class ClientImpl : public std::enable_shared_from_this { const CreateSubscriberResponse &resp, std::vector &fds); - bool CheckReload(details::ClientChannel *channel); + async::Task CheckReload(details::ClientChannel *channel); - absl::Status ReloadSubscriber(details::SubscriberImpl *channel); - absl::Status ReloadSubscribersIfNecessary(details::PublisherImpl *publisher); - absl::Status + // The Async API holds nothing across a suspension, but a thread-safe client + // keeps a mutex locked while a coroutine is suspended, which would let + // another coroutine on the same thread deadlock on it. So the Async API is + // only available on a client that isn't thread safe. + absl::Status CheckAsyncAllowed() const { + if (thread_safe_) { + return absl::FailedPreconditionError( + "The Async API can't be used on a thread-safe client"); + } + return absl::OkStatus(); + } + + // Cheap checks matching the early-outs of ReloadSubscribersIfNecessary and + // ReloadReliablePublishersIfNecessary. The hot paths test these first so + // they only create a coroutine frame when the server has to be consulted. + bool SubscribersChanged(details::PublisherImpl *publisher) const { + return publisher->NumUpdates() != + publisher->GetScb() + ->counters[publisher->GetChannelId()] + .num_sub_updates; + } + bool PublishersChanged(details::SubscriberImpl *subscriber) const { + return subscriber->NumUpdates() != + subscriber->GetScb() + ->counters[subscriber->GetChannelId()] + .num_pub_updates; + } + + async::Task + ReloadSubscriber(details::SubscriberImpl *channel); + async::Task + ReloadSubscribersIfNecessary(details::PublisherImpl *publisher); + async::Task ReloadReliablePublishersIfNecessary(details::SubscriberImpl *subscriber); absl::Status RemoveChannel(details::ClientChannel *channel); - absl::Status ActivateReliableChannel(details::PublisherImpl *channel); - absl::Status ActivateChannel(details::PublisherImpl *channel); - absl::StatusOr + async::Task ActivateReliableChannel(details::PublisherImpl *channel); + async::Task ActivateChannel(details::PublisherImpl *channel); + async::Task> ReadMessageInternal(details::SubscriberImpl *subscriber, ReadMode mode, bool pass_activation, bool clear_trigger); void ReportIfSubscriberStuck(details::SubscriberImpl *subscriber); - absl::StatusOr + async::Task> FindMessageInternal(details::SubscriberImpl *subscriber, uint64_t timestamp); - absl::StatusOr + async::Task> PublishMessageInternal(details::PublisherImpl *publisher, int64_t message_size, bool omit_prefix, bool use_prefix_slot_id, bool use_prefix_vchan_id, bool notify_subscribers); - absl::Status ResizeChannel(details::PublisherImpl *publisher, + async::Task + ResizeChannel(details::PublisherImpl *publisher, int64_t new_slot_size); - absl::StatusOr + async::Task> ReloadBuffersIfNecessary(details::ClientChannel *channel); const std::vector> & @@ -818,6 +874,16 @@ class ClientImpl : public std::enable_shared_from_this { // True when this client cooperates with a coroutine (has a yield_context); // false for a blocking client that uses synchronous socket I/O + poll(). bool IsCooperative() const { return async_ctx_.has_value(); } +#elif SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // Inside an Async call co20::self is the running coroutine, so socket waits + // suspend it. The blocking API runs the same code under SyncWait, which + // hides co20::self, so those waits go through co_ (if there is one) or poll. + async::Context SocketContext() const { + if (co20::Coroutine *running = co20::self; running != nullptr) { + return async::Context(running); + } + return async::Context(co_); + } #else const toolbelt::AsyncWaiter *SocketContext() const { return co_; } #endif @@ -878,28 +944,29 @@ class ClientImpl : public std::enable_shared_from_this { // by a publisher. Don't hold onto shared_ptr instances long than // you need to as it may prevent a publisher getting a slot. template -inline absl::StatusOr<::subspace::shared_ptr> +inline async::Task>> ClientImpl::ReadMessage(details::SubscriberImpl *subscriber, ReadMode mode, ClearTrigger clear_trigger) { - absl::StatusOr msg = ReadMessage(subscriber, mode, clear_trigger); + absl::StatusOr msg = + ASYNC_AWAIT(ReadMessage(subscriber, mode, clear_trigger)); if (!msg.ok()) { - return msg.status(); + ASYNC_RETURN msg.status(); } if (msg->length == 0) { - return ::subspace::shared_ptr(); + ASYNC_RETURN ::subspace::shared_ptr(); } - return ::subspace::shared_ptr(std::move(*msg)); + ASYNC_RETURN ::subspace::shared_ptr(std::move(*msg)); } template -inline absl::StatusOr<::subspace::shared_ptr> +inline async::Task>> ClientImpl::FindMessage(details::SubscriberImpl *subscriber, uint64_t timestamp) { - absl::StatusOr msg = FindMessage(subscriber, timestamp); + absl::StatusOr msg = ASYNC_AWAIT(FindMessage(subscriber, timestamp)); if (!msg.ok()) { - return msg.status(); + ASYNC_RETURN msg.status(); } - return ::subspace::shared_ptr(std::move(*msg)); + ASYNC_RETURN ::subspace::shared_ptr(std::move(*msg)); } // The Publisher and Subscriber classes are the main interface for sending @@ -907,9 +974,9 @@ ClientImpl::FindMessage(details::SubscriberImpl *subscriber, class Publisher { public: ~Publisher() { - if (client_ != nullptr && impl_ != nullptr) { + if (client_ != nullptr && impl_ != nullptr && !closed_) { UnregisterResizeCallback().IgnoreError(); - (void)client_->RemovePublisher(impl_.get()); + (void)ASYNC_BLOCK(client_->RemovePublisher(impl_.get())); } } @@ -918,7 +985,8 @@ class Publisher { Publisher(Publisher &&other) : client_(std::move(other.client_)), impl_(std::move(other.impl_)), - resize_callback_(std::move(other.resize_callback_)) { + resize_callback_(std::move(other.resize_callback_)), + closed_(other.closed_) { if (impl_ != nullptr && client_ != nullptr && resize_callback_ != nullptr) { client_->UnregisterResizeCallback(impl_.get()).IgnoreError(); RegisterResizeCallback(resize_callback_).IgnoreError(); @@ -931,6 +999,7 @@ class Publisher { client_ = std::move(other.client_); impl_ = std::move(other.impl_); resize_callback_ = std::move(other.resize_callback_); + closed_ = other.closed_; if (impl_ != nullptr && client_ != nullptr && resize_callback_ != nullptr) { client_->UnregisterResizeCallback(impl_.get()).IgnoreError(); RegisterResizeCallback(resize_callback_).IgnoreError(); @@ -960,14 +1029,19 @@ class Publisher { // publish using CancelPublish. This will release the lock. absl::StatusOr GetMessageBuffer(SlotSizeType max_size = -1, bool lock = true) { - return client_->GetMessageBuffer(impl_.get(), max_size, lock); + absl::StatusOr> span = ASYNC_BLOCK( + client_->GetMessageBufferSpan(impl_.get(), max_size, lock)); + if (!span.ok()) { + return span.status(); + } + return span->empty() ? nullptr : static_cast(span->data()); } // Get the messsage buffer as a span. Returns an empty span if there is no // buffer available. See GetMessageBuffer for details of absl::StatusOr> GetMessageBufferSpan(SlotSizeType max_size = -1, bool lock = true) { - return client_->GetMessageBufferSpan(impl_.get(), max_size, lock); + return ASYNC_BLOCK(client_->GetMessageBufferSpan(impl_.get(), max_size, lock)); } // Publish the message in the publisher's buffer. The message_size @@ -982,8 +1056,8 @@ class Publisher { // message in that batch is published with notification enabled. absl::StatusOr PublishMessage(int64_t message_size, bool notify_subscribers = true) { - return client_->PublishMessage(impl_.get(), message_size, - notify_subscribers); + return ASYNC_BLOCK(client_->PublishMessage(impl_.get(), message_size, + notify_subscribers)); } // Flush a batch whose messages were published without subscriber // notification. @@ -993,7 +1067,7 @@ class Publisher { // mutex across the lease lifetime. The maximum is configured by // PublisherOptions::SetMaxOutstandingSlotLeases(). absl::StatusOr AcquireBufferLease() { - return client_->AcquirePublisherBuffer(impl_.get()); + return ASYNC_BLOCK(client_->AcquirePublisherBuffer(impl_.get())); } absl::StatusOr AcquireScopedBufferLease() & { @@ -1006,12 +1080,12 @@ class Publisher { // Reclaim a specific slot reported by the retirement fd. absl::StatusOr ReclaimBufferLease(int32_t slot_id) { - return client_->ReclaimPublisherBuffer(impl_.get(), slot_id); + return ASYNC_BLOCK(client_->ReclaimPublisherBuffer(impl_.get(), slot_id)); } // Reclaim any slot currently marked retired when fd notifications are stale. absl::StatusOr ReclaimAnyBufferLease() { - return client_->ReclaimAnyPublisherBuffer(impl_.get()); + return ASYNC_BLOCK(client_->ReclaimAnyPublisherBuffer(impl_.get())); } absl::StatusOr @@ -1025,13 +1099,13 @@ class Publisher { absl::StatusOr PublishBufferLease(const PublisherBufferLease &lease, int64_t message_size) { - return client_->PublishPublisherBuffer(impl_.get(), lease, message_size); + return ASYNC_BLOCK(client_->PublishPublisherBuffer(impl_.get(), lease, message_size)); } absl::StatusOr PublishBufferLeaseCopy(const PublisherBufferLease &lease, absl::Span payload) { - return client_->PublishPublisherBufferCopy(impl_.get(), lease, payload); + return ASYNC_BLOCK(client_->PublishPublisherBufferCopy(impl_.get(), lease, payload)); } absl::Status ReleaseBufferLease(const PublisherBufferLease &lease) { @@ -1072,12 +1146,12 @@ class Publisher { // client is coroutine-aware, the coroutine will wait. If it's not, // the function will block on a poll until the publisher is triggered. absl::Status Wait(const toolbelt::AsyncWaiter *c = nullptr) { - return client_->WaitForReliablePublisher(impl_.get(), c); + return ASYNC_BLOCK(client_->WaitForReliablePublisher(impl_.get(), c)); } absl::Status Wait(std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c = nullptr) { - return client_->WaitForReliablePublisher(impl_.get(), timeout, c); + return ASYNC_BLOCK(client_->WaitForReliablePublisher(impl_.get(), timeout, c)); } // Wait until a reliable publisher can try again to send a message. If the @@ -1088,13 +1162,13 @@ class Publisher { // triggered the wait. absl::StatusOr Wait(const toolbelt::FileDescriptor &fd, const toolbelt::AsyncWaiter *c = nullptr) { - return client_->WaitForReliablePublisher(impl_.get(), fd, c); + return ASYNC_BLOCK(client_->WaitForReliablePublisher(impl_.get(), fd, c)); } absl::StatusOr Wait(const toolbelt::FileDescriptor &fd, std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c = nullptr) { - return client_->WaitForReliablePublisher(impl_.get(), fd, timeout, c); + return ASYNC_BLOCK(client_->WaitForReliablePublisher(impl_.get(), fd, timeout, c)); } #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO @@ -1325,6 +1399,166 @@ class Publisher { // empty span if MetadataSize() is 0. absl::Span GetMetadata() { return impl_->GetMetadata(); } +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // ---- Async API (C++20 coroutines) ------------------------------------ + // + // Each of these does what the function of the same name without "Async" + // does, but suspends the calling coroutine instead of blocking the thread + // while it waits for the server or for a reliable publisher. co_await the + // result from a coroutine running on a co20::Scheduler. Don't use the + // blocking functions from inside such a coroutine: they block the whole + // scheduler thread. + // + // The client must not be thread safe (FailedPrecondition otherwise), and + // only one Async call should be in progress on a client at a time because + // they share its socket to the server. The Publisher must stay in place + // until the call completes. + + async::Task> + GetMessageBufferAsync(SlotSizeType max_size = -1) { + auto span = ASYNC_AWAIT(GetMessageBufferSpanAsync(max_size)); + if (!span.ok()) { + co_return span.status(); + } + co_return span->empty() ? nullptr : static_cast(span->data()); + } + + async::Task>> + GetMessageBufferSpanAsync(SlotSizeType max_size = -1) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT( + client->GetMessageBufferSpan(impl.get(), max_size, /*lock=*/false)); + } + + async::Task> + PublishMessageAsync(int64_t message_size, bool notify_subscribers = true) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT( + client->PublishMessage(impl.get(), message_size, notify_subscribers)); + } + + // The same as PublishMessageWithPrefix, but suspends the calling coroutine. + async::Task> + PublishMessageWithPrefixAsync(int64_t message_size, + bool use_slot_id_from_prefix = true, + bool use_vchan_id_from_prefix = true) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(client->PublishMessageInternal( + impl.get(), message_size, /*omit_prefix=*/true, + use_slot_id_from_prefix, use_vchan_id_from_prefix, + /*notify_subscribers=*/true)); + } + + async::Task> AcquireBufferLeaseAsync() { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(client->AcquirePublisherBuffer(impl.get())); + } + + async::Task> + ReclaimBufferLeaseAsync(int32_t slot_id) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(client->ReclaimPublisherBuffer(impl.get(), slot_id)); + } + + async::Task> + ReclaimAnyBufferLeaseAsync() { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(client->ReclaimAnyPublisherBuffer(impl.get())); + } + + async::Task> + PublishBufferLeaseAsync(PublisherBufferLease lease, int64_t message_size) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT( + client->PublishPublisherBuffer(impl.get(), lease, message_size)); + } + + // The payload must stay valid until the call completes. + async::Task> + PublishBufferLeaseCopyAsync(PublisherBufferLease lease, + absl::Span payload) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT( + client->PublishPublisherBufferCopy(impl.get(), lease, payload)); + } + + // Wait until a reliable publisher can try again to send a message. A + // timeout of zero waits forever. + async::Task + WaitAsync(std::chrono::nanoseconds timeout = std::chrono::nanoseconds(0)) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT( + client->WaitForReliablePublisher(impl.get(), timeout, nullptr)); + } + + // As above, but also returns when fd becomes readable. Returns the fd that + // triggered the wait. + async::Task> + WaitAsync(const toolbelt::FileDescriptor &fd, + std::chrono::nanoseconds timeout = std::chrono::nanoseconds(0)) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT( + client->WaitForReliablePublisher(impl.get(), fd, timeout, nullptr)); + } + + // Removes the publisher from the server without blocking. The destructor + // does the same but blocks, so a publisher used from a coroutine should be + // closed with this first. The publisher can't be used afterwards. + async::Task CloseAsync() { + if (client_ == nullptr || impl_ == nullptr || closed_) { + co_return absl::OkStatus(); + } + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + closed_ = true; + UnregisterResizeCallback().IgnoreError(); + co_return ASYNC_AWAIT(client->RemovePublisher(impl.get())); + } +#endif + private: friend class Server; friend class ClientImpl; @@ -1337,9 +1571,9 @@ class Publisher { PublishMessageInternal(int64_t message_size, bool omit_prefix, bool use_prefix_slot_id, bool use_prefix_vchan_id = true) { - return client_->PublishMessageInternal( + return ASYNC_BLOCK(client_->PublishMessageInternal( impl_.get(), message_size, omit_prefix, use_prefix_slot_id, - use_prefix_vchan_id, /*notify_subscribers=*/true); + use_prefix_vchan_id, /*notify_subscribers=*/true)); } std::shared_ptr client_; @@ -1347,6 +1581,9 @@ class Publisher { std::function resize_callback_ = nullptr; std::vector address_cache_; + // Set by CloseAsync so that the destructor doesn't remove the publisher a + // second time (that removal would block). + bool closed_ = false; }; inline ScopedPublisherBufferLease::~ScopedPublisherBufferLease() { @@ -1407,11 +1644,11 @@ inline absl::Status ScopedPublisherBufferLease::Release() { class Subscriber { public: ~Subscriber() { - if (client_ != nullptr && impl_ != nullptr) { + if (client_ != nullptr && impl_ != nullptr && !closed_) { UnregisterDroppedMessageCallback().IgnoreError(); UnregisterStuckSubscriberCallback().IgnoreError(); UnregisterMessageCallback().IgnoreError(); - (void)client_->RemoveSubscriber(impl_.get()); + (void)ASYNC_BLOCK(client_->RemoveSubscriber(impl_.get())); } } Subscriber(const Subscriber &other) = delete; @@ -1423,7 +1660,8 @@ class Subscriber { dropped_message_callback_(std::move(other.dropped_message_callback_)), stuck_subscriber_callback_( std::move(other.stuck_subscriber_callback_)), - message_callback_(std::move(other.message_callback_)) { + message_callback_(std::move(other.message_callback_)), + closed_(other.closed_) { if (impl_ != nullptr && client_ != nullptr && dropped_message_callback_ != nullptr) { client_->UnregisterDroppedMessageCallback(impl_.get()).IgnoreError(); @@ -1450,6 +1688,7 @@ class Subscriber { dropped_message_callback_ = std::move(other.dropped_message_callback_); stuck_subscriber_callback_ = std::move(other.stuck_subscriber_callback_); message_callback_ = std::move(other.message_callback_); + closed_ = other.closed_; if (impl_ != nullptr && client_ != nullptr && dropped_message_callback_ != nullptr) { client_->UnregisterDroppedMessageCallback(impl_.get()).IgnoreError(); @@ -1480,12 +1719,12 @@ class Subscriber { // will wait. If it's not, the function will block on a poll // until the subscriber is triggered. absl::Status Wait(const toolbelt::AsyncWaiter *c = nullptr) { - return client_->WaitForSubscriber(impl_.get(), c); + return ASYNC_BLOCK(client_->WaitForSubscriber(impl_.get(), c)); } absl::Status Wait(std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c = nullptr) { - return client_->WaitForSubscriber(impl_.get(), timeout, c); + return ASYNC_BLOCK(client_->WaitForSubscriber(impl_.get(), timeout, c)); } // Wait until there's a message available to be read by the @@ -1497,13 +1736,13 @@ class Subscriber { // triggered the wait. absl::StatusOr Wait(const toolbelt::FileDescriptor &fd, const toolbelt::AsyncWaiter *c = nullptr) { - return client_->WaitForSubscriber(impl_.get(), fd, c); + return ASYNC_BLOCK(client_->WaitForSubscriber(impl_.get(), fd, c)); } absl::StatusOr Wait(const toolbelt::FileDescriptor &fd, std::chrono::nanoseconds timeout, const toolbelt::AsyncWaiter *c = nullptr) { - return client_->WaitForSubscriber(impl_.get(), fd, timeout, c); + return ASYNC_BLOCK(client_->WaitForSubscriber(impl_.get(), fd, timeout, c)); } #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO @@ -1540,11 +1779,11 @@ class Subscriber { absl::StatusOr ReadMessage(ReadMode mode = ReadMode::kReadNext, ClearTrigger clear_trigger = ClearTrigger::kClearTrigger) { - return client_->ReadMessage(impl_.get(), mode, clear_trigger); + return ASYNC_BLOCK(client_->ReadMessage(impl_.get(), mode, clear_trigger)); } absl::StatusOr ReadMessageFromBatch(ReadMode mode = ReadMode::kReadNext) { - return client_->ReadMessageFromBatch(impl_.get(), mode); + return ASYNC_BLOCK(client_->ReadMessageFromBatch(impl_.get(), mode)); } // Read and deserialize a telemetry message. Returns nullptr when no message @@ -1568,7 +1807,7 @@ class Subscriber { // Find a message given a timestamp. absl::StatusOr FindMessage(uint64_t timestamp) { - return client_->FindMessage(impl_.get(), timestamp); + return ASYNC_BLOCK(client_->FindMessage(impl_.get(), timestamp)); } // AsFindMessage above but returns a shared_ptr to the typed message. @@ -1700,12 +1939,12 @@ class Subscriber { void ClearOnReceiveCallback() { impl_->SetOnReceiveCallback(nullptr); } absl::Status ProcessAllMessages(ReadMode mode = ReadMode::kReadNext) { - return client_->ProcessAllMessages(impl_.get(), mode); + return ASYNC_BLOCK(client_->ProcessAllMessages(impl_.get(), mode)); } absl::StatusOr> GetAllMessages(ReadMode mode = ReadMode::kReadNext) { - return client_->GetAllMessages(impl_.get(), mode); + return ASYNC_BLOCK(client_->GetAllMessages(impl_.get(), mode)); } void Trigger() { impl_->Trigger(); } @@ -1841,6 +2080,121 @@ class Subscriber { return false; } +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // ---- Async API (C++20 coroutines) ------------------------------------ + // + // The same as the functions without "Async", but they suspend the calling + // coroutine instead of blocking the thread. See the Publisher Async API + // for the rules on using them. + + async::Task + WaitAsync(std::chrono::nanoseconds timeout = std::chrono::nanoseconds(0)) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT( + client->WaitForSubscriber(impl.get(), timeout, nullptr)); + } + + async::Task> + WaitAsync(const toolbelt::FileDescriptor &fd, + std::chrono::nanoseconds timeout = std::chrono::nanoseconds(0)) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT( + client->WaitForSubscriber(impl.get(), fd, timeout, nullptr)); + } + + async::Task> + ReadMessageAsync(ReadMode mode = ReadMode::kReadNext, + ClearTrigger clear_trigger = ClearTrigger::kClearTrigger) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT( + client->ReadMessage(impl.get(), mode, clear_trigger)); + } + + template + async::Task>> + ReadMessageAsync(ReadMode mode = ReadMode::kReadNext, + ClearTrigger clear_trigger = ClearTrigger::kClearTrigger) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT( + (client->ReadMessage(impl.get(), mode, clear_trigger))); + } + + async::Task> FindMessageAsync(uint64_t timestamp) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(client->FindMessage(impl.get(), timestamp)); + } + + template + async::Task>> + FindMessageAsync(uint64_t timestamp) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT( + (client->FindMessage(impl.get(), timestamp))); + } + + async::Task + ProcessAllMessagesAsync(ReadMode mode = ReadMode::kReadNext) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(client->ProcessAllMessages(impl.get(), mode)); + } + + async::Task>> + GetAllMessagesAsync(ReadMode mode = ReadMode::kReadNext) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(client->GetAllMessages(impl.get(), mode)); + } + + // Removes the subscriber from the server without blocking. The destructor + // does the same but blocks. The subscriber can't be used afterwards. + async::Task CloseAsync() { + if (client_ == nullptr || impl_ == nullptr || closed_) { + co_return absl::OkStatus(); + } + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + closed_ = true; + UnregisterDroppedMessageCallback().IgnoreError(); + UnregisterStuckSubscriberCallback().IgnoreError(); + UnregisterMessageCallback().IgnoreError(); + co_return ASYNC_AWAIT(client->RemoveSubscriber(impl.get())); + } +#endif + private: friend class Server; friend class ClientImpl; @@ -1851,8 +2205,21 @@ class Subscriber { absl::StatusOr ReadMessageInternal(ReadMode mode, bool pass_activation, bool clear_trigger) { - return client_->ReadMessageInternal(impl_.get(), mode, pass_activation, - clear_trigger); + return ASYNC_BLOCK(client_->ReadMessageInternal( + impl_.get(), mode, pass_activation, clear_trigger)); + } + + // Awaitable form for code on the scheduler, such as the in-process bridge. + async::Task> + ReadMessageInternalAsync(ReadMode mode, bool pass_activation, + bool clear_trigger) { + auto client = client_; + auto impl = impl_; + if (absl::Status s = client->CheckAsyncAllowed(); !s.ok()) { + ASYNC_RETURN s; + } + ASYNC_RETURN ASYNC_AWAIT(client->ReadMessageInternal( + impl.get(), mode, pass_activation, clear_trigger)); } std::shared_ptr client_; @@ -1863,18 +2230,21 @@ class Subscriber { std::function stuck_subscriber_callback_ = nullptr; std::function message_callback_ = nullptr; + // Set by CloseAsync so the destructor doesn't remove the subscriber again. + bool closed_ = false; }; template inline absl::StatusOr<::subspace::shared_ptr> Subscriber::ReadMessage(ReadMode mode, ClearTrigger clear_trigger) { - return client_->ReadMessage(impl_.get(), mode, clear_trigger); + return ASYNC_BLOCK( + client_->ReadMessage(impl_.get(), mode, clear_trigger)); } template inline absl::StatusOr<::subspace::shared_ptr> Subscriber::FindMessage(uint64_t timestamp) { - return client_->FindMessage(impl_.get(), timestamp); + return ASYNC_BLOCK(client_->FindMessage(impl_.get(), timestamp)); } // This is a wrapper around the ClientImpl that is created as a shared_ptr @@ -1903,6 +2273,12 @@ class Client { Client(const toolbelt::AsyncWaiter *c = nullptr) : impl_(std::make_shared(c)) {} +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // The Async API suspends whichever coroutine calls it (co20::self), so a + // co20 client doesn't need the coroutine it is created in. The context is + // accepted so code written for the other backends compiles unchanged. + explicit Client(async::Context) : impl_(std::make_shared()) {} +#endif #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO // Asio-backed client: the yield_context drives cooperative socket I/O. explicit Client(async::Context ctx) @@ -1915,7 +2291,7 @@ class Client { // Initialize the client by connecting to the server. absl::Status Init(const std::string &server_socket = kDefaultServerSocket, const std::string &client_name = "") { - return impl_->Init(server_socket, client_name); + return ASYNC_BLOCK(impl_->Init(server_socket, client_name)); } // Create a publisher for the given channel. If the channel doesn't exit @@ -1925,7 +2301,7 @@ class Client { CreatePublisher(const std::string &channel_name, SlotSizeType slot_size, int num_slots, const PublisherOptions &opts = PublisherOptions()) { - return impl_->CreatePublisher(channel_name, slot_size, num_slots, opts); + return ASYNC_BLOCK(impl_->CreatePublisher(channel_name, slot_size, num_slots, opts)); } // If you prefer, you can create the publisher with the slot size and @@ -1933,7 +2309,7 @@ class Client { absl::StatusOr CreatePublisher(const std::string &channel_name, const PublisherOptions &opts = PublisherOptions()) { - return impl_->CreatePublisher(channel_name, opts); + return ASYNC_BLOCK(impl_->CreatePublisher(channel_name, opts)); } // Create a subscriber for the given channel. This can be done before there @@ -1941,7 +2317,7 @@ class Client { absl::StatusOr CreateSubscriber(const std::string &channel_name, const SubscriberOptions &opts = SubscriberOptions()) { - return impl_->CreateSubscriber(channel_name, opts); + return ASYNC_BLOCK(impl_->CreateSubscriber(channel_name, opts)); } // Call with true to turn on some debug information. Kind of meaningless @@ -1964,24 +2340,118 @@ class Client { absl::StatusOr GetChannelInfo(const std::string &channelName) { - return impl_->GetChannelInfo(channelName); + return ASYNC_BLOCK(impl_->GetChannelInfo(channelName)); } absl::StatusOr> GetChannelInfo() { - return impl_->GetChannelInfo(); + return ASYNC_BLOCK(impl_->GetChannelInfo()); } absl::StatusOr GetChannelStats(const std::string &channelName) { - return impl_->GetChannelStats(channelName); + return ASYNC_BLOCK(impl_->GetChannelStats(channelName)); } absl::StatusOr> GetChannelStats() { - return impl_->GetChannelStats(); + return ASYNC_BLOCK(impl_->GetChannelStats()); } absl::StatusOr ChannelExists(const std::string &channelName) { - return impl_->ChannelExists(channelName); + return ASYNC_BLOCK(impl_->ChannelExists(channelName)); + } + +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // ---- Async API (C++20 coroutines) ------------------------------------ + // + // The same as the functions without "Async", but they suspend the calling + // coroutine instead of blocking the thread. See the Publisher Async API + // for the rules on using them. The Client must not be thread safe. + async::Task + InitAsync(const std::string &server_socket = kDefaultServerSocket, + const std::string &client_name = "") { + auto impl = impl_; + if (absl::Status s = impl->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(impl->Init(server_socket, client_name)); + } + + async::Task> + CreatePublisherAsync(const std::string &channel_name, SlotSizeType slot_size, + int num_slots, + const PublisherOptions &opts = PublisherOptions()) { + auto impl = impl_; + if (absl::Status s = impl->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT( + impl->CreatePublisher(channel_name, slot_size, num_slots, opts)); + } + + async::Task> + CreatePublisherAsync(const std::string &channel_name, + const PublisherOptions &opts = PublisherOptions()) { + auto impl = impl_; + if (absl::Status s = impl->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(impl->CreatePublisher(channel_name, opts)); + } + + async::Task> + CreateSubscriberAsync(const std::string &channel_name, + const SubscriberOptions &opts = SubscriberOptions()) { + auto impl = impl_; + if (absl::Status s = impl->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(impl->CreateSubscriber(channel_name, opts)); + } + + async::Task> + GetChannelInfoAsync(const std::string &channelName) { + auto impl = impl_; + if (absl::Status s = impl->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(impl->GetChannelInfo(channelName)); + } + + async::Task>> + GetChannelInfoAsync() { + auto impl = impl_; + if (absl::Status s = impl->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(impl->GetChannelInfo()); + } + + async::Task> + GetChannelStatsAsync(const std::string &channelName) { + auto impl = impl_; + if (absl::Status s = impl->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(impl->GetChannelStats(channelName)); + } + + async::Task>> + GetChannelStatsAsync() { + auto impl = impl_; + if (absl::Status s = impl->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(impl->GetChannelStats()); } + async::Task> + ChannelExistsAsync(const std::string &channelName) { + auto impl = impl_; + if (absl::Status s = impl->CheckAsyncAllowed(); !s.ok()) { + co_return s; + } + co_return ASYNC_AWAIT(impl->ChannelExists(channelName)); + } +#endif + private: std::shared_ptr impl_; }; diff --git a/client/client_channel.cc b/client/client_channel.cc index 4f478924..fbb69d51 100644 --- a/client/client_channel.cc +++ b/client/client_channel.cc @@ -3,6 +3,7 @@ // See LICENSE file for licensing information. #include "client/client_channel.h" +#include "common/async/wait.h" #include "common/syscall_shim.h" #include "common/system_info.h" #include @@ -275,13 +276,13 @@ absl::Status ClientChannel::Map(SharedMemoryFds fds, return absl::OkStatus(); } -absl::Status ClientChannel::UnmapUnusedBuffers() { +async::Task ClientChannel::UnmapUnusedBuffers() { for (size_t i = 0; i + 1 < buffers_.size(); i++) { if (bcb_->refs[i] == 0) { - UnmapBufferSet(i, *buffers_[i], /*destroy_owned_buffers=*/false); + ASYNC_AWAIT(UnmapBufferSet(i, *buffers_[i], /*destroy_owned_buffers=*/false)); } } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } void ClientChannel::UnmapShmBufferSet(BufferSet &buffer) { @@ -294,11 +295,11 @@ void ClientChannel::UnmapShmBufferSet(BufferSet &buffer) { buffer.slot_size = 0; } -void ClientChannel::UnmapBufferSet(size_t buffer_index, BufferSet &buffer, +async::Task ClientChannel::UnmapBufferSet(size_t buffer_index, BufferSet &buffer, bool destroy_owned_buffers) { if (buffer.IsSplitBuffers()) { - UnmapSplitBufferSet(buffer_index, buffer, destroy_owned_buffers); - return; + ASYNC_AWAIT(UnmapSplitBufferSet(buffer_index, buffer, destroy_owned_buffers)); + ASYNC_RETURN; } (void)buffer_index; (void)destroy_owned_buffers; @@ -308,7 +309,7 @@ void ClientChannel::UnmapBufferSet(size_t buffer_index, BufferSet &buffer, UnmapShmBufferSet(buffer); } -void ClientChannel::UnmapSplitBufferSet(size_t buffer_index, +async::Task ClientChannel::UnmapSplitBufferSet(size_t buffer_index, BufferSet &buffer, bool destroy_owned_buffers) { (void)buffer_index; @@ -352,50 +353,49 @@ void ClientChannel::UnmapSplitBufferSet(size_t buffer_index, if (destroy_owned_buffers && buffer.uses_split_callbacks && buffer.owns_split_buffers && client_buffer_unregistration_callback_) { - (void)client_buffer_unregistration_callback_( - ResolvedName(), session_id_, static_cast(buffer_index)); + (void)ASYNC_AWAIT(client_buffer_unregistration_callback_( + ResolvedName(), session_id_, static_cast(buffer_index))); } buffer.full_size = 0; buffer.slot_size = 0; } -bool ClientChannel::ValidateSlotBuffer(MessageSlot *slot) { +async::Task ClientChannel::ValidateSlotBuffer(MessageSlot *slot) { const int buffer_index = slot->buffer_index.load(std::memory_order_relaxed); if (buffer_index < 0) { - return true; + ASYNC_RETURN true; } if (static_cast(buffer_index) < buffers_.size() && buffers_[buffer_index]->IsSplitBuffers()) { - return slot->id >= 0 && - static_cast(slot->id) < - buffers_[buffer_index]->split_slot_buffers.size() && - buffers_[buffer_index]->split_slot_buffers[slot->id] != - nullptr; + ASYNC_RETURN slot->id >= 0 && + static_cast(slot->id) < + buffers_[buffer_index]->split_slot_buffers.size() && + buffers_[buffer_index]->split_slot_buffers[slot->id] != nullptr; } char *buf = Buffer(slot->id, false); int retries = 1000; while (retries-- > 0 && buf == nullptr) { - CheckReload(); + ASYNC_AWAIT(CheckReload()); buf = Buffer(slot->id, false); } if (buf == nullptr) { - return false; + ASYNC_RETURN false; } - return true; + ASYNC_RETURN true; } -absl::Status ClientChannel::AttachBuffers() { +async::Task ClientChannel::AttachBuffers() { // NOTE: the num_buffers variable in the CCB is atomic and could change while // we are in or after we are done with this loop. int num_buffers = ccb_->num_buffers; if (UseSplitBuffers()) { - return AttachSplitBuffers(num_buffers); + ASYNC_RETURN ASYNC_AWAIT(AttachSplitBuffers(num_buffers)); } - return AttachShmBuffers(num_buffers); + ASYNC_RETURN AttachShmBuffers(num_buffers); } absl::Status ClientChannel::AttachShmBuffers(int num_buffers) { @@ -450,34 +450,34 @@ absl::Status ClientChannel::AttachShmBuffers(int num_buffers) { return absl::OkStatus(); } -absl::Status ClientChannel::AttachSplitBuffers(int num_buffers) { +async::Task ClientChannel::AttachSplitBuffers(int num_buffers) { while (buffers_.size() < size_t(num_buffers)) { size_t buffer_index = buffers_.size(); uint64_t full_size = bcb_->sizes[buffer_index]; uint64_t slot_size = BufferSizeToSlotSize(full_size); - auto split_buffer = OpenSplitBufferSet(buffer_index, full_size, slot_size); + auto split_buffer = ASYNC_AWAIT(OpenSplitBufferSet(buffer_index, full_size, slot_size)); if (!split_buffer.ok()) { - return split_buffer.status(); + ASYNC_RETURN split_buffer.status(); } buffers_.push_back(std::move(*split_buffer)); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -void ClientChannel::UnmapForReload() { +async::Task ClientChannel::UnmapForReload() { UnmapChannelMemory(); for (size_t i = 0; i < buffers_.size(); i++) { - UnmapBufferSet(i, *buffers_[i], /*destroy_owned_buffers=*/true); + ASYNC_AWAIT(UnmapBufferSet(i, *buffers_[i], /*destroy_owned_buffers=*/true)); } buffers_.clear(); } -void ClientChannel::Unmap() { +async::Task ClientChannel::UnmapAsync() { if (scb_ == nullptr) { // Not yet mapped. - return; + ASYNC_RETURN; } - UnmapForReload(); + ASYNC_AWAIT(UnmapForReload()); auto *scb = scb_; scb_ = nullptr; UnmapMemory(scb, sizeof(SystemControlBlock), "SCB"); @@ -591,11 +591,11 @@ ClientChannel::CreateMemfdBuffer(const std::string &filename, size_t size) { } #endif -absl::StatusOr +async::Task> ClientChannel::GetRegisteredClientBuffer(uint32_t buffer_index, bool is_prefix, uint32_t slot_id) { if (!client_buffer_lookup_callback_) { - return absl::InternalError("No client buffer lookup callback registered"); + ASYNC_RETURN absl::InternalError("No client buffer lookup callback registered"); } absl::Status status; // The CCB/BCB can make a buffer generation visible before the server has @@ -603,10 +603,10 @@ ClientChannel::GetRegisteredClientBuffer(uint32_t buffer_index, bool is_prefix, // for the registration to catch up before treating it as missing. for (int attempt = 0; attempt < 100; attempt++) { absl::StatusOr> buffers = - client_buffer_lookup_callback_(ResolvedName(), session_id_, - buffer_index); + ASYNC_AWAIT(client_buffer_lookup_callback_(ResolvedName(), session_id_, + buffer_index)); if (!buffers.ok()) { - return buffers.status(); + ASYNC_RETURN buffers.status(); } for (RegisteredClientBuffer &buffer : *buffers) { if (buffer.metadata.is_prefix == is_prefix && @@ -614,19 +614,26 @@ ClientChannel::GetRegisteredClientBuffer(uint32_t buffer_index, bool is_prefix, if (!buffer.fd.Valid() && buffer.metadata.allocator != ClientBufferAllocatorKind::kSplitCallback) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "Registered client buffer %s/%u/%u missing FD", ResolvedName(), buffer_index, slot_id)); } - return std::move(buffer); + ASYNC_RETURN std::move(buffer); } } status = absl::NotFoundError(absl::StrFormat( "No registered client buffer for %s buffer %u slot %u prefix %d", ResolvedName(), buffer_index, slot_id, is_prefix)); + // Wait for the registration to catch up. This must not block the thread: + // under co20 the caller may be a coroutine on the scheduler thread. +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + ASYNC_AWAIT(async::Sleep(async::Context(co20::self), + std::chrono::milliseconds(1))); +#else std::this_thread::sleep_for(std::chrono::milliseconds(1)); +#endif } - return status; + ASYNC_RETURN status; } #if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_LINUX @@ -733,7 +740,7 @@ ClientChannel::CreatePosixBuffer(const std::string &filename, size_t size) { } #endif -absl::StatusOr> +async::Task>> ClientChannel::CreateSplitBufferSet(size_t buffer_index, size_t full_size, uint64_t slot_size) { auto buffer = std::make_unique(full_size, slot_size, nullptr); @@ -768,26 +775,26 @@ ClientChannel::CreateSplitBufferSet(size_t buffer_index, size_t full_size, auto created = CreateAnonymousSharedMemory(prefix_metadata.object_name, prefix_metadata.allocation_size); if (!created.ok()) { - return created.status(); + ASYNC_RETURN created.status(); } prefix_metadata.handle = static_cast(created->Fd()); if (client_buffer_registration_callback_) { - if (absl::Status status = client_buffer_registration_callback_( + if (absl::Status status = ASYNC_AWAIT(client_buffer_registration_callback_( ClientBufferFromSplitMetadata( prefix_metadata, ClientBufferAllocatorKind::kSplitShm), - &*created); + &*created)); !status.ok()) { - return status; + ASYNC_RETURN status; } } // `created` is closed here; if we won the race the server holds a dup, and // if we lost it the unused memfd is released. } auto prefix_registered = - GetRegisteredClientBuffer(static_cast(buffer_index), - /*is_prefix=*/true, /*slot_id=*/0); + ASYNC_AWAIT(GetRegisteredClientBuffer(static_cast(buffer_index), + /*is_prefix=*/true, /*slot_id=*/0)); if (!prefix_registered.ok()) { - return prefix_registered.status(); + ASYNC_RETURN prefix_registered.status(); } prefix_metadata.allocation_size = prefix_registered->metadata.allocation_size; prefix_metadata.handle = static_cast(prefix_registered->fd.Fd()); @@ -795,7 +802,7 @@ ClientChannel::CreateSplitBufferSet(size_t buffer_index, size_t full_size, MapBuffer(prefix_registered->fd, prefix_metadata.allocation_size, BufferMapMode::kReadWrite); if (!prefix_addr.ok()) { - return prefix_addr.status(); + ASYNC_RETURN prefix_addr.status(); } buffer->split_prefix_fd = std::move(prefix_registered->fd); buffer->split_prefix_buffer = *prefix_addr; @@ -804,30 +811,30 @@ ClientChannel::CreateSplitBufferSet(size_t buffer_index, size_t full_size, #else auto prefix_fd = CreateSplitSharedMemoryBuffer(prefix_metadata); if (!prefix_fd.ok()) { - return prefix_fd.status(); + ASYNC_RETURN prefix_fd.status(); } if (!prefix_fd->Valid()) { - return OpenSplitBufferSet(buffer_index, full_size, slot_size); + ASYNC_RETURN ASYNC_AWAIT(OpenSplitBufferSet(buffer_index, full_size, slot_size)); } auto prefix_addr = MapBuffer(*prefix_fd, prefix_metadata.allocation_size, BufferMapMode::kReadWrite); if (!prefix_addr.ok()) { - return prefix_addr.status(); + ASYNC_RETURN prefix_addr.status(); } prefix_metadata.handle = static_cast(prefix_fd->Fd()); if (absl::Status status = WriteSplitBufferMetadataFile(prefix_metadata); !status.ok()) { - return status; + ASYNC_RETURN status; } if (client_buffer_registration_callback_) { - if (absl::Status status = client_buffer_registration_callback_( + if (absl::Status status = ASYNC_AWAIT(client_buffer_registration_callback_( ClientBufferFromSplitMetadata( prefix_metadata, ClientBufferAllocatorKind::kSplitShm), - &*prefix_fd); + &*prefix_fd)); !status.ok()) { (void)DestroySplitSharedMemoryBuffer(prefix_metadata); - return status; + ASYNC_RETURN status; } } buffer->split_prefix_fd = std::move(*prefix_fd); @@ -865,10 +872,10 @@ ClientChannel::CreateSplitBufferSet(size_t buffer_index, size_t full_size, if (SplitBuffersCallbacks().allocate) { auto mapping = SplitBuffersCallbacks().allocate(metadata); if (!mapping.ok()) { - return mapping.status(); + ASYNC_RETURN mapping.status(); } if (mapping->address == nullptr) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( "Split buffer allocation callback returned an empty mapping"); } slot_addr = static_cast(mapping->address); @@ -891,32 +898,32 @@ ClientChannel::CreateSplitBufferSet(size_t buffer_index, size_t full_size, auto created_fd = CreateAnonymousSharedMemory(metadata.object_name, metadata.allocation_size); if (!created_fd.ok()) { - return created_fd.status(); + ASYNC_RETURN created_fd.status(); } metadata.handle = static_cast(created_fd->Fd()); if (client_buffer_registration_callback_) { - if (absl::Status status = client_buffer_registration_callback_( + if (absl::Status status = ASYNC_AWAIT(client_buffer_registration_callback_( ClientBufferFromSplitMetadata( metadata, ClientBufferAllocatorKind::kSplitShm), - &*created_fd); + &*created_fd)); !status.ok()) { - return status; + ASYNC_RETURN status; } } // `created_fd` is closed here; if we won the race the server holds a // dup, otherwise the unused memfd is released. } auto registered = - GetRegisteredClientBuffer(static_cast(buffer_index), + ASYNC_AWAIT(GetRegisteredClientBuffer(static_cast(buffer_index), /*is_prefix=*/false, - static_cast(slot)); + static_cast(slot))); if (!registered.ok()) { - return registered.status(); + ASYNC_RETURN registered.status(); } metadata.allocation_size = registered->metadata.allocation_size; auto addr = MapBuffer(registered->fd, payload_size, MapMode()); if (!addr.ok()) { - return addr.status(); + ASYNC_RETURN addr.status(); } slot_addr = *addr; slot_handle = static_cast(registered->fd.Fd()); @@ -926,16 +933,16 @@ ClientChannel::CreateSplitBufferSet(size_t buffer_index, size_t full_size, #else auto created_fd = CreateSplitSharedMemoryBuffer(metadata); if (!created_fd.ok()) { - return created_fd.status(); + ASYNC_RETURN created_fd.status(); } if (!created_fd->Valid()) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "Split buffer slot already exists for channel %s slot %d", ResolvedName(), slot)); } auto addr = MapBuffer(*created_fd, payload_size, MapMode()); if (!addr.ok()) { - return addr.status(); + ASYNC_RETURN addr.status(); } slot_addr = *addr; slot_handle = static_cast(created_fd->Fd()); @@ -946,19 +953,19 @@ ClientChannel::CreateSplitBufferSet(size_t buffer_index, size_t full_size, #if SUBSPACE_SHMEM_MODE != SUBSPACE_SHMEM_MODE_MEMFD if (absl::Status status = WriteSplitBufferMetadataFile(metadata); !status.ok()) { - return status; + ASYNC_RETURN status; } #endif if (client_buffer_registration_callback_ && !registered_via_memfd) { - if (absl::Status status = client_buffer_registration_callback_( + if (absl::Status status = ASYNC_AWAIT(client_buffer_registration_callback_( ClientBufferFromSplitMetadata( metadata, buffer->uses_split_callbacks ? ClientBufferAllocatorKind::kSplitCallback : ClientBufferAllocatorKind::kSplitShm), - slot_fd.has_value() ? &*slot_fd : nullptr); + slot_fd.has_value() ? &*slot_fd : nullptr)); !status.ok()) { - return status; + ASYNC_RETURN status; } } buffer->split_handles[slot] = slot_handle; @@ -970,10 +977,10 @@ ClientChannel::CreateSplitBufferSet(size_t buffer_index, size_t full_size, } buffer->split_metadata.push_back(std::move(metadata)); } - return buffer; + ASYNC_RETURN buffer; } -absl::StatusOr> +async::Task>> ClientChannel::OpenSplitBufferSet(size_t buffer_index, size_t full_size, uint64_t slot_size) { auto buffer = std::make_unique(full_size, slot_size, nullptr); @@ -984,16 +991,16 @@ ClientChannel::OpenSplitBufferSet(size_t buffer_index, size_t full_size, std::string prefix_name = metadata_base + "_prefix"; #if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD absl::StatusOr prefix_registered = - GetRegisteredClientBuffer(static_cast(buffer_index), - /*is_prefix=*/true, /*slot_id=*/0); + ASYNC_AWAIT(GetRegisteredClientBuffer(static_cast(buffer_index), + /*is_prefix=*/true, /*slot_id=*/0)); if (!prefix_registered.ok()) { - return prefix_registered.status(); + ASYNC_RETURN prefix_registered.status(); } auto prefix_addr = MapBuffer(prefix_registered->fd, prefix_registered->metadata.allocation_size, BufferMapMode::kReadWrite); if (!prefix_addr.ok()) { - return prefix_addr.status(); + ASYNC_RETURN prefix_addr.status(); } buffer->split_prefix_fd = std::move(prefix_registered->fd); buffer->split_prefix_buffer = *prefix_addr; @@ -1004,17 +1011,17 @@ ClientChannel::OpenSplitBufferSet(size_t buffer_index, size_t full_size, #else auto prefix_metadata = ReadSplitBufferMetadataFileWithRetry(prefix_name); if (!prefix_metadata.ok()) { - return prefix_metadata.status(); + ASYNC_RETURN prefix_metadata.status(); } auto prefix_fd = OpenSplitSharedMemoryBuffer(*prefix_metadata, O_RDWR); if (!prefix_fd.ok()) { - return prefix_fd.status(); + ASYNC_RETURN prefix_fd.status(); } auto prefix_addr = MapBuffer(*prefix_fd, prefix_metadata->allocation_size, BufferMapMode::kReadWrite); if (!prefix_addr.ok()) { - return prefix_addr.status(); + ASYNC_RETURN prefix_addr.status(); } buffer->split_prefix_fd = std::move(*prefix_fd); buffer->split_prefix_buffer = *prefix_addr; @@ -1031,11 +1038,11 @@ ClientChannel::OpenSplitBufferSet(size_t buffer_index, size_t full_size, for (int slot = 0; slot < NumSlots(); slot++) { #if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD absl::StatusOr registered = - GetRegisteredClientBuffer(static_cast(buffer_index), + ASYNC_AWAIT(GetRegisteredClientBuffer(static_cast(buffer_index), /*is_prefix=*/false, - static_cast(slot)); + static_cast(slot))); if (!registered.ok()) { - return registered.status(); + ASYNC_RETURN registered.status(); } SplitBufferMetadata metadata = SplitMetadataFromClientBuffer(registered->metadata); @@ -1044,7 +1051,7 @@ ClientChannel::OpenSplitBufferSet(size_t buffer_index, size_t full_size, std::string shadow_file = absl::StrFormat("%s_slot_%d", metadata_base, slot); auto metadata_or = ReadSplitBufferMetadataFileWithRetry(shadow_file); if (!metadata_or.ok()) { - return metadata_or.status(); + ASYNC_RETURN metadata_or.status(); } SplitBufferMetadata metadata = std::move(*metadata_or); #endif @@ -1056,11 +1063,11 @@ ClientChannel::OpenSplitBufferSet(size_t buffer_index, size_t full_size, if (SplitBuffersCallbacks().map) { #if SUBSPACE_SHMEM_MODE != SUBSPACE_SHMEM_MODE_MEMFD absl::StatusOr registered = - GetRegisteredClientBuffer(static_cast(buffer_index), + ASYNC_AWAIT(GetRegisteredClientBuffer(static_cast(buffer_index), /*is_prefix=*/false, - static_cast(slot)); + static_cast(slot))); if (!registered.ok()) { - return registered.status(); + ASYNC_RETURN registered.status(); } metadata = SplitMetadataFromClientBuffer(registered->metadata); registered_fd.emplace(std::move(registered->fd)); @@ -1070,10 +1077,10 @@ ClientChannel::OpenSplitBufferSet(size_t buffer_index, size_t full_size, } auto mapping = SplitBuffersCallbacks().map(metadata); if (!mapping.ok()) { - return mapping.status(); + ASYNC_RETURN mapping.status(); } if (mapping->address == nullptr) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( "Split buffer map callback returned an empty mapping"); } slot_addr = static_cast(mapping->address); @@ -1088,13 +1095,13 @@ ClientChannel::OpenSplitBufferSet(size_t buffer_index, size_t full_size, #else auto slot_fd_or = OpenSplitSharedMemoryBuffer(metadata, O_RDWR); if (!slot_fd_or.ok()) { - return slot_fd_or.status(); + ASYNC_RETURN slot_fd_or.status(); } toolbelt::FileDescriptor slot_fd = std::move(*slot_fd_or); #endif auto addr = MapBuffer(slot_fd, payload_size, MapMode()); if (!addr.ok()) { - return addr.status(); + ASYNC_RETURN addr.status(); } slot_addr = *addr; slot_handle = static_cast(slot_fd.Fd()); @@ -1109,7 +1116,7 @@ ClientChannel::OpenSplitBufferSet(size_t buffer_index, size_t full_size, buffer->split_private_data[slot] = slot_private_data; buffer->split_metadata.push_back(std::move(metadata)); } - return buffer; + ASYNC_RETURN buffer; } absl::StatusOr diff --git a/client/client_channel.h b/client/client_channel.h index 5f3fca8f..c7164813 100644 --- a/client/client_channel.h +++ b/client/client_channel.h @@ -85,7 +85,8 @@ class ClientChannel : public Channel { int subscriber_queue_size, uint64_t subscriber_queue_arena_size, int channel_id, int vchan_id, uint64_t session_id, std::string type, - std::function reload, int user_id, int group_id) + std::function(Channel *)> reload, int user_id, + int group_id) : Channel(name, num_slots, channel_id, subscriber_queue_size, subscriber_queue_arena_size, std::move(type), std::move(reload)), @@ -100,13 +101,16 @@ class ClientChannel : public Channel { return GetScb()->counters[GetChannelId()]; } - void Unmap() override; + // Unmaps everything. Blocks for the server to unregister the buffers, so it + // must not run inside a coroutine on the scheduler thread; use UnmapAsync. + void Unmap() override { ASYNC_BLOCK(UnmapAsync()); } + async::Task UnmapAsync(); // Unmaps the channel control block, buffer control block, and message // buffers before they are mapped again. The system control block stays // mapped because every channel in the client shares it, and other threads // read publisher and subscriber counts from it while a subscriber reloads. - void UnmapForReload(); + async::Task UnmapForReload(); void Dump(std::ostream &os) const override; @@ -119,7 +123,7 @@ class ClientChannel : public Channel { absl::Status Map(SharedMemoryFds fds, const toolbelt::FileDescriptor &scb_fd); absl::Status MapNewBuffers(std::vector buffers); - absl::Status UnmapUnusedBuffers(); + async::Task UnmapUnusedBuffers(); int VirtualChannelId() const { return vchan_id_; } @@ -234,9 +238,16 @@ class ClientChannel : public Channel { if (index >= 0 && static_cast(index) < buffers_.size()) { return buffers_.empty() ? nullptr : (buffers_[index]->buffer); } +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // Reloading needs a round trip that must be awaited, and this function + // is sync. Callers await CheckReload() before they get here + // (ValidateSlotBuffer does), so there is nothing to retry. + break; +#else CheckReload(); retries++; std::this_thread::yield(); +#endif } if (abort_on_range) { // If the index is out of range, we have a problem. @@ -308,7 +319,7 @@ class ClientChannel : public Channel { return true; } - absl::Status AttachBuffers(); + async::Task AttachBuffers(); void ClearRetirementTriggers() { std::unique_lock lock(retirement_lock_); @@ -327,18 +338,19 @@ class ClientChannel : public Channel { } void SetClientBufferRegistrationCallback( - std::function + std::function( + const ClientBufferHandleMetadata &, const toolbelt::FileDescriptor *)> callback) { client_buffer_registration_callback_ = std::move(callback); } void SetClientBufferLookupCallback( - std::function>( + std::function>>( const std::string &, uint64_t, uint32_t)> callback) { client_buffer_lookup_callback_ = std::move(callback); } void SetClientBufferUnregistrationCallback( - std::function + std::function(const std::string &, uint64_t, + uint32_t)> callback) { client_buffer_unregistration_callback_ = std::move(callback); } @@ -363,7 +375,7 @@ class ClientChannel : public Channel { void *GetCurrentBufferAddress() { return GetBufferAddress(slot_); } - bool ValidateSlotBuffer(MessageSlot *slot); + async::Task ValidateSlotBuffer(MessageSlot *slot); void SetMessageSize(int64_t message_size) { slot_->message_size.store(message_size, std::memory_order_relaxed); @@ -375,22 +387,22 @@ class ClientChannel : public Channel { absl::StatusOr CreateBuffer(int buffer_index, size_t size); absl::Status AttachShmBuffers(int num_buffers); - absl::Status AttachSplitBuffers(int num_buffers); + async::Task AttachSplitBuffers(int num_buffers); absl::StatusOr OpenBuffer(int buffer_index); absl::StatusOr GetBufferSize(toolbelt::FileDescriptor &shm_fd, int buffer_index) const; absl::StatusOr MapBuffer(toolbelt::FileDescriptor &shm_fd, size_t size, BufferMapMode mode); void UnmapShmBufferSet(BufferSet &buffer); - void UnmapSplitBufferSet(size_t buffer_index, BufferSet &buffer, + async::Task UnmapSplitBufferSet(size_t buffer_index, BufferSet &buffer, bool destroy_owned_buffers); - void UnmapBufferSet(size_t buffer_index, BufferSet &buffer, + async::Task UnmapBufferSet(size_t buffer_index, BufferSet &buffer, bool destroy_owned_buffers); #if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD absl::StatusOr CreateMemfdBuffer(const std::string &filename, size_t size); #endif - absl::StatusOr + async::Task> GetRegisteredClientBuffer(uint32_t buffer_index, bool is_prefix, uint32_t slot_id); #if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_LINUX @@ -400,10 +412,10 @@ class ClientChannel : public Channel { absl::StatusOr CreatePosixBuffer(const std::string &filename, size_t size); #endif - absl::StatusOr> + async::Task>> CreateSplitBufferSet(size_t buffer_index, size_t full_size, uint64_t slot_size); - absl::StatusOr> + async::Task>> OpenSplitBufferSet(size_t buffer_index, size_t full_size, uint64_t slot_size); @@ -415,13 +427,14 @@ class ClientChannel : public Channel { MessageSlot *slot_ = nullptr; // Current slot. int vchan_id_ = -1; // Virtual channel ID. uint64_t session_id_; - std::function + std::function(const ClientBufferHandleMetadata &, + const toolbelt::FileDescriptor *)> client_buffer_registration_callback_ = nullptr; - std::function>( + std::function>>( const std::string &, uint64_t, uint32_t)> client_buffer_lookup_callback_ = nullptr; - std::function + std::function(const std::string &, uint64_t, + uint32_t)> client_buffer_unregistration_callback_ = nullptr; std::vector> buffers_ = {}; int user_id_ = -1; diff --git a/client/publisher.cc b/client/publisher.cc index fd819ddc..c36a5b96 100644 --- a/client/publisher.cc +++ b/client/publisher.cc @@ -25,7 +25,7 @@ class SubscriberQueuePublishGuard { PublisherImpl &publisher_; }; -absl::Status PublisherImpl::CreateOrAttachBuffers(uint64_t final_slot_size) { +async::Task PublisherImpl::CreateOrAttachBuffers(uint64_t final_slot_size) { if (final_slot_size == 0) { // If we are being asked for a slot size of 0, we will just use 64 bytes. // This is the minimum slot size we can use. @@ -41,10 +41,10 @@ absl::Status PublisherImpl::CreateOrAttachBuffers(uint64_t final_slot_size) { size_t buffer_index = buffers_.size(); if (UseSplitBuffers()) { auto split_buffer = - CreateSplitBufferSet(buffer_index, final_buffer_size, - final_slot_size); + ASYNC_AWAIT(CreateSplitBufferSet(buffer_index, final_buffer_size, + final_slot_size)); if (!split_buffer.ok()) { - return split_buffer.status(); + ASYNC_RETURN split_buffer.status(); } bcb_->sizes[buffers_.size()].store(final_buffer_size, std::memory_order_relaxed); @@ -63,7 +63,7 @@ absl::Status PublisherImpl::CreateOrAttachBuffers(uint64_t final_slot_size) { auto shm_fd = CreateBuffer(buffer_index, final_buffer_size); #endif if (!shm_fd.ok()) { - return shm_fd.status(); + ASYNC_RETURN shm_fd.status(); } if (!shm_fd->Valid()) { // The named shared memory already exists so we attach to it instead of @@ -71,7 +71,7 @@ absl::Status PublisherImpl::CreateOrAttachBuffers(uint64_t final_slot_size) { opened_existing_buffer = true; shm_fd = OpenBuffer(buffer_index); if (!shm_fd.ok()) { - return shm_fd.status(); + ASYNC_RETURN shm_fd.status(); } } if (opened_existing_buffer) { @@ -82,14 +82,14 @@ absl::Status PublisherImpl::CreateOrAttachBuffers(uint64_t final_slot_size) { // slot with our smaller requested size. auto size = GetBufferSize(*shm_fd, buffer_index); if (!size.ok()) { - return size.status(); + ASYNC_RETURN size.status(); } current_slot_size = BufferSizeToSlotSize(*size); absl::StatusOr addr; if (current_slot_size > 0) { addr = MapBuffer(*shm_fd, *size, BufferMapMode::kReadWrite); if (!addr.ok()) { - return addr.status(); + ASYNC_RETURN addr.status(); } } else { addr = nullptr; @@ -106,7 +106,7 @@ absl::Status PublisherImpl::CreateOrAttachBuffers(uint64_t final_slot_size) { auto addr = MapBuffer(*shm_fd, final_buffer_size, BufferMapMode::kReadWrite); if (!addr.ok()) { - return addr.status(); + ASYNC_RETURN addr.status(); } auto buffer_set = std::make_unique( final_buffer_size, final_slot_size, *addr); @@ -141,7 +141,7 @@ absl::Status PublisherImpl::CreateOrAttachBuffers(uint64_t final_slot_size) { .allocator = ClientBufferAllocatorKind::kAndroidMemfd, }; if (absl::Status status = - client_buffer_registration_callback_(metadata, &buffer.fd); + ASYNC_AWAIT(client_buffer_registration_callback_(metadata, &buffer.fd)); !status.ok()) { int expected_num_buffers = new_num_buffers; if (ccb_->num_buffers.compare_exchange_strong( @@ -155,11 +155,11 @@ absl::Status PublisherImpl::CreateOrAttachBuffers(uint64_t final_slot_size) { std::min(static_cast(old_num_buffers), buffers_.size()); for (size_t j = rollback_to; j < buffers_.size(); j++) { - UnmapBufferSet(j, *buffers_[j], - /*destroy_owned_buffers=*/false); + ASYNC_AWAIT(UnmapBufferSet(j, *buffers_[j], + /*destroy_owned_buffers=*/false)); } buffers_.resize(rollback_to); - return status; + ASYNC_RETURN status; } } } @@ -170,7 +170,7 @@ absl::Status PublisherImpl::CreateOrAttachBuffers(uint64_t final_slot_size) { #if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD if (!UseSplitBuffers()) { for (size_t i = 0; i < buffers_.size(); i++) { - UnmapBufferSet(i, *buffers_[i], /*destroy_owned_buffers=*/false); + ASYNC_AWAIT(UnmapBufferSet(i, *buffers_[i], /*destroy_owned_buffers=*/false)); } buffers_.clear(); current_slot_size = 0; @@ -179,7 +179,7 @@ absl::Status PublisherImpl::CreateOrAttachBuffers(uint64_t final_slot_size) { // Another thread has updated the number of buffers in the CCB. We need to // retry. } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } void PublisherImpl::SetSlotToBiggestBuffer(MessageSlot *slot) { @@ -349,7 +349,8 @@ int PublisherImpl::FindRetiredSlotToReuse(bool oldest_first) { return oldest; } -MessageSlot *PublisherImpl::FindFreeSlotUnreliable(int owner) { +async::Task +PublisherImpl::FindFreeSlotUnreliable(int owner) { int retries = num_slots_ * 1000; MessageSlot *slot = nullptr; embargoed_slots_.ClearAll(); @@ -383,7 +384,9 @@ MessageSlot *PublisherImpl::FindFreeSlotUnreliable(int owner) { slot = nullptr; retired_slot = -1; free_slot = -1; - CheckReload(); + if (BuffersChanged()) { + ASYNC_AWAIT(CheckReload()); + } // Read the subscriber count off the reloaded CCB rather than caching it // across the loop, so a subscriber attaching while we retry here is seen. const bool no_subscribers = NumSubscribers(vchan_id_) == 0; @@ -467,7 +470,7 @@ MessageSlot *PublisherImpl::FindFreeSlotUnreliable(int owner) { // We are guaranteed to find a slot, but let's not go into an infinite // loop if something goes wrong. if (retries-- == 0) { - return nullptr; + ASYNC_RETURN nullptr; } continue; } @@ -492,7 +495,7 @@ MessageSlot *PublisherImpl::FindFreeSlotUnreliable(int owner) { if (slot->refs.compare_exchange_strong(expected, ref, std::memory_order_acquire, std::memory_order_relaxed)) { - if (!ValidateSlotBuffer(slot)) { + if (!ASYNC_AWAIT(ValidateSlotBuffer(slot))) { // No buffer for the slot. Embargo the slot so we don't see it again // this loop and try again. embargoed_slots_.Set(slot->id); @@ -503,7 +506,7 @@ MessageSlot *PublisherImpl::FindFreeSlotUnreliable(int owner) { } if (++cas_retries >= max_cas_retries) { if (retries-- == 0) { - return nullptr; + ASYNC_RETURN nullptr; } cas_retries = 0; std::this_thread::yield(); @@ -537,10 +540,11 @@ MessageSlot *PublisherImpl::FindFreeSlotUnreliable(int owner) { NotifyRetirementOnForcedReuse()) { TriggerRetirement(slot->id); } - return slot; + ASYNC_RETURN slot; } -MessageSlot *PublisherImpl::FindFreeSlotReliable(int owner) { +async::Task +PublisherImpl::FindFreeSlotReliable(int owner) { int retries = num_slots_ * 1000; MessageSlot *slot = nullptr; int retired_slot = -1; @@ -552,7 +556,9 @@ MessageSlot *PublisherImpl::FindFreeSlotReliable(int owner) { slot = nullptr; retired_slot = -1; free_slot = -1; - CheckReload(); + if (BuffersChanged()) { + ASYNC_AWAIT(CheckReload()); + } // Put all free slots into the active_slots vector. active_slots_.clear(); @@ -642,7 +648,7 @@ MessageSlot *PublisherImpl::FindFreeSlotReliable(int owner) { } } if (slot == nullptr) { - return nullptr; + ASYNC_RETURN nullptr; } // Claim the slot by setting the kPubOwned bit. uint64_t old_refs = slot->refs.load(std::memory_order_relaxed); @@ -660,7 +666,7 @@ MessageSlot *PublisherImpl::FindFreeSlotReliable(int owner) { if (slot->refs.compare_exchange_strong(expected, ref, std::memory_order_acquire, std::memory_order_relaxed)) { - if (!ValidateSlotBuffer(slot)) { + if (!ASYNC_AWAIT(ValidateSlotBuffer(slot))) { // No buffer for the slot. Embargo the slot so we don't see it again // this loop and try again. embargoed_slots_.Set(slot->id); @@ -672,7 +678,7 @@ MessageSlot *PublisherImpl::FindFreeSlotReliable(int owner) { } if (++cas_retries >= max_cas_retries) { if (retries-- == 0) { - return nullptr; + ASYNC_RETURN nullptr; } cas_retries = 0; std::this_thread::yield(); @@ -705,10 +711,11 @@ MessageSlot *PublisherImpl::FindFreeSlotReliable(int owner) { NotifyRetirementOnForcedReuse()) { TriggerRetirement(slot->id); } - return slot; + ASYNC_RETURN slot; } -Channel::PublishedMessage PublisherImpl::ActivateSlotAndGetAnother( +async::Task +PublisherImpl::ActivateSlotAndGetAnother( MessageSlot *slot, bool reliable, bool is_activation, int owner, bool omit_prefix, bool use_prefix_slot_id, bool for_tunnel, bool acquire_next, bool use_prefix_vchan_id) { @@ -873,18 +880,22 @@ Channel::PublishedMessage PublisherImpl::ActivateSlotAndGetAnother( } if (!acquire_next) { - return {nullptr, published_ordinal, published_timestamp}; + ASYNC_RETURN Channel::PublishedMessage{nullptr, published_ordinal, + published_timestamp}; } // A reliable publisher doesn't allocate a slot until it is asked for. if (reliable) { - CheckReload(); - return {nullptr, 0, 0}; + if (BuffersChanged()) { + ASYNC_AWAIT(CheckReload()); + } + ASYNC_RETURN Channel::PublishedMessage{nullptr, 0, 0}; } // Find a new slot.x - MessageSlot *new_slot = FindFreeSlotUnreliable(owner); + MessageSlot *new_slot = ASYNC_AWAIT(FindFreeSlotUnreliable(owner)); - return {new_slot, published_ordinal, published_timestamp}; + ASYNC_RETURN Channel::PublishedMessage{new_slot, published_ordinal, + published_timestamp}; } } // namespace details diff --git a/client/publisher.h b/client/publisher.h index c775d9ad..af891d04 100644 --- a/client/publisher.h +++ b/client/publisher.h @@ -23,7 +23,8 @@ class PublisherImpl : public ClientChannel { int publisher_id, int vchan_id, uint64_t session_id, std::string type, const PublisherOptions &options, - std::function reload, int user_id, int group_id) + std::function(Channel *)> reload, + int user_id, int group_id) : ClientChannel(name, num_slots, subscriber_queue_size, subscriber_queue_arena_size, channel_id, vchan_id, std::move(session_id), std::move(type), @@ -58,8 +59,8 @@ class PublisherImpl : public ClientChannel { // triggerfd. void TriggerReliable() { trigger_.Trigger(); } - MessageSlot *FindFreeSlotUnreliable(int owner); - MessageSlot *FindFreeSlotReliable(int owner); + async::Task FindFreeSlotUnreliable(int owner); + async::Task FindFreeSlotReliable(int owner); // Picks the retired slot to recycle next, or -1 if the retired pool holds // no usable slot. Takes the lowest-index slot unless oldest_first, which @@ -68,7 +69,7 @@ class PublisherImpl : public ClientChannel { void SetSlotToBiggestBuffer(MessageSlot *slot); - absl::Status CreateOrAttachBuffers(uint64_t slot_size); + async::Task CreateOrAttachBuffers(uint64_t slot_size); void SetRetirementFd(toolbelt::FileDescriptor fd) { retirement_fd_ = std::move(fd); @@ -161,22 +162,22 @@ class PublisherImpl : public ClientChannel { // notify: set to true if we should notify the subscribers. // // Locks the CCB. - Channel::PublishedMessage + async::Task ActivateSlotAndGetAnother(MessageSlot *slot, bool reliable, bool is_activation, int owner, bool omit_prefix, bool use_prefix_slot_id, bool for_tunnel = false, bool acquire_next = true, bool use_prefix_vchan_id = true); - Channel::PublishedMessage + async::Task ActivateSlotAndGetAnother(bool reliable, bool is_activation, bool omit_prefix, bool use_prefix_slot_id, bool for_tunnel = false, bool use_prefix_vchan_id = true) { - return ActivateSlotAndGetAnother( + ASYNC_RETURN ASYNC_AWAIT(ActivateSlotAndGetAnother( slot_, reliable, is_activation, publisher_id_, omit_prefix, use_prefix_slot_id, for_tunnel, /*acquire_next=*/true, - use_prefix_vchan_id); + use_prefix_vchan_id)); } void ClearSubscribers() { subscribers_.clear(); } diff --git a/client/subscriber.cc b/client/subscriber.cc index 01e32c42..c22b8dff 100644 --- a/client/subscriber.cc +++ b/client/subscriber.cc @@ -633,7 +633,8 @@ MessageSlot *SubscriberImpl::FindNextVisibleSlot(InPlaceAtomicBitset &bits, return best_slot; } -MessageSlot *SubscriberImpl::NextSlot(MessageSlot *slot, bool reliable, +async::Task +SubscriberImpl::NextSlot(MessageSlot *slot, bool reliable, int owner) { embargoed_slots_.ClearAll(); @@ -647,7 +648,9 @@ MessageSlot *SubscriberImpl::NextSlot(MessageSlot *slot, bool reliable, #else const bool print_errors = false; #endif - CheckReload(); + if (BuffersChanged()) { + ASYNC_AWAIT(CheckReload()); + } InPlaceAtomicBitset &bits = GetAvailableSlots(owner); const bool stable_poll_drain = PollDrainPending(); if (stable_poll_drain && poll_drain_exhausted_) { @@ -657,7 +660,7 @@ MessageSlot *SubscriberImpl::NextSlot(MessageSlot *slot, bool reliable, queue_drain_tail_valid_ = false; next_slot_cache_valid_ = false; } else { - return nullptr; + ASYNC_RETURN nullptr; } } if (slot == nullptr) { @@ -739,7 +742,7 @@ MessageSlot *SubscriberImpl::NextSlot(MessageSlot *slot, bool reliable, } const int buffer_index = new_slot->buffer_index.load(std::memory_order_relaxed); - if (!ValidateSlotBuffer(new_slot) || buffer_index == -1) { + if (!ASYNC_AWAIT(ValidateSlotBuffer(new_slot)) || buffer_index == -1) { if (print_errors) { std::cerr << "Subscriber for " << Name() << " detected buffer failure on slot: " << new_slot->id @@ -758,7 +761,7 @@ MessageSlot *SubscriberImpl::NextSlot(MessageSlot *slot, bool reliable, // dies before ClientImpl can allocate and claim the ActiveMessage, the // server must still be able to identify and release this reference. new_slot->sub_owners.Set(subscriber_id_); - return new_slot; + ASYNC_RETURN new_slot; } // Push() may fail after a peer dies or loses a bounded CAS race. The // publisher always records the slot in the bitset, so continue below and @@ -859,7 +862,7 @@ MessageSlot *SubscriberImpl::NextSlot(MessageSlot *slot, bool reliable, next_slot_cached_total_) { Trigger(); } - return nullptr; + ASYNC_RETURN nullptr; } if (print_errors) { std::cerr << "Warning: subscriber for " << Name() @@ -883,7 +886,7 @@ MessageSlot *SubscriberImpl::NextSlot(MessageSlot *slot, bool reliable, } const int buffer_index = new_slot->slot->buffer_index.load(std::memory_order_relaxed); - if (!ValidateSlotBuffer(new_slot->slot) || buffer_index == -1) { + if (!ASYNC_AWAIT(ValidateSlotBuffer(new_slot->slot)) || buffer_index == -1) { if (print_errors) { std::cerr << "Subscriber for " << Name() << " detected buffer failure on slot: " @@ -911,7 +914,7 @@ MessageSlot *SubscriberImpl::NextSlot(MessageSlot *slot, bool reliable, // Record ownership before returning the pinned slot. This closes the // crash window between AtomicIncRefCount and ClaimSlot. new_slot->slot->sub_owners.Set(subscriber_id_); - return new_slot->slot; + ASYNC_RETURN new_slot->slot; } // CAS failed: another subscriber raced us, or the slot was retired and // overwritten with a new ordinal. Drop the cache and re-snapshot. @@ -921,15 +924,18 @@ MessageSlot *SubscriberImpl::NextSlot(MessageSlot *slot, bool reliable, next_slot_cache_valid_ = false; } } - return nullptr; + ASYNC_RETURN nullptr; } -MessageSlot *SubscriberImpl::LastSlot(MessageSlot *slot, bool reliable, +async::Task +SubscriberImpl::LastSlot(MessageSlot *slot, bool reliable, int owner) { embargoed_slots_.ClearAll(); for (;;) { - CheckReload(); + if (BuffersChanged()) { + ASYNC_AWAIT(CheckReload()); + } InPlaceAtomicBitset &bits = GetAvailableSlots(owner); if (!reliable && SubscriberQueueSize() > 0) { if (InPlaceSlotQueue *queue = @@ -967,7 +973,7 @@ MessageSlot *SubscriberImpl::LastSlot(MessageSlot *slot, bool reliable, } if (new_slot == nullptr) { newest_snapshot_.clear(); - return nullptr; + ASYNC_RETURN nullptr; } // Increment the ref count. @@ -975,7 +981,7 @@ MessageSlot *SubscriberImpl::LastSlot(MessageSlot *slot, bool reliable, new_slot->vchan_id, false)) { const int buffer_index = new_slot->slot->buffer_index.load(std::memory_order_relaxed); - if (!ValidateSlotBuffer(new_slot->slot) || buffer_index == -1) { + if (!ASYNC_AWAIT(ValidateSlotBuffer(new_slot->slot)) || buffer_index == -1) { // Failed to get a buffer for the slot. Embargo the slot so we don't // see it again this loop and try again. embargoed_slots_.Set(new_slot->slot->id); @@ -986,18 +992,21 @@ MessageSlot *SubscriberImpl::LastSlot(MessageSlot *slot, bool reliable, // ReadNewest also returns a pinned slot through ClientImpl before // ClaimSlot runs, so make that transient reference server-visible. new_slot->slot->sub_owners.Set(subscriber_id_); - return new_slot->slot; + ASYNC_RETURN new_slot->slot; } newest_snapshot_.clear(); } } -MessageSlot *SubscriberImpl::FindActiveSlotByTimestamp( +async::Task +SubscriberImpl::FindActiveSlotByTimestamp( [[maybe_unused]] MessageSlot *old_slot, uint64_t timestamp, bool reliable, int owner, std::vector &buffer) { embargoed_slots_.ClearAll(); for (;;) { - CheckReload(); + if (BuffersChanged()) { + ASYNC_AWAIT(CheckReload()); + } buffer.clear(); buffer.reserve(NumSlots()); @@ -1021,7 +1030,7 @@ MessageSlot *SubscriberImpl::FindActiveSlotByTimestamp( // Apparently, lower_bound will return the first in the range if // the value is less than the whole range. That's unexpected. if (buffer.empty() || timestamp < buffer.front().timestamp) { - return nullptr; + ASYNC_RETURN nullptr; } // Binary search the search buffer. @@ -1030,16 +1039,16 @@ MessageSlot *SubscriberImpl::FindActiveSlotByTimestamp( [](ActiveSlot &s, uint64_t t) { return s.timestamp < t; }); if (it == buffer.end()) { // Not found, nothing changes. - return nullptr; + ASYNC_RETURN nullptr; } if (it->timestamp != timestamp) { - return nullptr; + ASYNC_RETURN nullptr; } // Try to increment the ref count. if (AtomicIncRefCount(it->slot, reliable, 1, it->ordinal, it->vchan_id, false)) { - if (!ValidateSlotBuffer(it->slot) || + if (!ASYNC_AWAIT(ValidateSlotBuffer(it->slot)) || it->slot->buffer_index.load(std::memory_order_relaxed) == -1) { // Failed to get a buffer for the slot. Embargo the slot so we don't // see it again this loop and try again. @@ -1054,7 +1063,7 @@ MessageSlot *SubscriberImpl::FindActiveSlotByTimestamp( std::memory_order_relaxed); } it->slot->sub_owners.Set(owner); - return it->slot; + ASYNC_RETURN it->slot; } // Publisher got there first, try again. } diff --git a/client/subscriber.h b/client/subscriber.h index 1cccfaa5..13eb036b 100644 --- a/client/subscriber.h +++ b/client/subscriber.h @@ -60,8 +60,8 @@ class SubscriberImpl : public ClientChannel { int subscriber_queue_size, int channel_id, int subscriber_id, int vchan_id, uint64_t session_id, std::string type, const SubscriberOptions &options, - std::function reload, int user_id, - int group_id) + std::function(Channel *)> reload, + int user_id, int group_id) : ClientChannel(name, num_slots, default_subscriber_queue_size, subscriber_queue_arena_size, channel_id, vchan_id, std::move(session_id), std::move(type), std::move(reload), @@ -185,8 +185,10 @@ class SubscriberImpl : public ClientChannel { // Can return nullptr if there is no slot. // If reliable is true, the reliable_ref_count in the MessageSlot will // be manipulated. The owner is the subscriber ID. - MessageSlot *NextSlot(MessageSlot *slot, bool reliable, int owner); - MessageSlot *LastSlot(MessageSlot *slot, bool reliable, int owner); + async::Task NextSlot(MessageSlot *slot, bool reliable, + int owner); + async::Task LastSlot(MessageSlot *slot, bool reliable, + int owner); std::shared_ptr GetActiveMessage() { return active_message_; } @@ -300,7 +302,7 @@ class SubscriberImpl : public ClientChannel { // buffer, but this function will modify it. This is to avoid memory // allocation for every search or buffer allocation for every subscriber when // searches are rare. - MessageSlot *FindActiveSlotByTimestamp(MessageSlot *old_slot, + async::Task FindActiveSlotByTimestamp(MessageSlot *old_slot, uint64_t timestamp, bool reliable, int owner, std::vector &buffer); @@ -405,12 +407,14 @@ class SubscriberImpl : public ClientChannel { } int GetSubscriberId() const { return subscriber_id_; } - MessageSlot *NextSlot() { - return NextSlot(CurrentSlot(), IsReliable(), subscriber_id_); + async::Task NextSlot() { + ASYNC_RETURN ASYNC_AWAIT( + NextSlot(CurrentSlot(), IsReliable(), subscriber_id_)); } - MessageSlot *LastSlot() { - return LastSlot(CurrentSlot(), IsReliable(), subscriber_id_); + async::Task LastSlot() { + ASYNC_RETURN ASYNC_AWAIT( + LastSlot(CurrentSlot(), IsReliable(), subscriber_id_)); } toolbelt::FileDescriptor &GetPollFd() { @@ -430,14 +434,14 @@ class SubscriberImpl : public ClientChannel { void ClearPollFd() { trigger_.Clear(); } bool PollDrainPending() const { return poll_drain_pending_; } - MessageSlot *FindMessage(uint64_t timestamp) { - MessageSlot *slot = + async::Task FindMessage(uint64_t timestamp) { + MessageSlot *slot = ASYNC_AWAIT( FindActiveSlotByTimestamp(CurrentSlot(), timestamp, IsReliable(), - GetSubscriberId(), search_buffer_); + GetSubscriberId(), search_buffer_)); if (slot != nullptr) { SetSlot(slot); } - return slot; + ASYNC_RETURN slot; } OrdinalTracker &GetOrdinalTracker(int vchan_id); diff --git a/common/BUILD.bazel b/common/BUILD.bazel index 135507ed..4aacbe1e 100644 --- a/common/BUILD.bazel +++ b/common/BUILD.bazel @@ -59,6 +59,7 @@ cc_library( ":max_channels_setting", ":max_buffers_setting", ":max_slot_owners_setting", + "//common/async:async", "//proto:subspace_cc_proto", "@abseil-cpp//absl/container:flat_hash_map", "@abseil-cpp//absl/status", diff --git a/common/async/task.h b/common/async/task.h index 133f95ce..480e1c5e 100644 --- a/common/async/task.h +++ b/common/async/task.h @@ -40,8 +40,72 @@ namespace subspace::async { template using Task = co20::ValueTask; -#define ASYNC_AWAIT(expr) (co_await (expr)) +namespace detail { + +// Runs `task` inline inside await_suspend when it finishes without parking on +// the scheduler, returning `false` so the caller resumes in place instead of +// via symmetric transfer. GCC at -O0 and under AddressSanitizer does not +// tail-call symmetric transfers (GCC bug 100897), so a coroutine loop whose +// awaits finish without parking would otherwise grow the C stack on every +// iteration and overflow. When `task` does park on the scheduler, `done()` is +// false, `continuation_` is wired to `caller`, and returning `true` unwinds +// the C stack back to `Scheduler::Run`. +template struct [[nodiscard]] FastValueTaskAwaiter { + co20::ValueTask task_; + + bool await_ready() const noexcept { return false; } + + bool await_suspend(std::coroutine_handle<> caller) noexcept { + task_.handle_.resume(); + if (task_.handle_.done()) { + return false; + } + task_.handle_.promise().continuation_ = caller; + return true; + } + + T await_resume() { return task_.await_resume(); } +}; + +template struct [[nodiscard]] FastValueTaskRefAwaiter { + co20::ValueTask &task_; + + bool await_ready() const noexcept { return false; } + + bool await_suspend(std::coroutine_handle<> caller) noexcept { + task_.handle_.resume(); + if (task_.handle_.done()) { + return false; + } + task_.handle_.promise().continuation_ = caller; + return true; + } + + T await_resume() { return task_.await_resume(); } +}; + +template A FastAwait(A &&a) { return std::forward(a); } + +template +FastValueTaskAwaiter FastAwait(co20::ValueTask &&task) { + return FastValueTaskAwaiter{std::move(task)}; +} + +template +FastValueTaskRefAwaiter FastAwait(co20::ValueTask &task) { + return FastValueTaskRefAwaiter{task}; +} + +} // namespace detail + +// Variadic so an expression with an unparenthesised comma, such as a call to +// a template with several arguments, works. +#define ASYNC_AWAIT(...) \ + (co_await ::subspace::async::detail::FastAwait(__VA_ARGS__)) #define ASYNC_RETURN co_return +// Runs a task to completion from code that isn't a coroutine, blocking the +// thread instead of suspending. See SyncWait. +#define ASYNC_BLOCK(...) (::subspace::async::SyncWait(__VA_ARGS__)) // Runs `task` to completion from code that is not a coroutine. Every wait in // the task must use a Context that doesn't suspend, so the task never @@ -74,8 +138,9 @@ namespace subspace::async { template using Task = T; -#define ASYNC_AWAIT(expr) (expr) +#define ASYNC_AWAIT(...) (__VA_ARGS__) #define ASYNC_RETURN return +#define ASYNC_BLOCK(...) (__VA_ARGS__) template T SyncWait(T value) { return value; } diff --git a/common/channel.cc b/common/channel.cc index 8a14bef7..2ef2e0b8 100644 --- a/common/channel.cc +++ b/common/channel.cc @@ -144,7 +144,7 @@ void UnmapMemory(void *p, size_t size, Channel::Channel(const std::string &name, int num_slots, int channel_id, int subscriber_queue_size, uint64_t subscriber_queue_arena_size, std::string type, - std::function reload) + std::function(Channel *)> reload) : name_(name), num_slots_(num_slots), subscriber_queue_size_( ResolveSubscriberQueueSize(num_slots, subscriber_queue_size)), diff --git a/common/channel.h b/common/channel.h index 5a0578fa..7ba690b5 100644 --- a/common/channel.h +++ b/common/channel.h @@ -11,6 +11,7 @@ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" +#include "common/async/task.h" #include "common/atomic_bitset.h" #include "toolbelt/bitset.h" #include "toolbelt/fd.h" @@ -1109,7 +1110,7 @@ class Channel : public std::enable_shared_from_this { Channel(const std::string &name, int num_slots, int channel_id, int subscriber_queue_size, uint64_t subscriber_queue_arena_size, std::string type, - std::function reload = nullptr); + std::function(Channel *)> reload = nullptr); virtual ~Channel() { Unmap(); } virtual void Unmap(); @@ -1479,15 +1480,20 @@ class Channel : public std::enable_shared_from_this { void DecrementBufferRefs(int buffer_index); void IncrementBufferRefs(int buffer_index); - void CheckReload() { + // Runs the reload callback until it reports that there is nothing more to + // reload. The callback may need a round trip to the server, so this is a + // task: under co20 a caller that is inside a coroutine must await it, since + // blocking the scheduler thread would deadlock. + async::Task CheckReload() { if (reload_callback_ == nullptr) { - return; + ASYNC_RETURN; } for (;;) { - if (!reload_callback_(this)) { + if (!ASYNC_AWAIT(reload_callback_(this))) { break; } } + ASYNC_RETURN; } std::string name_; @@ -1507,7 +1513,7 @@ class Channel : public std::enable_shared_from_this { ChannelControlBlock *ccb_ = nullptr; BufferControlBlock *bcb_ = nullptr; bool debug_ = false; - std::function reload_callback_; + std::function(Channel *)> reload_callback_; }; } // namespace subspace diff --git a/docs/cpp20-coroutines.md b/docs/cpp20-coroutines.md new file mode 100644 index 00000000..8b2464c9 --- /dev/null +++ b/docs/cpp20-coroutines.md @@ -0,0 +1,167 @@ +# C++20 Coroutines (co20) Backend + +Subspace can run its server and client internals on C++20 coroutines +(`co20`) instead of the stackful `co` library. This document describes what +changes under `co20`, how to build it, and the rules callers must follow. + +The default build still uses `co`. `co20` is selected at build time and the +wire protocol, shared memory layout, and blocking client API are unchanged. + +## Building + +### Bazel + +```bash +bazelisk test --config=cpp20 //client/... //server/... +``` + +`--config=cpp20` sets `-std=c++20` and `--//:coro_backend=co20`. The config +setting `//:coro_backend_co20` is true under this backend. + +### CMake + +```bash +cmake -S . -B build -DCMAKE_CXX_STANDARD=20 -DSUBSPACE_CORO_BACKEND=co20 +``` + +`SUBSPACE_CORO_BACKEND` accepts `auto` (the default, which picks co20 for C++20 +and later and `co` otherwise), `co`, `co20`, or `asio`. Requesting `co20` with +a standard older than C++20 is an error. + +## What Changes Under co20 + +Under `co20` the server's internal coroutines are `async::Task` values +(`common/async/task.h`) instead of stackful `co` coroutines. Code that needs to +wait on a reply writes `ASYNC_AWAIT(...)` and returns through `ASYNC_RETURN`. +The macros expand to nothing on the `co` and `asio` backends: + +| Macro | co20 | co / asio | +|-------|------|-----------| +| `ASYNC_AWAIT(expr)` | `(co_await FastAwait(expr))` | `(expr)` | +| `ASYNC_RETURN ...` | `co_return ...` | `return ...` | +| `ASYNC_BLOCK(expr)` | `SyncWait(expr)` | `(expr)` | + +`FastAwait` resumes `ValueTask`s directly and returns `false` from +`await_suspend` whenever the callee finishes without parking on the scheduler, +keeping C stack depth bounded even when the compiler does not tail-call-optimize +coroutine symmetric transfer (for example GCC at `-O0` or under ASan). + +A stackless coroutine only suspends at a `co_await` in its own body. Every +function between a coroutine and the point where it waits must therefore also +return `Task`. This is why the reload and buffer chain in the client is +converted as a whole rather than one function at a time. + +## Client API: the `Async` Variants + +Each client method that can wait on the server has a blocking form and an +`...Async` form that returns `async::Task`: + +```cpp +// Blocking caller, outside any coroutine: +absl::StatusOr pub = client.CreatePublisher("chan", options); + +// Caller inside a coroutine (for example, a server-side in-process client): +absl::StatusOr pub = + co_await client.CreatePublisherAsync("chan", options); +``` + +The naming scheme is `Async`. The blocking method is a thin wrapper +over the Async method: + +```cpp +absl::StatusOr ReadMessageInternal(ReadMode mode, bool pass_activation, bool clear_trigger) { + return ASYNC_BLOCK(client_->ReadMessageInternal(impl_.get(), mode, pass_activation, clear_trigger)); +} +``` + +`SyncWait(task)` runs a task to completion from non-coroutine code. It hides the +current coroutine while it runs and aborts if the task suspends. + +## The In-Process Rule + +**Code that runs on the server's scheduler thread must use the Async API.** + +The server runs every coroutine on one scheduler thread. A blocking client call +from a server coroutine waits for a reply that only that same thread can +deliver, so it deadlocks. `SERVER_CLIENT_CALL((blocking), async...)` in +`server/server.h` picks the right form per backend. For example, the bridge +transmitter reads through `ReadMessageInternalAsync` under co20. + +Code that runs on a separate thread or process (ordinary applications, the C +and Rust clients, and tests that run the client from `main`) keeps using the +blocking API. + +## Reload Design + +Buffers can be added or removed while a client is running. When a client +receives a buffer it does not yet have mapped, it asks the server for the +buffer, which is a round trip. Under co20 that round trip is a `Task`: + +- `Channel::CheckReload()` is `async::Task` and loops over + `reload_callback_`, which is `std::function(Channel *)>`. + In the default build `Task` is plain `bool`. +- `ClientChannel`'s buffer functions (`AttachBuffers`, `AttachSplitBuffers`, + `ValidateSlotBuffer`, `GetRegisteredClientBuffer`, `UnmapForReload`, and so + on) are Tasks. The publisher and subscriber slot search that calls them + (`FindFreeSlotUnreliable`, `NextSlot`, `LastSlot`, and similar) is also a Task. +- `Channel::Buffer()` does not reload under co20. It breaks out of its loop + instead, so callers must `ASYNC_AWAIT(CheckReload())` first. + `ValidateSlotBuffer` does this. +- `ClientChannel::Unmap()` is virtual and stays synchronous through + `ASYNC_BLOCK(UnmapAsync())`. + +Under co20 a blocking sleep inside the reload path is replaced by +`async::Sleep(async::Context(co20::self), ...)`, so waiting yields the +scheduler instead of blocking it. + +## Known Limitations + +- **Destroying a Publisher or Subscriber inside a coroutine.** The destructors + call `ASYNC_BLOCK(RemovePublisher/RemoveSubscriber)` and the sync `Unmap`. A + destructor that has to unregister a user-provided split buffer makes a round + trip, which blocks when it runs inside a coroutine. Call `CloseAsync()` first + in that case. `CloseAsync()` does not unmap the buffers itself, because a + live `Message` may still reference them. +- **Coroutine frames on hot paths.** A co20 coroutine allocates its frame on + each call. Code that asserts zero allocations on a hot path does not hold + under co20. `//client:alloc_test` is gated for this reason and runs under the + default backend. +- **Client thread-safe mode.** Thread-safe mode is not compatible with the + Async API. +- **Destruction order.** `co20` `Scheduler::~Scheduler` destroys suspended + frames. Stop the server gracefully (non-force `Stop`) so that no coroutine is + left suspended when the scheduler is destroyed. + +## Gated Targets + +These targets depend on the `co` stackful API, or on the zero-allocation +property above. They are marked `target_compatible_with` the incompatible +platform under `--config=cpp20`, so `bazelisk test --config=cpp20 //...` +skips them: + +- `//client:alloc_test` +- `//c_client:client_test` +- `//rpc/client:client_test` +- `//rpc/server:server_test` +- `//rpc/test:rpc_test` +- `//shadow:shadow_test` + +`co20_rpc/` is the existing co20 RPC library. The `rpc/` tree is co-only and +is not part of the co20 build. + +## Testing + +```bash +# Default backend: +bazelisk test //... + +# co20 backend: +bazelisk test --config=cpp20 //... + +# Sanitizers under co20 (use Linux; macOS ASan is unreliable): +bazelisk test --config=cpp20 --config=asan +bazelisk test --config=cpp20 --config=tsan +``` + +Run the bridge and tunnel suites under co20 when you change the reload chain. +They exercise the in-process Async paths end to end. diff --git a/plugins/nop_plugin.cc b/plugins/nop_plugin.cc index d609d298..6ba55816 100644 --- a/plugins/nop_plugin.cc +++ b/plugins/nop_plugin.cc @@ -11,28 +11,34 @@ constexpr int kHeartbeatSlotSize = 256; constexpr int kHeartbeatNumSlots = 16; constexpr uint64_t kHeartbeatPeriodNs = 1000000000ULL; // 1 second -void HeartbeatCoroutine(subspace::Server &server, subspace::PluginContext *ctx, - subspace::async::Context coro_ctx) { +subspace::async::Task +HeartbeatCoroutine(subspace::Server &server, subspace::PluginContext *ctx, + subspace::async::Context coro_ctx) { if (server.ShuttingDown()) { - return; + ASYNC_RETURN; } subspace::Client client(coro_ctx); - absl::Status status = client.Init(server.GetSocketName()); + absl::Status status = SERVER_CLIENT_CALL( + (client.Init(server.GetSocketName())), + client.InitAsync(server.GetSocketName())); if (!status.ok()) { ctx->logger.Log(toolbelt::LogLevel::kError, "NOP plugin: failed to init client for heartbeat: %s", status.ToString().c_str()); - return; + ASYNC_RETURN; } - absl::StatusOr pub = client.CreatePublisher( - "/nop/Heartbeat", kHeartbeatSlotSize, kHeartbeatNumSlots); + absl::StatusOr pub = SERVER_CLIENT_CALL( + (client.CreatePublisher("/nop/Heartbeat", kHeartbeatSlotSize, + kHeartbeatNumSlots)), + client.CreatePublisherAsync("/nop/Heartbeat", kHeartbeatSlotSize, + kHeartbeatNumSlots)); if (!pub.ok()) { ctx->logger.Log(toolbelt::LogLevel::kError, "NOP plugin: failed to create heartbeat publisher: %s", pub.status().ToString().c_str()); - return; + ASYNC_RETURN; } uint64_t seq = 0; @@ -40,14 +46,15 @@ void HeartbeatCoroutine(subspace::Server &server, subspace::PluginContext *ctx, // Wait up to one period for the shutdown fd. Ok() means it became // readable (shutting down); DeadlineExceeded means it is time to emit a // heartbeat. - absl::Status wait_status = subspace::async::WaitReadable( + absl::Status wait_status = ASYNC_AWAIT(subspace::async::WaitReadable( coro_ctx, server.GetShutdownTriggerFd(), - std::chrono::nanoseconds(kHeartbeatPeriodNs)); + std::chrono::nanoseconds(kHeartbeatPeriodNs))); if (wait_status.ok()) { break; } - absl::StatusOr buffer = pub->GetMessageBuffer(); + absl::StatusOr buffer = SERVER_CLIENT_CALL( + (pub->GetMessageBuffer()), pub->GetMessageBufferAsync()); if (!buffer.ok()) { ctx->logger.Log(toolbelt::LogLevel::kError, "NOP plugin: failed to get heartbeat buffer: %s", @@ -55,8 +62,9 @@ void HeartbeatCoroutine(subspace::Server &server, subspace::PluginContext *ctx, continue; } memcpy(*buffer, &seq, sizeof(seq)); - absl::StatusOr msg = - pub->PublishMessage(sizeof(seq)); + absl::StatusOr msg = SERVER_CLIENT_CALL( + (pub->PublishMessage(sizeof(seq))), + pub->PublishMessageAsync(sizeof(seq))); if (!msg.ok()) { ctx->logger.Log(toolbelt::LogLevel::kError, "NOP plugin: failed to publish heartbeat: %s", @@ -64,6 +72,7 @@ void HeartbeatCoroutine(subspace::Server &server, subspace::PluginContext *ctx, } seq++; } + SERVER_CLIENT_CLOSE(*pub); } absl::Status OnStartup(subspace::Server & /*s*/, const std::string &name, @@ -76,8 +85,9 @@ void OnReady(subspace::Server &s, subspace::PluginContext *ctx) { ctx->logger.Log(toolbelt::LogLevel::kInfo, "NOP plugin ready\n"); s.SpawnCoroutine( - [&s, ctx](subspace::async::Context coro_ctx) { - HeartbeatCoroutine(s, ctx, coro_ctx); + [&s, ctx](subspace::async::Context coro_ctx) + -> subspace::async::Task { + ASYNC_AWAIT(HeartbeatCoroutine(s, ctx, coro_ctx)); }, {.name = "NOP heartbeat", .interrupt_fd = s.GetShutdownTriggerFd()}); } diff --git a/rpc/client/BUILD.bazel b/rpc/client/BUILD.bazel index 597550b0..070b79bf 100644 --- a/rpc/client/BUILD.bazel +++ b/rpc/client/BUILD.bazel @@ -29,6 +29,12 @@ cc_library( cc_test( name = "client_test", + # Co-only: these use the stackful co API directly (or, for alloc_test, assert + # zero allocations on the hot path, which co20 coroutine frames violate). + target_compatible_with = select({ + "//:coro_backend_co20": ["@platforms//:incompatible"], + "//conditions:default": [], + }), srcs = ["client_test.cc"], data = [ "//server:subspace_server", diff --git a/rpc/server/BUILD.bazel b/rpc/server/BUILD.bazel index 581225e0..ff5b7626 100644 --- a/rpc/server/BUILD.bazel +++ b/rpc/server/BUILD.bazel @@ -29,6 +29,12 @@ cc_library( cc_test( name = "server_test", + # Co-only: these use the stackful co API directly (or, for alloc_test, assert + # zero allocations on the hot path, which co20 coroutine frames violate). + target_compatible_with = select({ + "//:coro_backend_co20": ["@platforms//:incompatible"], + "//conditions:default": [], + }), srcs = ["server_test.cc"], data = [ "//server:subspace_server", diff --git a/rpc/test/BUILD.bazel b/rpc/test/BUILD.bazel index 3b42fe6a..a4a95d99 100644 --- a/rpc/test/BUILD.bazel +++ b/rpc/test/BUILD.bazel @@ -4,6 +4,12 @@ load("@rules_cc//cc:defs.bzl", "cc_test") cc_test( name = "rpc_test", + # Co-only: these use the stackful co API directly (or, for alloc_test, assert + # zero allocations on the hot path, which co20 coroutine frames violate). + target_compatible_with = select({ + "//:coro_backend_co20": ["@platforms//:incompatible"], + "//conditions:default": [], + }), srcs = ["rpc_test.cc"], data = [ "//server:subspace_server", diff --git a/server/client_handler.cc b/server/client_handler.cc index 63811f60..5760f512 100644 --- a/server/client_handler.cc +++ b/server/client_handler.cc @@ -88,7 +88,7 @@ FromPublisherSplitBufferRequest(const CreatePublisherRequest &req) { ClientHandler::~ClientHandler() { server_->RemoveAllUsersFor(this); } -void ClientHandler::Run(async::Context ctx) { +async::Task ClientHandler::Run(async::Context ctx) { // The data is placed 4 bytes into the buffer. The first 4 // bytes of the buffer are used by SendMessage and ReceiveMessage // for the length of the data. @@ -97,19 +97,19 @@ void ClientHandler::Run(async::Context ctx) { { absl::StatusOr> receive_buffer = - socket_.ReceiveVariableLengthMessage(ctx); + ASYNC_AWAIT(socket_.ReceiveVariableLengthMessage(ctx)); if (!receive_buffer.ok()) { - return; + ASYNC_RETURN; } if (receive_buffer->empty()) { // Connection closed. - return; + ASYNC_RETURN; } if (!request.ParseFromArray(receive_buffer->data(), int(receive_buffer->size()))) { server_->logger_.Log(toolbelt::LogLevel::kError, "Failed to parse request\n"); - return; + ASYNC_RETURN; } } @@ -118,11 +118,11 @@ void ClientHandler::Run(async::Context ctx) { if (request.request_case() == subspace::Request::kRegisterClientBuffer) { std::vector register_fds; if (request.register_client_buffer().has_fd()) { - if (absl::Status s = socket_.ReceiveFds(register_fds, ctx); + if (absl::Status s = ASYNC_AWAIT(socket_.ReceiveFds(register_fds, ctx)); !s.ok()) { server_->logger_.Log(toolbelt::LogLevel::kError, "%s\n", s.ToString().c_str()); - return; + ASYNC_RETURN; } } if (absl::Status s = @@ -149,7 +149,7 @@ void ClientHandler::Run(async::Context ctx) { if (absl::Status s = HandleMessage(request, response, fds); !s.ok()) { server_->logger_.Log(toolbelt::LogLevel::kError, "%s\n", s.ToString().c_str()); - return; + ASYNC_RETURN; } } @@ -159,18 +159,18 @@ void ClientHandler::Run(async::Context ctx) { msglen)) { server_->logger_.Log(toolbelt::LogLevel::kError, "Failed to serialize response\n"); - return; + ASYNC_RETURN; } - absl::StatusOr n_sent = socket_.SendMessage( - send_buffer.data() + sizeof(int32_t), msglen, ctx); + absl::StatusOr n_sent = ASYNC_AWAIT(socket_.SendMessage( + send_buffer.data() + sizeof(int32_t), msglen, ctx)); if (!n_sent.ok()) { - return; + ASYNC_RETURN; } - if (absl::Status status = socket_.SendFds(fds, ctx); !status.ok()) { + if (absl::Status status = ASYNC_AWAIT(socket_.SendFds(fds, ctx)); !status.ok()) { server_->logger_.Log(toolbelt::LogLevel::kError, "%s\n", status.ToString().c_str()); - return; + ASYNC_RETURN; } } } diff --git a/server/client_handler.h b/server/client_handler.h index 778baaba..d6a112fb 100644 --- a/server/client_handler.h +++ b/server/client_handler.h @@ -29,7 +29,7 @@ class ClientHandler { // Run the client handler receiver in a coroutine. Terminates // when the connection to the client is closed. The Context drives the // cooperative socket I/O for the active backend. - void Run(async::Context ctx); + async::Task Run(async::Context ctx); const std::string &ClientName() const { return client_name_; } private: diff --git a/server/main.cc b/server/main.cc index 66e2d904..9f275bde 100644 --- a/server/main.cc +++ b/server/main.cc @@ -27,10 +27,12 @@ #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO #include #else -static co::CoroutineScheduler *g_scheduler; +static subspace::async::RuntimeEngine *g_scheduler; void Signal(int sig) { printf("\nAll coroutines:\n"); +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO g_scheduler->Show(); +#endif signal(sig, SIG_DFL); raise(sig); } @@ -187,7 +189,7 @@ int main(int argc, char **argv) { boost::asio::io_context engine; signal(SIGPIPE, SIG_IGN); #else - co::CoroutineScheduler engine; + subspace::async::RuntimeEngine engine; g_scheduler = &engine; // For signal handler. signal(SIGPIPE, SIG_IGN); signal(SIGQUIT, Signal); diff --git a/server/plugin.h b/server/plugin.h index 97485045..0ebf189a 100644 --- a/server/plugin.h +++ b/server/plugin.h @@ -5,6 +5,7 @@ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" +#include "common/async/runtime.h" #include "common/client_buffer.h" #include "toolbelt/logging.h" #include @@ -13,10 +14,6 @@ #include #include -namespace co { -class CoroutineScheduler; -} - namespace subspace { class Server; @@ -24,7 +21,7 @@ struct PluginContext { PluginContext(const std::string &name) : logger(name) {} virtual ~PluginContext() = default; toolbelt::Logger logger; - co::CoroutineScheduler *scheduler = nullptr; + async::RuntimeEngine *scheduler = nullptr; }; // Payload passed to an egress plugin. `bytes` does not include the prefix. @@ -158,7 +155,7 @@ class PluginInterface { slot_id, ctx_.get()); } - void SetScheduler(co::CoroutineScheduler &scheduler) { + void SetScheduler(async::RuntimeEngine &scheduler) { if (ctx_) { ctx_->scheduler = &scheduler; } diff --git a/server/python/server.cc b/server/python/server.cc index 4bb9af2f..34899cf8 100644 --- a/server/python/server.cc +++ b/server/python/server.cc @@ -1,7 +1,7 @@ #include "server/server.h" -#include "co/coroutine.h" +#include "common/async/runtime.h" #include "pybind11/pybind11.h" #include #include @@ -93,7 +93,7 @@ class ServerWrapper { std::string socket_name_; bool local_; - co::CoroutineScheduler scheduler_; + subspace::async::RuntimeEngine scheduler_; std::unique_ptr server_; std::thread server_thread_; int notify_read_fd_ = -1; diff --git a/server/server.cc b/server/server.cc index 7922925f..d1df546d 100644 --- a/server/server.cc +++ b/server/server.cc @@ -147,8 +147,8 @@ static absl::Status FindIPAddresses(const std::string &interface, return absl::OkStatus(); } -#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO -Server::Server(co::CoroutineScheduler &scheduler, +#if SUBSPACE_CORO_BACKEND != SUBSPACE_CORO_BACKEND_ASIO +Server::Server(async::RuntimeEngine &scheduler, const std::string &socket_name, const std::string &interface, int disc_port, int peer_port, bool local, int notify_fd, int initial_ordinal, bool wait_for_clients, @@ -162,7 +162,7 @@ Server::Server(co::CoroutineScheduler &scheduler, CreateShutdownTrigger(); } -Server::Server(co::CoroutineScheduler &scheduler, +Server::Server(async::RuntimeEngine &scheduler, const std::string &socket_name, const std::string &interface, const toolbelt::InetAddress &peer, int disc_port, int peer_port, bool local, int notify_fd, int initial_ordinal, @@ -236,11 +236,24 @@ void Server::Stop(bool force) { } shutdown_trigger_fd_.Trigger(); runtime_.StopGracefully(); +#else +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // A suspended co20 coroutine is destroyed with its scheduler, which runs its + // locals' destructors. A Publisher or Subscriber destructor makes a round + // trip to this server, so stopping the scheduler with coroutines still + // suspended can hang. Shut down through the drain instead: the interrupt + // fds wake every coroutine, and Run returns once the listener is the last + // one left. Only a forced stop abandons them. + if (force) { + runtime_.Stop(); + return; + } #else if (force || !wait_for_clients_) { runtime_.Stop(); return; } +#endif shutting_down_ = true; for (auto &plugin : plugins_) { plugin->interface->OnShutdown(); @@ -273,7 +286,7 @@ void Server::CloseHandler(ClientHandler *handler) { // This coroutine listens for incoming client connections on the given // UDS and spawns a handler coroutine to handle the communication with // the client. -void Server::ListenerCoroutine(async::Context ctx, +async::Task Server::ListenerCoroutine(async::Context ctx, async::UnixSocket &listen_socket) { for (;;) { if (shutting_down_) { @@ -287,20 +300,24 @@ void Server::ListenerCoroutine(async::Context ctx, if (strings.size() == 1) { break; } -#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO - // Shutdown was signalled (our Accept was cancelled by StopGracefully). - // Stop accepting new connections and instead poll the drain count, - // yielding the strand via a short sleep so the remaining coroutines - // (notably the client handlers that service the orderly disconnect of - // the in-process clients) can run and finish. Asio cancellation is - // one-shot, so we cannot simply re-block in Accept and expect to wake - // again; this poll plays the role the persistently-readable interrupt fd - // plays on the co backend. - async::Sleep(ctx, std::chrono::milliseconds(5)); +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + // Yield rather than Sleep: this coroutine's interrupt fd is already + // readable during shutdown, so Sleep would wake immediately on epoll + // while allocating a timerfd on every turn. + co_await ctx.Coroutine()->Yield(); + continue; +#elif SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO + // Shutdown was signalled. Stop accepting new connections and instead + // poll the drain count, yielding via a short sleep so the remaining + // coroutines (notably the client handlers that service the orderly + // disconnect of the in-process clients) can run and finish. On Asio the + // cancellation is one-shot, so re-running Accept would hang without ever + // letting the other coroutines run. + ASYNC_AWAIT(async::Sleep(ctx, std::chrono::milliseconds(5))); continue; #endif } - absl::Status status = HandleIncomingConnection(ctx, listen_socket); + absl::Status status = ASYNC_AWAIT(HandleIncomingConnection(ctx, listen_socket)); if (!status.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Unable to make incoming connection: %s", @@ -466,7 +483,9 @@ absl::Status Server::Run(int num_asio_threads) { // Notify listener that the server is ready. Do this in a coroutine so that // it executes when we start running. if (notify_fd_.Valid()) { - runtime_.Spawn([this](async::Context) { NotifyViaFd(kServerReady); }); + runtime_.Spawn([this](async::Context) -> async::Task { NotifyViaFd(kServerReady); + ASYNC_RETURN; + }); } OnReady(); @@ -708,8 +727,8 @@ absl::Status Server::Run(int num_asio_threads) { // serialized with the client handlers it spawns (they all share the // client_handlers_ vector and the server's channel state). runtime_.SpawnOnStrand( - [this, &listen_socket](async::Context ctx) { - ListenerCoroutine(ctx, listen_socket); + [this, &listen_socket](async::Context ctx) -> async::Task { + ASYNC_AWAIT(ListenerCoroutine(ctx, listen_socket)); }, {.name = "Listener UDS", .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); @@ -727,13 +746,13 @@ absl::Status Server::Run(int num_asio_threads) { if (publish_server_channels_) { // Start the channel directory coroutine. runtime_.SpawnOnStrand( - [this](async::Context ctx) { ChannelDirectoryCoroutine(ctx); }, + [this](async::Context ctx) -> async::Task { ASYNC_AWAIT(ChannelDirectoryCoroutine(ctx)); }, {.name = "Channel directory", .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); // Start the channel stats coroutine. runtime_.SpawnOnStrand( - [this](async::Context ctx) { StatisticsCoroutine(ctx); }, + [this](async::Context ctx) -> async::Task { ASYNC_AWAIT(StatisticsCoroutine(ctx)); }, {.name = "Channel stats", .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); } @@ -744,19 +763,19 @@ absl::Status Server::Run(int num_asio_threads) { // listen for an incoming discovery connection. if (peer_address_.Valid()) { runtime_.SpawnOnStrand( - [this](async::Context ctx) { DiscoveryConnectorCoroutine(ctx); }, + [this](async::Context ctx) -> async::Task { ASYNC_AWAIT(DiscoveryConnectorCoroutine(ctx)); }, {.name = "Discovery connector", .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); } else { runtime_.SpawnOnStrand( - [this](async::Context ctx) { DiscoveryListenerCoroutine(ctx); }, + [this](async::Context ctx) -> async::Task { ASYNC_AWAIT(DiscoveryListenerCoroutine(ctx)); }, {.name = "Discovery listener", .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); } } else { // Start the discovery receiver coroutine. runtime_.SpawnOnStrand( - [this](async::Context ctx) { DiscoveryReceiverCoroutine(ctx); }, + [this](async::Context ctx) -> async::Task { ASYNC_AWAIT(DiscoveryReceiverCoroutine(ctx)); }, {.name = "Discovery receiver", .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); } @@ -764,7 +783,7 @@ absl::Status Server::Run(int num_asio_threads) { // Start the gratuitous Advertiser coroutine. This sends Advertise messages // every 5 seconds. runtime_.SpawnOnStrand( - [this](async::Context ctx) { GratuitousAdvertiseCoroutine(ctx); }, + [this](async::Context ctx) -> async::Task { ASYNC_AWAIT(GratuitousAdvertiseCoroutine(ctx)); }, {.name = "Gratuitous advertiser", .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); @@ -793,12 +812,12 @@ absl::Status Server::Run(int num_asio_threads) { return absl::OkStatus(); } -absl::Status +async::Task Server::HandleIncomingConnection(async::Context ctx, async::UnixSocket &listen_socket) { - absl::StatusOr s = listen_socket.Accept(ctx); + absl::StatusOr s = ASYNC_AWAIT(listen_socket.Accept(ctx)); if (!s.ok()) { - return s.status(); + ASYNC_RETURN s.status(); } client_handlers_.push_back( std::make_unique(this, std::move(*s))); @@ -809,13 +828,17 @@ Server::HandleIncomingConnection(async::Context ctx, // invariant for all client-handler logic and the shared server state they // touch, without any mutexes, even when the io_context runs on many threads. runtime_.SpawnOnStrand( - [this, handler_ptr](async::Context handler_ctx) { - handler_ptr->Run(handler_ctx); + [this, handler_ptr](async::Context handler_ctx) -> async::Task { + ASYNC_AWAIT(handler_ptr->Run(handler_ctx)); CloseHandler(handler_ptr); }, {.name = "Client handler", .interrupt_fd = +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + shutdown_trigger_fd_.GetPollFd().Fd(), +#else wait_for_clients_ ? shutdown_trigger_fd_.GetPollFd().Fd() : -1, +#endif // On Asio, do not force-cancel client handlers at shutdown: they must // stay alive to service the orderly disconnect of the server's // in-process clients (statistics / channel directory). They exit on @@ -823,7 +846,7 @@ Server::HandleIncomingConnection(async::Context ctx, // for them via the drain count before stopping. .cancellable = false}); - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } void Server::SetTunnelConfig(const TunnelConfig &config) { @@ -837,19 +860,19 @@ void Server::SetMtlsCredentials(std::string cert_file, std::string key_file, mtls_ca_ = std::move(ca_file); } -absl::Status Server::SecureConnection(async::Context ctx, +async::Task Server::SecureConnection(async::Context ctx, async::ByteStream &stream, bool server_role) { if (mtls_ == nullptr) { - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } - absl::Status status = stream.HandshakeTls(mtls_, server_role, ctx, - std::chrono::seconds(5)); + absl::Status status = ASYNC_AWAIT(stream.HandshakeTls(mtls_, server_role, ctx, + std::chrono::seconds(5))); if (!status.ok()) { logger_.Log(toolbelt::LogLevel::kWarning, "mTLS handshake failed: %s", status.ToString().c_str()); } - return status; + ASYNC_RETURN status; } } // namespace subspace diff --git a/server/server.h b/server/server.h index 0e777bac..3373f46a 100644 --- a/server/server.h +++ b/server/server.h @@ -16,6 +16,7 @@ #include "co/coroutine.h" #include "common/async/context.h" #include "common/async/runtime.h" +#include "common/async/task.h" #include "common/async/byte_stream.h" #include "common/async/socket.h" #include "common/async/wait.h" @@ -35,6 +36,21 @@ #include #include +// The server's in-process clients run on the server's own scheduler, so a +// blocking client call from a server coroutine would stop the server from +// answering it. Under co20 these calls suspend the coroutine through the +// client's Async API instead. The blocking form is kept for the other +// backends, and is the first argument so its commas don't split the macro. +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 +#define SERVER_CLIENT_CALL(blocking, ...) ASYNC_AWAIT(__VA_ARGS__) +// A publisher or subscriber destructor blocks on the server, so it must be +// closed with its Async API first. Other backends close in the destructor. +#define SERVER_CLIENT_CLOSE(handle) ((void)ASYNC_AWAIT((handle).CloseAsync())) +#else +#define SERVER_CLIENT_CALL(blocking, ...) (blocking) +#define SERVER_CLIENT_CLOSE(handle) ((void)0) +#endif + namespace subspace { class Publisher; @@ -66,15 +82,17 @@ class Server { // it is shutting down. It will write 8 bytes to it so it can be // either a pipe or an eventfd. If notify_fd is -1 then it won't be used. // The values are written in host byte order. - Server(co::CoroutineScheduler &scheduler, const std::string &socket_name, +#if SUBSPACE_CORO_BACKEND != SUBSPACE_CORO_BACKEND_ASIO + Server(async::RuntimeEngine &scheduler, const std::string &socket_name, const std::string &interface, int disc_port, int peer_port, bool local, int notify_fd = -1, int initial_ordinal = 1, bool wait_for_clients = false, bool publish_server_channels = true); // This constructor can be used when you have a single peer server to talk to. - Server(co::CoroutineScheduler &scheduler, const std::string &socket_name, + Server(async::RuntimeEngine &scheduler, const std::string &socket_name, const std::string &interface, const toolbelt::InetAddress &peer, int disc_port, int peer_port, bool local, int notify_fd = -1, int initial_ordinal = 1, bool wait_for_clients = false, bool publish_server_channels = true); +#endif #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO // Asio-backed server. These mirror the co::CoroutineScheduler constructors @@ -217,15 +235,15 @@ class Server { checksum_callback_ = std::move(callback); } -#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO - virtual co::CoroutineScheduler &GetScheduler() { return runtime_.scheduler(); } +#if SUBSPACE_CORO_BACKEND != SUBSPACE_CORO_BACKEND_ASIO + virtual async::RuntimeEngine &GetScheduler() { return runtime_.scheduler(); } #endif // Backend-agnostic way for plugins (and internal code) to spawn a coroutine // on the server's runtime. The spawned function receives the active // async::Context (a co::Coroutine* under the co backend, a yield_context // under Asio) which it threads into client/socket/wait calls. - void SpawnCoroutine(std::function fn, + void SpawnCoroutine(async::CoroutineFunction fn, async::SpawnOptions opts = {}) { runtime_.Spawn(std::move(fn), std::move(opts)); } @@ -243,7 +261,7 @@ class Server { size_t GetNumChannels() const { return channels_.size(); } - absl::Status HandleIncomingConnection(async::Context ctx, + async::Task HandleIncomingConnection(async::Context ctx, async::UnixSocket &listen_socket); // Create a channel in both process and shared memory. For a placeholder @@ -349,11 +367,11 @@ class Server { // Restarts coroutines whose subscribers were recovered from the shadow. void StartRecoveredTelemetryCoroutines(); // Owns the internal publisher and emits at most one batch per second. - void TelemetryCoroutine(async::Context ctx, std::string target_name, + async::Task TelemetryCoroutine(async::Context ctx, std::string target_name, std::shared_ptr state); - void PublishTelemetryBatch(const std::string &target_name, - const std::shared_ptr &state, - Publisher &publisher); + async::Task PublishTelemetryBatch( + const std::string &target_name, + const std::shared_ptr &state, Publisher &publisher); void ReconcileTelemetryParticipants(const std::string &target_name, TelemetryState &state); void QueueTelemetrySnapshot(const std::string &target_name, @@ -364,14 +382,14 @@ class Server { void CloseHandler(ClientHandler *handler); void NotifyViaFd(int64_t val); void CreateShutdownTrigger(); - void ListenerCoroutine(async::Context ctx, async::UnixSocket &listen_socket); - void ChannelDirectoryCoroutine(async::Context ctx); + async::Task ListenerCoroutine(async::Context ctx, async::UnixSocket &listen_socket); + async::Task ChannelDirectoryCoroutine(async::Context ctx); void SendChannelDirectory(); - void StatisticsCoroutine(async::Context ctx); - void DiscoveryReceiverCoroutine(async::Context ctx); - void DiscoveryListenerCoroutine(async::Context ctx); - void DiscoveryConnectorCoroutine(async::Context ctx); - void DiscoveryConnectionReaderLoop(async::Context ctx, + async::Task StatisticsCoroutine(async::Context ctx); + async::Task DiscoveryReceiverCoroutine(async::Context ctx); + async::Task DiscoveryListenerCoroutine(async::Context ctx); + async::Task DiscoveryConnectorCoroutine(async::Context ctx); + async::Task DiscoveryConnectionReaderLoop(async::Context ctx, std::shared_ptr conn); void AddDiscoveryConnection(std::shared_ptr conn); void @@ -383,13 +401,13 @@ class Server { // coroutines can't interleave on a connection (the Context is ignored). On // the Asio backend the single-threaded io_context can't block, so the Context // drives cooperative non-blocking sends. - absl::Status TransmitDiscovery(const Discovery &disc, + async::Task TransmitDiscovery(const Discovery &disc, const toolbelt::InetAddress &udp_dest, async::Context ctx); // The address bridge listeners bind to: the any-address when a bridge // advertise address is configured, otherwise the local interface address. toolbelt::SocketAddress BridgeBindBase() const; - void PublisherCoroutine(async::Context ctx); + async::Task PublisherCoroutine(async::Context ctx); void SendQuery(const std::string &channel_name); void SendAdvertise(const std::string &channel_name, bool reliable); // Immutable snapshot of the channel state a bridge transmitter needs. It is @@ -407,28 +425,28 @@ class Server { bool split_buffers_over_bridge = false; }; struct BridgeRetirementState; - void BridgeTransmitterCoroutine(async::Context ctx, BridgeChannelInfo info, + async::Task BridgeTransmitterCoroutine(async::Context ctx, BridgeChannelInfo info, bool pub_reliable, bool sub_reliable, toolbelt::SocketAddress subscriber, toolbelt::InetAddress sender, bool notify_retirement); - void BridgeReceiverCoroutine(async::Context ctx, std::string channel_name, + async::Task BridgeReceiverCoroutine(async::Context ctx, std::string channel_name, bool sub_reliable, bool split_buffers_over_bridge, toolbelt::InetAddress publisher, bool local_has_split_options, bool local_use_split_buffers); - void RetirementCoroutine( + async::Task RetirementCoroutine( async::Context ctx, const std::string &channel_name, toolbelt::FileDescriptor &&retirement_fd, std::shared_ptr retirement_transmitter); // No-op unless SetMtlsCredentials was loaded. `server_role` is true on // the side that accepted the connection. - absl::Status SecureConnection(async::Context ctx, async::ByteStream &stream, + async::Task SecureConnection(async::Context ctx, async::ByteStream &stream, bool server_role); - void RetirementReceiverCoroutine( + async::Task RetirementReceiverCoroutine( async::Context ctx, std::shared_ptr retirement_listener, std::shared_ptr retirement_state); @@ -444,11 +462,11 @@ class Server { void IncomingSubscribe(const Discovery::Subscribe &subscribe, const toolbelt::InetAddress &sender, const std::string &server_id); - void GratuitousAdvertiseCoroutine(async::Context ctx); + async::Task GratuitousAdvertiseCoroutine(async::Context ctx); absl::Status BindBridgeListener(async::StreamSocket &listener); absl::Status RegisterPlugin(const std::string &name, void *handle, std::unique_ptr interface); - absl::Status SendSubscribeMessage(const std::string &channel_name, + async::Task SendSubscribeMessage(const std::string &channel_name, bool reliable, toolbelt::InetAddress publisher, async::StreamSocket &receiver_listener, diff --git a/server/server_bridge_receiver.cc b/server/server_bridge_receiver.cc index b5cb7876..64c7779c 100644 --- a/server/server_bridge_receiver.cc +++ b/server/server_bridge_receiver.cc @@ -28,60 +28,60 @@ struct BridgeReceivedMessage { size_t payload_length = 0; }; -static absl::StatusOr +static async::Task> ReceiveSplitBridgeMessage(async::Context ctx, async::ByteStream &bridge, const Subscribed &subscribed, const BridgeReceiveTarget &target) { - absl::StatusOr prefix = bridge.ReceiveMessage( - target.prefix_without_padding, target.prefix_length, ctx); + absl::StatusOr prefix = ASYNC_AWAIT(bridge.ReceiveMessage( + target.prefix_without_padding, target.prefix_length, ctx)); if (!prefix.ok()) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "failed to read bridge prefix: %s", prefix.status().ToString())); } if (static_cast(*prefix) != target.prefix_length) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("bridge prefix has invalid length %zd, expected %zu", *prefix, target.prefix_length)); } if (target.prefix->message_size > static_cast(subscribed.slot_size())) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "bridge payload is too large: %llu > %d", static_cast(target.prefix->message_size), subscribed.slot_size())); } absl::StatusOr payload = - bridge.ReceiveMessage(static_cast(target.payload), + ASYNC_AWAIT(bridge.ReceiveMessage(static_cast(target.payload), static_cast(target.prefix->message_size), - ctx); + ctx)); if (!payload.ok()) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "failed to read bridge payload: %s", payload.status().ToString())); } size_t payload_length = static_cast(*payload); if (payload_length != static_cast(target.prefix->message_size)) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "bridge payload has invalid length %zu, expected %llu", payload_length, static_cast(target.prefix->message_size))); } - return payload_length; + ASYNC_RETURN payload_length; } -static absl::StatusOr +static async::Task> ReceiveCombinedBridgeMessageForSplitPublisher(async::Context ctx, async::ByteStream &bridge, const Subscribed &subscribed, const BridgeReceiveTarget &target) { std::vector combined(subscribed.slot_size() + target.prefix_length); absl::StatusOr n = - bridge.ReceiveMessage(combined.data(), combined.size(), ctx); + ASYNC_AWAIT(bridge.ReceiveMessage(combined.data(), combined.size(), ctx)); if (!n.ok()) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "failed to read bridge message: %s", n.status().ToString())); } if (static_cast(*n) < target.prefix_length) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("bridge message is too short: %zd < %zu", *n, target.prefix_length)); } @@ -89,28 +89,28 @@ ReceiveCombinedBridgeMessageForSplitPublisher(async::Context ctx, size_t payload_length = static_cast(*n) - target.prefix_length; memcpy(target.payload, combined.data() + target.prefix_length, payload_length); - return payload_length; + ASYNC_RETURN payload_length; } -static absl::StatusOr +static async::Task> ReceiveCombinedBridgeMessage(async::Context ctx, async::ByteStream &bridge, const Subscribed &subscribed, const BridgeReceiveTarget &target) { - absl::StatusOr n = bridge.ReceiveMessage( + absl::StatusOr n = ASYNC_AWAIT(bridge.ReceiveMessage( target.prefix_without_padding, - subscribed.slot_size() + target.prefix_length, ctx); + subscribed.slot_size() + target.prefix_length, ctx)); if (!n.ok()) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "failed to read bridge message: %s", n.status().ToString())); } if (static_cast(*n) < target.prefix_length) { - return absl::InternalError(absl::StrFormat( + ASYNC_RETURN absl::InternalError(absl::StrFormat( "bridge message is too short: %zd < %zu", *n, target.prefix_length)); } - return static_cast(*n) - target.prefix_length; + ASYNC_RETURN static_cast(*n) - target.prefix_length; } -static absl::StatusOr +static async::Task> ReceiveBridgeMessage(async::Context ctx, async::ByteStream &bridge, Publisher &pub, const Subscribed &subscribed, void *payload_buffer) { @@ -124,41 +124,41 @@ ReceiveBridgeMessage(async::Context ctx, async::ByteStream &bridge, .payload = payload_buffer, }; if (target.prefix == nullptr) { - return absl::InternalError("failed to find message prefix"); + ASYNC_RETURN absl::InternalError("failed to find message prefix"); } char *prefix_addr = reinterpret_cast(target.prefix); target.prefix_without_padding = prefix_addr + sizeof(int32_t); if (subscribed.split_buffers()) { absl::StatusOr payload_length = - ReceiveSplitBridgeMessage(ctx, bridge, subscribed, target); + ASYNC_AWAIT(ReceiveSplitBridgeMessage(ctx, bridge, subscribed, target)); if (!payload_length.ok()) { - return payload_length.status(); + ASYNC_RETURN payload_length.status(); } - return BridgeReceivedMessage{.prefix = target.prefix, + ASYNC_RETURN BridgeReceivedMessage{.prefix = target.prefix, .payload_length = *payload_length}; } if (pub.UsesSplitBuffers()) { absl::StatusOr payload_length = - ReceiveCombinedBridgeMessageForSplitPublisher(ctx, bridge, subscribed, - target); + ASYNC_AWAIT(ReceiveCombinedBridgeMessageForSplitPublisher(ctx, bridge, subscribed, + target)); if (!payload_length.ok()) { - return payload_length.status(); + ASYNC_RETURN payload_length.status(); } - return BridgeReceivedMessage{.prefix = target.prefix, + ASYNC_RETURN BridgeReceivedMessage{.prefix = target.prefix, .payload_length = *payload_length}; } absl::StatusOr payload_length = - ReceiveCombinedBridgeMessage(ctx, bridge, subscribed, target); + ASYNC_AWAIT(ReceiveCombinedBridgeMessage(ctx, bridge, subscribed, target)); if (!payload_length.ok()) { - return payload_length.status(); + ASYNC_RETURN payload_length.status(); } - return BridgeReceivedMessage{.prefix = target.prefix, + ASYNC_RETURN BridgeReceivedMessage{.prefix = target.prefix, .payload_length = *payload_length}; } // Send a Subscribe message over UDP. -absl::Status +async::Task Server::SendSubscribeMessage(const std::string &channel_name, bool reliable, toolbelt::InetAddress publisher, async::StreamSocket &receiver_listener, @@ -196,7 +196,7 @@ Server::SendSubscribeMessage(const std::string &channel_name, bool reliable, break; } default: - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("Unsupported address type for subscribe: %s", receiver_addr.ToString().c_str())); } @@ -206,12 +206,12 @@ Server::SendSubscribeMessage(const std::string &channel_name, bool reliable, (void)buffer_size; logger_.Log(toolbelt::LogLevel::kDebug, "Sending subscribe to %s: %s", publisher.ToString().c_str(), disc.DebugString().c_str()); - absl::Status s = TransmitDiscovery(disc, publisher, ctx); + absl::Status s = ASYNC_AWAIT(TransmitDiscovery(disc, publisher, ctx)); if (!s.ok()) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("Failed to send subscribe: %s", s.ToString())); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } // This coroutine receives messages on a TCP socket and publishes @@ -219,7 +219,7 @@ Server::SendSubscribeMessage(const std::string &channel_name, bool reliable, // is sent intact to the channel. It first receives a 'Subscribed' message // with the channel details, then enters a loop reading message from the // bridge and publishing them to the local channel. -void Server::BridgeReceiverCoroutine(async::Context ctx, +async::Task Server::BridgeReceiverCoroutine(async::Context ctx, std::string channel_name, bool sub_reliable, bool split_buffers_over_bridge, @@ -258,56 +258,56 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, logger_.Log(toolbelt::LogLevel::kError, "Unable to bind socket for bridge receiver for %s: %s", channel_name.c_str(), s.ToString().c_str()); - return; + ASYNC_RETURN; } const toolbelt::SocketAddress &receiver_addr = receiver_listener.BoundAddress(); logger_.Log(toolbelt::LogLevel::kDebug, "Bridge receiver socket: %s", receiver_addr.ToString().c_str()); - s = SendSubscribeMessage(channel_name, sub_reliable, publisher, - receiver_listener, buffer, sizeof(buffer), ctx); + s = ASYNC_AWAIT(SendSubscribeMessage(channel_name, sub_reliable, publisher, + receiver_listener, buffer, sizeof(buffer), ctx)); if (!s.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to send Subscribe message for channel %s: %s", channel_name.c_str(), s.ToString().c_str()); - return; + ASYNC_RETURN; } // Accept connection on listen socket. - absl::StatusOr accepted = receiver_listener.Accept(ctx); + absl::StatusOr accepted = ASYNC_AWAIT(receiver_listener.Accept(ctx)); if (!accepted.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to accept incoming bridge connection: %s", accepted.status().ToString().c_str()); - return; + ASYNC_RETURN; } async::ByteStream bridge(std::move(*accepted)); if (absl::Status handshake = - SecureConnection(ctx, bridge, /*server_role=*/true); + ASYNC_AWAIT(SecureConnection(ctx, bridge, /*server_role=*/true)); !handshake.ok()) { logger_.Log(toolbelt::LogLevel::kError, "mTLS handshake on bridge connection failed: %s", handshake.ToString().c_str()); - return; + ASYNC_RETURN; } // Wait for the Subscribed message from the server. Subscribed subscribed; // Recieve it into offset 3 in buffer so that we can write the length for // sending it out again to the bridge notification pipe. - absl::StatusOr n_recv = bridge.ReceiveMessage( - buffer + sizeof(int32_t), sizeof(buffer) - sizeof(int32_t), ctx); + absl::StatusOr n_recv = ASYNC_AWAIT(bridge.ReceiveMessage( + buffer + sizeof(int32_t), sizeof(buffer) - sizeof(int32_t), ctx)); if (!n_recv.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to receive Subscribed: %s", n_recv.status().ToString().c_str()); - return; + ASYNC_RETURN; } if (!subscribed.ParseFromArray(buffer + sizeof(int32_t), static_cast(*n_recv))) { logger_.Log(toolbelt::LogLevel::kError, "Failed to parse Subscribed message"); - return; + ASYNC_RETURN; } bool bridge_publisher_split_buffers = split_buffers_over_bridge || subscribed.split_buffers_over_bridge(); @@ -321,12 +321,13 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, // Build a publisher to publish incoming bridge messages to the channel. Client client(ctx); - s = client.Init(socket_name_); + s = SERVER_CLIENT_CALL((client.Init(socket_name_)), + client.InitAsync(socket_name_)); if (!s.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to connect to Subspace server: %s", s.ToString().c_str()); - return; + ASYNC_RETURN; } std::shared_ptr retirement_transmitter; @@ -349,7 +350,7 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, logger_.Log(toolbelt::LogLevel::kError, "Invalid retirement socket for %s: %s", channel_name.c_str(), retirement_addr.status().ToString().c_str()); - return; + ASYNC_RETURN; } s = retirement_transmitter->Socket().Connect(*retirement_addr); @@ -357,15 +358,15 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, logger_.Log(toolbelt::LogLevel::kError, "Failed to connect to retirement socket for %s: %s", channel_name.c_str(), s.ToString().c_str()); - return; + ASYNC_RETURN; } - if (absl::Status handshake = SecureConnection( - ctx, *retirement_transmitter, /*server_role=*/false); + if (absl::Status handshake = ASYNC_AWAIT(SecureConnection( + ctx, *retirement_transmitter, /*server_role=*/false)); !handshake.ok()) { logger_.Log(toolbelt::LogLevel::kError, "mTLS handshake to retirement socket for %s failed: %s", channel_name.c_str(), handshake.ToString().c_str()); - return; + ASYNC_RETURN; } } // For a reliable publisher, this will send an activation message @@ -378,22 +379,34 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, if (bridge_ms < 0) { bridge_ms = 0; } - absl::StatusOr pub = client.CreatePublisher( - channel_name, subscribed.slot_size(), subscribed.num_slots(), - PublisherOptions() - .SetSubscriberQueueArenaSize( - subscribed.subscriber_queue_arena_size()) - .SetReliable(subscribed.reliable()) - .SetBridge(true) - .SetNotifyRetirement(subscribed.notify_retirement()) - .SetChecksumSize(bridge_cs) - .SetMetadataSize(bridge_ms) - .SetUseSplitBuffers(bridge_publisher_split_buffers)); + absl::StatusOr pub = SERVER_CLIENT_CALL( + (client.CreatePublisher( + channel_name, subscribed.slot_size(), subscribed.num_slots(), + PublisherOptions() + .SetSubscriberQueueArenaSize( + subscribed.subscriber_queue_arena_size()) + .SetReliable(subscribed.reliable()) + .SetBridge(true) + .SetNotifyRetirement(subscribed.notify_retirement()) + .SetChecksumSize(bridge_cs) + .SetMetadataSize(bridge_ms) + .SetUseSplitBuffers(bridge_publisher_split_buffers))), + client.CreatePublisherAsync( + channel_name, subscribed.slot_size(), subscribed.num_slots(), + PublisherOptions() + .SetSubscriberQueueArenaSize( + subscribed.subscriber_queue_arena_size()) + .SetReliable(subscribed.reliable()) + .SetBridge(true) + .SetNotifyRetirement(subscribed.notify_retirement()) + .SetChecksumSize(bridge_cs) + .SetMetadataSize(bridge_ms) + .SetUseSplitBuffers(bridge_publisher_split_buffers))); if (!pub.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to create bridge publisher for %s: %s", channel_name.c_str(), pub.status().ToString().c_str()); - return; + ASYNC_RETURN; } toolbelt::FileDescriptor retirement_fd; @@ -404,7 +417,8 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, if (!retirement_fd.Valid()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to get retirement fd for %s", channel_name.c_str()); - return; + SERVER_CLIENT_CLOSE(*pub); + ASYNC_RETURN; } // Add a coroutine to listen for retirement notifications and send them to @@ -412,9 +426,9 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, runtime_.SpawnOnNewStrand( [this, retirement_fd = std::move(retirement_fd), retirement_transmitter, - channel_name](async::Context ret_ctx) mutable { - RetirementCoroutine(ret_ctx, channel_name, std::move(retirement_fd), - retirement_transmitter); + channel_name](async::Context ret_ctx) mutable -> async::Task { + ASYNC_AWAIT(RetirementCoroutine(ret_ctx, channel_name, std::move(retirement_fd), + retirement_transmitter)); }, {.name = absl::StrFormat("Retirement notifier for %s", channel_name), .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); @@ -445,7 +459,8 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, // Now we receive messages from the bridge and send to the // publisher. for (;;) { - absl::StatusOr buf = pub->GetMessageBuffer(); + absl::StatusOr buf = SERVER_CLIENT_CALL( + (pub->GetMessageBuffer()), pub->GetMessageBufferAsync()); if (!buf.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to get buffer for bridge subscriber %s: %s", @@ -467,7 +482,9 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, // buffers fill up, it will stop sending until we can read the // message. The backpressure is thus propagated up the // chain. - if (absl::Status status = pub->Wait(); !status.ok()) { + if (absl::Status status = SERVER_CLIENT_CALL( + (pub->Wait()), pub->WaitAsync()); + !status.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to wait for reliable publisher: %s", status.ToString().c_str()); @@ -477,7 +494,7 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, } absl::StatusOr bridge_msg = - ReceiveBridgeMessage(ctx, bridge, *pub, subscribed, *buf); + ASYNC_AWAIT(ReceiveBridgeMessage(ctx, bridge, *pub, subscribed, *buf)); if (!bridge_msg.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to read bridge message for %s: %s", @@ -514,9 +531,10 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, } prefix->flags |= kMessageBridged; - absl::StatusOr pub_msg = pub->PublishMessageInternal( - payload_length, /*omit_prefix=*/true, - /*omit_prefix_slot_id=*/true); + absl::StatusOr pub_msg = SERVER_CLIENT_CALL( + (pub->PublishMessageInternal(payload_length, /*omit_prefix=*/true, + /*omit_prefix_slot_id=*/true)), + pub->PublishMessageWithPrefixAsync(payload_length, true, true)); if (!pub_msg.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to publish bridge message for %s: %s", @@ -524,6 +542,7 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, } } + SERVER_CLIENT_CLOSE(*pub); logger_.Log(toolbelt::LogLevel::kDebug, "Bridge receiver coroutine terminating"); } @@ -533,13 +552,13 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, // message. The slot ID sent back to the original server is the slot of the // original message, not this side's slot. That is held in the MessagePrefix // which is kept intact. -void Server::RetirementCoroutine( +async::Task Server::RetirementCoroutine( async::Context ctx, const std::string &channel_name, toolbelt::FileDescriptor &&retirement_fd, std::shared_ptr retirement_transmitter) { logger_.Log(toolbelt::LogLevel::kDebug, "Retirement coroutine for %s running", channel_name.c_str()); -#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO +#if SUBSPACE_CORO_BACKEND != SUBSPACE_CORO_BACKEND_CO // The retirement fd is read on the io_context thread, so the read must never // block it. WaitReadable can report readiness that this reader cannot then // satisfy with a blocking read - e.g. a spurious epoll edge, or a second @@ -555,7 +574,7 @@ void Server::RetirementCoroutine( #endif for (;;) { int32_t slot_id; -#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO +#if SUBSPACE_CORO_BACKEND != SUBSPACE_CORO_BACKEND_CO absl::StatusOr n; for (;;) { ssize_t r = ::read(retirement_fd.Fd(), &slot_id, sizeof(slot_id)); @@ -564,24 +583,24 @@ void Server::RetirementCoroutine( break; } if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) { - if (absl::Status w = async::WaitReadable(ctx, retirement_fd.Fd()); + if (absl::Status w = ASYNC_AWAIT(async::WaitReadable(ctx, retirement_fd.Fd())); !w.ok()) { - return; // Cancelled (graceful shutdown) or wait failed. + ASYNC_RETURN; // Cancelled (graceful shutdown) or wait failed. } continue; } - return; // Read error, we're done. + ASYNC_RETURN; // Read error, we're done. } #else absl::StatusOr n = retirement_fd.Read(&slot_id, sizeof(slot_id), ctx); if (!n.ok()) { // Failed to read the slot ID, we're done. - return; + ASYNC_RETURN; } #endif if (*n == 0) { - return; // EOF, we're done. + ASYNC_RETURN; // EOF, we're done. } // We received a retirement notification, send the fd. @@ -603,15 +622,15 @@ void Server::RetirementCoroutine( logger_.Log(toolbelt::LogLevel::kError, "Failed to serialize retirement notification for %s", channel_name.c_str()); - return; + ASYNC_RETURN; } - absl::StatusOr nsent = retirement_transmitter->SendMessage( - buffer + sizeof(int32_t), msg.ByteSizeLong(), ctx); + absl::StatusOr nsent = ASYNC_AWAIT(retirement_transmitter->SendMessage( + buffer + sizeof(int32_t), msg.ByteSizeLong(), ctx)); if (!nsent.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to send retirement fd for %s: %s", channel_name.c_str(), nsent.status().ToString().c_str()); - return; + ASYNC_RETURN; } } } diff --git a/server/server_bridge_transmitter.cc b/server/server_bridge_transmitter.cc index be3e9f03..411ece2d 100644 --- a/server/server_bridge_transmitter.cc +++ b/server/server_bridge_transmitter.cc @@ -66,7 +66,7 @@ struct Server::BridgeRetirementState { std::vector> active_messages; }; -static absl::Status SendSplitBridgeMessage(async::Context ctx, +static async::Task SendSplitBridgeMessage(async::Context ctx, async::ByteStream &bridge, const void *payload, size_t payload_length, @@ -77,33 +77,33 @@ static absl::Status SendSplitBridgeMessage(async::Context ctx, const_cast(prefix_addr) + sizeof(int32_t); size_t prefix_length = prefix_area - sizeof(int32_t); if (absl::StatusOr n = - bridge.SendMessage(prefix_without_padding, prefix_length, ctx); + ASYNC_AWAIT(bridge.SendMessage(prefix_without_padding, prefix_length, ctx)); !n.ok()) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("failed to send bridge prefix: %s", n.status().ToString())); } int32_t wire_length = htonl(static_cast(payload_length)); if (absl::StatusOr n = - bridge.Send(reinterpret_cast(&wire_length), - sizeof(wire_length), ctx); + ASYNC_AWAIT(bridge.Send(reinterpret_cast(&wire_length), + sizeof(wire_length), ctx)); !n.ok()) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("failed to send bridge payload length: %s", n.status().ToString())); } if (absl::StatusOr n = - bridge.Send(static_cast(payload), payload_length, ctx); + ASYNC_AWAIT(bridge.Send(static_cast(payload), payload_length, ctx)); !n.ok()) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("failed to send bridge payload: %s", n.status().ToString())); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -static absl::Status SendCombinedBridgeMessage(async::Context ctx, +static async::Task SendCombinedBridgeMessage(async::Context ctx, async::ByteStream &bridge, const void *payload, size_t payload_length, @@ -126,16 +126,16 @@ static absl::Status SendCombinedBridgeMessage(async::Context ctx, data_addr = copied.data() + sizeof(int32_t); } if (absl::StatusOr n = - bridge.SendMessage(data_addr, message_length, ctx); + ASYNC_AWAIT(bridge.SendMessage(data_addr, message_length, ctx)); !n.ok()) { - return absl::InternalError( + ASYNC_RETURN absl::InternalError( absl::StrFormat("failed to send bridge message: %s", n.status().ToString())); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -static absl::Status SendBridgeMessage(async::Context ctx, +static async::Task SendBridgeMessage(async::Context ctx, async::ByteStream &bridge, const void *payload, size_t payload_length, @@ -143,11 +143,11 @@ static absl::Status SendBridgeMessage(async::Context ctx, size_t prefix_area, bool split_buffers_on_wire) { if (split_buffers_on_wire) { - return SendSplitBridgeMessage(ctx, bridge, payload, payload_length, prefix, - prefix_area); + ASYNC_RETURN ASYNC_AWAIT(SendSplitBridgeMessage(ctx, bridge, payload, payload_length, prefix, + prefix_area)); } - return SendCombinedBridgeMessage(ctx, bridge, payload, payload_length, - prefix, prefix_area); + ASYNC_RETURN ASYNC_AWAIT(SendCombinedBridgeMessage(ctx, bridge, payload, payload_length, + prefix, prefix_area)); } // This coroutine creates a subscriber to the given channel and sends @@ -155,7 +155,7 @@ static absl::Status SendBridgeMessage(async::Context ctx, // a 'Subscribed' message detailing the information about the channel then // enters a loop reading messages sent to the channel on this side of the // bridge and sending them over. -void Server::BridgeTransmitterCoroutine(async::Context ctx, +async::Task Server::BridgeTransmitterCoroutine(async::Context ctx, BridgeChannelInfo info, bool pub_reliable, bool sub_reliable, toolbelt::SocketAddress subscriber, @@ -191,19 +191,19 @@ void Server::BridgeTransmitterCoroutine(async::Context ctx, logger_.Log(toolbelt::LogLevel::kError, "Failed to connect to bridge subscriber: %s", status.ToString().c_str()); - return; + ASYNC_RETURN; } if (absl::Status status = connected.SetNonBlocking(); !status.ok()) { logger_.Log(toolbelt::LogLevel::kError, "%s", status.ToString().c_str()); - return; + ASYNC_RETURN; } async::ByteStream bridge(std::move(connected)); - if (absl::Status status = SecureConnection(ctx, bridge, /*server_role=*/false); + if (absl::Status status = ASYNC_AWAIT(SecureConnection(ctx, bridge, /*server_role=*/false)); !status.ok()) { logger_.Log(toolbelt::LogLevel::kError, "mTLS handshake to bridge subscriber failed: %s", status.ToString().c_str()); - return; + ASYNC_RETURN; } const std::string &channel_name = info.channel_name; @@ -253,7 +253,7 @@ void Server::BridgeTransmitterCoroutine(async::Context ctx, logger_.Log(toolbelt::LogLevel::kError, "Unable to bind socket for retirement receiver for %s: %s", channel_name.c_str(), s.ToString().c_str()); - return; + ASYNC_RETURN; } retirement_addr = retirement_listener->BoundAddress(); logger_.Log(toolbelt::LogLevel::kDebug, "Retirement listener: %s", @@ -281,7 +281,7 @@ void Server::BridgeTransmitterCoroutine(async::Context ctx, logger_.Log(toolbelt::LogLevel::kError, "Unsupported address type for retirement notification: %s", retirement_addr.ToString().c_str()); - return; + ASYNC_RETURN; } ret_addr->set_port(retirement_addr.Port()); @@ -291,33 +291,39 @@ void Server::BridgeTransmitterCoroutine(async::Context ctx, if (!ok) { logger_.Log(toolbelt::LogLevel::kError, "Failed to serialize subscribed message"); - return; + ASYNC_RETURN; } int64_t length = subscribed.ByteSizeLong(); absl::StatusOr n_sent_1 = - bridge.SendMessage(databuf, length, ctx); + ASYNC_AWAIT(bridge.SendMessage(databuf, length, ctx)); if (!n_sent_1.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to send subscribed for %s: %s", channel_name.c_str(), n_sent_1.status().ToString().c_str()); - return; + ASYNC_RETURN; } Client client(ctx); - if (absl::Status s = client.Init(socket_name_); !s.ok()) { + if (absl::Status s = SERVER_CLIENT_CALL((client.Init(socket_name_)), + client.InitAsync(socket_name_)); + !s.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to connect to Subspace server: %s", s.ToString().c_str()); - return; + ASYNC_RETURN; } - absl::StatusOr sub = client.CreateSubscriber( - channel_name, - SubscriberOptions().SetReliable(sub_reliable).SetBridge(true)); + absl::StatusOr sub = SERVER_CLIENT_CALL( + (client.CreateSubscriber( + channel_name, + SubscriberOptions().SetReliable(sub_reliable).SetBridge(true))), + client.CreateSubscriberAsync( + channel_name, + SubscriberOptions().SetReliable(sub_reliable).SetBridge(true))); if (!sub.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to create bridge subscriber for %s: %s", channel_name.c_str(), sub.status().ToString().c_str()); - return; + ASYNC_RETURN; } // For retirement notifications, we keep track of the Messages we @@ -339,9 +345,9 @@ void Server::BridgeTransmitterCoroutine(async::Context ctx, runtime_.SpawnOnCurrentStrand( ctx, [this, retirement_listener, - retirement_state](async::Context ret_ctx) mutable { - return RetirementReceiverCoroutine(ret_ctx, retirement_listener, - retirement_state); + retirement_state](async::Context ret_ctx) mutable -> async::Task { + ASYNC_RETURN ASYNC_AWAIT(RetirementReceiverCoroutine(ret_ctx, retirement_listener, + retirement_state)); }, {.name = absl::StrFormat("Retirement listener for %s", channel_name), .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); @@ -366,7 +372,9 @@ void Server::BridgeTransmitterCoroutine(async::Context ctx, // Read messages from subscriber and send to bridge socket. bool done = false; while (!done) { - if (absl::Status status = sub->Wait(); !status.ok()) { + if (absl::Status status = + SERVER_CLIENT_CALL((sub->Wait()), sub->WaitAsync()); + !status.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to wait for subscriber: %s", status.ToString().c_str()); @@ -374,9 +382,12 @@ void Server::BridgeTransmitterCoroutine(async::Context ctx, } // Read all available messages and send to transmitter. for (;;) { - absl::StatusOr msg = sub->ReadMessageInternal( - ReadMode::kReadNext, /*pass_activation=*/true, - /*clear_trigger=*/true); + absl::StatusOr msg = SERVER_CLIENT_CALL( + (sub->ReadMessageInternal(ReadMode::kReadNext, /*pass_activation=*/true, + /*clear_trigger=*/true)), + sub->ReadMessageInternalAsync(ReadMode::kReadNext, + /*pass_activation=*/true, + /*clear_trigger=*/true)); if (!msg.ok()) { done = true; logger_.Log(toolbelt::LogLevel::kError, @@ -451,9 +462,9 @@ void Server::BridgeTransmitterCoroutine(async::Context ctx, // returns. retirement_state->Track(slot_id, std::move(msg->active_message)); } - if (absl::Status status = SendBridgeMessage( + if (absl::Status status = ASYNC_AWAIT(SendBridgeMessage( ctx, bridge, payload, payload_length, wire_prefix, prefix_area, - wire_split_buffers); + wire_split_buffers)); !status.ok()) { if (notifying_of_retirement) { retirement_state->Release(slot_id); @@ -473,6 +484,7 @@ void Server::BridgeTransmitterCoroutine(async::Context ctx, } } + SERVER_CLIENT_CLOSE(*sub); logger_.Log(toolbelt::LogLevel::kDebug, "Bridge transmitter for %s terminating", channel_name.c_str()); // bridge_guard removes the bridged-publisher entry (by `sender`) as we @@ -484,36 +496,36 @@ void Server::BridgeTransmitterCoroutine(async::Context ctx, // References to the active messages are kept in a vector, indexed by slot_id. // If these references are the last reference to the slot, it will be retired // on this side and the publisher's retirement FD is sent the slot. -void Server::RetirementReceiverCoroutine( +async::Task Server::RetirementReceiverCoroutine( async::Context ctx, std::shared_ptr retirement_listener, std::shared_ptr retirement_state) { // Accept connection on the retirement listener socket. absl::StatusOr accepted = - retirement_listener->Accept(ctx); + ASYNC_AWAIT(retirement_listener->Accept(ctx)); if (!accepted.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to accept retirement connection: %s", accepted.status().ToString().c_str()); - return; + ASYNC_RETURN; } async::ByteStream retirement_socket(std::move(*accepted)); if (absl::Status status = - SecureConnection(ctx, retirement_socket, /*server_role=*/true); + ASYNC_AWAIT(SecureConnection(ctx, retirement_socket, /*server_role=*/true)); !status.ok()) { logger_.Log(toolbelt::LogLevel::kError, "mTLS handshake on a retirement connection failed: %s", status.ToString().c_str()); - return; + ASYNC_RETURN; } // Read retirement messages from the socket. char buffer[kDiscoveryBufferSize]; for (;;) { absl::StatusOr n_recv = - retirement_socket.ReceiveMessage(buffer, sizeof(buffer), ctx); + ASYNC_AWAIT(retirement_socket.ReceiveMessage(buffer, sizeof(buffer), ctx)); if (!n_recv.ok()) { - return; + ASYNC_RETURN; } if (*n_recv == 0) { // No more messages, we're done. diff --git a/server/server_channels.cc b/server/server_channels.cc index 4f9f6f60..7b5016b5 100644 --- a/server/server_channels.cc +++ b/server/server_channels.cc @@ -303,34 +303,41 @@ void Server::RemoveAllUsersFor(ClientHandler *handler) { } } -void Server::ChannelDirectoryCoroutine(async::Context ctx) { +async::Task Server::ChannelDirectoryCoroutine(async::Context ctx) { // Coroutine aware client. Client client(ctx); - absl::Status status = client.Init(socket_name_); + absl::Status status = SERVER_CLIENT_CALL( + (client.Init(socket_name_)), client.InitAsync(socket_name_)); if (!status.ok()) { logger_.Log( toolbelt::LogLevel::kError, "Failed to initialize Subspace client for channel directory: %s", status.ToString().c_str()); - return; + ASYNC_RETURN; } constexpr int kDirectorySlotSize = 1024; constexpr int kDirectoryNumSlots = 32; - absl::StatusOr channel_directory = client.CreatePublisher( - "/subspace/ChannelDirectory", kDirectorySlotSize, kDirectoryNumSlots, - PublisherOptions() - .SetType("subspace.ChannelDirectory") - .SetUseSplitBuffers(false)); + absl::StatusOr channel_directory = SERVER_CLIENT_CALL( + (client.CreatePublisher("/subspace/ChannelDirectory", kDirectorySlotSize, + kDirectoryNumSlots, + PublisherOptions() + .SetType("subspace.ChannelDirectory") + .SetUseSplitBuffers(false))), + client.CreatePublisherAsync( + "/subspace/ChannelDirectory", kDirectorySlotSize, kDirectoryNumSlots, + PublisherOptions() + .SetType("subspace.ChannelDirectory") + .SetUseSplitBuffers(false))); if (!channel_directory.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to create channel directory channel: %s", channel_directory.status().ToString().c_str()); - return; + ASYNC_RETURN; } while (!shutting_down_) { - (void)async::WaitReadable(ctx, - channel_directory_trigger_fd_.GetPollFd().Fd()); + (void)ASYNC_AWAIT(async::WaitReadable(ctx, + channel_directory_trigger_fd_.GetPollFd().Fd())); channel_directory_trigger_fd_.Clear(); ChannelDirectory directory; @@ -343,13 +350,15 @@ void Server::ChannelDirectoryCoroutine(async::Context ctx) { channel.second->GetChannelInfo(info); } int64_t length = directory.ByteSizeLong(); - absl::StatusOr buffer = - channel_directory->GetMessageBuffer(int32_t(length)); + absl::StatusOr buffer = SERVER_CLIENT_CALL( + (channel_directory->GetMessageBuffer(int32_t(length))), + channel_directory->GetMessageBufferAsync(int32_t(length))); if (!buffer.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to get channel directory buffer: %s", buffer.status().ToString().c_str()); - return; + SERVER_CLIENT_CLOSE(*channel_directory); + ASYNC_RETURN; } bool ok = directory.SerializeToArray(*buffer, length); if (!ok) { @@ -357,13 +366,16 @@ void Server::ChannelDirectoryCoroutine(async::Context ctx) { "Failed to serialize channel directory"); continue; } - absl::StatusOr s = channel_directory->PublishMessage(length); + absl::StatusOr s = SERVER_CLIENT_CALL( + (channel_directory->PublishMessage(length)), + channel_directory->PublishMessageAsync(length)); if (!s.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to publish channel directory: %s", s.status().ToString().c_str()); } } + SERVER_CLIENT_CLOSE(*channel_directory); } void Server::SendChannelDirectory() { @@ -373,28 +385,35 @@ void Server::SendChannelDirectory() { } } -void Server::StatisticsCoroutine(async::Context ctx) { +async::Task Server::StatisticsCoroutine(async::Context ctx) { Client client(ctx); - absl::Status status = client.Init(socket_name_); + absl::Status status = SERVER_CLIENT_CALL( + (client.Init(socket_name_)), client.InitAsync(socket_name_)); if (!status.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to initialize Subspace client for statistics: %s", status.ToString().c_str()); - return; + ASYNC_RETURN; } constexpr int kStatsSlotSize = 1024; constexpr int kStatsNumSlots = 32; - absl::StatusOr pub = client.CreatePublisher( - "/subspace/Statistics", kStatsSlotSize, kStatsNumSlots, - PublisherOptions() - .SetType("subspace.Statistics") - .SetUseSplitBuffers(false)); + absl::StatusOr pub = SERVER_CLIENT_CALL( + (client.CreatePublisher("/subspace/Statistics", kStatsSlotSize, + kStatsNumSlots, + PublisherOptions() + .SetType("subspace.Statistics") + .SetUseSplitBuffers(false))), + client.CreatePublisherAsync("/subspace/Statistics", kStatsSlotSize, + kStatsNumSlots, + PublisherOptions() + .SetType("subspace.Statistics") + .SetUseSplitBuffers(false))); if (!pub.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to create statistics channel: %s", pub.status().ToString().c_str()); - return; + ASYNC_RETURN; } auto delivered_statistics_messages = [this]() -> uint64_t { @@ -410,7 +429,7 @@ void Server::StatisticsCoroutine(async::Context ctx) { constexpr int kPeriodSecs = 2; uint64_t sequence = 0; while (!shutting_down_) { - async::Sleep(ctx, kPeriodSecs); + ASYNC_AWAIT(async::Sleep(ctx, kPeriodSecs)); Statistics stats; stats.set_timestamp(toolbelt::Now()); stats.set_server_id(server_id_); @@ -447,12 +466,15 @@ void Server::StatisticsCoroutine(async::Context ctx) { } int64_t length = stats.ByteSizeLong(); - absl::StatusOr buffer = pub->GetMessageBuffer(int32_t(length)); + absl::StatusOr buffer = SERVER_CLIENT_CALL( + (pub->GetMessageBuffer(int32_t(length))), + pub->GetMessageBufferAsync(int32_t(length))); if (!buffer.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to get channel stats buffer: %s", buffer.status().ToString().c_str()); - return; + SERVER_CLIENT_CLOSE(*pub); + ASYNC_RETURN; } bool ok = stats.SerializeToArray(*buffer, length); if (!ok) { @@ -461,7 +483,8 @@ void Server::StatisticsCoroutine(async::Context ctx) { continue; } const uint64_t delivered_before = delivered_statistics_messages(); - absl::StatusOr s = pub->PublishMessage(length); + absl::StatusOr s = SERVER_CLIENT_CALL( + (pub->PublishMessage(length)), pub->PublishMessageAsync(length)); if (!s.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to publish statistics: %s", @@ -484,6 +507,7 @@ void Server::StatisticsCoroutine(async::Context ctx) { statistics_totals_ = std::move(totals); ++sequence; } + SERVER_CLIENT_CLOSE(*pub); } } // namespace subspace diff --git a/server/server_discovery.cc b/server/server_discovery.cc index 3e604f1a..39063221 100644 --- a/server/server_discovery.cc +++ b/server/server_discovery.cc @@ -41,7 +41,7 @@ void Server::SendQuery(const std::string &channel_name) { // it shares the discovery sockets/connections with the discovery coroutines // and is itself invoked from client handlers (also on the strand). runtime_.SpawnOnStrand( - [this, channel_name](async::Context ctx) { + [this, channel_name](async::Context ctx) -> async::Task { logger_.Log(toolbelt::LogLevel::kDebug, "Sending Query %s with discovery port %d", channel_name.c_str(), discovery_port_); @@ -51,11 +51,11 @@ void Server::SendQuery(const std::string &channel_name) { auto *query = disc.mutable_query(); query->set_channel_name(channel_name); - if (absl::Status s = TransmitDiscovery(disc, discovery_addr_, ctx); + if (absl::Status s = ASYNC_AWAIT(TransmitDiscovery(disc, discovery_addr_, ctx)); !s.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to send Query: %s", s.ToString().c_str()); - return; + ASYNC_RETURN; } }, {.name = "Send discovery query", @@ -71,7 +71,7 @@ void Server::SendAdvertise(const std::string &channel_name, bool reliable) { // (shares the discovery sockets/connections with the discovery coroutines and // is invoked from client handlers). runtime_.SpawnOnStrand( - [this, channel_name, reliable](async::Context ctx) { + [this, channel_name, reliable](async::Context ctx) -> async::Task { logger_.Log(toolbelt::LogLevel::kDebug, "Sending Advertise %s with discovery port %d", channel_name.c_str(), discovery_port_); @@ -85,18 +85,18 @@ void Server::SendAdvertise(const std::string &channel_name, bool reliable) { advertise->set_split_buffers( ChannelUsesSplitBuffersOverBridge(it->second.get())); } - if (absl::Status s = TransmitDiscovery(disc, discovery_addr_, ctx); + if (absl::Status s = ASYNC_AWAIT(TransmitDiscovery(disc, discovery_addr_, ctx)); !s.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to send Advertise: %s", s.ToString().c_str()); - return; + ASYNC_RETURN; } }, {.name = "Send discovery advertise", .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); } -absl::Status Server::TransmitDiscovery(const Discovery &disc, +async::Task Server::TransmitDiscovery(const Discovery &disc, const toolbelt::InetAddress &udp_dest, [[maybe_unused]] async::Context ctx) { if (tcp_discovery_) { @@ -106,7 +106,7 @@ absl::Status Server::TransmitDiscovery(const Discovery &disc, std::vector buffer(sizeof(int32_t) + length); if (!disc.SerializeToArray(buffer.data() + sizeof(int32_t), static_cast(length))) { - return absl::InternalError("Failed to serialize discovery message"); + ASYNC_RETURN absl::InternalError("Failed to serialize discovery message"); } // Copy the connection list so a send that drops a connection can't // invalidate the iterator. Writes are blocking (no coroutine yield) so @@ -114,11 +114,12 @@ absl::Status Server::TransmitDiscovery(const Discovery &disc, auto connections = discovery_connections_; for (const auto &conn : connections) { #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO - absl::StatusOr n = conn->socket->SendMessage( - buffer.data() + sizeof(int32_t), length, ctx); + absl::StatusOr n = ASYNC_AWAIT(conn->socket->SendMessage( + buffer.data() + sizeof(int32_t), length, ctx)); #else absl::StatusOr n = - conn->socket->SendMessage(buffer.data() + sizeof(int32_t), length); + ASYNC_AWAIT(conn->socket->SendMessage(buffer.data() + sizeof(int32_t), length, + async::NullContext())); #endif if (!n.ok()) { logger_.Log(toolbelt::LogLevel::kError, @@ -126,18 +127,19 @@ absl::Status Server::TransmitDiscovery(const Discovery &disc, conn->remote.ToString().c_str(), n.status().ToString().c_str()); } } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } char buffer[kDiscoveryBufferSize]; if (!disc.SerializeToArray(buffer, sizeof(buffer))) { - return absl::InternalError("Failed to serialize discovery message"); + ASYNC_RETURN absl::InternalError("Failed to serialize discovery message"); } #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO - return discovery_transmitter_.SendTo(udp_dest, buffer, disc.ByteSizeLong(), - ctx); + ASYNC_RETURN ASYNC_AWAIT(discovery_transmitter_.SendTo(udp_dest, buffer, disc.ByteSizeLong(), + ctx)); #else - return discovery_transmitter_.SendTo(udp_dest, buffer, disc.ByteSizeLong()); + ASYNC_RETURN ASYNC_AWAIT(discovery_transmitter_.SendTo( + udp_dest, buffer, disc.ByteSizeLong(), async::NullContext())); #endif } @@ -161,23 +163,23 @@ void Server::AdvertiseAllChannels() { // Reads length-delimited Discovery protobufs from a single TCP discovery // connection and dispatches them to the same handlers used by UDP discovery. // Returns when the connection is closed or fails. -void Server::DiscoveryConnectionReaderLoop( +async::Task Server::DiscoveryConnectionReaderLoop( async::Context ctx, std::shared_ptr conn) { char buffer[kDiscoveryBufferSize]; for (;;) { absl::StatusOr n = - conn->socket->ReceiveMessage(buffer, sizeof(buffer), ctx); + ASYNC_AWAIT(conn->socket->ReceiveMessage(buffer, sizeof(buffer), ctx)); if (!n.ok()) { logger_.Log(toolbelt::LogLevel::kDebug, "Discovery connection to %s closed: %s", conn->remote.ToString().c_str(), n.status().ToString().c_str()); - return; + ASYNC_RETURN; } if (*n == 0) { logger_.Log(toolbelt::LogLevel::kDebug, "Discovery connection to %s closed by peer", conn->remote.ToString().c_str()); - return; + ASYNC_RETURN; } Discovery disc; if (!disc.ParseFromArray(buffer, static_cast(*n))) { @@ -212,7 +214,7 @@ void Server::DiscoveryConnectionReaderLoop( // Listens for an incoming TCP discovery connection and serves each one with a // reader coroutine. Used by the server that does not have a peer address. -void Server::DiscoveryListenerCoroutine(async::Context ctx) { +async::Task Server::DiscoveryListenerCoroutine(async::Context ctx) { async::StreamSocket listener; if (absl::Status s = listener.Bind( toolbelt::InetAddress::AnyAddress(discovery_port_), true); @@ -220,16 +222,16 @@ void Server::DiscoveryListenerCoroutine(async::Context ctx) { logger_.Log(toolbelt::LogLevel::kError, "Failed to bind TCP discovery listener on port %d: %s", discovery_port_, s.ToString().c_str()); - return; + ASYNC_RETURN; } logger_.Log(toolbelt::LogLevel::kInfo, "Listening for TCP discovery connections on port %d", discovery_port_); for (;;) { - absl::StatusOr incoming = listener.Accept(ctx); + absl::StatusOr incoming = ASYNC_AWAIT(listener.Accept(ctx)); if (!incoming.ok()) { if (shutting_down_) { - return; + ASYNC_RETURN; } logger_.Log(toolbelt::LogLevel::kError, "Failed to accept discovery connection: %s", @@ -254,8 +256,8 @@ void Server::DiscoveryListenerCoroutine(async::Context ctx) { // Runs on the client strand: the reader handles incoming // Advertise/Subscribe messages which mutate channels_ and channel_ids_. runtime_.SpawnOnStrand( - [this, conn](async::Context reader_ctx) { - DiscoveryConnectionReaderLoop(reader_ctx, conn); + [this, conn](async::Context reader_ctx) -> async::Task { + ASYNC_AWAIT(DiscoveryConnectionReaderLoop(reader_ctx, conn)); RemoveDiscoveryConnection(conn); }, {.name = "Discovery reader", @@ -265,18 +267,18 @@ void Server::DiscoveryListenerCoroutine(async::Context ctx) { // Dials the configured peer for TCP discovery, retrying on failure, and serves // the connection inline. Used by the server that has a peer address. -void Server::DiscoveryConnectorCoroutine(async::Context ctx) { +async::Task Server::DiscoveryConnectorCoroutine(async::Context ctx) { constexpr int kRetrySecs = 1; for (;;) { if (shutting_down_) { - return; + ASYNC_RETURN; } auto socket = std::make_shared(); if (absl::Status s = socket->Connect(peer_address_); !s.ok()) { logger_.Log(toolbelt::LogLevel::kDebug, "TCP discovery connect to %s failed: %s; retrying", peer_address_.ToString().c_str(), s.ToString().c_str()); - async::Sleep(ctx, kRetrySecs); + ASYNC_AWAIT(async::Sleep(ctx, kRetrySecs)); continue; } auto conn = std::make_shared(); @@ -287,26 +289,26 @@ void Server::DiscoveryConnectorCoroutine(async::Context ctx) { peer_address_.ToString().c_str()); AddDiscoveryConnection(conn); AdvertiseAllChannels(); - DiscoveryConnectionReaderLoop(ctx, conn); + ASYNC_AWAIT(DiscoveryConnectionReaderLoop(ctx, conn)); RemoveDiscoveryConnection(conn); if (shutting_down_) { - return; + ASYNC_RETURN; } - async::Sleep(ctx, kRetrySecs); + ASYNC_AWAIT(async::Sleep(ctx, kRetrySecs)); } } // This coroutine receives discovery messages over UDP. -void Server::DiscoveryReceiverCoroutine(async::Context ctx) { +async::Task Server::DiscoveryReceiverCoroutine(async::Context ctx) { char buffer[kDiscoveryBufferSize]; for (;;) { toolbelt::InetAddress sender; - absl::StatusOr n = discovery_receiver_.ReceiveFrom( - sender, buffer, sizeof(buffer), ctx); + absl::StatusOr n = ASYNC_AWAIT(discovery_receiver_.ReceiveFrom( + sender, buffer, sizeof(buffer), ctx)); if (!n.ok()) { if (shutting_down_) { - return; + ASYNC_RETURN; } logger_.Log(toolbelt::LogLevel::kError, "Failed to read discovery message: %s", @@ -320,7 +322,7 @@ void Server::DiscoveryReceiverCoroutine(async::Context ctx) { continue; } if (disc.server_id() == server_id_) { - return; + ASYNC_RETURN; } sender.SetPort(disc.port()); logger_.Log(toolbelt::LogLevel::kDebug, "Discovery message from %s\n%s", @@ -355,11 +357,11 @@ void Server::SubscribeOverBridge(ServerChannel *channel, bool reliable, std::string channel_name = channel->Name(); runtime_.SpawnOnNewStrand( [this, channel_name, reliable, split_buffers_over_bridge, publisher, - local_has_split_options, local_use_split_buffers](async::Context ctx) { - BridgeReceiverCoroutine(ctx, channel_name, reliable, + local_has_split_options, local_use_split_buffers](async::Context ctx) -> async::Task { + ASYNC_AWAIT(BridgeReceiverCoroutine(ctx, channel_name, reliable, split_buffers_over_bridge, publisher, local_has_split_options, - local_use_split_buffers); + local_use_split_buffers)); }, {.name = absl::StrFormat("Bridge receiver for %s", channel_name), .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); @@ -467,10 +469,10 @@ void Server::IncomingSubscribe(const Discovery::Subscribe &subscribe, runtime_.SpawnOnNewStrand( [this, info = std::move(info), pub_reliable, sub_reliable, subscriber_addr = std::move(*subscriber_addr), sender, - notify_retirement](async::Context ctx) mutable { - BridgeTransmitterCoroutine(ctx, std::move(info), pub_reliable, + notify_retirement](async::Context ctx) mutable -> async::Task { + ASYNC_AWAIT(BridgeTransmitterCoroutine(ctx, std::move(info), pub_reliable, sub_reliable, std::move(subscriber_addr), - sender, notify_retirement); + sender, notify_retirement)); }, {.name = absl::StrFormat("Bridge transmitter for %s", channel->first) .c_str(), @@ -482,10 +484,10 @@ void Server::IncomingSubscribe(const Discovery::Subscribe &subscribe, } } -void Server::GratuitousAdvertiseCoroutine(async::Context ctx) { +async::Task Server::GratuitousAdvertiseCoroutine(async::Context ctx) { constexpr int kPeriodSecs = 5; while (!shutting_down_) { - async::Sleep(ctx, kPeriodSecs); + ASYNC_AWAIT(async::Sleep(ctx, kPeriodSecs)); if (shutting_down_) { break; } diff --git a/server/server_ffi.cc b/server/server_ffi.cc index 858573ca..0046c050 100644 --- a/server/server_ffi.cc +++ b/server/server_ffi.cc @@ -3,13 +3,13 @@ // See LICENSE file for licensing information. #include "server/server_ffi.h" -#include "co/coroutine.h" +#include "common/async/runtime.h" #include "server/server.h" #include #include struct SubspaceServerHandle { - co::CoroutineScheduler scheduler; + subspace::async::RuntimeEngine scheduler; std::unique_ptr server; std::string socket_name; }; diff --git a/server/server_telemetry.cc b/server/server_telemetry.cc index 17af184b..047df65c 100644 --- a/server/server_telemetry.cc +++ b/server/server_telemetry.cc @@ -232,8 +232,8 @@ void Server::StartTelemetryCoroutine( } state->coroutine_running = true; runtime_.SpawnOnStrand( - [this, target_name, state](async::Context ctx) { - TelemetryCoroutine(ctx, target_name, state); + [this, target_name, state](async::Context ctx) -> async::Task { + ASYNC_AWAIT(TelemetryCoroutine(ctx, target_name, state)); }, {.name = absl::StrFormat("Channel telemetry for %s", target_name), .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); @@ -248,25 +248,26 @@ void Server::StartRecoveredTelemetryCoroutines() { } } -void Server::TelemetryCoroutine(async::Context ctx, std::string target_name, +async::Task Server::TelemetryCoroutine(async::Context ctx, std::string target_name, std::shared_ptr state) { Client client(ctx); - absl::Status status = - client.Init(socket_name_, "subspace-telemetry-internal"); + absl::Status status = SERVER_CLIENT_CALL( + (client.Init(socket_name_, "subspace-telemetry-internal")), + client.InitAsync(socket_name_, "subspace-telemetry-internal")); if (!status.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to initialize telemetry client for %s: %s", target_name.c_str(), status.ToString().c_str()); state->coroutine_running = false; - return; + ASYNC_RETURN; } // Keeping the publisher local ties its lifetime to this target's coroutine. std::optional publisher; while (!shutting_down_) { // Triggers handle lifecycle changes; timeout is the batching period. - absl::Status wait_status = async::WaitReadable( - ctx, state->trigger.GetPollFd().Fd(), std::chrono::seconds(1)); + absl::Status wait_status = ASYNC_AWAIT(async::WaitReadable( + ctx, state->trigger.GetPollFd().Fd(), std::chrono::seconds(1))); const bool publish_batch = absl::IsDeadlineExceeded(wait_status); if (wait_status.ok()) { state->trigger.Clear(); @@ -281,8 +282,11 @@ void Server::TelemetryCoroutine(async::Context ctx, std::string target_name, } if (state->subscriber_count == 0) { - // Publisher destruction can yield, so recheck the shared state afterward - // in case another subscriber arrived while it was being removed. + // Closing the publisher can suspend, so recheck the shared state + // afterward in case another subscriber arrived while it was removed. + if (publisher.has_value()) { + SERVER_CLIENT_CLOSE(*publisher); + } publisher.reset(); current = telemetry_states_.find(target_name); if (current == telemetry_states_.end() || current->second != state) { @@ -299,11 +303,17 @@ void Server::TelemetryCoroutine(async::Context ctx, std::string target_name, } if (!publisher.has_value()) { - absl::StatusOr created = client.CreatePublisher( - state->hidden_channel_name, kTelemetrySlotSize, kTelemetryNumSlots, - PublisherOptions() - .SetType("subspace.Telemetry") - .SetUseSplitBuffers(false)); + absl::StatusOr created = SERVER_CLIENT_CALL( + (client.CreatePublisher(state->hidden_channel_name, + kTelemetrySlotSize, kTelemetryNumSlots, + PublisherOptions() + .SetType("subspace.Telemetry") + .SetUseSplitBuffers(false))), + client.CreatePublisherAsync(state->hidden_channel_name, + kTelemetrySlotSize, kTelemetryNumSlots, + PublisherOptions() + .SetType("subspace.Telemetry") + .SetUseSplitBuffers(false))); if (!created.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to create telemetry publisher for %s: %s", @@ -325,9 +335,12 @@ void Server::TelemetryCoroutine(async::Context ctx, std::string target_name, continue; } - PublishTelemetryBatch(target_name, state, *publisher); + ASYNC_AWAIT(PublishTelemetryBatch(target_name, state, *publisher)); } + if (publisher.has_value()) { + SERVER_CLIENT_CLOSE(*publisher); + } publisher.reset(); auto current = telemetry_states_.find(target_name); if (current != telemetry_states_.end() && current->second == state) { @@ -335,9 +348,9 @@ void Server::TelemetryCoroutine(async::Context ctx, std::string target_name, } } -void Server::PublishTelemetryBatch(const std::string &target_name, - const std::shared_ptr &state, - Publisher &publisher) { +async::Task Server::PublishTelemetryBatch( + const std::string &target_name, + const std::shared_ptr &state, Publisher &publisher) { if (state->snapshot_requested) { // A new watcher receives the current participants before later deltas. QueueTelemetrySnapshot(target_name, *state); @@ -396,7 +409,7 @@ void Server::PublishTelemetryBatch(const std::string &target_name, telemetry.drops().empty() && telemetry.resizes().empty()) { state->last_total_drops = current_drops; state->resize_count = current_resize_count; - return; + ASYNC_RETURN; } // Publishing yields. Commit only the entries present before that yield; @@ -404,26 +417,29 @@ void Server::PublishTelemetryBatch(const std::string &target_name, const std::string hidden_channel_name = state->hidden_channel_name; const size_t pending_participant_count = state->pending_participants.size(); int64_t length = telemetry.ByteSizeLong(); - absl::StatusOr buffer = publisher.GetMessageBuffer(int32_t(length)); + absl::StatusOr buffer = SERVER_CLIENT_CALL( + (publisher.GetMessageBuffer(int32_t(length))), + publisher.GetMessageBufferAsync(int32_t(length))); if (!buffer.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to get telemetry buffer for %s: %s", target_name.c_str(), buffer.status().ToString().c_str()); - return; + ASYNC_RETURN; } if (!telemetry.SerializeToArray(*buffer, int(length))) { logger_.Log(toolbelt::LogLevel::kError, "Failed to serialize telemetry for %s", target_name.c_str()); publisher.CancelPublish(); - return; + ASYNC_RETURN; } - absl::StatusOr published = - publisher.PublishMessage(int32_t(length)); + absl::StatusOr published = SERVER_CLIENT_CALL( + (publisher.PublishMessage(int32_t(length))), + publisher.PublishMessageAsync(int32_t(length))); if (!published.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to publish telemetry for %s: %s", target_name.c_str(), published.status().ToString().c_str()); - return; + ASYNC_RETURN; } auto current = telemetry_states_.find(target_name); diff --git a/server/tunnel.cc b/server/tunnel.cc index 0e63a1bf..9a234f4e 100644 --- a/server/tunnel.cc +++ b/server/tunnel.cc @@ -93,66 +93,66 @@ void SetNoDelay(const async::StreamSocket &socket) { using Deadline = std::chrono::steady_clock::time_point; // Reads exactly `length` bytes, by `deadline` if there is one. -absl::Status ReadFully(async::ByteStream &socket, void *buffer, size_t length, +async::Task ReadFully(async::ByteStream &socket, void *buffer, size_t length, async::Context ctx, std::optional deadline = std::nullopt) { - return socket.ReadFully(buffer, length, ctx, deadline); + ASYNC_RETURN ASYNC_AWAIT(socket.ReadFully(buffer, length, ctx, deadline)); } -absl::Status Skip(async::ByteStream &socket, size_t length, +async::Task Skip(async::ByteStream &socket, size_t length, async::Context ctx, std::optional deadline = std::nullopt) { std::vector scratch(std::min(length, 64 * 1024)); while (length > 0) { size_t chunk = std::min(length, scratch.size()); if (absl::Status s = - ReadFully(socket, scratch.data(), chunk, ctx, deadline); + ASYNC_AWAIT(ReadFully(socket, scratch.data(), chunk, ctx, deadline)); !s.ok()) { - return s; + ASYNC_RETURN s; } length -= chunk; } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -absl::StatusOr +async::Task> ReadHeader(async::ByteStream &socket, async::Context ctx, std::optional deadline = std::nullopt) { std::array buffer{}; if (absl::Status s = - ReadFully(socket, buffer.data(), buffer.size(), ctx, deadline); + ASYNC_AWAIT(ReadFully(socket, buffer.data(), buffer.size(), ctx, deadline)); !s.ok()) { - return s; + ASYNC_RETURN s; } - return tunnel::DecodePacketHeader(buffer); + ASYNC_RETURN tunnel::DecodePacketHeader(buffer); } -absl::Status SendAll(async::ByteStream &socket, const void *data, size_t length, +async::Task SendAll(async::ByteStream &socket, const void *data, size_t length, async::Context ctx) { - return socket.SendAll(data, length, ctx); + ASYNC_RETURN ASYNC_AWAIT(socket.SendAll(data, length, ctx)); } -absl::Status SendPacket(async::ByteStream &socket, PacketType type, +async::Task SendPacket(async::ByteStream &socket, PacketType type, uint64_t seq, const void *body, size_t body_size, async::Context ctx) { absl::StatusOr header = tunnel::MakePacketHeader(type, body_size, seq, tunnel::RealtimeNowNs()); if (!header.ok()) { - return header.status(); + ASYNC_RETURN header.status(); } std::vector packet(tunnel::kPacketHeaderSize + body_size); tunnel::EncodePacketHeader(*header, packet.data()); if (body_size > 0) { memcpy(packet.data() + tunnel::kPacketHeaderSize, body, body_size); } - return SendAll(socket, packet.data(), packet.size(), ctx); + ASYNC_RETURN ASYNC_AWAIT(SendAll(socket, packet.data(), packet.size(), ctx)); } -absl::Status SendHandshake(async::ByteStream &socket, +async::Task SendHandshake(async::ByteStream &socket, const Handshake &handshake, async::Context ctx) { std::string body = handshake.SerializeAsString(); - return SendPacket(socket, PacketType::kHandshake, 0, body.data(), - body.size(), ctx); + ASYNC_RETURN ASYNC_AWAIT(SendPacket(socket, PacketType::kHandshake, 0, body.data(), + body.size(), ctx)); } Handshake DiscoveryHandshake() { @@ -275,9 +275,9 @@ int TunnelManager::ListenPort() const { } void TunnelManager::Spawn() { - SpawnOnStrand([this](async::Context ctx) { ListenerCoroutine(ctx); }, + SpawnOnStrand([this](async::Context ctx) -> async::Task { ASYNC_AWAIT(ListenerCoroutine(ctx)); }, "Tunnel listener"); - SpawnOnStrand([this](async::Context ctx) { ScannerCoroutine(ctx); }, + SpawnOnStrand([this](async::Context ctx) -> async::Task { ASYNC_AWAIT(ScannerCoroutine(ctx)); }, "Tunnel scanner"); for (const std::unique_ptr &peer : peers_) { if (!peer->discovery) { @@ -285,14 +285,14 @@ void TunnelManager::Spawn() { } Peer *p = peer.get(); SpawnOnStrand( - [this, p](async::Context ctx) { DiscoverySenderCoroutine(ctx, p); }, + [this, p](async::Context ctx) -> async::Task { ASYNC_AWAIT(DiscoverySenderCoroutine(ctx, p)); }, absl::StrFormat("Tunnel discovery to %s", p->config.name())); } } void TunnelManager::ChannelsChanged() { rescan_trigger_.Trigger(); } -void TunnelManager::SpawnOnStrand(std::function fn, +void TunnelManager::SpawnOnStrand(async::CoroutineFunction fn, std::string name) { server_->runtime_.SpawnOnStrand( std::move(fn), @@ -300,7 +300,7 @@ void TunnelManager::SpawnOnStrand(std::function fn, .interrupt_fd = server_->shutdown_trigger_fd_.GetPollFd().Fd()}); } -void TunnelManager::SpawnOnNewStrand(std::function fn, +void TunnelManager::SpawnOnNewStrand(async::CoroutineFunction fn, std::string name) { server_->runtime_.SpawnOnNewStrand( std::move(fn), @@ -308,9 +308,9 @@ void TunnelManager::SpawnOnNewStrand(std::function fn, .interrupt_fd = server_->shutdown_trigger_fd_.GetPollFd().Fd()}); } -void TunnelManager::ListenerCoroutine(async::Context ctx) { +async::Task TunnelManager::ListenerCoroutine(async::Context ctx) { while (!server_->shutting_down_) { - absl::StatusOr socket = listener_.Accept(ctx); + absl::StatusOr socket = ASYNC_AWAIT(listener_.Accept(ctx)); if (server_->shutting_down_) { break; } @@ -318,7 +318,7 @@ void TunnelManager::ListenerCoroutine(async::Context ctx) { server_->logger_.Log(toolbelt::LogLevel::kError, "Tunnel can't accept a connection: %s", socket.status().ToString().c_str()); - async::Sleep(ctx, std::chrono::seconds(1)); + ASYNC_AWAIT(async::Sleep(ctx, std::chrono::seconds(1))); continue; } auto connection = std::make_shared(std::move(*socket)); @@ -331,40 +331,40 @@ void TunnelManager::ListenerCoroutine(async::Context ctx) { SetNoDelay(connection->Socket()); std::string peer = PeerAddress(connection->Socket()); SpawnOnStrand( - [this, connection, peer](async::Context handshake_ctx) { - HandshakeCoroutine(handshake_ctx, connection, peer); + [this, connection, peer](async::Context handshake_ctx) -> async::Task { + ASYNC_AWAIT(HandshakeCoroutine(handshake_ctx, connection, peer)); }, "Tunnel handshake from " + peer); } listener_.Close(); } -void TunnelManager::HandshakeCoroutine( +async::Task TunnelManager::HandshakeCoroutine( async::Context ctx, std::shared_ptr socket, std::string peer) { if (server_->shutting_down_) { - return; + ASYNC_RETURN; } if (absl::Status s = - server_->SecureConnection(ctx, *socket, /*server_role=*/true); + ASYNC_AWAIT(server_->SecureConnection(ctx, *socket, /*server_role=*/true)); !s.ok()) { server_->logger_.Log(toolbelt::LogLevel::kWarning, "Tunnel mTLS handshake from %s failed: %s", peer.c_str(), s.ToString().c_str()); - return; + ASYNC_RETURN; } const Deadline deadline = std::chrono::steady_clock::now() + kHandshakeTimeout; absl::Status status; for (;;) { - absl::StatusOr header = ReadHeader(*socket, ctx, deadline); + absl::StatusOr header = ASYNC_AWAIT(ReadHeader(*socket, ctx, deadline)); if (!header.ok()) { status = header.status(); break; } if (header->type != PacketType::kHandshake) { // Nothing can be published before the handshake says where. - status = Skip(*socket, header->BodySize(), ctx, deadline); + status = ASYNC_AWAIT(Skip(*socket, header->BodySize(), ctx, deadline)); if (!status.ok()) { break; } @@ -377,7 +377,7 @@ void TunnelManager::HandshakeCoroutine( break; } std::string body(header->BodySize(), '\0'); - status = ReadFully(*socket, body.data(), body.size(), ctx, deadline); + status = ASYNC_AWAIT(ReadFully(*socket, body.data(), body.size(), ctx, deadline)); if (!status.ok()) { break; } @@ -391,25 +391,25 @@ void TunnelManager::HandshakeCoroutine( break; } if (server_->shutting_down_) { - return; + ASYNC_RETURN; } if (handshake.topic_name() == tunnel::kDiscoveryChannelName && !config_.disable_discovery()) { - DiscoveryReceiverLoop(ctx, *socket, handshake, peer); - return; + ASYNC_AWAIT(DiscoveryReceiverLoop(ctx, *socket, handshake, peer)); + ASYNC_RETURN; } if (tunnel::IsInternalChannel(handshake.topic_name())) { - DiscardConnection(ctx, *socket, handshake.topic_name(), peer); - return; + ASYNC_AWAIT(DiscardConnection(ctx, *socket, handshake.topic_name(), peer)); + ASYNC_RETURN; } IngressPlan plan = PlanIngress(handshake, peer); std::string name = "Tunnel ingress " + plan.topic + " from " + peer; SpawnOnNewStrand( - [this, socket, plan = std::move(plan)](async::Context ingress_ctx) { - IngressCoroutine(ingress_ctx, socket, plan); + [this, socket, plan = std::move(plan)](async::Context ingress_ctx) -> async::Task { + ASYNC_AWAIT(IngressCoroutine(ingress_ctx, socket, plan)); }, std::move(name)); - return; + ASYNC_RETURN; } socket->Close(); if (absl::IsDeadlineExceeded(status)) { @@ -505,28 +505,31 @@ TunnelManager::PlanIngress(const Handshake &handshake, return plan; } -void TunnelManager::IngressCoroutine( +async::Task TunnelManager::IngressCoroutine( async::Context ctx, std::shared_ptr socket, IngressPlan plan) { if (server_->shutting_down_) { - return; + ASYNC_RETURN; } const std::string &topic = plan.topic; Client client(ctx); - if (absl::Status s = - client.Init(server_->socket_name_, "tunnel ingress " + topic); + if (absl::Status s = SERVER_CLIENT_CALL( + (client.Init(server_->socket_name_, "tunnel ingress " + topic)), + client.InitAsync(server_->socket_name_, "tunnel ingress " + topic)); !s.ok()) { server_->logger_.Log(toolbelt::LogLevel::kError, "Tunnel can't connect to the server for %s: %s", topic.c_str(), s.ToString().c_str()); - return; + ASYNC_RETURN; } - absl::StatusOr pub = client.CreatePublisher(topic, plan.options); + absl::StatusOr pub = SERVER_CLIENT_CALL( + (client.CreatePublisher(topic, plan.options)), + client.CreatePublisherAsync(topic, plan.options)); if (!pub.ok()) { server_->logger_.Log(toolbelt::LogLevel::kError, "Tunnel can't publish %s for %s: %s", topic.c_str(), plan.peer.c_str(), pub.status().ToString().c_str()); - return; + ASYNC_RETURN; } if (pub->PrefixSize() != plan.wire_prefix_size) { server_->logger_.Log(toolbelt::LogLevel::kError, @@ -534,7 +537,8 @@ void TunnelManager::IngressCoroutine( "but the peer's is %d", topic.c_str(), plan.peer.c_str(), pub->PrefixSize(), plan.wire_prefix_size); - return; + SERVER_CLIENT_CLOSE(*pub); + ASYNC_RETURN; } server_->logger_.Log(toolbelt::LogLevel::kInfo, "Tunnel receiving %s from %s", topic.c_str(), @@ -543,7 +547,7 @@ void TunnelManager::IngressCoroutine( const size_t prefix_size = static_cast(plan.wire_prefix_size); absl::Status status; while (!server_->shutting_down_) { - absl::StatusOr header = ReadHeader(*socket, ctx); + absl::StatusOr header = ASYNC_AWAIT(ReadHeader(*socket, ctx)); if (!header.ok()) { status = header.status(); break; @@ -557,7 +561,7 @@ void TunnelManager::IngressCoroutine( if (header->type == PacketType::kData) { stats_.malformed_received++; } - status = Skip(*socket, body_size, ctx); + status = ASYNC_AWAIT(Skip(*socket, body_size, ctx)); if (!status.ok()) { break; } @@ -579,7 +583,7 @@ void TunnelManager::IngressCoroutine( "too large for the channel", payload_size, topic.c_str(), plan.peer.c_str()); } - status = Skip(*socket, body_size, ctx); + status = ASYNC_AWAIT(Skip(*socket, body_size, ctx)); if (!status.ok()) { break; } @@ -588,12 +592,19 @@ void TunnelManager::IngressCoroutine( absl::StatusOr buffer; for (;;) { - buffer = pub->GetMessageBuffer(static_cast(payload_size)); + buffer = SERVER_CLIENT_CALL( + (pub->GetMessageBuffer(static_cast(payload_size))), + pub->GetMessageBufferAsync(static_cast(payload_size))); if (!buffer.ok() || *buffer != nullptr || server_->shutting_down_) { break; } // A reliable publisher has to wait for its subscribers to free a slot. - if (absl::Status s = pub->Wait(ctx); !s.ok()) { +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + absl::Status s = ASYNC_AWAIT(pub->WaitAsync()); +#else + absl::Status s = pub->Wait(ctx); +#endif + if (!s.ok()) { buffer = s; break; } @@ -609,9 +620,9 @@ void TunnelManager::IngressCoroutine( break; } std::byte *prefix_bytes = reinterpret_cast(pub->Prefix()); - status = ReadFully(*socket, prefix_bytes, prefix_size, ctx); + status = ASYNC_AWAIT(ReadFully(*socket, prefix_bytes, prefix_size, ctx)); if (status.ok()) { - status = ReadFully(*socket, *buffer, payload_size, ctx); + status = ASYNC_AWAIT(ReadFully(*socket, *buffer, payload_size, ctx)); } if (!status.ok()) { pub->CancelPublish(); @@ -652,16 +663,21 @@ void TunnelManager::IngressCoroutine( // channel ID stays in the prefix, where the checksum does cover it, and // the message goes to this publisher's virtual channel. prefix->SetIsBridged(); - absl::StatusOr published = - pub->PublishMessageWithPrefix(static_cast(published_size), - /*use_slot_id_from_prefix=*/false, - /*use_vchan_id_from_prefix=*/false); + absl::StatusOr published = SERVER_CLIENT_CALL( + (pub->PublishMessageWithPrefix(static_cast(published_size), + /*use_slot_id_from_prefix=*/false, + /*use_vchan_id_from_prefix=*/false)), + pub->PublishMessageWithPrefixAsync( + static_cast(published_size), + /*use_slot_id_from_prefix=*/false, + /*use_vchan_id_from_prefix=*/false)); if (!published.ok()) { status = published.status(); break; } stats_.messages_received++; } + SERVER_CLIENT_CLOSE(*pub); if (!server_->shutting_down_ && !IsPeerClosed(status)) { server_->logger_.Log(toolbelt::LogLevel::kWarning, "Tunnel stopped receiving %s from %s: %s", @@ -674,20 +690,21 @@ void TunnelManager::IngressCoroutine( } } -void TunnelManager::EgressCoroutine(async::Context ctx, EgressRoute route) { +async::Task TunnelManager::EgressCoroutine(async::Context ctx, EgressRoute route) { if (server_->shutting_down_) { - return; + ASYNC_RETURN; } const std::string &topic = route.topic; const std::string &peer_name = route.peer.name(); Client client(ctx); - if (absl::Status s = - client.Init(server_->socket_name_, "tunnel egress " + topic); + if (absl::Status s = SERVER_CLIENT_CALL( + (client.Init(server_->socket_name_, "tunnel egress " + topic)), + client.InitAsync(server_->socket_name_, "tunnel egress " + topic)); !s.ok()) { server_->logger_.Log(toolbelt::LogLevel::kError, "Tunnel can't connect to the server for %s: %s", topic.c_str(), s.ToString().c_str()); - return; + ASYNC_RETURN; } std::string last_failure; while (!server_->shutting_down_) { @@ -698,13 +715,13 @@ void TunnelManager::EgressCoroutine(async::Context ctx, EgressRoute route) { LogFailure(last_failure, absl::StrFormat("Tunnel can't send %s to %s: %s", topic, peer_name, address.status().ToString())); - async::Sleep(ctx, kReconnectInterval); + ASYNC_AWAIT(async::Sleep(ctx, kReconnectInterval)); continue; } route.address = *address; } absl::StatusOr socket = - async::ConnectStream(route.address, kConnectTimeout, ctx); + ASYNC_AWAIT(async::ConnectStream(route.address, kConnectTimeout, ctx)); if (server_->shutting_down_) { break; } @@ -712,21 +729,21 @@ void TunnelManager::EgressCoroutine(async::Context ctx, EgressRoute route) { LogFailure(last_failure, absl::StrFormat("Tunnel can't connect to %s for %s: %s", peer_name, topic, socket.status().ToString())); - async::Sleep(ctx, kReconnectInterval); + ASYNC_AWAIT(async::Sleep(ctx, kReconnectInterval)); continue; } async::ByteStream stream(std::move(*socket)); SetNoDelay(stream.Socket()); if (absl::Status secure = - server_->SecureConnection(ctx, stream, /*server_role=*/false); + ASYNC_AWAIT(server_->SecureConnection(ctx, stream, /*server_role=*/false)); !secure.ok()) { LogFailure(last_failure, absl::StrFormat("Tunnel mTLS handshake to %s for %s failed: %s", peer_name, topic, secure.ToString())); - async::Sleep(ctx, kReconnectInterval); + ASYNC_AWAIT(async::Sleep(ctx, kReconnectInterval)); continue; } - absl::Status status = ForwardChannel(ctx, client, stream, route); + absl::Status status = ASYNC_AWAIT(ForwardChannel(ctx, client, stream, route)); stream.Close(); if (server_->shutting_down_) { break; @@ -734,7 +751,7 @@ void TunnelManager::EgressCoroutine(async::Context ctx, EgressRoute route) { LogFailure(last_failure, absl::StrFormat("Tunnel stopped sending %s to %s: %s", topic, peer_name, status.ToString())); - async::Sleep(ctx, kReconnectInterval); + ASYNC_AWAIT(async::Sleep(ctx, kReconnectInterval)); } } @@ -746,7 +763,7 @@ void TunnelManager::LogFailure(std::string &last_failure, last_failure = std::move(failure); } -absl::Status TunnelManager::ForwardChannel(async::Context ctx, Client &client, +async::Task TunnelManager::ForwardChannel(async::Context ctx, Client &client, async::ByteStream &socket, const EgressRoute &route) { const LocalPublication &publication = route.publication; @@ -755,11 +772,22 @@ absl::Status TunnelManager::ForwardChannel(async::Context ctx, Client &client, if (!publication.mux.empty()) { options.SetMux(publication.mux).SetVchanId(publication.vchan_id); } - absl::StatusOr sub = client.CreateSubscriber(route.topic, options); + absl::StatusOr sub = SERVER_CLIENT_CALL( + (client.CreateSubscriber(route.topic, options)), + client.CreateSubscriberAsync(route.topic, options)); if (!sub.ok()) { - return sub.status(); + ASYNC_RETURN sub.status(); } + absl::Status status = + ASYNC_AWAIT(ForwardSubscriber(ctx, &*sub, socket, route)); + SERVER_CLIENT_CLOSE(*sub); + ASYNC_RETURN status; +} +async::Task TunnelManager::ForwardSubscriber( + async::Context ctx, Subscriber *sub, async::ByteStream &socket, + const EgressRoute &route) { + const LocalPublication &publication = route.publication; Handshake handshake; handshake.set_topic_name(route.topic); handshake.set_channel_type(sub->Type()); @@ -774,8 +802,8 @@ absl::Status TunnelManager::ForwardChannel(async::Context ctx, Client &client, transport->set_vchan_id(publication.mux.empty() ? -1 : publication.vchan_id); transport->set_checksum_size(sub->ChecksumSize()); transport->set_metadata_size(sub->MetadataSize()); - if (absl::Status s = SendHandshake(socket, handshake, ctx); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(SendHandshake(socket, handshake, ctx)); !s.ok()) { + ASYNC_RETURN s; } server_->logger_.Log(toolbelt::LogLevel::kInfo, "Tunnel sending %s to %s", route.topic.c_str(), route.peer.name().c_str()); @@ -785,29 +813,34 @@ absl::Status TunnelManager::ForwardChannel(async::Context ctx, Client &client, uint64_t seq = 0; std::vector packet; for (;;) { +#if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 + absl::StatusOr fd = ASYNC_AWAIT(sub->WaitAsync(socket_fd)); +#else absl::StatusOr fd = sub->Wait(socket_fd, ctx); +#endif if (server_->shutting_down_) { - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } if (!fd.ok()) { - return fd.status(); + ASYNC_RETURN fd.status(); } if (*fd == socket_fd.Fd()) { // Peers never send on this connection, so this is a close. char byte; - absl::StatusOr n = socket.Receive(&byte, 1, ctx); + absl::StatusOr n = ASYNC_AWAIT(socket.Receive(&byte, 1, ctx)); if (!n.ok()) { - return n.status(); + ASYNC_RETURN n.status(); } if (*n <= 0) { - return PeerClosed(); + ASYNC_RETURN PeerClosed(); } continue; } for (;;) { - absl::StatusOr msg = sub->ReadMessage(); + absl::StatusOr msg = SERVER_CLIENT_CALL( + (sub->ReadMessage()), sub->ReadMessageAsync()); if (!msg.ok()) { - return msg.status(); + ASYNC_RETURN msg.status(); } if (msg->length == 0) { break; @@ -820,7 +853,7 @@ absl::Status TunnelManager::ForwardChannel(async::Context ctx, Client &client, continue; } if (sub->PrefixSize() != prefix_size) { - return absl::FailedPreconditionError("the channel's prefix changed"); + ASYNC_RETURN absl::FailedPreconditionError("the channel's prefix changed"); } Server::EgressPluginResult egress = server_->ApplyEgressPlugins( route.topic, msg->buffer, static_cast(msg->length)); @@ -870,14 +903,14 @@ absl::Status TunnelManager::ForwardChannel(async::Context ctx, Client &client, if (coalesce) { memcpy(packet_prefix + prefix_size, payload, payload_length); } - if (absl::Status s = SendAll(socket, packet.data(), packet.size(), ctx); + if (absl::Status s = ASYNC_AWAIT(SendAll(socket, packet.data(), packet.size(), ctx)); !s.ok()) { - return s; + ASYNC_RETURN s; } if (!coalesce) { - if (absl::Status s = SendAll(socket, payload, payload_length, ctx); + if (absl::Status s = ASYNC_AWAIT(SendAll(socket, payload, payload_length, ctx)); !s.ok()) { - return s; + ASYNC_RETURN s; } } seq++; @@ -886,11 +919,11 @@ absl::Status TunnelManager::ForwardChannel(async::Context ctx, Client &client, } } -void TunnelManager::ScannerCoroutine(async::Context ctx) { +async::Task TunnelManager::ScannerCoroutine(async::Context ctx) { Rescan(); while (!server_->shutting_down_) { absl::Status status = - async::WaitReadable(ctx, rescan_trigger_.GetPollFd().Fd()); + ASYNC_AWAIT(async::WaitReadable(ctx, rescan_trigger_.GetPollFd().Fd())); if (server_->shutting_down_) { break; } @@ -898,7 +931,7 @@ void TunnelManager::ScannerCoroutine(async::Context ctx) { server_->logger_.Log(toolbelt::LogLevel::kError, "Tunnel channel scanner: %s", status.ToString().c_str()); - async::Sleep(ctx, std::chrono::seconds(1)); + ASYNC_AWAIT(async::Sleep(ctx, std::chrono::seconds(1))); continue; } rescan_trigger_.Clear(); @@ -1006,8 +1039,8 @@ void TunnelManager::EnsureRoute(const std::string &topic, Peer &peer) { .address = peer.address}; std::string name = "Tunnel egress " + topic + " to " + peer.config.name(); SpawnOnNewStrand( - [this, route = std::move(route)](async::Context ctx) { - EgressCoroutine(ctx, route); + [this, route = std::move(route)](async::Context ctx) -> async::Task { + ASYNC_AWAIT(EgressCoroutine(ctx, route)); }, std::move(name)); } @@ -1040,15 +1073,15 @@ TunnelManager::BuildDiscoveryMessage(const Peer &peer) const { return msg; } -void TunnelManager::WaitToReconnect(async::Context ctx, Peer &peer) { - if (async::WaitReadable(ctx, peer.discovery_trigger.GetPollFd().Fd(), - kReconnectInterval) +async::Task TunnelManager::WaitToReconnect(async::Context ctx, Peer &peer) { + if (ASYNC_AWAIT(async::WaitReadable(ctx, peer.discovery_trigger.GetPollFd().Fd(), + kReconnectInterval)) .ok()) { peer.discovery_trigger.Clear(); } } -void TunnelManager::DiscoverySenderCoroutine(async::Context ctx, Peer *peer) { +async::Task TunnelManager::DiscoverySenderCoroutine(async::Context ctx, Peer *peer) { const std::string &name = peer->config.name(); std::string last_failure; while (!server_->shutting_down_) { @@ -1059,13 +1092,13 @@ void TunnelManager::DiscoverySenderCoroutine(async::Context ctx, Peer *peer) { LogFailure(last_failure, absl::StrFormat("Tunnel can't reach peer %s: %s", name, address.status().ToString())); - WaitToReconnect(ctx, *peer); + ASYNC_AWAIT(WaitToReconnect(ctx, *peer)); continue; } peer->address = *address; } absl::StatusOr socket = - async::ConnectStream(peer->address, kConnectTimeout, ctx); + ASYNC_AWAIT(async::ConnectStream(peer->address, kConnectTimeout, ctx)); if (server_->shutting_down_) { break; } @@ -1073,21 +1106,21 @@ void TunnelManager::DiscoverySenderCoroutine(async::Context ctx, Peer *peer) { LogFailure(last_failure, absl::StrFormat("Tunnel can't reach peer %s: %s", name, socket.status().ToString())); - WaitToReconnect(ctx, *peer); + ASYNC_AWAIT(WaitToReconnect(ctx, *peer)); continue; } async::ByteStream stream(std::move(*socket)); SetNoDelay(stream.Socket()); if (absl::Status secure = - server_->SecureConnection(ctx, stream, /*server_role=*/false); + ASYNC_AWAIT(server_->SecureConnection(ctx, stream, /*server_role=*/false)); !secure.ok()) { LogFailure(last_failure, absl::StrFormat("Tunnel mTLS handshake to %s failed: %s", name, secure.ToString())); - WaitToReconnect(ctx, *peer); + ASYNC_AWAIT(WaitToReconnect(ctx, *peer)); continue; } - absl::Status status = RunDiscoveryConnection(ctx, stream, *peer); + absl::Status status = ASYNC_AWAIT(RunDiscoveryConnection(ctx, stream, *peer)); stream.Close(); if (server_->shutting_down_) { break; @@ -1095,16 +1128,16 @@ void TunnelManager::DiscoverySenderCoroutine(async::Context ctx, Peer *peer) { LogFailure(last_failure, absl::StrFormat("Tunnel discovery connection to %s closed: %s", name, status.ToString())); - WaitToReconnect(ctx, *peer); + ASYNC_AWAIT(WaitToReconnect(ctx, *peer)); } } -absl::Status TunnelManager::RunDiscoveryConnection(async::Context ctx, +async::Task TunnelManager::RunDiscoveryConnection(async::Context ctx, async::ByteStream &socket, Peer &peer) { - if (absl::Status s = SendHandshake(socket, DiscoveryHandshake(), ctx); + if (absl::Status s = ASYNC_AWAIT(SendHandshake(socket, DiscoveryHandshake(), ctx)); !s.ok()) { - return s; + ASYNC_RETURN s; } server_->logger_.Log(toolbelt::LogLevel::kInfo, "Tunnel discovery connected to %s", @@ -1119,8 +1152,8 @@ absl::Status TunnelManager::RunDiscoveryConnection(async::Context ctx, // Clear first: a change made while sending triggers another send. peer.discovery_trigger.Clear(); peer.sent_generation = discovery_generation_; - if (absl::Status s = SendDiscovery(ctx, socket, peer, ++seq); !s.ok()) { - return s; + if (absl::Status s = ASYNC_AWAIT(SendDiscovery(ctx, socket, peer, ++seq)); !s.ok()) { + ASYNC_RETURN s; } next_refresh = std::chrono::steady_clock::now() + refresh_interval_; send = false; @@ -1131,17 +1164,17 @@ absl::Status TunnelManager::RunDiscoveryConnection(async::Context ctx, next_refresh - std::chrono::steady_clock::now(), std::chrono::milliseconds(1)); } - absl::StatusOr fd = async::WaitEither(ctx, trigger_fd, socket_fd, - timeout); + absl::StatusOr fd = ASYNC_AWAIT(async::WaitEither(ctx, trigger_fd, socket_fd, + timeout)); if (server_->shutting_down_) { - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } if (absl::IsDeadlineExceeded(fd.status())) { send = true; continue; } if (!fd.ok()) { - return fd.status(); + ASYNC_RETURN fd.status(); } if (*fd == trigger_fd) { peer.discovery_trigger.Clear(); @@ -1150,17 +1183,17 @@ absl::Status TunnelManager::RunDiscoveryConnection(async::Context ctx, } // Peers never send on this connection, so this is a close. char byte; - absl::StatusOr n = socket.Receive(&byte, 1, ctx); + absl::StatusOr n = ASYNC_AWAIT(socket.Receive(&byte, 1, ctx)); if (!n.ok()) { - return n.status(); + ASYNC_RETURN n.status(); } if (*n <= 0) { - return PeerClosed(); + ASYNC_RETURN PeerClosed(); } } } -absl::Status TunnelManager::SendDiscovery(async::Context ctx, +async::Task TunnelManager::SendDiscovery(async::Context ctx, async::ByteStream &socket, const Peer &peer, uint64_t seq) { // Never empty, because the device name is required. @@ -1176,16 +1209,16 @@ absl::Status TunnelManager::SendDiscovery(async::Context ctx, std::vector body(prefix_size + payload.size()); memcpy(body.data(), &prefix, sizeof(prefix)); memcpy(body.data() + prefix_size, payload.data(), payload.size()); - if (absl::Status s = SendPacket(socket, PacketType::kData, seq, body.data(), - body.size(), ctx); + if (absl::Status s = ASYNC_AWAIT(SendPacket(socket, PacketType::kData, seq, body.data(), + body.size(), ctx)); !s.ok()) { - return s; + ASYNC_RETURN s; } stats_.discovery_sent++; - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } -void TunnelManager::DiscoveryReceiverLoop(async::Context ctx, +async::Task TunnelManager::DiscoveryReceiverLoop(async::Context ctx, async::ByteStream &socket, const Handshake &handshake, const std::string &peer) { @@ -1193,14 +1226,14 @@ void TunnelManager::DiscoveryReceiverLoop(async::Context ctx, static_cast(tunnel::WirePrefixSize(handshake.subspace())); absl::Status status; while (!server_->shutting_down_) { - absl::StatusOr header = ReadHeader(socket, ctx); + absl::StatusOr header = ASYNC_AWAIT(ReadHeader(socket, ctx)); if (!header.ok()) { status = header.status(); break; } const size_t body_size = header->BodySize(); if (header->type != PacketType::kData || body_size <= prefix_size) { - if (status = Skip(socket, body_size, ctx); !status.ok()) { + if (status = ASYNC_AWAIT(Skip(socket, body_size, ctx)); !status.ok()) { break; } continue; @@ -1211,7 +1244,7 @@ void TunnelManager::DiscoveryReceiverLoop(async::Context ctx, break; } std::vector body(body_size); - if (status = ReadFully(socket, body.data(), body.size(), ctx); + if (status = ASYNC_AWAIT(ReadFully(socket, body.data(), body.size(), ctx)); !status.ok()) { break; } @@ -1239,7 +1272,7 @@ void TunnelManager::DiscoveryReceiverLoop(async::Context ctx, } } -void TunnelManager::DiscardConnection(async::Context ctx, +async::Task TunnelManager::DiscardConnection(async::Context ctx, async::ByteStream &socket, const std::string &topic, const std::string &peer) { @@ -1249,9 +1282,9 @@ void TunnelManager::DiscardConnection(async::Context ctx, std::vector scratch(64 * 1024); while (!server_->shutting_down_) { absl::StatusOr n = - socket.Receive(scratch.data(), scratch.size(), ctx); + ASYNC_AWAIT(socket.Receive(scratch.data(), scratch.size(), ctx)); if (!n.ok() || *n <= 0) { - return; + ASYNC_RETURN; } } } diff --git a/server/tunnel.h b/server/tunnel.h index f235529e..8fbce3b8 100644 --- a/server/tunnel.h +++ b/server/tunnel.h @@ -10,6 +10,7 @@ #include "absl/status/statusor.h" #include "client/options.h" #include "common/async/context.h" +#include "common/async/runtime.h" #include "common/async/byte_stream.h" #include "common/async/socket.h" #include "proto/tunnel_config.pb.h" @@ -30,6 +31,7 @@ namespace subspace { class Client; +class Subscriber; class Server; // Tunnel-compatible discovery and bridging. Each configured peer is sent a @@ -129,32 +131,38 @@ class TunnelManager { int32_t wire_prefix_size = 0; }; - void ListenerCoroutine(async::Context ctx); - void HandshakeCoroutine(async::Context ctx, + async::Task ListenerCoroutine(async::Context ctx); + async::Task HandshakeCoroutine(async::Context ctx, std::shared_ptr socket, std::string peer); - void IngressCoroutine(async::Context ctx, + async::Task IngressCoroutine(async::Context ctx, std::shared_ptr socket, IngressPlan plan); - void EgressCoroutine(async::Context ctx, EgressRoute route); - absl::Status ForwardChannel(async::Context ctx, Client &client, + async::Task EgressCoroutine(async::Context ctx, EgressRoute route); + async::Task ForwardChannel(async::Context ctx, Client &client, async::ByteStream &socket, const EgressRoute &route); - void ScannerCoroutine(async::Context ctx); - void DiscoverySenderCoroutine(async::Context ctx, Peer *peer); + // Sends the subscriber's messages over the tunnel until the connection or the + // channel fails. The caller owns `sub` and must close it. + async::Task ForwardSubscriber(async::Context ctx, + Subscriber *sub, + async::ByteStream &socket, + const EgressRoute &route); + async::Task ScannerCoroutine(async::Context ctx); + async::Task DiscoverySenderCoroutine(async::Context ctx, Peer *peer); // Waits out the reconnect interval, ending early when there is something // new to tell the peer. - void WaitToReconnect(async::Context ctx, Peer &peer); - absl::Status RunDiscoveryConnection(async::Context ctx, + async::Task WaitToReconnect(async::Context ctx, Peer &peer); + async::Task RunDiscoveryConnection(async::Context ctx, async::ByteStream &socket, Peer &peer); - absl::Status SendDiscovery(async::Context ctx, async::ByteStream &socket, + async::Task SendDiscovery(async::Context ctx, async::ByteStream &socket, const Peer &peer, uint64_t seq); - void DiscoveryReceiverLoop(async::Context ctx, async::ByteStream &socket, + async::Task DiscoveryReceiverLoop(async::Context ctx, async::ByteStream &socket, const tunnel::Handshake &handshake, const std::string &peer); // Reads and discards a connection for an internal channel until the peer // closes it. Closing it instead would make the peer reconnect forever. - void DiscardConnection(async::Context ctx, async::ByteStream &socket, + async::Task DiscardConnection(async::Context ctx, async::ByteStream &socket, const std::string &topic, const std::string &peer); IngressPlan PlanIngress(const tunnel::Handshake &handshake, @@ -173,8 +181,8 @@ class TunnelManager { // Logs a connection failure at info level, or at debug level when it // repeats the previous one. void LogFailure(std::string &last_failure, std::string failure); - void SpawnOnStrand(std::function fn, std::string name); - void SpawnOnNewStrand(std::function fn, + void SpawnOnStrand(async::CoroutineFunction fn, std::string name); + void SpawnOnNewStrand(async::CoroutineFunction fn, std::string name); Server *server_; diff --git a/shadow/BUILD.bazel b/shadow/BUILD.bazel index 05ec2b6d..9402d457 100644 --- a/shadow/BUILD.bazel +++ b/shadow/BUILD.bazel @@ -45,6 +45,12 @@ cc_binary( cc_test( name = "shadow_test", + # Co-only: these use the stackful co API directly (or, for alloc_test, assert + # zero allocations on the hot path, which co20 coroutine frames violate). + target_compatible_with = select({ + "//:coro_backend_co20": ["@platforms//:incompatible"], + "//conditions:default": [], + }), size = "small", srcs = ["shadow_test.cc"], copts = [ From d57c04e9136b3c86ed6d0a979be405152f5c9f40 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Tue, 24 Nov 2026 15:45:18 -0800 Subject: [PATCH 6/9] Add Linux co20 verification and debug handoff guide --- docs/co20-linux-debug-handoff.md | 262 +++++++++++++++++++++++++++++++ 1 file changed, 262 insertions(+) create mode 100644 docs/co20-linux-debug-handoff.md diff --git a/docs/co20-linux-debug-handoff.md b/docs/co20-linux-debug-handoff.md new file mode 100644 index 00000000..2c3dfb30 --- /dev/null +++ b/docs/co20-linux-debug-handoff.md @@ -0,0 +1,262 @@ +# C++20 Coroutines (`co20`) — Linux Verification & Debug Handoff + +This document is a handoff guide for continuing verification and debugging of +the C++20 stackless coroutine (`co20`) backend on a native Linux host. + +For the general architecture and API rules of the `co20` backend, read +`docs/cpp20-coroutines.md` first. + +--- + +## 1. Current State on Branch `co20` + +- **Branch**: `co20` (`origin/co20`) +- **Workspace rule**: Always use `bazelisk` (not `bazel`). +- **What is implemented**: + - `common/async/` (`task.h`, `wait.h`, `wait.cc`, `socket.*`, `byte_stream.*`, + `runtime.h`) supports `SUBSPACE_CORO_BACKEND_CO20` (`--config=cpp20`). + - `ClientImpl` server round-trips, channel reload callbacks + (`Channel::CheckReload`), split-buffer registration/lookup/unmapping, and + `PublisherImpl`/`SubscriberImpl` slot searches return `async::Task` + (`co20::ValueTask`) via `ASYNC_AWAIT` / `ASYNC_RETURN`. + - Public `Client`, `Publisher`, and `Subscriber` blocking APIs remain + unchanged via `ASYNC_BLOCK` (`SyncWait`), and `Async` methods + (including `CloseAsync`) suspend on a `co20::Scheduler`. + - `Server`, `ClientHandler`, `TunnelManager`, FFI, Python server bindings, + and plugins run on `async::RuntimeEngine` / `async::Task`, using + `SERVER_CLIENT_CALL` and `SERVER_CLIENT_CLOSE` for in-process clients on + the server's scheduler thread. + - Gated targets (`target_compatible_with` skipped under `//:coro_backend_co20`): + `//client:alloc_test`, `//c_client:client_test`, `//rpc/client:client_test`, + `//rpc/server:server_test`, `//rpc/test:rpc_test`, and `//shadow:shadow_test`. + +### Already Verified Before Handoff +- **macOS full default (`co`) suite**: `bazelisk test //...` — **passed**. +- **macOS full `co20` suite**: `bazelisk test --config=cpp20 //...` — **passed** + (all 31 compatible targets pass; 12 incompatible targets skipped). +- **Linux (`ubuntu:24.04` GCC in Docker) targeted runs**: + `//client:client_test`, `//client:bridge_test`, `//server:server_test`, + `//server:tunnel_test`, `//server:tunnel_fake_peer_test`, and + `//server:tunnel_stress_test` passed under `--config=cpp20` and + `--config=cpp20 --config=asan`. + +--- + +## 2. Prioritized Linux Test Matrix to Run + +Run these in order on the Linux host and investigate/fix any failures: + +### Step 1: Full `co20` Bazel Suite (matches `.github/workflows/ci.yml`) +```bash +bazelisk test --config=cpp20 --test_output=errors //... +``` + +### Step 2: Full Default (`co`) Regression Suite +```bash +bazelisk test --test_output=errors //... +``` + +### Step 3: AddressSanitizer under `co20` +Catches coroutine frame use-after-free across `co_await`, dangling lambda +captures, and stack overflows: +```bash +bazelisk test --config=cpp20 --config=asan --test_output=errors \ + //common/... //client/... //server/... //co20_rpc/... //asio_rpc/... //coro_rpc/... +``` +Also stress-run the multi-coroutine bridge and tunnel tests without cache: +```bash +bazelisk test --config=cpp20 --config=asan --nocache_test_results --runs_per_test=5 --test_output=errors \ + //client:bridge_test //server:tunnel_test //server:tunnel_fake_peer_test //server:tunnel_stress_test +``` + +### Step 4: ThreadSanitizer under `co20` +Catches races between blocking client threads (`SyncWait`), shared memory +atomics, and the server scheduler thread (specify C++ targets directly so Rust +targets do not fail linking TSan): +```bash +bazelisk test --config=cpp20 --config=tsan --test_output=errors \ + //common/... //client:client_test //client:bridge_test \ + //server:server_test //server:tunnel_test //server:tunnel_fake_peer_test \ + //server:tunnel_stress_test //co20_rpc/... +``` + +### Step 5: Linux Anonymous `memfd` Shared Memory (`--config=linux_memfd`) +**Important**: Default Linux builds use `/dev/shm` (`SUBSPACE_SHMEM_MODE_LINUX`). +`--config=linux_memfd` switches to `SUBSPACE_SHMEM_MODE_MEMFD` (the same path +Android uses), which compiles additional `ASYNC_AWAIT` code paths in +`client/client_channel.cc` (`CreateSplitBufferSet`, `OpenSplitBufferSet`, +`GetRegisteredClientBuffer`, `PublisherImpl::CreateOrAttachBuffers`) that were +not compiled in `/dev/shm` or macOS POSIX builds: +```bash +bazelisk test --config=cpp20 --config=linux_memfd --test_output=errors \ + //client:client_test //client:bridge_test //server:server_test //server:tunnel_test +``` + +### Step 6: Mutual TLS (`--config=mtls`) & 64-bit Slot Sizes (`--config=slot_size_64`) +Exercises the `co20` OpenSSL paths in `common/async/byte_stream.cc` and widened +API signatures in `client/client.h`: +```bash +bazelisk test --config=cpp20 --config=mtls --test_output=errors \ + //client:bridge_test //server:tunnel_test //server:tunnel_stress_test + +bazelisk test --config=cpp20 --config=slot_size_64 --test_output=errors \ + //client:client_test //server:server_test +``` + +### Step 7: Clang (`--config=clang`) vs GCC +If both `g++` and `clang++` are installed on the Linux machine, run at least +`//client:client_test`, `//client:bridge_test`, `//server:tunnel_stress_test`, +and `//co20_rpc/test:rpc_test` under `--config=cpp20 --config=clang` as well. +Clang and GCC lower coroutine frames and symmetric transfer differently. + +### Step 8: Native CMake C++20 Build +```bash +cmake -S . -B build-co20 -DCMAKE_CXX_STANDARD=20 -DSUBSPACE_CORO_BACKEND=co20 +cmake --build build-co20 --target subspace_server client_test server_test co20_rpc_test -j +ctest --test-dir build-co20 --output-on-failure -R "^(client_test|server_test|co20_rpc.*)$" +``` +> **Known CMake gap to check/fix if needed**: In Bazel, `c_client_test`, +> `shadow_test`, `rpc_client_test`, `rpc_server_test`, and `rpc_test` are gated +> off under `//:coro_backend_co20` because those test `.cc` files construct +> `subspace::Server` with a `co::CoroutineScheduler` directly. In CMake +> (`c_client/CMakeLists.txt`, `shadow/CMakeLists.txt`, `rpc/CMakeLists.txt`), +> those test executables are not yet wrapped in +> `if(NOT SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "co20")`, so a bare +> `cmake --build build-co20` (all targets) will try to compile them against a +> `co20` `libserver`. Keep `subspace_rpc_plugin` in `rpc/CMakeLists.txt` +> enabled if you gate the `rpc_*_test` targets, because `co20_rpc` uses that +> host plugin to generate its stubs. + +--- + +## 3. Linux Bugs Already Found & Fixed (Read Before Debugging Similar Symptoms) + +### Finding A: GCC `-O0` / ASan C-Stack Overflow on Symmetric Transfer +- **Symptom**: `SIGSEGV` on a guard page or `AddressSanitizer: stack-overflow` + deep inside `ValueTaskAwaiter::await_suspend` / `actor(frame*)` chains during + long non-parking loops (originally seen in `//server:tunnel_stress_test`). +- **Root cause**: At `-O0` (`fastbuild`) and under AddressSanitizer, GCC does + not tail-call-optimize C++20 coroutine symmetric transfer + (`std::coroutine_handle<> await_suspend(...)`, GCC bug 100897). Every raw + `co_await` of a `co20::ValueTask` that finishes without parking on the + scheduler pushes C stack frames that only unwind when a coroutine finally + suspends back to `co20::Scheduler::Run`. +- **How it is fixed**: `ASYNC_AWAIT(expr)` in `common/async/task.h` wraps + `ValueTask`s in `detail::FastAwait(...)` (`FastValueTaskAwaiter`). Its + `bool await_suspend(caller)` resumes the child inline; if `handle_.done()` is + `true`, `continuation_` was never set, `resume()` returns normally, and + `await_suspend` returns `false` so the caller continues with \(O(1)\) C stack + depth. Only when the child actually parks on `co20::Scheduler` (`!done()`) + does it wire `continuation_ = caller` and return `true`. +- **Watch out for**: Any code that uses **raw `co_await`** (instead of + `ASYNC_AWAIT`) on a `ValueTask` inside a tight non-parking loop can still hit + this under GCC `-O0` / ASan. Notably, `co20_rpc/` uses raw `co_await` on + `co20::ValueTask`; if a `co20_rpc` test overflows the stack under ASan on + Linux, apply `FastAwait` or `ASYNC_AWAIT` there too. + +### Finding B: Server Shutdown Reconnect Deadlock on Linux UDS Backlog +- **Symptom**: `TunnelStressTest.ManyChannelsFlowBothWaysAtOnce` hung for 300s + during `Server::Stop()` teardown on Linux (2/3 runs before fix). +- **Root cause**: Both `ClientHandler` coroutines and in-process client + coroutines (`TunnelManager`, `ChannelDirectoryCoroutine`, `SendChannelStats`) + share `Server::shutdown_trigger_fd_` as their `interrupt_fd`. Idle + `ClientHandler`s have older `LastTick()` timestamps in `co20::Scheduler`, so + they wake first and close the server end of the UDS sockets. When in-process + client coroutines wake next and run `SERVER_CLIENT_CLOSE` (`CloseAsync`), + `send()` fails synchronously with `EPIPE` (`InternalError`, not + `CancelledError`). `ClientImpl::ShouldReconnect` previously saw a + non-cancelled error and called synchronous `UnixSocket::Connect` against + `listen_socket` (`listen(..., 5)`), whose backlog was no longer being drained. + On Linux, the 6th blocking `connect()` on a full UDS listen backlog blocks in + the kernel forever, wedging the scheduler thread. +- **How it is fixed**: + 1. `ClientImpl::ShouldReconnect` (`client/client.cc`) checks + `co->IsAborted()` and does a non-blocking `poll(..., 0)` on + `co->GetInterruptFd()` under `co20`, returning `false` when shutdown is + signaled. + 2. `Server::ListenerCoroutine` (`server/server.cc`) yields via + `co_await ctx.Coroutine()->Yield()` instead of `async::Sleep(ctx, 5ms)` + while waiting for child coroutines to drain (since `interrupt_fd` is + already readable during drain, `Sleep` woke immediately via `epoll` churn). +- **Watch out for**: `toolbelt::UnixSocket::Connect` in `ClientImpl::Init` / + `Reconnect` is synchronous. Never create/connect more than 5 in-process + clients concurrently before the server's `ListenerCoroutine` gets a turn to + `accept()` them on the scheduler. + +### Finding C: Blocking Client Calls or Unclosed Destructors on the Scheduler Thread +- **Rule**: `ASYNC_BLOCK(expr)` calls `SyncWait`, which sets + `co20::CoroutineScope(nullptr)` while running `expr`. + - If `expr` hits a socket wait (`SocketContext()`), `co20::self` is `nullptr`, + so `common/async/socket.cc` falls back to blocking `poll()`. If the server + lives on the **same** scheduler thread, blocking `poll()` deadlocks the + thread forever. + - If `expr` hits an unconditional coroutine suspension (`!task.done()`), + `SyncWait` calls `std::abort()`. +- **Destructor trap**: `~Publisher()` and `~Subscriber()` call + `ASYNC_BLOCK(client_->RemovePublisher(...))` unless `CloseAsync()` was + awaited first (`closed_ == true`). Every `Publisher` / `Subscriber` owned by + a server coroutine **must** be closed via `SERVER_CLIENT_CLOSE(x)` on **all** + exit paths (normal exit, error return, shutdown). + +--- + +## 4. Debugging Playbook on Linux + +### 1. Diagnosing a Hang / 300s Test Timeout +Run the test binary directly (or attach to the Bazel test process before timeout) +and dump all thread backtraces: +```bash +# Run directly with GDB batch on hang, or attach to running PID: +gdb -p -batch -ex "info threads" -ex "thread apply all bt" +``` +Check what the `Server` thread (`co20::Scheduler::Run`) is doing: +- **Stuck in `poll()` inside `subspace::async::SyncWait`**: + Look up the stack above `SyncWait` — a server-side coroutine called a + synchronous `Client`/`Publisher`/`Subscriber` method (or ran `~Publisher()` / + `~Subscriber()` without `SERVER_CLIENT_CLOSE`). Convert that call site to its + `*Async` / `SERVER_CLIENT_CALL` / `SERVER_CLIENT_CLOSE` equivalent. +- **Stuck in `connect()` inside `toolbelt::UnixSocket::Connect`**: + UDS listen backlog (5) is full while the listener coroutine is either stopped + or starved on the same scheduler thread. +- **Stuck in `epoll_wait()` inside `co20::Scheduler::Run` during teardown**: + A server coroutine has not exited during `Server::Stop()`'s drain loop + (`while (!coroutines_.empty())` in `server/server.cc`). Print the names of + live coroutines in `coroutines_` (each `co20::Coroutine` has `Name()`) to see + which coroutine is ignoring `shutdown_trigger_fd_` or waiting without an + `interrupt_fd`. + +### 2. Diagnosing a `SIGSEGV` or Stack Overflow +Re-run the failing test with `--config=cpp20 --config=asan --test_output=errors`: +- **`AddressSanitizer: stack-overflow`**: + Inspect the repeating 2–6 frame cycle in the ASan trace. One of the calls in + that cycle is using raw `co_await` instead of `ASYNC_AWAIT` (`FastAwait`), or + calling a synchronous recursion in `ReadMessageInternal` (e.g. skipping + activation messages). +- **`AddressSanitizer: heap-use-after-free` on `resume()` or promise access**: + Check for: + 1. **Coroutine lambda capture lifetime**: In C++20, a lambda coroutine + `auto task = [x]() -> async::Task { ... }();` stores `x` inside the + **lambda closure object**, NOT inside the coroutine frame! If the closure + temporary is destroyed before `task` finishes (e.g. `Spawn`ed onto + `co20::Scheduler` or stored and `co_await`ed later), any capture (`[this]`, + `[&]`, `[=]`) is a `heap-use-after-free` / `stack-use-after-return` after + the first suspension point. Pass values as **function parameters** to a + named coroutine/static helper (as `Server::SpawnCoroutine` does in + `server/server.h`), or ensure the `std::function` / closure outlives the + awaited `Task` within the same full-expression. + 2. **`this` or reference invalidation across `ASYNC_AWAIT`**: Check that + containers (`channels_`, `client_handlers_`, `egress_channels_`) are not + mutated/erased by another coroutine while a raw pointer/iterator is held + across an `ASYNC_AWAIT`. + +### 3. Diagnosing `--config=linux_memfd` Failures +If a test fails only with `--config=cpp20 --config=linux_memfd`: +- Focus on `client/client_channel.cc` (`#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD` + blocks) and `client/publisher.cc` (`CreateOrAttachBuffers` memfd registration + and rollback). +- Check `GetRegisteredClientBuffer` retry timing (100 attempts x 1ms via + `async::Sleep(async::Context(co20::self), 1ms)`): under heavy ASan/TSan load + on many-core machines, 100ms total retry budget might be tight if the server + scheduler is busy. +- Check fd ownership (`toolbelt::FileDescriptor`) across `ASYNC_AWAIT` in + `RegisterClientBuffer` / `GetClientBuffers`. From f8eb4fb1cd36e07ad0665e8acba8fa9cd272cb73 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Tue, 24 Nov 2026 17:17:45 -0800 Subject: [PATCH 7/9] Fix co20 memfd build and CMake co20 build on Linux - Make ClientChannel::OpenBuffer and AttachShmBuffers async::Task so the memfd path can await GetRegisteredClientBuffer under co20. - Update the memfd-only AndroidBufferRegistrationTest for Task callbacks. - Gate c_client/shadow/rpc test targets off under the co20 CMake backend and link subspace_async into subspace_common so common tests link. - Record Linux verification results in the co20 handoff doc. --- c_client/CMakeLists.txt | 4 ++++ client/client_channel.cc | 30 ++++++++++++------------ client/client_channel.h | 5 ++-- client/client_test.cc | 22 ++++++++++++------ client/publisher.cc | 11 +++++---- common/CMakeLists.txt | 7 ++++++ docs/co20-linux-debug-handoff.md | 40 +++++++++++++++++++++----------- rpc/CMakeLists.txt | 4 ++++ shadow/CMakeLists.txt | 4 ++++ 9 files changed, 86 insertions(+), 41 deletions(-) diff --git a/c_client/CMakeLists.txt b/c_client/CMakeLists.txt index 428ad244..48dcb0d3 100644 --- a/c_client/CMakeLists.txt +++ b/c_client/CMakeLists.txt @@ -19,7 +19,11 @@ target_link_libraries(subspace_c_client PUBLIC subspace_client ) +# These tests construct subspace::Server with a co::CoroutineScheduler, which the +# co20 backend doesn't provide (mirrors target_compatible_with in Bazel). +if(NOT SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "co20") add_executable(c_client_test client_test.cc) add_test(NAME c_client_test COMMAND c_client_test) add_test(NAME c_client_split_buffer_test COMMAND c_client_test --use_split_buffers) target_link_libraries(c_client_test PUBLIC subspace_c_client libserver gtest absl::flags_parse) +endif() diff --git a/client/client_channel.cc b/client/client_channel.cc index fbb69d51..70227da5 100644 --- a/client/client_channel.cc +++ b/client/client_channel.cc @@ -395,15 +395,15 @@ async::Task ClientChannel::AttachBuffers() { if (UseSplitBuffers()) { ASYNC_RETURN ASYNC_AWAIT(AttachSplitBuffers(num_buffers)); } - ASYNC_RETURN AttachShmBuffers(num_buffers); + ASYNC_RETURN ASYNC_AWAIT(AttachShmBuffers(num_buffers)); } -absl::Status ClientChannel::AttachShmBuffers(int num_buffers) { +async::Task ClientChannel::AttachShmBuffers(int num_buffers) { BufferMapMode mode = MapMode(); while (buffers_.size() < size_t(num_buffers)) { // We need to open the next buffer in the list. The buffer index is size_t buffer_index = buffers_.size(); - auto shm_fd = OpenBuffer(buffer_index); + auto shm_fd = ASYNC_AWAIT(OpenBuffer(buffer_index)); if (!shm_fd.ok()) { #if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_POSIX if (buffers_.size() + 1 < size_t(num_buffers)) { @@ -414,11 +414,11 @@ absl::Status ClientChannel::AttachShmBuffers(int num_buffers) { continue; } #endif - return shm_fd.status(); + ASYNC_RETURN shm_fd.status(); } auto size = GetBufferSize(*shm_fd, buffer_index); if (!size.ok()) { - return size.status(); + ASYNC_RETURN size.status(); } if (*size == 0) { #if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_LINUX @@ -438,7 +438,7 @@ absl::Status ClientChannel::AttachShmBuffers(int num_buffers) { // Map the shared memory buffer. addr = MapBuffer(*shm_fd, *size, mode); if (!addr.ok()) { - return addr.status(); + ASYNC_RETURN addr.status(); } } else { addr = nullptr; @@ -447,7 +447,7 @@ absl::Status ClientChannel::AttachShmBuffers(int num_buffers) { buffer_set->fd = std::move(*shm_fd); buffers_.push_back(std::move(buffer_set)); } - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); } async::Task ClientChannel::AttachSplitBuffers(int num_buffers) { @@ -1119,26 +1119,26 @@ ClientChannel::OpenSplitBufferSet(size_t buffer_index, size_t full_size, ASYNC_RETURN buffer; } -absl::StatusOr +async::Task> ClientChannel::OpenBuffer(int buffer_index) { std::string filename = BufferSharedMemoryName(buffer_index); #if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD absl::StatusOr buffer = - GetRegisteredClientBuffer(static_cast(buffer_index), - /*is_prefix=*/false, /*slot_id=*/0); + ASYNC_AWAIT(GetRegisteredClientBuffer(static_cast(buffer_index), + /*is_prefix=*/false, /*slot_id=*/0)); if (!buffer.ok()) { - return buffer.status(); + ASYNC_RETURN buffer.status(); } - return std::move(buffer->fd); + ASYNC_RETURN std::move(buffer->fd); #elif SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_LINUX // Open the shared memory file. - return OpenSharedMemoryFile(filename, O_RDWR); + ASYNC_RETURN OpenSharedMemoryFile(filename, O_RDWR); #else auto shm_name = PosixSharedMemoryName(filename); if (!shm_name.ok()) { - return shm_name.status(); + ASYNC_RETURN shm_name.status(); } - return OpenSharedMemoryFile(*shm_name, O_RDWR); + ASYNC_RETURN OpenSharedMemoryFile(*shm_name, O_RDWR); #endif } diff --git a/client/client_channel.h b/client/client_channel.h index c7164813..fdaa7666 100644 --- a/client/client_channel.h +++ b/client/client_channel.h @@ -386,9 +386,10 @@ class ClientChannel : public Channel { absl::StatusOr CreateBuffer(int buffer_index, size_t size); - absl::Status AttachShmBuffers(int num_buffers); + async::Task AttachShmBuffers(int num_buffers); async::Task AttachSplitBuffers(int num_buffers); - absl::StatusOr OpenBuffer(int buffer_index); + async::Task> + OpenBuffer(int buffer_index); absl::StatusOr GetBufferSize(toolbelt::FileDescriptor &shm_fd, int buffer_index) const; absl::StatusOr MapBuffer(toolbelt::FileDescriptor &shm_fd, diff --git a/client/client_test.cc b/client/client_test.cc index aaf837d8..a5465364 100644 --- a/client/client_test.cc +++ b/client/client_test.cc @@ -475,7 +475,10 @@ TEST(AndroidBufferRegistrationTest, FailedRegistrationRollsBackNumBuffers) { /*subscriber_queue_size=*/0, /*subscriber_queue_arena_size=*/0, /*channel_id=*/0, /*publisher_id=*/0, /*vchan_id=*/-1, /*session_id=*/123, "", - options, [](subspace::Channel *) { return false; }, + options, + [](subspace::Channel *) -> subspace::async::Task { + ASYNC_RETURN false; + }, /*user_id=*/0, /*group_id=*/0); ASSERT_OK(publisher.Map( subspace::SharedMemoryFds(std::move(*ccb_fd), std::move(*bcb_fd)), @@ -484,15 +487,17 @@ TEST(AndroidBufferRegistrationTest, FailedRegistrationRollsBackNumBuffers) { int failed_registration_attempts = 0; publisher.SetClientBufferRegistrationCallback( [&](const subspace::ClientBufferHandleMetadata &metadata, - const toolbelt::FileDescriptor *fd) { + const toolbelt::FileDescriptor *fd) + -> subspace::async::Task { failed_registration_attempts++; EXPECT_EQ(0u, metadata.buffer_index); EXPECT_NE(nullptr, fd); EXPECT_TRUE(fd->Valid()); - return absl::InternalError("injected registration failure"); + ASYNC_RETURN absl::InternalError("injected registration failure"); }); - absl::Status status = publisher.CreateOrAttachBuffers(/*slot_size=*/128); + absl::Status status = + ASYNC_BLOCK(publisher.CreateOrAttachBuffers(/*slot_size=*/128)); EXPECT_FALSE(status.ok()); EXPECT_EQ(1, failed_registration_attempts); EXPECT_EQ(0, publisher.GetCcb()->num_buffers.load(std::memory_order_relaxed)); @@ -501,14 +506,17 @@ TEST(AndroidBufferRegistrationTest, FailedRegistrationRollsBackNumBuffers) { std::vector registered_indices; publisher.SetClientBufferRegistrationCallback( [&](const subspace::ClientBufferHandleMetadata &metadata, - const toolbelt::FileDescriptor *fd) { + const toolbelt::FileDescriptor *fd) + -> subspace::async::Task { EXPECT_NE(nullptr, fd); EXPECT_TRUE(fd->Valid()); registered_indices.push_back(metadata.buffer_index); - return absl::OkStatus(); + ASYNC_RETURN absl::OkStatus(); }); - ASSERT_OK(publisher.CreateOrAttachBuffers(/*slot_size=*/128)); + absl::Status status2 = + ASYNC_BLOCK(publisher.CreateOrAttachBuffers(/*slot_size=*/128)); + ASSERT_OK(status2); ASSERT_EQ(1u, registered_indices.size()); EXPECT_EQ(0u, registered_indices[0]); EXPECT_EQ(1, publisher.GetCcb()->num_buffers.load(std::memory_order_relaxed)); diff --git a/client/publisher.cc b/client/publisher.cc index c36a5b96..5bae1da6 100644 --- a/client/publisher.cc +++ b/client/publisher.cc @@ -55,9 +55,12 @@ async::Task PublisherImpl::CreateOrAttachBuffers(uint64_t final_sl #if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD bool opened_existing_buffer = buffer_index < size_t(num_buffers); absl::StatusOr shm_fd = - opened_existing_buffer - ? OpenBuffer(buffer_index) - : CreateBuffer(buffer_index, final_buffer_size); + absl::InternalError("unset"); + if (opened_existing_buffer) { + shm_fd = ASYNC_AWAIT(OpenBuffer(buffer_index)); + } else { + shm_fd = CreateBuffer(buffer_index, final_buffer_size); + } #else bool opened_existing_buffer = false; auto shm_fd = CreateBuffer(buffer_index, final_buffer_size); @@ -69,7 +72,7 @@ async::Task PublisherImpl::CreateOrAttachBuffers(uint64_t final_sl // The named shared memory already exists so we attach to it instead of // creating it. opened_existing_buffer = true; - shm_fd = OpenBuffer(buffer_index); + shm_fd = ASYNC_AWAIT(OpenBuffer(buffer_index)); if (!shm_fd.ok()) { ASYNC_RETURN shm_fd.status(); } diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 25bd40f7..3a7c440b 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -30,6 +30,13 @@ target_link_libraries(subspace_common PUBLIC protobuf::libprotobuf ) +# channel.h refers to co20 types and the backend link-check symbol (defined by +# subspace_async, which also brings in co_cpp20) when the C++20 coroutine +# backend is selected. +if(SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "co20") + target_link_libraries(subspace_common PUBLIC subspace_async) +endif() + if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND NOT ANDROID) target_link_libraries(subspace_common PUBLIC rt) elseif(ANDROID) diff --git a/docs/co20-linux-debug-handoff.md b/docs/co20-linux-debug-handoff.md index 2c3dfb30..1191c324 100644 --- a/docs/co20-linux-debug-handoff.md +++ b/docs/co20-linux-debug-handoff.md @@ -112,20 +112,12 @@ Clang and GCC lower coroutine frames and symmetric transfer differently. ### Step 8: Native CMake C++20 Build ```bash cmake -S . -B build-co20 -DCMAKE_CXX_STANDARD=20 -DSUBSPACE_CORO_BACKEND=co20 -cmake --build build-co20 --target subspace_server client_test server_test co20_rpc_test -j -ctest --test-dir build-co20 --output-on-failure -R "^(client_test|server_test|co20_rpc.*)$" +cmake --build build-co20 -j +ctest --test-dir build-co20 --output-on-failure ``` -> **Known CMake gap to check/fix if needed**: In Bazel, `c_client_test`, -> `shadow_test`, `rpc_client_test`, `rpc_server_test`, and `rpc_test` are gated -> off under `//:coro_backend_co20` because those test `.cc` files construct -> `subspace::Server` with a `co::CoroutineScheduler` directly. In CMake -> (`c_client/CMakeLists.txt`, `shadow/CMakeLists.txt`, `rpc/CMakeLists.txt`), -> those test executables are not yet wrapped in -> `if(NOT SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "co20")`, so a bare -> `cmake --build build-co20` (all targets) will try to compile them against a -> `co20` `libserver`. Keep `subspace_rpc_plugin` in `rpc/CMakeLists.txt` -> enabled if you gate the `rpc_*_test` targets, because `co20_rpc` uses that -> host plugin to generate its stubs. +> The `c_client_test`, `shadow_test`, `rpc_*_test` CMake targets are now gated +> off under `co20` (matching Bazel), and `subspace_common` links +> `subspace_async` under `co20` so `common_test` / `split_buffer_test` link. --- @@ -260,3 +252,25 @@ If a test fails only with `--config=cpp20 --config=linux_memfd`: scheduler is busy. - Check fd ownership (`toolbelt::FileDescriptor`) across `ASYNC_AWAIT` in `RegisterClientBuffer` / `GetClientBuffers`. + +--- + +## 5. Linux Verification Results (Ubuntu 22.04, GCC 11, 32 cores) + +| Step | Result | +|------|--------| +| 1. `--config=cpp20 //...` | Pass (36 run, 7 skipped) | +| 2. default `//...` | Pass (43/43) | +| 3. `cpp20` + `asan` | Pass, including `--runs_per_test=5` stress. `//client/python:client_test` (ASan runtime not first in library list) and `//coro_rpc/{client,test}` (leaks in the old `coro_rpc` code) fail identically on the default backend, so they are not `co20` regressions. | +| 4. `cpp20` + `tsan` | Pass except `//client:client_test` `PluginTest`: `nop_plugin` logs from `Server::Stop()` on the stopping thread while the server thread logs through the same `toolbelt::Logger` buffer. The same race occurs on the default backend. TSan needs `--run_under="setarch x86_64 -R"` on kernels with `vm.mmap_rnd_bits=32`; skip Rust targets (their protoc build step is TSan-instrumented and crashes). | +| 5. `cpp20` + `linux_memfd` | Fixed (see below), then pass. `//rust_client:client_test` cross-language tests fail identically on the default backend (Rust client has no memfd support on Linux). | +| 6. `mtls`, `slot_size_64` | Pass | +| 7. Clang | Not run (clang not installed) | +| 8. CMake `co20` | Fixed (see below), 21/21 ctest pass | + +### Finding D: memfd `OpenBuffer` was not async +`ClientChannel::OpenBuffer` called `GetRegisteredClientBuffer` (an +`async::Task`) synchronously, which only compiled in `SUBSPACE_SHMEM_MODE_MEMFD` +under `co20`. `OpenBuffer` and `AttachShmBuffers` now return `async::Task<>`, and +callers in `client_channel.cc` / `publisher.cc` await them. The memfd-only test +`AndroidBufferRegistrationTest` was updated for the `Task`-returning callbacks. diff --git a/rpc/CMakeLists.txt b/rpc/CMakeLists.txt index f64d6cc1..55a46bd9 100644 --- a/rpc/CMakeLists.txt +++ b/rpc/CMakeLists.txt @@ -186,6 +186,9 @@ target_link_libraries(rpc_test_subspace_rpc_server PUBLIC rpc_test_cc_proto rpc_ # These start the subspace server in-process (linking libserver), matching the # other CMake tests in this project. +# These tests construct subspace::Server with a co::CoroutineScheduler, which the +# co20 backend doesn't provide (mirrors target_compatible_with in Bazel). +if(NOT SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "co20") add_executable(rpc_client_test client/client_test.cc) add_test(NAME rpc_client_test COMMAND rpc_client_test) set_tests_properties(rpc_client_test PROPERTIES WORKING_DIRECTORY "${CMAKE_BINARY_DIR}") @@ -225,6 +228,7 @@ target_link_libraries(rpc_test PUBLIC gmock absl::flags_parse ) +endif() # --- Example binaries (built but not registered as tests, matching the # "manual" tag in Bazel) --- diff --git a/shadow/CMakeLists.txt b/shadow/CMakeLists.txt index 35ea280c..4f4bce95 100644 --- a/shadow/CMakeLists.txt +++ b/shadow/CMakeLists.txt @@ -34,6 +34,9 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND NOT ANDROID) target_link_libraries(subspace_shadow PRIVATE rt) endif() +# These tests construct subspace::Server with a co::CoroutineScheduler, which the +# co20 backend doesn't provide (mirrors target_compatible_with in Bazel). +if(NOT SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "co20") add_executable(shadow_test shadow_test.cc) add_test(NAME shadow_test COMMAND shadow_test) target_link_libraries(shadow_test PUBLIC @@ -50,3 +53,4 @@ target_link_libraries(shadow_test PUBLIC if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND NOT ANDROID) target_link_libraries(shadow_test PRIVATE rt dl) endif() +endif() From 0f60695c2dcf4da15fdf1d9ccc7567ff43533472 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Tue, 24 Nov 2026 17:46:43 -0800 Subject: [PATCH 8/9] CMake: link subspace_async into subspace_common for all backends common_test and split_buffer_test failed to link on every backend because context.h references a backend link-check symbol defined in subspace_async. --- common/CMakeLists.txt | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 3a7c440b..3e9abca9 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -30,12 +30,10 @@ target_link_libraries(subspace_common PUBLIC protobuf::libprotobuf ) -# channel.h refers to co20 types and the backend link-check symbol (defined by -# subspace_async, which also brings in co_cpp20) when the C++20 coroutine -# backend is selected. -if(SUBSPACE_CORO_BACKEND_RESOLVED STREQUAL "co20") - target_link_libraries(subspace_common PUBLIC subspace_async) -endif() +# Headers in common/ include async/context.h, which references a backend +# link-check symbol (and, for co20, co20 types). subspace_async defines that +# symbol and brings in the backend's coroutine library. +target_link_libraries(subspace_common PUBLIC subspace_async) if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND NOT ANDROID) target_link_libraries(subspace_common PUBLIC rt) From f70d08e9db42e2f62d936f9cf3c82135f6b01285 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Wed, 25 Nov 2026 09:38:51 -0800 Subject: [PATCH 9/9] Pool co20 coroutine frames so publish and read allocate nothing Every call to an async::Task function allocated a coroutine frame from the global heap: about 7 allocations per publish and 5 per read. Give every co20::ValueTask a promise type (via a std::coroutine_traits specialisation) whose operator new/delete use a per-thread, size-class frame pool, so a path that has run once on a thread allocates nothing. - Add common/async/frame_pool.{h,cc}. The pool is off under ASan/TSan so they still see frame lifetimes; SUBSPACE_ASYNC_FRAME_POOL=0/1 overrides. - Include task.h from co20_rpc's shared_ptr_pipe.h so every definition of its ValueTask coroutine uses the same promise type. - Run //client:alloc_test under co20 now that it holds, and add frame pool tests to async_test. - Update the co20 docs. --- client/BUILD.bazel | 6 -- co20_rpc/common/BUILD.bazel | 1 + co20_rpc/common/shared_ptr_pipe.h | 3 + common/CMakeLists.txt | 2 + common/async/BUILD.bazel | 2 + common/async/async_test.cc | 59 ++++++++++++++ common/async/frame_pool.cc | 129 ++++++++++++++++++++++++++++++ common/async/frame_pool.h | 70 ++++++++++++++++ common/async/task.h | 60 ++++++++++++++ docs/co20-linux-debug-handoff.md | 2 +- docs/cpp20-coroutines.md | 27 ++++--- 11 files changed, 345 insertions(+), 16 deletions(-) create mode 100644 common/async/frame_pool.cc create mode 100644 common/async/frame_pool.h diff --git a/client/BUILD.bazel b/client/BUILD.bazel index ba16b866..1d5b9e90 100644 --- a/client/BUILD.bazel +++ b/client/BUILD.bazel @@ -60,12 +60,6 @@ cc_library( cc_test( name = "alloc_test", - # Co-only: these use the stackful co API directly (or, for alloc_test, assert - # zero allocations on the hot path, which co20 coroutine frames violate). - target_compatible_with = select({ - "//:coro_backend_co20": ["@platforms//:incompatible"], - "//conditions:default": [], - }), size = "small", srcs = ["alloc_test.cc"], copts = [ diff --git a/co20_rpc/common/BUILD.bazel b/co20_rpc/common/BUILD.bazel index 4120ff93..a0b19a9e 100644 --- a/co20_rpc/common/BUILD.bazel +++ b/co20_rpc/common/BUILD.bazel @@ -7,6 +7,7 @@ cc_library( hdrs = ["shared_ptr_pipe.h"], copts = ["-std=c++20"], deps = [ + "//common/async:async", "//rpc/common:shared_ptr_pipe_base", "@abseil-cpp//absl/status", "@abseil-cpp//absl/status:statusor", diff --git a/co20_rpc/common/shared_ptr_pipe.h b/co20_rpc/common/shared_ptr_pipe.h index 41a44dcd..f1662064 100644 --- a/co20_rpc/common/shared_ptr_pipe.h +++ b/co20_rpc/common/shared_ptr_pipe.h @@ -8,6 +8,9 @@ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "co/coroutine_cpp20.h" +// Installs the frame pool for co20::ValueTask coroutines such as Read(). Every +// definition of a ValueTask coroutine must see it to agree on the promise type. +#include "common/async/task.h" #include "rpc/common/shared_ptr_pipe_base.h" #include diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 3e9abca9..596aa2ed 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -50,6 +50,8 @@ add_library(subspace_async STATIC async/mtls.h async/byte_stream.h async/byte_stream.cc + async/frame_pool.h + async/frame_pool.cc async/socket.h async/socket.cc async/task.h diff --git a/common/async/BUILD.bazel b/common/async/BUILD.bazel index 5e27a9ff..52611cdc 100644 --- a/common/async/BUILD.bazel +++ b/common/async/BUILD.bazel @@ -14,12 +14,14 @@ cc_library( name = "async", srcs = [ "byte_stream.cc", + "frame_pool.cc", "socket.cc", "wait.cc", ], hdrs = [ "byte_stream.h", "context.h", + "frame_pool.h", "mtls.h", "runtime.h", "socket.h", diff --git a/common/async/async_test.cc b/common/async/async_test.cc index 50c78196..40a4d777 100644 --- a/common/async/async_test.cc +++ b/common/async/async_test.cc @@ -4,6 +4,7 @@ // All Rights Reserved // See LICENSE file for licensing information. +#include "common/async/frame_pool.h" #include "common/async/runtime.h" #include "common/async/socket.h" #include "common/async/task.h" @@ -11,6 +12,8 @@ #include "common/coroutine_stack.h" #include +#include +#include #include #include #include @@ -546,6 +549,62 @@ TEST(AsyncTest, AllCoroutineStringsDropsDestroyedCoroutines) { ::close(fds[1]); } +Task AddOneTask(int x) { ASYNC_RETURN x + 1; } + +Task AddTwoTask(int x) { + int y = ASYNC_AWAIT(AddOneTask(x)); + ASYNC_RETURN ASYNC_AWAIT(AddOneTask(y)); +} + +Task NothingTask() { ASYNC_RETURN; } + +Task ThrowingTask() { + throw std::runtime_error("boom"); + ASYNC_RETURN 0; +} + +// Tasks made from the pooled promise still produce their results, including +// for void and for an exception. +TEST(AsyncTest, PooledTasksProduceResults) { + EXPECT_EQ(3, SyncWait(AddTwoTask(1))); + SyncWait(NothingTask()); + EXPECT_THROW(SyncWait(ThrowingTask()), std::runtime_error); +} + +// Once a thread has run a task of each size, running them again takes every +// frame from the pool. +TEST(AsyncTest, FramePoolReusesFrames) { + if (!kFramePoolEnabled) { + GTEST_SKIP() << "frame pool is disabled in this build"; + } + for (int i = 0; i < 4; i++) { + EXPECT_EQ(i + 2, SyncWait(AddTwoTask(i))); + } + const size_t before = FramePoolHeapAllocations(); + for (int i = 0; i < 1000; i++) { + EXPECT_EQ(i + 2, SyncWait(AddTwoTask(i))); + SyncWait(NothingTask()); + } + EXPECT_EQ(before, FramePoolHeapAllocations()); +} + +// A frame can be released by a thread other than the one that allocated it, +// and a thread that exits with frames in its pool gives them back. +TEST(AsyncTest, FramePoolAcrossThreads) { + for (int round = 0; round < 20; round++) { + // The frame is created here and finished and freed on the other thread. + Task task = AddTwoTask(round); + int result = -1; + std::thread t([&] { result = SyncWait(std::move(task)); }); + t.join(); + EXPECT_EQ(round + 2, result); + + // A thread whose pool holds frames when it exits. + std::thread u([&] { EXPECT_EQ(5, SyncWait(AddTwoTask(3))); }); + u.join(); + } +} + // Outside a coroutine, a task whose Context doesn't suspend runs to the end // in SyncWait, blocking the thread in poll(). TEST(AsyncTest, SyncWaitBlocksWithNullContext) { diff --git a/common/async/frame_pool.cc b/common/async/frame_pool.cc new file mode 100644 index 00000000..92a6943f --- /dev/null +++ b/common/async/frame_pool.cc @@ -0,0 +1,129 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "common/async/frame_pool.h" + +#include +#include + +namespace subspace::async { +namespace detail { + +#if SUBSPACE_ASYNC_FRAME_POOL + +namespace { + +// Every block starts with a header that records its size class, so freeing +// does not depend on the compiler passing the frame size. The header is the +// size of the strictest fundamental alignment so the frame after it is +// suitably aligned. +constexpr std::size_t kHeaderSize = alignof(std::max_align_t); +constexpr std::size_t kGranule = 64; +constexpr std::size_t kNumClasses = kMaxPooledFrameSize / kGranule; +// The most blocks each size class keeps. This bounds the memory a thread +// holds on to after a burst of deeply nested coroutines. +constexpr std::uint32_t kMaxCachedPerClass = 256; +// Class value for blocks that came straight from the global allocator. +constexpr std::uint32_t kHeapClass = UINT32_MAX; + +static_assert(kHeaderSize >= sizeof(std::uint32_t)); +static_assert(kMaxPooledFrameSize % kGranule == 0); + +struct Header { + std::uint32_t size_class; +}; + +// A free block. The link lives in the frame area so the header stays valid +// while the block is on a list. +struct FreeBlock { + FreeBlock *next; +}; + +struct Pool { + FreeBlock *head[kNumClasses] = {}; + std::uint32_t count[kNumClasses] = {}; + std::size_t heap_allocations = 0; + + ~Pool(); +}; + +// Set when this thread's pool has been destroyed. A coroutine frame can be +// released from another thread-local object's destructor after that, in which +// case it goes to the global allocator. Constant initialized and trivially +// destructible, so it is always safe to read. +thread_local bool pool_destroyed = false; + +Pool::~Pool() { + pool_destroyed = true; + for (std::size_t i = 0; i < kNumClasses; i++) { + while (head[i] != nullptr) { + FreeBlock *block = head[i]; + head[i] = block->next; + ::operator delete(reinterpret_cast(block) - kHeaderSize); + } + } +} + +thread_local Pool pool; + +Header *HeaderOf(void *frame) { + return reinterpret_cast
(static_cast(frame) - kHeaderSize); +} + +} // namespace + +void *AllocateFrame(std::size_t size) { + const std::size_t total = size + kHeaderSize; + char *block; + if (total > kMaxPooledFrameSize || pool_destroyed) { + block = static_cast(::operator new(total)); + reinterpret_cast
(block)->size_class = kHeapClass; + return block + kHeaderSize; + } + const std::uint32_t size_class = + static_cast((total - 1) / kGranule); + Pool &p = pool; + if (FreeBlock *free_block = p.head[size_class]; free_block != nullptr) { + p.head[size_class] = free_block->next; + p.count[size_class]--; + return free_block; + } + p.heap_allocations++; + block = static_cast(::operator new((size_class + 1) * kGranule)); + reinterpret_cast
(block)->size_class = size_class; + return block + kHeaderSize; +} + +void DeallocateFrame(void *frame) noexcept { + const std::uint32_t size_class = HeaderOf(frame)->size_class; + if (size_class == kHeapClass || pool_destroyed || + pool.count[size_class] >= kMaxCachedPerClass) { + ::operator delete(static_cast(frame) - kHeaderSize); + return; + } + Pool &p = pool; + auto *free_block = static_cast(frame); + free_block->next = p.head[size_class]; + p.head[size_class] = free_block; + p.count[size_class]++; +} + +} // namespace detail + +std::size_t FramePoolHeapAllocations() { + return detail::pool_destroyed ? 0 : detail::pool.heap_allocations; +} + +#else // !SUBSPACE_ASYNC_FRAME_POOL + +void *AllocateFrame(std::size_t size) { return ::operator new(size); } +void DeallocateFrame(void *frame) noexcept { ::operator delete(frame); } + +} // namespace detail + +std::size_t FramePoolHeapAllocations() { return 0; } + +#endif + +} // namespace subspace::async diff --git a/common/async/frame_pool.h b/common/async/frame_pool.h new file mode 100644 index 00000000..7666d28e --- /dev/null +++ b/common/async/frame_pool.h @@ -0,0 +1,70 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#ifndef _COMMON_ASYNC_FRAME_POOL_H +#define _COMMON_ASYNC_FRAME_POOL_H + +// A recycling allocator for C++20 coroutine frames. +// +// Under the co20 backend every call to a function returning async::Task +// allocates a coroutine frame. The publish and read paths are made of several +// such calls, so with the global allocator each message costs several heap +// allocations. The frame pool keeps the frames of finished coroutines on a +// per-thread free list for each size class and hands them out again, so once a +// thread has run each path once the paths allocate nothing. +// +// task.h installs the pool for every co20::ValueTask, so nothing needs to call +// this directly except tests. +// +// Details: +// - Each thread has its own free lists, so there are no locks. A frame +// freed on a different thread from the one that allocated it just joins +// the freeing thread's list. +// - Frames larger than kMaxPooledFrameSize, and frames beyond the cap each +// list keeps, go to the global allocator. +// - The pool is disabled under AddressSanitizer and ThreadSanitizer so that +// they still see every frame's lifetime and can report a use after free. +// Define SUBSPACE_ASYNC_FRAME_POOL=0 to disable it everywhere, or =1 to +// force it on. + +#include + +#ifndef SUBSPACE_ASYNC_FRAME_POOL +#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__) || \ + defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) +#define SUBSPACE_ASYNC_FRAME_POOL 0 +#elif defined(__has_feature) +#if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) +#define SUBSPACE_ASYNC_FRAME_POOL 0 +#endif +#endif +#endif +#ifndef SUBSPACE_ASYNC_FRAME_POOL +#define SUBSPACE_ASYNC_FRAME_POOL 1 +#endif + +namespace subspace::async { + +// True if coroutine frames are recycled. +inline constexpr bool kFramePoolEnabled = SUBSPACE_ASYNC_FRAME_POOL != 0; + +// The largest frame, header included, that the pool recycles. +inline constexpr std::size_t kMaxPooledFrameSize = 4096; + +namespace detail { + +// Allocate and free a coroutine frame. DeallocateFrame must be given a +// pointer from AllocateFrame, on any thread. +void *AllocateFrame(std::size_t size); +void DeallocateFrame(void *frame) noexcept; + +} // namespace detail + +// The number of times the calling thread had to ask the global allocator for a +// frame. Pool hits are not counted. Zero when the pool is disabled. +std::size_t FramePoolHeapAllocations(); + +} // namespace subspace::async + +#endif // _COMMON_ASYNC_FRAME_POOL_H diff --git a/common/async/task.h b/common/async/task.h index 480e1c5e..13a94628 100644 --- a/common/async/task.h +++ b/common/async/task.h @@ -31,17 +31,77 @@ #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_CO20 +#include #include #include #include #include +#include "common/async/frame_pool.h" + namespace subspace::async { template using Task = co20::ValueTask; namespace detail { +// co20::ValueTask's promise with its coroutine frames taken from the frame +// pool (see frame_pool.h) instead of the global allocator. Without this each +// call to a Task function is a heap allocation, and the publish and read +// paths make several. +// +// This adds no data, only the allocation functions, so it has the layout of +// the promise that ValueTask, its awaiters and ValueTaskFinalAwaiter expect. +// They only ever see it through the base class. +template struct PooledPromise : Promise { + // Not an aggregate. GCC would otherwise try to build the promise from the + // coroutine's arguments. See the comment on ValueTask::promise_type. + PooledPromise() {} + + // As co20::internal::ValueTaskFinalAwaiter, which is written for the base + // class's coroutine_handle and so doesn't accept this one: resume whoever + // awaited the task. + struct FinalAwaiter { + bool await_ready() const noexcept { return false; } + std::coroutine_handle<> + await_suspend(std::coroutine_handle handle) const noexcept { + if (std::coroutine_handle<> continuation = + handle.promise().continuation_) { + return continuation; + } + return std::noop_coroutine(); + } + void await_resume() const noexcept {} + }; + FinalAwaiter final_suspend() noexcept { return {}; } + + static void *operator new(std::size_t size) { return AllocateFrame(size); } + static void operator delete(void *frame) noexcept { DeallocateFrame(frame); } +}; + +} // namespace detail + +} // namespace subspace::async + +// Every coroutine that returns a co20::ValueTask uses the pooled promise. +// This has to be visible wherever such a coroutine is defined, which it is +// because they all return async::Task and so include this header. +namespace std { +template +struct coroutine_traits, Args...> { + using promise_type = subspace::async::detail::PooledPromise< + typename co20::ValueTask::promise_type>; + static_assert(sizeof(promise_type) == + sizeof(typename co20::ValueTask::promise_type) && + alignof(promise_type) == + alignof(typename co20::ValueTask::promise_type)); +}; +} // namespace std + +namespace subspace::async { + +namespace detail { + // Runs `task` inline inside await_suspend when it finishes without parking on // the scheduler, returning `false` so the caller resumes in place instead of // via symmetric transfer. GCC at -O0 and under AddressSanitizer does not diff --git a/docs/co20-linux-debug-handoff.md b/docs/co20-linux-debug-handoff.md index 1191c324..9515ea19 100644 --- a/docs/co20-linux-debug-handoff.md +++ b/docs/co20-linux-debug-handoff.md @@ -27,7 +27,7 @@ For the general architecture and API rules of the `co20` backend, read `SERVER_CLIENT_CALL` and `SERVER_CLIENT_CLOSE` for in-process clients on the server's scheduler thread. - Gated targets (`target_compatible_with` skipped under `//:coro_backend_co20`): - `//client:alloc_test`, `//c_client:client_test`, `//rpc/client:client_test`, + `//c_client:client_test`, `//rpc/client:client_test`, `//rpc/server:server_test`, `//rpc/test:rpc_test`, and `//shadow:shadow_test`. ### Already Verified Before Handoff diff --git a/docs/cpp20-coroutines.md b/docs/cpp20-coroutines.md index 8b2464c9..2164d624 100644 --- a/docs/cpp20-coroutines.md +++ b/docs/cpp20-coroutines.md @@ -122,10 +122,21 @@ scheduler instead of blocking it. trip, which blocks when it runs inside a coroutine. Call `CloseAsync()` first in that case. `CloseAsync()` does not unmap the buffers itself, because a live `Message` may still reference them. -- **Coroutine frames on hot paths.** A co20 coroutine allocates its frame on - each call. Code that asserts zero allocations on a hot path does not hold - under co20. `//client:alloc_test` is gated for this reason and runs under the - default backend. +- **Coroutine frames.** A co20 coroutine needs a frame for every call to a + function returning `async::Task`, and the publish and read paths are made + of several such calls. The global allocator would make each message cost + several heap allocations, so `common/async/task.h` gives every + `co20::ValueTask` a promise type that takes its frames from a per-thread + recycling pool (`common/async/frame_pool.h`). Once a thread has run a path + once, the path allocates nothing, and `//client:alloc_test` checks this under + co20 as it does under the default backend. The first message on a thread (or + the first time it needs a larger frame) still allocates. Frames over 4 KB, and + frames beyond 256 cached per size class, use the global allocator. The pool + is off under AddressSanitizer and ThreadSanitizer so they can see frame + lifetimes; `-DSUBSPACE_ASYNC_FRAME_POOL=0` turns it off everywhere. Any code + that defines a `co20::ValueTask` coroutine must include + `common/async/task.h` so that every definition of the coroutine uses the same + promise type. - **Client thread-safe mode.** Thread-safe mode is not compatible with the Async API. - **Destruction order.** `co20` `Scheduler::~Scheduler` destroys suspended @@ -134,12 +145,10 @@ scheduler instead of blocking it. ## Gated Targets -These targets depend on the `co` stackful API, or on the zero-allocation -property above. They are marked `target_compatible_with` the incompatible -platform under `--config=cpp20`, so `bazelisk test --config=cpp20 //...` -skips them: +These targets depend on the `co` stackful API. They are marked +`target_compatible_with` the incompatible platform under `--config=cpp20`, so +`bazelisk test --config=cpp20 //...` skips them: -- `//client:alloc_test` - `//c_client:client_test` - `//rpc/client:client_test` - `//rpc/server:server_test`