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

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

No files matched your search

+1 -1
View File
@@ -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);
+51
View File
@@ -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
+184
View File
@@ -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
+205
View File
@@ -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