feat(rpc): implement P2 S-RPC-01..03 Wire v1 binary codec and unary HTTP/1.1 RPC subsystem
This commit is contained in:
1 parent
691808eab6
commit
5184d1cf8c
11 files changed
+1778
-1
No files matched your search
@@ -0,0 +1,339 @@
|
||||
#include <Void/RPC/Codec.hpp>
|
||||
#include <Void/Binary/Reader.hpp>
|
||||
#include <Void/Binary/Writer.hpp>
|
||||
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <limits>
|
||||
#include <random>
|
||||
|
||||
namespace Void::RPC
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] bool is_valid_frame_kind(std::uint8_t raw) noexcept
|
||||
{
|
||||
return raw >= static_cast<std::uint8_t>(FrameKind::UnaryRequest) &&
|
||||
raw <= static_cast<std::uint8_t>(FrameKind::StreamTerminal);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_valid_status_code(std::uint16_t raw) noexcept
|
||||
{
|
||||
return raw <=
|
||||
static_cast<std::uint16_t>(RpcStatusCode::IncompatibleVersion);
|
||||
}
|
||||
} // namespace
|
||||
|
||||
CallId CallId::generate()
|
||||
{
|
||||
CallId id;
|
||||
std::random_device rd;
|
||||
for (std::size_t i = 0; i < 16U; i += 4U) {
|
||||
const std::uint32_t v = rd();
|
||||
id.bytes[i + 0] = static_cast<std::byte>((v >> 24U) & 0xFFU);
|
||||
id.bytes[i + 1] = static_cast<std::byte>((v >> 16U) & 0xFFU);
|
||||
id.bytes[i + 2] = static_cast<std::byte>((v >> 8U) & 0xFFU);
|
||||
id.bytes[i + 3] = static_cast<std::byte>(v & 0xFFU);
|
||||
}
|
||||
// Mark UUIDv4 version & RFC 4122 variant bits.
|
||||
id.bytes[6] = (id.bytes[6] & std::byte{0x0F}) | std::byte{0x40};
|
||||
id.bytes[8] = (id.bytes[8] & std::byte{0x3F}) | std::byte{0x80};
|
||||
return id;
|
||||
}
|
||||
|
||||
Void::Result::Result<std::vector<std::byte>>
|
||||
encode_envelope(const WireEnvelope& env, const RpcLimits& limits)
|
||||
{
|
||||
if (env.major != kWireMajorV1) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::IncompatibleVersion,
|
||||
std::format("RPC::encode_envelope: unsupported major {}",
|
||||
env.major))};
|
||||
}
|
||||
if ((env.flags & kFlagRequiredMask) != 0) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::encode_envelope: unsupported required flags")};
|
||||
}
|
||||
if (env.metadata.size() > limits.max_metadata_entries) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ResourceExhausted,
|
||||
"RPC::encode_envelope: metadata count exceeds limit")};
|
||||
}
|
||||
if (env.payload.size() > limits.max_payload_bytes) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ResourceExhausted,
|
||||
"RPC::encode_envelope: payload exceeds limit")};
|
||||
}
|
||||
|
||||
// Compute exact header size with overflow checks.
|
||||
std::uint64_t header_len = kWireFixedHeaderBytes;
|
||||
for (const auto& entry : env.metadata) {
|
||||
if (entry.key.size() > std::numeric_limits<std::uint16_t>::max() ||
|
||||
entry.value.size() > std::numeric_limits<std::uint16_t>::max()) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::InvalidArgument,
|
||||
"RPC::encode_envelope: metadata field exceeds uint16")};
|
||||
}
|
||||
header_len += 4ULL + entry.key.size() + entry.value.size();
|
||||
if (header_len > limits.max_header_bytes) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ResourceExhausted,
|
||||
"RPC::encode_envelope: header size exceeds limit")};
|
||||
}
|
||||
}
|
||||
|
||||
const std::uint64_t total_len = header_len + env.payload.size();
|
||||
if (total_len > std::numeric_limits<std::uint32_t>::max()) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ResourceExhausted,
|
||||
"RPC::encode_envelope: total frame exceeds uint32")};
|
||||
}
|
||||
|
||||
std::vector<std::byte> out(static_cast<std::size_t>(total_len));
|
||||
Void::Binary::Writer w{out};
|
||||
|
||||
auto check = [](Void::Result::Result<void> r) -> bool {
|
||||
return r.has_value();
|
||||
};
|
||||
const bool ok =
|
||||
check(w.writeBytes(kWireMagic)) &&
|
||||
check(w.writeBig<std::uint16_t>(env.major)) &&
|
||||
check(w.writeBig<std::uint16_t>(env.minor)) &&
|
||||
check(w.writeBig<std::uint32_t>(
|
||||
static_cast<std::uint32_t>(header_len))) &&
|
||||
check(w.writeBig<std::uint32_t>(
|
||||
static_cast<std::uint32_t>(total_len))) &&
|
||||
check(w.writeBig<std::uint8_t>(
|
||||
static_cast<std::uint8_t>(env.kind))) &&
|
||||
check(w.writeBig<std::uint8_t>(env.flags)) &&
|
||||
check(w.writeBig<std::uint16_t>(0U)) && // reserved = 0
|
||||
check(w.writeBytes(env.call_id.bytes)) &&
|
||||
check(w.writeBig<std::uint64_t>(env.method.service)) &&
|
||||
check(w.writeBig<std::uint32_t>(env.method.method)) &&
|
||||
check(w.writeBig<std::uint32_t>(env.schema_version)) &&
|
||||
check(w.writeBig<std::uint32_t>(env.remaining_timeout_ms)) &&
|
||||
check(w.writeBig<std::uint16_t>(
|
||||
static_cast<std::uint16_t>(env.status_code))) &&
|
||||
check(w.writeBig<std::uint16_t>(
|
||||
static_cast<std::uint16_t>(env.metadata.size())));
|
||||
if (!ok) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::Internal,
|
||||
"RPC::encode_envelope: header write failure")};
|
||||
}
|
||||
|
||||
for (const auto& entry : env.metadata) {
|
||||
if (!w.writeBig<std::uint16_t>(
|
||||
static_cast<std::uint16_t>(entry.key.size()))
|
||||
.has_value() ||
|
||||
!w.writeBytes(
|
||||
std::span<const std::byte>{
|
||||
reinterpret_cast<const std::byte*>(entry.key.data()),
|
||||
entry.key.size()})
|
||||
.has_value() ||
|
||||
!w.writeBig<std::uint16_t>(
|
||||
static_cast<std::uint16_t>(entry.value.size()))
|
||||
.has_value() ||
|
||||
!w.writeBytes(
|
||||
std::span<const std::byte>{
|
||||
reinterpret_cast<const std::byte*>(
|
||||
entry.value.data()),
|
||||
entry.value.size()})
|
||||
.has_value()) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::Internal,
|
||||
"RPC::encode_envelope: metadata write failure")};
|
||||
}
|
||||
}
|
||||
|
||||
if (!env.payload.empty() && !w.writeBytes(env.payload).has_value()) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::Internal,
|
||||
"RPC::encode_envelope: payload write failure")};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
Void::Result::Result<WireEnvelope>
|
||||
decode_envelope(std::span<const std::byte> bytes,
|
||||
const RpcLimits& limits)
|
||||
{
|
||||
if (bytes.size() < kWireFixedHeaderBytes) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: truncated fixed header")};
|
||||
}
|
||||
|
||||
Void::Binary::Reader r{bytes};
|
||||
auto magic = r.readBytes(4U);
|
||||
if (!magic.has_value() ||
|
||||
std::memcmp(magic->data(), kWireMagic.data(), 4U) != 0) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: invalid VRPC magic")};
|
||||
}
|
||||
|
||||
auto major = r.readBig<std::uint16_t>();
|
||||
auto minor = r.readBig<std::uint16_t>();
|
||||
auto header_len = r.readBig<std::uint32_t>();
|
||||
auto total_len = r.readBig<std::uint32_t>();
|
||||
auto raw_kind = r.readBig<std::uint8_t>();
|
||||
auto flags = r.readBig<std::uint8_t>();
|
||||
auto reserved = r.readBig<std::uint16_t>();
|
||||
auto call_id_bytes = r.readBytes(16U);
|
||||
auto service_id = r.readBig<std::uint64_t>();
|
||||
auto method_id = r.readBig<std::uint32_t>();
|
||||
auto schema_ver = r.readBig<std::uint32_t>();
|
||||
auto timeout_ms = r.readBig<std::uint32_t>();
|
||||
auto raw_status = r.readBig<std::uint16_t>();
|
||||
auto meta_count = r.readBig<std::uint16_t>();
|
||||
|
||||
if (!major || !minor || !header_len || !total_len || !raw_kind ||
|
||||
!flags || !reserved || !call_id_bytes || !service_id ||
|
||||
!method_id || !schema_ver || !timeout_ms || !raw_status ||
|
||||
!meta_count) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: truncated header fields")};
|
||||
}
|
||||
|
||||
if (*major != kWireMajorV1) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::IncompatibleVersion,
|
||||
std::format("RPC::decode_envelope: unsupported wire major {}",
|
||||
*major))};
|
||||
}
|
||||
if (*reserved != 0U) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: non-zero reserved header field")};
|
||||
}
|
||||
if ((*flags & kFlagRequiredMask) != 0U) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::IncompatibleVersion,
|
||||
"RPC::decode_envelope: unknown required frame flag")};
|
||||
}
|
||||
if (!is_valid_frame_kind(*raw_kind)) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: invalid frame kind")};
|
||||
}
|
||||
if (!is_valid_status_code(*raw_status)) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: invalid status code")};
|
||||
}
|
||||
|
||||
// Validate lengths & overflow BEFORE subtracting or allocating!
|
||||
if (*header_len < kWireFixedHeaderBytes) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: header_length smaller than fixed "
|
||||
"header")};
|
||||
}
|
||||
if (*header_len > limits.max_header_bytes) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ResourceExhausted,
|
||||
"RPC::decode_envelope: header_length exceeds limit")};
|
||||
}
|
||||
if (*total_len < *header_len) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: total_length smaller than "
|
||||
"header_length")};
|
||||
}
|
||||
if (*total_len != bytes.size()) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: frame length mismatch")};
|
||||
}
|
||||
const std::size_t payload_len =
|
||||
static_cast<std::size_t>(*total_len) -
|
||||
static_cast<std::size_t>(*header_len);
|
||||
if (payload_len > limits.max_payload_bytes) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ResourceExhausted,
|
||||
"RPC::decode_envelope: payload exceeds limit")};
|
||||
}
|
||||
if (*meta_count > limits.max_metadata_entries) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ResourceExhausted,
|
||||
"RPC::decode_envelope: metadata count exceeds limit")};
|
||||
}
|
||||
|
||||
WireEnvelope env;
|
||||
env.major = *major;
|
||||
env.minor = *minor;
|
||||
env.kind = static_cast<FrameKind>(*raw_kind);
|
||||
env.flags = *flags;
|
||||
std::memcpy(env.call_id.bytes.data(), call_id_bytes->data(), 16U);
|
||||
env.method = MethodId{*service_id, *method_id};
|
||||
env.schema_version = *schema_ver;
|
||||
env.remaining_timeout_ms = *timeout_ms;
|
||||
env.status_code = static_cast<RpcStatusCode>(*raw_status);
|
||||
|
||||
env.metadata.reserve(*meta_count);
|
||||
for (std::uint16_t i = 0; i < *meta_count; ++i) {
|
||||
if (r.position() + 2U > *header_len) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: metadata overruns header_length")};
|
||||
}
|
||||
auto klen = r.readBig<std::uint16_t>();
|
||||
if (!klen || r.position() + *klen + 2U > *header_len) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: metadata key overruns header")};
|
||||
}
|
||||
auto kbytes = r.readBytes(*klen);
|
||||
auto vlen = r.readBig<std::uint16_t>();
|
||||
if (!kbytes || !vlen || r.position() + *vlen > *header_len) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: metadata value overruns header")};
|
||||
}
|
||||
auto vbytes = r.readBytes(*vlen);
|
||||
if (!vbytes) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: truncated metadata value")};
|
||||
}
|
||||
env.metadata.push_back(MetadataEntry{
|
||||
.key = std::string{
|
||||
reinterpret_cast<const char*>(kbytes->data()),
|
||||
kbytes->size()},
|
||||
.value = std::string{
|
||||
reinterpret_cast<const char*>(vbytes->data()),
|
||||
vbytes->size()},
|
||||
});
|
||||
}
|
||||
|
||||
// Minor-version optional header extensions (if minor > 0) are
|
||||
// length-skippable up to `header_len`; reject unexpected bytes on
|
||||
// minor == 0.
|
||||
if (r.position() < *header_len) {
|
||||
if (*minor == 0U) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: unexpected trailing header bytes "
|
||||
"for minor 0")};
|
||||
}
|
||||
if (!r.seek(*header_len).has_value()) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: failed to skip minor extension")};
|
||||
}
|
||||
}
|
||||
|
||||
auto pay = r.readBytes(payload_len);
|
||||
if (!pay.has_value()) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::ProtocolError,
|
||||
"RPC::decode_envelope: truncated payload")};
|
||||
}
|
||||
env.payload.assign(pay->begin(), pay->end());
|
||||
return env;
|
||||
}
|
||||
|
||||
} // namespace Void::RPC
|
||||
+652
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(RPC
|
||||
INTERNAL_DEPS Core Functional Binary Data Time Async Net
|
||||
)
|
||||
Reference in new issue
Block a user