From 310fea8d7bcca0b8520a96977d4c91fcaf37df47 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Thu, 3 Dec 2026 19:50:29 +0300 Subject: [PATCH] RPC: bounded streaming with credit, half-close and cancellation (S-RPC-04) --- include/Void/RPC/Rpc.hpp | 2 +- include/Void/RPC/Stream.hpp | 131 +++++++++++ include/Void/RPC/Types.hpp | 3 + src/RPC/Stream.cpp | 391 ++++++++++++++++++++++++++++++++ tests/standalone/RPC/Stream.cpp | 195 ++++++++++++++++ 5 files changed, 721 insertions(+), 1 deletion(-) create mode 100644 include/Void/RPC/Stream.hpp create mode 100644 src/RPC/Stream.cpp create mode 100644 tests/standalone/RPC/Stream.cpp diff --git a/include/Void/RPC/Rpc.hpp b/include/Void/RPC/Rpc.hpp index 163bbe6..00dbde2 100644 --- a/include/Void/RPC/Rpc.hpp +++ b/include/Void/RPC/Rpc.hpp @@ -20,7 +20,7 @@ namespace Void::RPC { - using OwnedBytes = std::vector; + struct CallContext { CallId call_id{}; diff --git a/include/Void/RPC/Stream.hpp b/include/Void/RPC/Stream.hpp new file mode 100644 index 0000000..e5431ea --- /dev/null +++ b/include/Void/RPC/Stream.hpp @@ -0,0 +1,131 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::RPC +{ + /// Bounds for one streaming call. The initial credit window is the hard + /// upper bound on bytes buffered in either direction: a sender can never + /// have more than `initial_credit_bytes` unacknowledged bytes in flight, + /// so a stalled consumer applies backpressure instead of growing memory. + struct StreamLimits { + std::size_t initial_credit_bytes{256ULL * 1024}; + std::size_t max_data_frame_bytes{64ULL * 1024}; + std::size_t max_control_reserve_bytes{64ULL * 1024}; + std::size_t max_streams_per_connection{128}; + std::chrono::milliseconds default_timeout{std::chrono::seconds{30}}; + }; + + enum class StreamState : std::uint8_t { + Open, + HalfClosedLocal, + HalfClosedRemote, + Closed, + Cancelled, + }; + + /// Final outcome delivered by the server side of a stream. + struct StreamTerminal { + RpcStatus status{}; + OwnedBytes payload{}; + }; + + /// One endpoint of a duplex RPC stream: a bounded, credit-controlled + /// byte pipe in each direction with half-close, cancellation and a single + /// terminal outcome. + /// + /// `write` blocks while the peer has not granted credit (the consumer is + /// stalled); `read` blocks until data, EOF or cancellation. Every byte + /// consumed by `read` replenishes the peer's credit. A call has exactly + /// one outcome: the first of server `finish`, `cancel`, or transport loss + /// wins; later attempts are rejected without changing the outcome. + class StreamEndpoint + { + public: + + StreamEndpoint() noexcept = default; + + /// Send bytes to the peer. Blocks until credit is available. + /// Returns `cancelled` after cancellation, `failed_precondition` + /// when this side already half-closed, and succeeds early with + /// a `cancelled` error if `stop` is requested. + [[nodiscard]] Void::Result::Result + write(std::span bytes, + std::stop_token stop = {}); + + /// Receive the next data chunk. Blocks until data, EOF or + /// cancellation. An empty successful result means EOF: the peer + /// half-closed (or sent a terminal frame) and all buffered data + /// was consumed. + [[nodiscard]] Void::Result::Result + read(std::stop_token stop = {}); + + /// No more writes from this side; the peer's `read` observes EOF + /// after draining buffered data. Idempotent. + void half_close() noexcept; + + /// Abort the call for both sides. Idempotent; a no-op once a + /// terminal outcome is committed. + void cancel() noexcept; + + /// Server side only: commit the terminal outcome. The client + /// observes EOF after buffered data and receives the status from + /// `wait_terminal`. Rejected after cancellation or a previous + /// terminal. + [[nodiscard]] Void::Result::Result + finish(RpcStatus status, OwnedBytes payload = {}); + + /// Client side only: block until the server terminal outcome or + /// cancellation. + [[nodiscard]] Void::Result::Result + wait_terminal(std::stop_token stop = {}); + + [[nodiscard]] bool eof() const noexcept; + [[nodiscard]] bool local_half_closed() const noexcept; + [[nodiscard]] bool cancelled() const noexcept; + [[nodiscard]] StreamState state() const noexcept; + + /// Create a connected client/server endpoint pair over one bounded + /// in-process stream. + [[nodiscard]] static std::pair + make_pair(StreamLimits limits = {}); + + /// Bytes currently buffered in this endpoint's receive queue. + [[nodiscard]] std::size_t buffered_bytes() const noexcept; + /// High-water mark of the receive queue (bounded by the credit + /// window); useful for stalled-consumer assertions. + [[nodiscard]] std::size_t peak_buffered_bytes() const noexcept; + /// Remaining send credit granted by the peer. + [[nodiscard]] std::size_t credit_available() const noexcept; + + private: + + friend struct StreamPair; + struct Impl; + explicit StreamEndpoint(std::shared_ptr impl) noexcept + : m_impl(std::move(impl)) + { + } + + std::shared_ptr m_impl; + }; + + /// Connected client/server endpoints of one in-process duplex stream. + struct StreamPair { + StreamEndpoint client; + StreamEndpoint server; + }; + + /// Create a connected duplex stream pair with bounded credit. + [[nodiscard]] StreamPair make_stream_pair(StreamLimits limits = {}); + +} // namespace Void::RPC diff --git a/include/Void/RPC/Types.hpp b/include/Void/RPC/Types.hpp index fd6d24f..7f48d1f 100644 --- a/include/Void/RPC/Types.hpp +++ b/include/Void/RPC/Types.hpp @@ -15,6 +15,9 @@ namespace Void::RPC { + /// Owned byte payload used by unary and streaming calls. + using OwnedBytes = std::vector; + inline constexpr std::array kWireMagic{ std::byte{'V'}, std::byte{'R'}, std::byte{'P'}, std::byte{'C'}}; inline constexpr std::uint16_t kWireMajorV1{1}; diff --git a/src/RPC/Stream.cpp b/src/RPC/Stream.cpp new file mode 100644 index 0000000..5b05e63 --- /dev/null +++ b/src/RPC/Stream.cpp @@ -0,0 +1,391 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::RPC +{ + namespace + { + struct SharedState { + std::mutex mutex{}; + std::condition_variable_any cv{}; + StreamLimits limits{}; + + // Data queued towards each endpoint. + std::deque to_client{}; + std::deque to_server{}; + + bool client_closed{false}; + bool server_closed{false}; + bool cancelled{false}; + std::optional terminal{}; + + // High-water marks of each queue. + std::size_t peak_to_client{0}; + std::size_t peak_to_server{0}; + }; + + [[nodiscard]] std::deque& + outgoing(SharedState& state, bool client) noexcept + { + return client ? state.to_server : state.to_client; + } + + [[nodiscard]] std::deque& + incoming(SharedState& state, bool client) noexcept + { + return client ? state.to_client : state.to_server; + } + + [[nodiscard]] bool& local_closed(SharedState& state, bool client) noexcept + { + return client ? state.client_closed : state.server_closed; + } + + [[nodiscard]] bool& peer_closed(SharedState& state, bool client) noexcept + { + return client ? state.server_closed : state.client_closed; + } + + [[nodiscard]] std::size_t& + peak_of(SharedState& state, bool client_incoming) noexcept + { + return client_incoming ? state.peak_to_client : state.peak_to_server; + } + + [[nodiscard]] std::size_t + capacity_of(const SharedState& state) noexcept + { + return state.limits.initial_credit_bytes; + } + } // namespace + + struct StreamEndpoint::Impl { + std::shared_ptr shared{}; + bool is_client{false}; + }; + + std::pair + StreamEndpoint::make_pair(StreamLimits limits) + { + if (limits.initial_credit_bytes == 0) { + limits.initial_credit_bytes = 1; + } + if (limits.max_data_frame_bytes == 0) { + limits.max_data_frame_bytes = 1; + } + auto shared = std::make_shared(); + shared->limits = limits; + + auto client = std::make_shared(); + client->shared = shared; + client->is_client = true; + auto server = std::make_shared(); + server->shared = std::move(shared); + server->is_client = false; + return {StreamEndpoint{std::move(client)}, + StreamEndpoint{std::move(server)}}; + } + + StreamPair make_stream_pair(StreamLimits limits) + { + auto [client, server] = StreamEndpoint::make_pair(limits); + return StreamPair{std::move(client), std::move(server)}; + } + + Void::Result::Result + StreamEndpoint::write(std::span bytes, + std::stop_token stop) + { + if (!m_impl) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::Unimplemented, + "RPC stream endpoint is not connected")); + } + SharedState& state = *m_impl->shared; + const bool client = m_impl->is_client; + std::unique_lock lock{state.mutex}; + + if (local_closed(state, client)) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::FailedPrecondition, + "RPC stream write side is already half-closed")); + } + + std::stop_callback wake{stop, [&state] { state.cv.notify_all(); }}; + std::size_t written = 0; + while (written < bytes.size()) { + if (state.cancelled) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::Cancelled, + "RPC stream was cancelled")); + } + if (stop.stop_requested()) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::Cancelled, + "RPC stream write was stopped")); + } + + auto& queue = outgoing(state, client); + const std::size_t capacity = capacity_of(state); + if (queue.size() < capacity) { + const std::size_t space = capacity - queue.size(); + const std::size_t take = + std::min(space, bytes.size() - written); + for (std::size_t i = 0; i < take; ++i) { + queue.push_back(bytes[written + i]); + } + written += take; + peak_of(state, !client) = + std::max(peak_of(state, !client), queue.size()); + state.cv.notify_all(); + continue; + } + + state.cv.wait(lock, [&] { + return state.cancelled || stop.stop_requested() || + outgoing(state, client).size() < capacity; + }); + } + return {}; + } + + Void::Result::Result + StreamEndpoint::read(std::stop_token stop) + { + if (!m_impl) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::Unimplemented, + "RPC stream endpoint is not connected")); + } + SharedState& state = *m_impl->shared; + const bool client = m_impl->is_client; + std::unique_lock lock{state.mutex}; + + std::stop_callback wake{stop, [&state] { state.cv.notify_all(); }}; + for (;;) { + auto& queue = incoming(state, client); + if (!queue.empty()) { + const std::size_t take = std::min( + queue.size(), state.limits.max_data_frame_bytes); + OwnedBytes out; + out.reserve(take); + for (std::size_t i = 0; i < take; ++i) { + out.push_back(queue.front()); + queue.pop_front(); + } + state.cv.notify_all(); + return out; + } + if (state.cancelled) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::Cancelled, + "RPC stream was cancelled")); + } + // EOF: the peer half-closed or committed a terminal outcome and + // every buffered byte has been consumed. + if (peer_closed(state, client) || state.terminal.has_value()) { + return OwnedBytes{}; + } + if (stop.stop_requested()) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::Cancelled, + "RPC stream read was stopped")); + } + state.cv.wait(lock, [&] { + return state.cancelled || stop.stop_requested() || + !incoming(state, client).empty() || + peer_closed(state, client) || + state.terminal.has_value(); + }); + } + } + + void StreamEndpoint::half_close() noexcept + { + if (!m_impl) { + return; + } + SharedState& state = *m_impl->shared; + std::lock_guard lock{state.mutex}; + local_closed(state, m_impl->is_client) = true; + state.cv.notify_all(); + } + + void StreamEndpoint::cancel() noexcept + { + if (!m_impl) { + return; + } + SharedState& state = *m_impl->shared; + std::lock_guard lock{state.mutex}; + if (state.terminal.has_value()) { + return; + } + state.cancelled = true; + state.cv.notify_all(); + } + + Void::Result::Result + StreamEndpoint::finish(RpcStatus status, OwnedBytes payload) + { + if (!m_impl) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::Unimplemented, + "RPC stream endpoint is not connected")); + } + if (m_impl->is_client) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::FailedPrecondition, + "RPC stream terminal outcome is server-side only")); + } + SharedState& state = *m_impl->shared; + std::lock_guard lock{state.mutex}; + if (state.cancelled) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::Cancelled, + "RPC stream was cancelled")); + } + if (state.terminal.has_value()) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::FailedPrecondition, + "RPC stream terminal outcome already committed")); + } + state.terminal.emplace(StreamTerminal{ + .status = std::move(status), .payload = std::move(payload)}); + state.server_closed = true; + state.cv.notify_all(); + return {}; + } + + Void::Result::Result + StreamEndpoint::wait_terminal(std::stop_token stop) + { + if (!m_impl) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::Unimplemented, + "RPC stream endpoint is not connected")); + } + SharedState& state = *m_impl->shared; + std::unique_lock lock{state.mutex}; + std::stop_callback wake{stop, [&state] { state.cv.notify_all(); }}; + for (;;) { + if (state.terminal.has_value()) { + return *state.terminal; + } + if (state.cancelled) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::Cancelled, + "RPC stream was cancelled")); + } + if (stop.stop_requested()) { + return Void::Result::fail( + make_rpc_error(RpcStatusCode::Cancelled, + "RPC stream terminal wait was stopped")); + } + state.cv.wait(lock, [&] { + return state.terminal.has_value() || state.cancelled || + stop.stop_requested(); + }); + } + } + + bool StreamEndpoint::eof() const noexcept + { + if (!m_impl) { + return true; + } + SharedState& state = *m_impl->shared; + std::lock_guard lock{state.mutex}; + return incoming(state, m_impl->is_client).empty() && + (peer_closed(state, m_impl->is_client) || + state.terminal.has_value()); + } + + bool StreamEndpoint::local_half_closed() const noexcept + { + if (!m_impl) { + return true; + } + SharedState& state = *m_impl->shared; + std::lock_guard lock{state.mutex}; + return local_closed(state, m_impl->is_client); + } + + bool StreamEndpoint::cancelled() const noexcept + { + if (!m_impl) { + return false; + } + SharedState& state = *m_impl->shared; + std::lock_guard lock{state.mutex}; + return state.cancelled; + } + + StreamState StreamEndpoint::state() const noexcept + { + if (!m_impl) { + return StreamState::Closed; + } + SharedState& shared = *m_impl->shared; + std::lock_guard lock{shared.mutex}; + if (shared.cancelled) { + return StreamState::Cancelled; + } + const bool local = local_closed(shared, m_impl->is_client); + const bool peer = peer_closed(shared, m_impl->is_client); + if (local && peer) { + return StreamState::Closed; + } + if (local) { + return StreamState::HalfClosedLocal; + } + if (peer) { + return StreamState::HalfClosedRemote; + } + return StreamState::Open; + } + + std::size_t StreamEndpoint::buffered_bytes() const noexcept + { + if (!m_impl) { + return 0; + } + SharedState& state = *m_impl->shared; + std::lock_guard lock{state.mutex}; + return incoming(state, m_impl->is_client).size(); + } + + std::size_t StreamEndpoint::peak_buffered_bytes() const noexcept + { + if (!m_impl) { + return 0; + } + SharedState& state = *m_impl->shared; + std::lock_guard lock{state.mutex}; + return peak_of(state, m_impl->is_client); + } + + std::size_t StreamEndpoint::credit_available() const noexcept + { + if (!m_impl) { + return 0; + } + SharedState& state = *m_impl->shared; + std::lock_guard lock{state.mutex}; + const std::size_t queued = outgoing(state, m_impl->is_client).size(); + const std::size_t capacity = capacity_of(state); + return queued >= capacity ? 0 : capacity - queued; + } +} // namespace Void::RPC diff --git a/tests/standalone/RPC/Stream.cpp b/tests/standalone/RPC/Stream.cpp new file mode 100644 index 0000000..c6c2ac9 --- /dev/null +++ b/tests/standalone/RPC/Stream.cpp @@ -0,0 +1,195 @@ +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace Void::RPC; + using namespace std::chrono_literals; + + OwnedBytes bytes_of(std::string_view text) + { + OwnedBytes out; + out.reserve(text.size()); + for (const char ch : text) { + out.push_back(static_cast(ch)); + } + return out; + } + + std::string text_of(std::span bytes) + { + std::string out; + out.reserve(bytes.size()); + for (const std::byte b : bytes) { + out.push_back(static_cast(std::to_integer(b))); + } + return out; + } + + std::string read_all(StreamEndpoint& endpoint, std::size_t expected) + { + std::string out; + while (out.size() < expected) { + auto chunk = endpoint.read(); + Void::Testing::require(chunk.has_value()); + if (chunk->empty()) { + break; + } + out += text_of(*chunk); + } + return out; + } +} // namespace + +Void::Testing::Test rpc_stream_round_trip_and_credit_bounds() +{ + // Credit must cover the whole message for a single synchronous write; + // the frame cap still splits reads into small chunks. + auto pair = make_stream_pair( + StreamLimits{.initial_credit_bytes = 16, .max_data_frame_bytes = 4}); + + const auto message = bytes_of("hello stream"); + Void::Testing::require(pair.client.write(message).has_value()); + Void::Testing::expect_eq(read_all(pair.server, message.size()), + std::string{"hello stream"}); + Void::Testing::expect_eq(pair.client.credit_available(), std::size_t{16}); + Void::Testing::expect(pair.server.peak_buffered_bytes() <= 16); + + // Reverse direction is independent. + const auto reply = bytes_of("reply"); + Void::Testing::require(pair.server.write(reply).has_value()); + Void::Testing::expect_eq(read_all(pair.client, reply.size()), + std::string{"reply"}); +} + +Void::Testing::Test rpc_stream_half_close_is_directional() +{ + auto pair = make_stream_pair( + StreamLimits{.initial_credit_bytes = 16, .max_data_frame_bytes = 16}); + + Void::Testing::require(pair.client.write(bytes_of("tail")).has_value()); + pair.client.half_close(); + Void::Testing::expect(pair.client.local_half_closed()); + Void::Testing::expect(pair.client.state() == StreamState::HalfClosedLocal); + + // The peer drains buffered data, then observes EOF. + Void::Testing::expect_eq(read_all(pair.server, 4), std::string{"tail"}); + auto eof = pair.server.read(); + Void::Testing::require(eof.has_value()); + Void::Testing::expect(eof->empty()); + Void::Testing::expect(pair.server.eof()); + + // The server may still write in the other direction. + Void::Testing::require(pair.server.write(bytes_of("after")).has_value()); + Void::Testing::expect_eq(read_all(pair.client, 5), std::string{"after"}); + + // Writing on a half-closed side is rejected. + auto rejected = pair.client.write(bytes_of("x")); + Void::Testing::require(!rejected.has_value()); + Void::Testing::expect_eq( + rejected.error().code().value, + static_cast(RpcStatusCode::FailedPrecondition)); +} + +Void::Testing::Test rpc_stream_cancel_aborts_both_sides() +{ + auto pair = make_stream_pair(); + pair.client.cancel(); + Void::Testing::expect(pair.client.cancelled()); + Void::Testing::expect(pair.client.state() == StreamState::Cancelled); + + auto read = pair.server.read(); + Void::Testing::require(!read.has_value()); + Void::Testing::expect_eq(read.error().code().value, + static_cast(RpcStatusCode::Cancelled)); + auto write = pair.server.write(bytes_of("x")); + Void::Testing::require(!write.has_value()); + auto terminal = pair.server.wait_terminal(); + Void::Testing::require(!terminal.has_value()); + + // Idempotent, and a terminal outcome can no longer be committed. + pair.server.cancel(); + Void::Testing::require(!pair.server.finish(RpcStatus{}).has_value()); +} + +Void::Testing::Test rpc_stream_terminal_outcome_is_single() +{ + auto pair = make_stream_pair( + StreamLimits{.initial_credit_bytes = 16, .max_data_frame_bytes = 16}); + Void::Testing::require(pair.server.write(bytes_of("body")).has_value()); + Void::Testing::require( + pair.server + .finish(RpcStatus{.code = RpcStatusCode::Ok, .message = "done"}, + bytes_of("trailer")) + .has_value()); + + Void::Testing::expect_eq(read_all(pair.client, 4), std::string{"body"}); + // The terminal payload is delivered by wait_terminal, not the data stream. + auto eof = pair.client.read(); + Void::Testing::require(eof.has_value()); + Void::Testing::expect(eof->empty()); + + auto terminal = pair.client.wait_terminal(); + Void::Testing::require(terminal.has_value()); + Void::Testing::expect(terminal->status.code == RpcStatusCode::Ok); + Void::Testing::expect_eq(terminal->status.message, std::string{"done"}); + Void::Testing::expect_eq(text_of(terminal->payload), std::string{"trailer"}); + + // A second terminal is rejected. + Void::Testing::require(!pair.server.finish(RpcStatus{}).has_value()); + + // finish is server-side only. + auto client_finish = pair.client.finish(RpcStatus{}); + Void::Testing::require(!client_finish.has_value()); +} + +Void::Testing::Test rpc_stream_stalled_consumer_is_bounded() +{ + constexpr std::size_t kCredit = 16; + constexpr std::size_t kTotal = 64; + auto pair = make_stream_pair( + StreamLimits{.initial_credit_bytes = kCredit, .max_data_frame_bytes = 16}); + + const std::vector payload(kTotal, std::byte{0x5A}); + std::atomic done{false}; + std::atomic write_ok{false}; + std::thread writer([&] { + const auto result = pair.client.write(payload); + write_ok.store(result.has_value(), std::memory_order_relaxed); + // Signal EOF so the draining reader cannot block after the last + // chunk when the writer has already returned. + pair.client.half_close(); + done.store(true, std::memory_order_release); + }); + + // The consumer stalls: the writer can only buffer one credit window. + std::this_thread::sleep_for(50ms); + Void::Testing::expect(!done.load(std::memory_order_acquire)); + Void::Testing::expect(pair.server.buffered_bytes() <= kCredit); + Void::Testing::expect(pair.server.peak_buffered_bytes() <= kCredit); + Void::Testing::expect_eq(pair.client.credit_available(), std::size_t{0}); + + // Draining replenishes credit and lets the writer finish. + std::size_t received = 0; + while (!done.load(std::memory_order_acquire) || pair.server.buffered_bytes() > 0) { + auto chunk = pair.server.read(); + Void::Testing::require(chunk.has_value()); + if (chunk->empty()) { + break; + } + received += chunk->size(); + } + writer.join(); + Void::Testing::expect(write_ok.load()); + Void::Testing::expect_eq(received, kTotal); + Void::Testing::expect(pair.server.peak_buffered_bytes() <= kCredit); +}