feat(rpc): implement P2 S-RPC-01..03 Wire v1 binary codec and unary HTTP/1.1 RPC subsystem

This commit is contained in:
faumaray committed 2026-11-27 01:27:32 +03:00
1 parent 691808eab6
commit 5184d1cf8c
11 files changed
+1778 -1

No files matched your search

+652
View File
@@ -0,0 +1,652 @@
#include <Void/RPC/Rpc.hpp>
#include <algorithm>
#include <atomic>
#include <condition_variable>
#include <cstring>
#include <exception>
#include <format>
#include <limits>
#include <map>
#include <mutex>
#include <stop_token>
#include <utility>
namespace Void::RPC
{
namespace
{
constexpr std::string_view kErrorMessageMetaKey = "x-void-rpc-error";
[[nodiscard]] OwnedBytes
encode_error_response(const WireEnvelope* req_env,
RpcStatusCode code, std::string_view message,
const RpcLimits& limits)
{
WireEnvelope resp;
resp.major = kWireMajorV1;
resp.minor = kWireMinorV1;
resp.kind = FrameKind::UnaryResponse;
resp.flags = kFlagEndOfMessage;
if (req_env != nullptr) {
resp.call_id = req_env->call_id;
resp.method = req_env->method;
resp.schema_version = req_env->schema_version;
}
resp.status_code = code;
if (!message.empty()) {
std::string clipped{message.substr(0, 512U)};
resp.metadata.push_back(MetadataEntry{
std::string{kErrorMessageMetaKey}, std::move(clipped)});
}
auto enc = encode_envelope(resp, limits);
if (enc.has_value()) {
return std::move(*enc);
}
// Fallback without metadata if limits were tight.
resp.metadata.clear();
auto fallback = encode_envelope(resp, RpcLimits{});
return fallback.has_value() ? std::move(*fallback) : OwnedBytes{};
}
} // namespace
struct Server::State {
struct BoundMethod {
std::uint64_t reg_gen{0};
MethodDescriptor desc{};
UnaryHandler handler{};
bool accepting{true};
std::size_t in_flight{0};
std::condition_variable cv{};
};
ServerOptions options{};
std::optional<Void::Net::HttpServer> owned_http{};
std::stop_source stop_source{};
mutable std::mutex mutex{};
std::condition_variable drain_cv{};
bool accepting{true};
std::uint64_t next_reg_gen{1};
std::size_t executing_calls{0};
std::size_t queued_bytes{0};
std::map<MethodId, std::shared_ptr<BoundMethod>> methods{};
void unregister_and_drain(MethodId id, std::uint64_t gen) noexcept
{
std::shared_ptr<BoundMethod> target;
{
std::unique_lock lock{mutex};
const auto it = methods.find(id);
if (it == methods.end() || it->second->reg_gen != gen) {
return;
}
target = it->second;
target->accepting = false;
methods.erase(it);
target->cv.wait(lock,
[&] { return target->in_flight == 0; });
}
}
[[nodiscard]] OwnedBytes dispatch_raw(
std::span<const std::byte> request_bytes,
const std::vector<Void::Net::Header>& transport_headers)
{
auto decoded = decode_envelope(request_bytes, options.limits);
if (!decoded.has_value()) {
return encode_error_response(
nullptr, rpc_status_from_error(decoded.error()),
decoded.error().message(), options.limits);
}
WireEnvelope req = std::move(*decoded);
if (req.kind != FrameKind::UnaryRequest) {
return encode_error_response(
&req, RpcStatusCode::ProtocolError,
"RPC::Server: expected UnaryRequest frame",
options.limits);
}
std::shared_ptr<BoundMethod> bound;
MethodDescriptor desc;
UnaryHandler handler;
const std::size_t payload_sz = req.payload.size();
{
std::lock_guard lock{mutex};
if (!accepting) {
return encode_error_response(
&req, RpcStatusCode::Unavailable,
"RPC::Server: server shutting down",
options.limits);
}
const auto it = methods.find(req.method);
if (it == methods.end() || !it->second->accepting) {
return encode_error_response(
&req, RpcStatusCode::Unimplemented,
"RPC::Server: unknown method", options.limits);
}
if (req.schema_version != it->second->desc.schema_version) {
return encode_error_response(
&req, RpcStatusCode::IncompatibleVersion,
std::format("RPC::Server: schema version mismatch "
"(got {}, expected {})",
req.schema_version,
it->second->desc.schema_version),
options.limits);
}
if (executing_calls >=
options.limits.max_server_executing ||
payload_sz > options.limits.max_server_queued_bytes ||
queued_bytes >
options.limits.max_server_queued_bytes -
payload_sz) {
return encode_error_response(
&req, RpcStatusCode::ResourceExhausted,
"RPC::Server: concurrency or payload budget "
"exhausted",
options.limits);
}
bound = it->second;
desc = bound->desc;
handler = bound->handler;
++bound->in_flight;
++executing_calls;
queued_bytes += payload_sz;
}
struct InFlightGuard {
State* st;
std::shared_ptr<BoundMethod> bm;
std::size_t bytes;
~InFlightGuard() noexcept
{
std::lock_guard lock{st->mutex};
if (bm->in_flight > 0) {
--bm->in_flight;
}
if (bm->in_flight == 0) {
bm->cv.notify_all();
}
if (st->executing_calls > 0) {
--st->executing_calls;
}
if (st->queued_bytes >= bytes) {
st->queued_bytes -= bytes;
} else {
st->queued_bytes = 0;
}
if (st->executing_calls == 0) {
st->drain_cv.notify_all();
}
}
} guard{this, bound, payload_sz};
// Execute authentication & authorization OUTSIDE dispatch locks.
PrincipalView principal;
if (options.auth.authenticate) {
auto ar =
options.auth.authenticate(transport_headers, req.metadata);
if (!ar.has_value()) {
return encode_error_response(
&req, RpcStatusCode::Unauthenticated,
ar.error().message(), options.limits);
}
principal = std::move(*ar);
}
if (options.auth.authorize) {
auto az = options.auth.authorize(desc, principal);
if (!az.has_value()) {
return encode_error_response(
&req, RpcStatusCode::PermissionDenied,
az.error().message(), options.limits);
}
}
// Convert relative timeout into local steady deadline clamped
// to `limits.max_server_timeout`.
const auto* clk =
options.clock != nullptr
? options.clock
: &Void::Time::SystemMonotonicClock::instance();
std::chrono::milliseconds rel_timeout =
req.remaining_timeout_ms > 0
? std::chrono::milliseconds{req.remaining_timeout_ms}
: options.limits.max_server_timeout;
if (rel_timeout > options.limits.max_server_timeout) {
rel_timeout = options.limits.max_server_timeout;
}
CallContext ctx;
ctx.call_id = req.call_id;
ctx.method = desc;
ctx.principal = std::move(principal);
ctx.clock = clk;
ctx.deadline = clk->now() + rel_timeout;
ctx.metadata = std::move(req.metadata);
ctx.stop = stop_source.get_token();
Void::Result::Result<OwnedBytes> handler_res =
std::unexpected{make_rpc_error(RpcStatusCode::Internal,
"uninitialized")};
try {
handler_res = handler(ctx, std::move(req.payload));
} catch (const std::exception&) {
// Sanitized error — never leak internal exception text.
return encode_error_response(
&req, RpcStatusCode::Internal,
"RPC::Server: internal handler error", options.limits);
} catch (...) {
return encode_error_response(
&req, RpcStatusCode::Internal,
"RPC::Server: internal handler error", options.limits);
}
if (!handler_res.has_value()) {
return encode_error_response(
&req, rpc_status_from_error(handler_res.error()),
handler_res.error().message(), options.limits);
}
WireEnvelope resp;
resp.major = kWireMajorV1;
resp.minor = kWireMinorV1;
resp.kind = FrameKind::UnaryResponse;
resp.flags = kFlagEndOfMessage;
resp.call_id = req.call_id;
resp.method = req.method;
resp.schema_version = desc.schema_version;
resp.status_code = RpcStatusCode::Ok;
resp.payload = std::move(*handler_res);
auto encoded = encode_envelope(resp, options.limits);
if (!encoded.has_value()) {
return encode_error_response(
&req, rpc_status_from_error(encoded.error()),
encoded.error().message(), options.limits);
}
return std::move(*encoded);
}
};
// ── Registration ────────────────────────────────────────────────────────
Registration::~Registration() noexcept { unregister_and_drain(); }
Registration::Registration(Registration&& other) noexcept
: m_server_state(std::move(other.m_server_state)),
m_id(std::exchange(other.m_id, MethodId{})),
m_reg_gen(std::exchange(other.m_reg_gen, 0)),
m_active(std::exchange(other.m_active, false))
{
}
Registration& Registration::operator=(Registration&& other) noexcept
{
if (this != &other) {
unregister_and_drain();
m_server_state = std::move(other.m_server_state);
m_id = std::exchange(other.m_id, MethodId{});
m_reg_gen = std::exchange(other.m_reg_gen, 0);
m_active = std::exchange(other.m_active, false);
}
return *this;
}
bool Registration::active() const noexcept { return m_active; }
void Registration::unregister_and_drain() noexcept
{
if (!m_active) {
return;
}
m_active = false;
auto st =
std::static_pointer_cast<Server::State>(std::move(m_server_state));
if (st) {
st->unregister_and_drain(m_id, m_reg_gen);
}
}
// ── Server ──────────────────────────────────────────────────────────────
Server::Server(ServerOptions options) : m_state(std::make_shared<State>())
{
m_state->options = std::move(options);
if (m_state->options.http_options.max_body_bytes <
m_state->options.limits.max_header_bytes +
m_state->options.limits.max_payload_bytes) {
m_state->options.http_options.max_body_bytes =
m_state->options.limits.max_header_bytes +
m_state->options.limits.max_payload_bytes;
}
}
Server::~Server() noexcept { shutdown(std::chrono::seconds{5}); }
Server::Server(Server&&) noexcept = default;
Server& Server::operator=(Server&&) noexcept = default;
Void::Result::Result<Registration>
Server::bind(MethodDescriptor descriptor, UnaryHandler handler)
{
if (!m_state) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument, "RPC::Server: moved-from")};
}
if (!handler) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument,
"RPC::Server: handler cannot be empty")};
}
if (descriptor.id.service == 0 || descriptor.id.method == 0) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument,
"RPC::Server: service and method IDs must be non-zero")};
}
std::lock_guard lock{m_state->mutex};
if (!m_state->accepting) {
return std::unexpected{make_rpc_error(
RpcStatusCode::FailedPrecondition,
"RPC::Server: cannot bind after shutdown")};
}
if (m_state->methods.contains(descriptor.id)) {
return std::unexpected{make_rpc_error(
RpcStatusCode::FailedPrecondition,
"RPC::Server: method ID already bound")};
}
const std::uint64_t gen = m_state->next_reg_gen++;
auto bm = std::make_shared<State::BoundMethod>();
bm->reg_gen = gen;
bm->desc = std::move(descriptor);
bm->handler = std::move(handler);
const MethodId mid = bm->desc.id;
m_state->methods.emplace(mid, std::move(bm));
Registration reg;
reg.m_server_state = m_state;
reg.m_id = mid;
reg.m_reg_gen = gen;
reg.m_active = true;
return reg;
}
Void::Result::Result<void> Server::mount(Void::Net::HttpServer& http_server)
{
if (!m_state) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument, "RPC::Server: moved-from")};
}
std::weak_ptr<State> weak_state = m_state;
return http_server.add_route(
Void::Net::Method::Post, std::string{kUnaryHttpPath},
[weak_state](const Void::Net::ServerRequest& req)
-> Void::Net::RouteResult {
auto st = weak_state.lock();
if (!st) {
return Void::Net::ServerResponse{
.status = 503, .body = "RPC server unavailable"};
}
const auto req_bytes = std::span<const std::byte>{
reinterpret_cast<const std::byte*>(req.body.data()),
req.body.size()};
auto resp_bytes = st->dispatch_raw(req_bytes, req.headers);
std::string body_str(
reinterpret_cast<const char*>(resp_bytes.data()),
resp_bytes.size());
return Void::Net::ServerResponse{
.status = 200,
.headers = {Void::Net::Header{
"Content-Type", std::string{kWireContentType}}},
.body = std::move(body_str),
};
});
}
Void::Result::Result<void> Server::start()
{
if (!m_state) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument, "RPC::Server: moved-from")};
}
if (m_state->owned_http.has_value() && m_state->owned_http->running()) {
return std::unexpected{make_rpc_error(
RpcStatusCode::FailedPrecondition,
"RPC::Server: already running")};
}
m_state->owned_http.emplace(m_state->options.http_options);
auto mr = mount(*m_state->owned_http);
if (!mr.has_value()) {
m_state->owned_http.reset();
return mr;
}
auto sr = m_state->owned_http->start();
if (!sr.has_value()) {
m_state->owned_http.reset();
return sr;
}
return {};
}
void Server::shutdown(std::chrono::milliseconds drain_timeout) noexcept
{
if (!m_state) {
return;
}
{
std::lock_guard lock{m_state->mutex};
m_state->accepting = false;
for (auto& [id, bm] : m_state->methods) {
(void)id;
bm->accepting = false;
}
}
if (m_state->owned_http.has_value()) {
m_state->owned_http->shutdown(drain_timeout);
}
{
std::unique_lock lock{m_state->mutex};
if (!m_state->drain_cv.wait_for(
lock, drain_timeout,
[&] { return m_state->executing_calls == 0; })) {
m_state->stop_source.request_stop();
m_state->drain_cv.wait(
lock, [&] { return m_state->executing_calls == 0; });
}
m_state->methods.clear();
}
}
bool Server::running() const noexcept
{
return m_state && m_state->owned_http.has_value() &&
m_state->owned_http->running();
}
std::uint16_t Server::bound_port() const noexcept
{
return (m_state && m_state->owned_http.has_value())
? m_state->owned_http->bound_port()
: 0;
}
std::string Server::base_url() const
{
return (m_state && m_state->owned_http.has_value())
? m_state->owned_http->base_url()
: std::string{};
}
Void::Result::Result<OwnedBytes> Server::handle_raw_envelope(
std::span<const std::byte> request_bytes,
const std::vector<Void::Net::Header>& transport_headers)
{
if (!m_state) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument, "RPC::Server: moved-from")};
}
return m_state->dispatch_raw(request_bytes, transport_headers);
}
// ── Client ──────────────────────────────────────────────────────────────
struct Client::State {
ClientOptions options{};
Void::Net::HttpClient http_client{};
std::atomic<std::size_t> in_flight{0};
};
Client::Client(ClientOptions options) : m_state(std::make_shared<State>())
{
while (options.endpoint_base_url.size() > 1U &&
options.endpoint_base_url.back() == '/') {
options.endpoint_base_url.pop_back();
}
options.http_options.max_body_size =
options.limits.max_header_bytes + options.limits.max_payload_bytes;
m_state->http_client = Void::Net::HttpClient{options.http_options};
m_state->options = std::move(options);
}
Client::~Client() noexcept = default;
Client::Client(Client&&) noexcept = default;
Client& Client::operator=(Client&&) noexcept = default;
std::size_t Client::in_flight_calls() const noexcept
{
return m_state ? m_state->in_flight.load(std::memory_order_acquire) : 0;
}
Void::Result::Result<OwnedBytes>
Client::call(MethodId method, OwnedBytes payload,
const CallOptions& options)
{
if (!m_state) {
return std::unexpected{make_rpc_error(
RpcStatusCode::InvalidArgument, "RPC::Client: moved-from")};
}
if (options.stop.stop_requested()) {
return std::unexpected{make_rpc_error(
RpcStatusCode::Cancelled, "RPC::Client: call cancelled")};
}
if (payload.size() > m_state->options.limits.max_payload_bytes) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ResourceExhausted,
"RPC::Client: request payload exceeds max_payload_bytes")};
}
// Acquire client concurrency slot.
std::size_t cur = m_state->in_flight.load(std::memory_order_relaxed);
for (;;) {
if (cur >= m_state->options.limits.max_client_calls) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ResourceExhausted,
"RPC::Client: max_client_calls reached")};
}
if (m_state->in_flight.compare_exchange_weak(
cur, cur + 1U, std::memory_order_acq_rel,
std::memory_order_relaxed)) {
break;
}
}
struct ClientSlot {
std::atomic<std::size_t>* count;
~ClientSlot() noexcept
{
count->fetch_sub(1, std::memory_order_acq_rel);
}
} slot{&m_state->in_flight};
WireEnvelope env;
env.major = kWireMajorV1;
env.minor = kWireMinorV1;
env.kind = FrameKind::UnaryRequest;
env.flags = kFlagEndOfMessage;
env.call_id = CallId::generate();
env.method = method;
env.schema_version = options.schema_version;
const auto ms = std::clamp<long long>(
options.timeout.count(), 0,
static_cast<long long>(std::numeric_limits<std::uint32_t>::max()));
env.remaining_timeout_ms = static_cast<std::uint32_t>(ms);
env.metadata = options.metadata;
env.payload = std::move(payload);
auto encoded = encode_envelope(env, m_state->options.limits);
if (!encoded.has_value()) {
return std::unexpected{std::move(encoded.error())};
}
Void::Net::Request http_req;
http_req.method = Void::Net::Method::Post;
http_req.url =
m_state->options.endpoint_base_url + std::string{kUnaryHttpPath};
http_req.headers = options.transport_headers;
http_req.headers.push_back(Void::Net::Header{
"Content-Type", std::string{kWireContentType}});
http_req.body = std::string(
reinterpret_cast<const char*>(encoded->data()), encoded->size());
http_req.timeout = std::chrono::seconds{
std::max<long long>(1, (options.timeout.count() + 999) / 1000)};
auto http_resp = m_state->http_client.send(http_req);
if (!http_resp.has_value()) {
if (http_resp.error().kind() == Void::Result::ErrorKind::timeout) {
return std::unexpected{make_rpc_error(
RpcStatusCode::DeadlineExceeded,
std::format("RPC::Client: call timed out (remote commit "
"unknown): {}",
http_resp.error().message()))};
}
if (http_resp.error().kind() ==
Void::Result::ErrorKind::cancelled) {
return std::unexpected{make_rpc_error(
RpcStatusCode::Cancelled,
std::format("RPC::Client: call cancelled: {}",
http_resp.error().message()))};
}
return std::unexpected{make_rpc_error(
RpcStatusCode::Unavailable,
std::format("RPC::Client: transport failed: {}",
http_resp.error().message()))};
}
if (http_resp->status != 200) {
return std::unexpected{make_rpc_error(
RpcStatusCode::Unavailable,
std::format("RPC::Client: HTTP transport status {}",
http_resp->status))};
}
const auto resp_span = std::span<const std::byte>{
reinterpret_cast<const std::byte*>(http_resp->body.data()),
http_resp->body.size()};
auto resp_env = decode_envelope(resp_span, m_state->options.limits);
if (!resp_env.has_value()) {
return std::unexpected{std::move(resp_env.error())};
}
if (resp_env->kind != FrameKind::UnaryResponse) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::Client: expected UnaryResponse frame")};
}
if (resp_env->call_id != env.call_id) {
return std::unexpected{make_rpc_error(
RpcStatusCode::ProtocolError,
"RPC::Client: response call_id mismatch")};
}
if (resp_env->status_code != RpcStatusCode::Ok) {
std::string msg = "RPC domain error";
for (const auto& m : resp_env->metadata) {
if (m.key == kErrorMessageMetaKey) {
msg = m.value;
break;
}
}
return std::unexpected{
make_rpc_error(resp_env->status_code, std::move(msg))};
}
return std::move(resp_env->payload);
}
} // namespace Void::RPC