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
@@ -188,7 +188,7 @@ public:
|
||||
return std::unexpected{bytes.error()};
|
||||
}
|
||||
std::array<std::byte, sizeof(T)> storage{};
|
||||
std::ranges::copy(*bytes, storage.begin());
|
||||
std::memcpy(storage.data(), bytes->data(), sizeof(T));
|
||||
T value = std::bit_cast<T>(storage);
|
||||
if (byteOrder != std::endian::native) {
|
||||
value = std::byteswap(value);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/RPC/Types.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::RPC
|
||||
{
|
||||
/// Decoded Wire v1 envelope (deterministic big-endian binary format).
|
||||
struct WireEnvelope {
|
||||
std::uint16_t major{kWireMajorV1};
|
||||
std::uint16_t minor{kWireMinorV1};
|
||||
FrameKind kind{FrameKind::UnaryRequest};
|
||||
std::uint8_t flags{kFlagEndOfMessage};
|
||||
CallId call_id{};
|
||||
MethodId method{};
|
||||
std::uint32_t schema_version{1};
|
||||
std::uint32_t remaining_timeout_ms{0};
|
||||
RpcStatusCode status_code{RpcStatusCode::Ok};
|
||||
std::vector<MetadataEntry> metadata{};
|
||||
std::vector<std::byte> payload{};
|
||||
};
|
||||
|
||||
/// Fixed Wire v1 header prefix size in bytes before metadata entries:
|
||||
/// magic(4) + major(2) + minor(2) + header_len(4) + total_len(4) +
|
||||
/// kind(1) + flags(1) + reserved(2) + call_id(16) + service_id(8) +
|
||||
/// method_id(4) + schema_ver(4) + timeout_ms(4) + status_code(2) +
|
||||
/// metadata_count(2) = 60 bytes.
|
||||
inline constexpr std::size_t kWireFixedHeaderBytes{60};
|
||||
|
||||
/// Encode a Wire v1 envelope in explicit network byte order, validating
|
||||
/// all header, metadata, and payload limits before allocation.
|
||||
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
|
||||
encode_envelope(const WireEnvelope& env,
|
||||
const RpcLimits& limits = {});
|
||||
|
||||
/// Decode a Wire v1 envelope in explicit network byte order. Rejects bad
|
||||
/// magic, unsupported major versions, non-zero reserved bytes, unknown
|
||||
/// required flags, integer overflow, truncation, trailing garbage, and
|
||||
/// limit violations BEFORE allocating payload/metadata buffers. Unknown
|
||||
/// optional minor header extensions beyond metadata are length-skipped.
|
||||
[[nodiscard]] Void::Result::Result<WireEnvelope>
|
||||
decode_envelope(std::span<const std::byte> bytes,
|
||||
const RpcLimits& limits = {});
|
||||
|
||||
} // namespace Void::RPC
|
||||
@@ -0,0 +1,184 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/Net/HttpServer.hpp>
|
||||
#include <Void/RPC/Codec.hpp>
|
||||
#include <Void/RPC/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::RPC
|
||||
{
|
||||
using OwnedBytes = std::vector<std::byte>;
|
||||
|
||||
struct CallContext {
|
||||
CallId call_id{};
|
||||
MethodDescriptor method{};
|
||||
PrincipalView principal{};
|
||||
Void::Time::MonotonicClock::time_point deadline{};
|
||||
const Void::Time::MonotonicClock* clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
std::vector<MetadataEntry> metadata{};
|
||||
std::stop_token stop{};
|
||||
|
||||
[[nodiscard]] std::chrono::milliseconds
|
||||
remaining_timeout() const noexcept
|
||||
{
|
||||
const auto rem = Void::Time::remaining_until(*clock, deadline);
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
rem);
|
||||
}
|
||||
};
|
||||
|
||||
struct CallOptions {
|
||||
std::chrono::milliseconds timeout{std::chrono::seconds{10}};
|
||||
std::vector<MetadataEntry> metadata{};
|
||||
std::vector<Void::Net::Header> transport_headers{};
|
||||
std::stop_token stop{};
|
||||
std::uint32_t schema_version{1};
|
||||
};
|
||||
|
||||
using UnaryHandler =
|
||||
std::function<Void::Result::Result<OwnedBytes>(const CallContext&,
|
||||
OwnedBytes)>;
|
||||
|
||||
struct AuthHook {
|
||||
std::function<Void::Result::Result<PrincipalView>(
|
||||
const std::vector<Void::Net::Header>& transport_headers,
|
||||
const std::vector<MetadataEntry>& metadata)>
|
||||
authenticate{};
|
||||
|
||||
std::function<Void::Result::Result<void>(
|
||||
const MethodDescriptor& method, const PrincipalView& principal)>
|
||||
authorize{};
|
||||
};
|
||||
|
||||
/// Move-only RAII method registration handle. Unregistering stops new
|
||||
/// admission for the method and drains already-admitted calls before
|
||||
/// returning.
|
||||
class Registration final
|
||||
{
|
||||
public:
|
||||
|
||||
Registration() noexcept = default;
|
||||
~Registration() noexcept;
|
||||
|
||||
Registration(Registration&& other) noexcept;
|
||||
Registration& operator=(Registration&& other) noexcept;
|
||||
Registration(const Registration&) = delete;
|
||||
Registration& operator=(const Registration&) = delete;
|
||||
|
||||
[[nodiscard]] bool active() const noexcept;
|
||||
void unregister_and_drain() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
friend class Server;
|
||||
struct Entry;
|
||||
std::shared_ptr<void> m_server_state{};
|
||||
MethodId m_id{};
|
||||
std::uint64_t m_reg_gen{0};
|
||||
bool m_active{false};
|
||||
};
|
||||
|
||||
struct ServerOptions {
|
||||
Void::Net::HttpServerOptions http_options{};
|
||||
RpcLimits limits{};
|
||||
AuthHook auth{};
|
||||
const Void::Time::MonotonicClock* clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
};
|
||||
|
||||
/// Ownership-safe unary HTTP/1.1 RPC server implementing `/void-rpc/v1/call`.
|
||||
class Server final
|
||||
{
|
||||
public:
|
||||
|
||||
explicit Server(ServerOptions options = {});
|
||||
~Server() noexcept;
|
||||
|
||||
Server(Server&&) noexcept;
|
||||
Server& operator=(Server&&) noexcept;
|
||||
Server(const Server&) = delete;
|
||||
Server& operator=(const Server&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<Registration>
|
||||
bind(MethodDescriptor descriptor, UnaryHandler handler);
|
||||
|
||||
/// Mount `/void-rpc/v1/call` onto an external HttpServer (or call
|
||||
/// `start()` to run the owned HttpServer directly).
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
mount(Void::Net::HttpServer& http_server);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> start();
|
||||
|
||||
void shutdown(std::chrono::milliseconds drain_timeout =
|
||||
std::chrono::seconds{10}) noexcept;
|
||||
|
||||
[[nodiscard]] bool running() const noexcept;
|
||||
[[nodiscard]] std::uint16_t bound_port() const noexcept;
|
||||
[[nodiscard]] std::string base_url() const;
|
||||
|
||||
/// Direct in-process Wire v1 dispatch (useful for deterministic
|
||||
/// unit/fault testing without TCP sockets).
|
||||
[[nodiscard]] Void::Result::Result<OwnedBytes>
|
||||
handle_raw_envelope(
|
||||
std::span<const std::byte> request_bytes,
|
||||
const std::vector<Void::Net::Header>& transport_headers =
|
||||
{});
|
||||
|
||||
private:
|
||||
|
||||
friend class Registration;
|
||||
struct State;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
struct ClientOptions {
|
||||
std::string endpoint_base_url{};
|
||||
Void::Net::HttpClientOptions http_options{
|
||||
.verify_tls = true,
|
||||
};
|
||||
RpcLimits limits{};
|
||||
const Void::Time::MonotonicClock* clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
};
|
||||
|
||||
/// Unary HTTP/1.1 RPC client encoding Wire v1 envelopes over
|
||||
/// `Void::Net::HttpClient`.
|
||||
class Client final
|
||||
{
|
||||
public:
|
||||
|
||||
explicit Client(ClientOptions options);
|
||||
~Client() noexcept;
|
||||
|
||||
Client(Client&&) noexcept;
|
||||
Client& operator=(Client&&) noexcept;
|
||||
Client(const Client&) = delete;
|
||||
Client& operator=(const Client&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<OwnedBytes>
|
||||
call(MethodId method, OwnedBytes payload,
|
||||
const CallOptions& options = {});
|
||||
|
||||
[[nodiscard]] std::size_t in_flight_calls() const noexcept;
|
||||
|
||||
private:
|
||||
|
||||
struct State;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
} // namespace Void::RPC
|
||||
@@ -0,0 +1,205 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <chrono>
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::RPC
|
||||
{
|
||||
inline constexpr std::array<std::byte, 4> kWireMagic{
|
||||
std::byte{'V'}, std::byte{'R'}, std::byte{'P'}, std::byte{'C'}};
|
||||
inline constexpr std::uint16_t kWireMajorV1{1};
|
||||
inline constexpr std::uint16_t kWireMinorV1{0};
|
||||
inline constexpr std::string_view kUnaryHttpPath{"/void-rpc/v1/call"};
|
||||
inline constexpr std::string_view kWireContentType{
|
||||
"application/vnd.void.rpc.v1"};
|
||||
|
||||
enum class RpcStatusCode : std::uint16_t {
|
||||
Ok = 0,
|
||||
Cancelled = 1,
|
||||
InvalidArgument = 2,
|
||||
DeadlineExceeded = 3,
|
||||
NotFound = 4,
|
||||
PermissionDenied = 5,
|
||||
Unauthenticated = 6,
|
||||
ResourceExhausted = 7,
|
||||
FailedPrecondition = 8,
|
||||
Unimplemented = 9,
|
||||
Unavailable = 10,
|
||||
Internal = 11,
|
||||
DataLoss = 12,
|
||||
UnknownOutcome = 13,
|
||||
ProtocolError = 14,
|
||||
IncompatibleVersion = 15,
|
||||
};
|
||||
|
||||
enum class FrameKind : std::uint8_t {
|
||||
UnaryRequest = 1,
|
||||
UnaryResponse = 2,
|
||||
StreamOpen = 3,
|
||||
StreamData = 4,
|
||||
StreamCredit = 5,
|
||||
StreamHalfClose = 6,
|
||||
StreamCancel = 7,
|
||||
StreamTerminal = 8,
|
||||
};
|
||||
|
||||
/// Wire v1 frame flags. Bits 0..3 are optional/informational; bits 4..7 are
|
||||
/// required-to-understand (unknown required flags fail closed).
|
||||
inline constexpr std::uint8_t kFlagNone = 0x00U;
|
||||
inline constexpr std::uint8_t kFlagEndOfMessage = 0x01U;
|
||||
inline constexpr std::uint8_t kFlagRequiredMask = 0xF0U;
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_rpc_error(RpcStatusCode code, std::string message)
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case RpcStatusCode::Ok:
|
||||
case RpcStatusCode::Internal:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case RpcStatusCode::Cancelled:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case RpcStatusCode::InvalidArgument:
|
||||
case RpcStatusCode::PermissionDenied:
|
||||
case RpcStatusCode::Unauthenticated:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case RpcStatusCode::DeadlineExceeded:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case RpcStatusCode::NotFound:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case RpcStatusCode::ResourceExhausted:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case RpcStatusCode::FailedPrecondition:
|
||||
case RpcStatusCode::UnknownOutcome:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case RpcStatusCode::Unimplemented:
|
||||
case RpcStatusCode::IncompatibleVersion:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case RpcStatusCode::Unavailable:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case RpcStatusCode::DataLoss:
|
||||
case RpcStatusCode::ProtocolError:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
}
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kRpcErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
[[nodiscard]] inline RpcStatusCode
|
||||
rpc_status_from_error(const Void::Result::Error& err) noexcept
|
||||
{
|
||||
if (err.code().domain == Void::Result::kRpcErrorDomain) {
|
||||
return static_cast<RpcStatusCode>(err.code().value);
|
||||
}
|
||||
switch (err.kind()) {
|
||||
case Void::Result::ErrorKind::cancelled:
|
||||
return RpcStatusCode::Cancelled;
|
||||
case Void::Result::ErrorKind::invalid_argument:
|
||||
return RpcStatusCode::InvalidArgument;
|
||||
case Void::Result::ErrorKind::timeout:
|
||||
return RpcStatusCode::DeadlineExceeded;
|
||||
case Void::Result::ErrorKind::not_found:
|
||||
return RpcStatusCode::NotFound;
|
||||
case Void::Result::ErrorKind::exhausted:
|
||||
return RpcStatusCode::ResourceExhausted;
|
||||
case Void::Result::ErrorKind::conflict:
|
||||
return RpcStatusCode::FailedPrecondition;
|
||||
case Void::Result::ErrorKind::unsupported:
|
||||
return RpcStatusCode::Unimplemented;
|
||||
case Void::Result::ErrorKind::overloaded:
|
||||
return RpcStatusCode::Unavailable;
|
||||
case Void::Result::ErrorKind::corrupt:
|
||||
return RpcStatusCode::ProtocolError;
|
||||
default:
|
||||
return RpcStatusCode::Internal;
|
||||
}
|
||||
}
|
||||
|
||||
struct MethodId {
|
||||
std::uint64_t service{0};
|
||||
std::uint32_t method{0};
|
||||
|
||||
[[nodiscard]] auto
|
||||
operator<=>(const MethodId&) const noexcept = default;
|
||||
};
|
||||
|
||||
struct CallId {
|
||||
std::array<std::byte, 16> bytes{};
|
||||
|
||||
[[nodiscard]] auto
|
||||
operator<=>(const CallId&) const noexcept = default;
|
||||
|
||||
[[nodiscard]] static CallId generate();
|
||||
};
|
||||
|
||||
struct MetadataEntry {
|
||||
std::string key{};
|
||||
std::string value{};
|
||||
|
||||
[[nodiscard]] bool
|
||||
operator==(const MetadataEntry&) const noexcept = default;
|
||||
};
|
||||
|
||||
/// Immutable authenticated principal descriptor provided by AuthHook.
|
||||
struct PrincipalView {
|
||||
bool authenticated{false};
|
||||
std::string subject{};
|
||||
std::vector<std::string> roles{};
|
||||
std::map<std::string, std::string, std::less<>> attributes{};
|
||||
};
|
||||
|
||||
struct MethodDescriptor {
|
||||
MethodId id{};
|
||||
std::string service_name{};
|
||||
std::string method_name{};
|
||||
std::uint32_t schema_version{1};
|
||||
bool replay_safe{false};
|
||||
};
|
||||
|
||||
struct RpcLimits {
|
||||
std::size_t max_header_bytes{16ULL * 1024};
|
||||
std::size_t max_metadata_entries{64};
|
||||
std::size_t max_payload_bytes{4ULL * 1024 * 1024};
|
||||
std::size_t max_client_calls{1024};
|
||||
std::size_t max_server_executing{256};
|
||||
std::size_t max_server_queued_bytes{64ULL * 1024 * 1024};
|
||||
std::chrono::milliseconds max_server_timeout{
|
||||
std::chrono::seconds{30}};
|
||||
};
|
||||
|
||||
struct RpcStatus {
|
||||
RpcStatusCode code{RpcStatusCode::Ok};
|
||||
std::string message{};
|
||||
|
||||
[[nodiscard]] bool ok() const noexcept
|
||||
{
|
||||
return code == RpcStatusCode::Ok;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::RPC
|
||||
@@ -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
|
||||
)
|
||||
@@ -305,6 +305,19 @@ if(_has_testing_mock)
|
||||
run_consumer(TestingMockOnly "${install_prefix}" "TestingMockOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
has_modules(_has_short_url ShortUrl Service Time Functional)
|
||||
if(_has_short_url)
|
||||
run_consumer(ShortUrlOnly "${install_prefix}" "ShortUrlOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
has_modules(_has_rpc RPC Net Binary Data Time Async Functional Core)
|
||||
if(_has_rpc)
|
||||
run_consumer(RpcOnly "${install_prefix}" "RpcOnly"
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE
|
||||
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
|
||||
endif()
|
||||
|
||||
# Foundation consumer with Core-formatting bridge and zero external packages.
|
||||
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
|
||||
if(_has_foundation)
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidRpcOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void CONFIG REQUIRED COMPONENTS RPC)
|
||||
|
||||
add_executable(rpc_only_consumer main.cpp)
|
||||
target_link_libraries(rpc_only_consumer PRIVATE Void::RPC)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME rpc_only_consumer COMMAND rpc_only_consumer)
|
||||
@@ -0,0 +1,26 @@
|
||||
#include <Void/RPC/Codec.hpp>
|
||||
#include <Void/RPC/Rpc.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
|
||||
int main()
|
||||
{
|
||||
using namespace Void::RPC;
|
||||
Server server;
|
||||
constexpr MethodId kPing{1, 1};
|
||||
auto reg = server.bind(
|
||||
MethodDescriptor{kPing, "sys", "ping", 1, true},
|
||||
[](const CallContext&, OwnedBytes body) { return Void::Result::ok(body); });
|
||||
if (!reg.has_value() || !server.start().has_value()) {
|
||||
return 1;
|
||||
}
|
||||
Client client{ClientOptions{.endpoint_base_url = server.base_url()}};
|
||||
OwnedBytes payload{std::byte{'o'}, std::byte{'k'}};
|
||||
auto resp = client.call(kPing, payload);
|
||||
server.shutdown();
|
||||
if (!resp.has_value() || resp->size() != 2 || (*resp)[0] != std::byte{'o'}) {
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
#include <Void/RPC/Codec.hpp>
|
||||
#include <Void/RPC/Rpc.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
Void::RPC::OwnedBytes to_bytes(std::string_view s)
|
||||
{
|
||||
Void::RPC::OwnedBytes out(s.size());
|
||||
if (!s.empty()) {
|
||||
std::memcpy(out.data(), s.data(), s.size());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string from_bytes(const Void::RPC::OwnedBytes& b)
|
||||
{
|
||||
return std::string(reinterpret_cast<const char*>(b.data()), b.size());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test rpc_wire_v1_codec_roundtrip_and_malformed_rejection()
|
||||
{
|
||||
using namespace Void::RPC;
|
||||
|
||||
WireEnvelope env;
|
||||
env.kind = FrameKind::UnaryRequest;
|
||||
env.call_id = CallId::generate();
|
||||
env.method = MethodId{0x0102030405060708ULL, 42U};
|
||||
env.schema_version = 3U;
|
||||
env.remaining_timeout_ms = 5000U;
|
||||
env.metadata = {{"trace-id", "t-123"}, {"tenant", "alpha"}};
|
||||
env.payload = to_bytes("hello-vrpc");
|
||||
|
||||
auto encoded = encode_envelope(env);
|
||||
Void::Testing::require(encoded.has_value());
|
||||
Void::Testing::expect(encoded->size() >= kWireFixedHeaderBytes);
|
||||
|
||||
auto decoded = decode_envelope(*encoded);
|
||||
Void::Testing::require(decoded.has_value());
|
||||
Void::Testing::expect(decoded->call_id == env.call_id);
|
||||
Void::Testing::expect(decoded->method == env.method);
|
||||
Void::Testing::expect_eq(decoded->schema_version, 3U);
|
||||
Void::Testing::expect_eq(decoded->remaining_timeout_ms, 5000U);
|
||||
Void::Testing::expect(decoded->metadata == env.metadata);
|
||||
Void::Testing::expect_eq(from_bytes(decoded->payload),
|
||||
std::string{"hello-vrpc"});
|
||||
|
||||
// 1. Bad magic rejected.
|
||||
auto bad_magic = *encoded;
|
||||
bad_magic[0] = std::byte{'X'};
|
||||
Void::Testing::expect(!decode_envelope(bad_magic).has_value());
|
||||
|
||||
// 2. Unknown major version rejected with IncompatibleVersion.
|
||||
auto bad_major = *encoded;
|
||||
bad_major[4] = std::byte{0};
|
||||
bad_major[5] = std::byte{2};
|
||||
auto r_maj = decode_envelope(bad_major);
|
||||
Void::Testing::expect(!r_maj.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_maj.error()) ==
|
||||
RpcStatusCode::IncompatibleVersion);
|
||||
|
||||
// 3. Non-zero reserved bytes rejected.
|
||||
auto bad_res = *encoded;
|
||||
bad_res[18] = std::byte{0x01};
|
||||
Void::Testing::expect(!decode_envelope(bad_res).has_value());
|
||||
|
||||
// 4. Unknown required flag fails closed.
|
||||
auto bad_flag = *encoded;
|
||||
bad_flag[17] = std::byte{0x10};
|
||||
auto r_flag = decode_envelope(bad_flag);
|
||||
Void::Testing::expect(!r_flag.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_flag.error()) ==
|
||||
RpcStatusCode::IncompatibleVersion);
|
||||
|
||||
// 5. Truncated frame rejected.
|
||||
auto trunc = *encoded;
|
||||
trunc.pop_back();
|
||||
Void::Testing::expect(!decode_envelope(trunc).has_value());
|
||||
|
||||
// 6. Oversized payload limit rejected before allocation.
|
||||
RpcLimits tiny;
|
||||
tiny.max_payload_bytes = 4;
|
||||
auto r_big = decode_envelope(*encoded, tiny);
|
||||
Void::Testing::expect(!r_big.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_big.error()) ==
|
||||
RpcStatusCode::ResourceExhausted);
|
||||
|
||||
// 7. Minor > 0 optional trailing header extension is length-skippable!
|
||||
auto minor_ext = *encoded;
|
||||
// Bump minor = 1, header_len += 4, total_len += 4, insert 4 extension bytes
|
||||
// right before payload.
|
||||
const std::size_t orig_hdr_len = encoded->size() - env.payload.size();
|
||||
minor_ext[7] = std::byte{1};
|
||||
const std::uint32_t new_hdr_len = static_cast<std::uint32_t>(orig_hdr_len + 4U);
|
||||
const std::uint32_t new_tot_len = static_cast<std::uint32_t>(encoded->size() + 4U);
|
||||
minor_ext[8] = static_cast<std::byte>((new_hdr_len >> 24U) & 0xFFU);
|
||||
minor_ext[9] = static_cast<std::byte>((new_hdr_len >> 16U) & 0xFFU);
|
||||
minor_ext[10] = static_cast<std::byte>((new_hdr_len >> 8U) & 0xFFU);
|
||||
minor_ext[11] = static_cast<std::byte>(new_hdr_len & 0xFFU);
|
||||
minor_ext[12] = static_cast<std::byte>((new_tot_len >> 24U) & 0xFFU);
|
||||
minor_ext[13] = static_cast<std::byte>((new_tot_len >> 16U) & 0xFFU);
|
||||
minor_ext[14] = static_cast<std::byte>((new_tot_len >> 8U) & 0xFFU);
|
||||
minor_ext[15] = static_cast<std::byte>(new_tot_len & 0xFFU);
|
||||
const std::array<std::byte, 4> ext_bytes{
|
||||
std::byte{0xAA}, std::byte{0xBB}, std::byte{0xCC}, std::byte{0xDD}};
|
||||
minor_ext.insert(
|
||||
minor_ext.begin() + static_cast<std::ptrdiff_t>(orig_hdr_len),
|
||||
ext_bytes.begin(), ext_bytes.end());
|
||||
auto dec_minor = decode_envelope(minor_ext);
|
||||
Void::Testing::require(dec_minor.has_value());
|
||||
Void::Testing::expect_eq(dec_minor->minor, std::uint16_t{1});
|
||||
Void::Testing::expect_eq(from_bytes(dec_minor->payload),
|
||||
std::string{"hello-vrpc"});
|
||||
}
|
||||
|
||||
Void::Testing::Test rpc_unary_http_dispatch_auth_schema_clamp_and_unregister_drain()
|
||||
{
|
||||
using namespace Void::RPC;
|
||||
|
||||
static constexpr MethodId kEcho{100, 1};
|
||||
static constexpr MethodId kThrow{100, 2};
|
||||
static constexpr MethodId kSlow{100, 3};
|
||||
|
||||
ServerOptions sopts;
|
||||
sopts.limits.max_server_timeout = std::chrono::seconds{5};
|
||||
sopts.auth.authenticate =
|
||||
[](const std::vector<Void::Net::Header>& hdrs,
|
||||
const std::vector<MetadataEntry>&)
|
||||
-> Void::Result::Result<PrincipalView> {
|
||||
for (const auto& h : hdrs) {
|
||||
if (h.name == "X-Test-Token" && h.value == "valid-admin") {
|
||||
return PrincipalView{
|
||||
.authenticated = true,
|
||||
.subject = "alice",
|
||||
.roles = {"admin"},
|
||||
};
|
||||
}
|
||||
if (h.name == "X-Test-Token" && h.value == "valid-guest") {
|
||||
return PrincipalView{
|
||||
.authenticated = true,
|
||||
.subject = "bob",
|
||||
.roles = {"guest"},
|
||||
};
|
||||
}
|
||||
}
|
||||
return std::unexpected{
|
||||
make_rpc_error(RpcStatusCode::Unauthenticated, "missing token")};
|
||||
};
|
||||
sopts.auth.authorize = [](const MethodDescriptor& m,
|
||||
const PrincipalView& p)
|
||||
-> Void::Result::Result<void> {
|
||||
if (m.id == kThrow &&
|
||||
std::find(p.roles.begin(), p.roles.end(), "admin") ==
|
||||
p.roles.end()) {
|
||||
return std::unexpected{make_rpc_error(
|
||||
RpcStatusCode::PermissionDenied, "admin role required")};
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
Server server{std::move(sopts)};
|
||||
|
||||
std::atomic<long long> observed_timeout_ms{0};
|
||||
auto reg_echo = server.bind(
|
||||
MethodDescriptor{kEcho, "demo", "echo", 2, true},
|
||||
[&](const CallContext& ctx, OwnedBytes body)
|
||||
-> Void::Result::Result<OwnedBytes> {
|
||||
observed_timeout_ms.store(ctx.remaining_timeout().count(),
|
||||
std::memory_order_release);
|
||||
return to_bytes(ctx.principal.subject + ":" + from_bytes(body));
|
||||
});
|
||||
Void::Testing::require(reg_echo.has_value());
|
||||
|
||||
auto reg_throw = server.bind(
|
||||
MethodDescriptor{kThrow, "demo", "throw", 1, false},
|
||||
[](const CallContext&, OwnedBytes) -> Void::Result::Result<OwnedBytes> {
|
||||
throw std::runtime_error("sensitive-internal-secret");
|
||||
});
|
||||
Void::Testing::require(reg_throw.has_value());
|
||||
|
||||
std::atomic<bool> slow_entered{false};
|
||||
std::atomic<bool> slow_release{false};
|
||||
std::atomic<bool> slow_finished{false};
|
||||
auto reg_slow = server.bind(
|
||||
MethodDescriptor{kSlow, "demo", "slow", 1, false},
|
||||
[&](const CallContext&, OwnedBytes body)
|
||||
-> Void::Result::Result<OwnedBytes> {
|
||||
slow_entered.store(true, std::memory_order_release);
|
||||
while (!slow_release.load(std::memory_order_acquire)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
}
|
||||
slow_finished.store(true, std::memory_order_release);
|
||||
return body;
|
||||
});
|
||||
Void::Testing::require(reg_slow.has_value());
|
||||
|
||||
Void::Testing::require(server.start().has_value());
|
||||
|
||||
ClientOptions copts;
|
||||
copts.endpoint_base_url = server.base_url();
|
||||
Client client{std::move(copts)};
|
||||
|
||||
// 1. Authorized unary call succeeds and clamps excessive caller timeout
|
||||
// (60s -> <= 5s server max).
|
||||
CallOptions ok_opts;
|
||||
ok_opts.schema_version = 2;
|
||||
ok_opts.timeout = std::chrono::seconds{60};
|
||||
ok_opts.transport_headers = {{"X-Test-Token", "valid-admin"}};
|
||||
auto r_ok = client.call(kEcho, to_bytes("ping"), ok_opts);
|
||||
Void::Testing::require(r_ok.has_value());
|
||||
Void::Testing::expect_eq(from_bytes(*r_ok), std::string{"alice:ping"});
|
||||
Void::Testing::expect(observed_timeout_ms.load() <= 5000);
|
||||
Void::Testing::expect(observed_timeout_ms.load() > 0);
|
||||
|
||||
// 2. Schema version mismatch rejected with IncompatibleVersion.
|
||||
CallOptions bad_schema = ok_opts;
|
||||
bad_schema.schema_version = 99;
|
||||
auto r_ver = client.call(kEcho, to_bytes("ping"), bad_schema);
|
||||
Void::Testing::expect(!r_ver.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_ver.error()) ==
|
||||
RpcStatusCode::IncompatibleVersion);
|
||||
|
||||
// 3. Unauthenticated request denied before handler admission.
|
||||
CallOptions no_auth;
|
||||
no_auth.schema_version = 2;
|
||||
auto r_unauth = client.call(kEcho, to_bytes("x"), no_auth);
|
||||
Void::Testing::expect(!r_unauth.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_unauth.error()) ==
|
||||
RpcStatusCode::Unauthenticated);
|
||||
|
||||
// 4. Unauthorized guest denied on admin-only method.
|
||||
CallOptions guest_opts;
|
||||
guest_opts.schema_version = 1;
|
||||
guest_opts.transport_headers = {{"X-Test-Token", "valid-guest"}};
|
||||
auto r_perm = client.call(kThrow, to_bytes("x"), guest_opts);
|
||||
Void::Testing::expect(!r_perm.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_perm.error()) ==
|
||||
RpcStatusCode::PermissionDenied);
|
||||
|
||||
// 5. Handler exception returns sanitized Internal error without leaking
|
||||
// exception message.
|
||||
CallOptions admin_v1;
|
||||
admin_v1.schema_version = 1;
|
||||
admin_v1.transport_headers = {{"X-Test-Token", "valid-admin"}};
|
||||
auto r_throw = client.call(kThrow, to_bytes("x"), admin_v1);
|
||||
Void::Testing::expect(!r_throw.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(r_throw.error()) ==
|
||||
RpcStatusCode::Internal);
|
||||
Void::Testing::expect(r_throw.error().message().find("sensitive") ==
|
||||
std::string_view::npos);
|
||||
|
||||
// 6. Registration::unregister_and_drain() waits for in-flight call to
|
||||
// finish before returning, then rejects subsequent calls.
|
||||
Void::Result::Result<OwnedBytes> slow_out =
|
||||
std::unexpected{make_rpc_error(RpcStatusCode::Internal, "pending")};
|
||||
std::thread slow_caller(
|
||||
[&]() { slow_out = client.call(kSlow, to_bytes("drain-ok"), admin_v1); });
|
||||
|
||||
while (!slow_entered.load(std::memory_order_acquire)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{2});
|
||||
}
|
||||
std::thread releaser([&]() {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{25});
|
||||
slow_release.store(true, std::memory_order_release);
|
||||
});
|
||||
reg_slow->unregister_and_drain();
|
||||
Void::Testing::expect(slow_finished.load(std::memory_order_acquire));
|
||||
releaser.join();
|
||||
slow_caller.join();
|
||||
Void::Testing::require(slow_out.has_value());
|
||||
Void::Testing::expect_eq(from_bytes(*slow_out), std::string{"drain-ok"});
|
||||
|
||||
auto after_unreg = client.call(kSlow, to_bytes("late"), admin_v1);
|
||||
Void::Testing::expect(!after_unreg.has_value());
|
||||
Void::Testing::expect(rpc_status_from_error(after_unreg.error()) ==
|
||||
RpcStatusCode::Unimplemented);
|
||||
|
||||
server.shutdown();
|
||||
}
|
||||
Reference in new issue
Block a user