From 2489098478b44de1deeacc6f13c937342e5c49b2 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Fri, 4 Dec 2026 10:21:43 +0300 Subject: [PATCH] DistributedApplications: single-node reference composition with authenticated peer fixture (P-DISTRIBUTED-03) --- .../distributed/host-graph/CMakeLists.txt | 12 +- .../include/distributed_host/single_node.hpp | 161 ++++++++ .../host-graph/src/single_node.cpp | 376 ++++++++++++++++++ .../host-graph/tests/single_node_test.cpp | 177 +++++++++ 4 files changed, 723 insertions(+), 3 deletions(-) create mode 100644 examples/distributed/host-graph/include/distributed_host/single_node.hpp create mode 100644 examples/distributed/host-graph/src/single_node.cpp create mode 100644 examples/distributed/host-graph/tests/single_node_test.cpp diff --git a/examples/distributed/host-graph/CMakeLists.txt b/examples/distributed/host-graph/CMakeLists.txt index 9856702..bf6130b 100644 --- a/examples/distributed/host-graph/CMakeLists.txt +++ b/examples/distributed/host-graph/CMakeLists.txt @@ -7,14 +7,20 @@ set(CMAKE_CXX_STANDARD 26) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) -find_package(Void CONFIG REQUIRED COMPONENTS Functional) +find_package(Void CONFIG REQUIRED COMPONENTS Functional Net) -add_library(distributed_host_graph STATIC src/host_graph.cpp) +add_library(distributed_host_graph STATIC + src/host_graph.cpp + src/single_node.cpp) target_include_directories(distributed_host_graph PUBLIC include) -target_link_libraries(distributed_host_graph PUBLIC Void::Functional) +target_link_libraries(distributed_host_graph PUBLIC Void::Functional Void::Net) add_executable(distributed_host_graph_test tests/host_graph_test.cpp) target_link_libraries(distributed_host_graph_test PRIVATE distributed_host_graph) +add_executable(distributed_single_node_test tests/single_node_test.cpp) +target_link_libraries(distributed_single_node_test PRIVATE distributed_host_graph) + enable_testing() add_test(NAME distributed_host_graph COMMAND distributed_host_graph_test) +add_test(NAME distributed_single_node COMMAND distributed_single_node_test) diff --git a/examples/distributed/host-graph/include/distributed_host/single_node.hpp b/examples/distributed/host-graph/include/distributed_host/single_node.hpp new file mode 100644 index 0000000..0f511b6 --- /dev/null +++ b/examples/distributed/host-graph/include/distributed_host/single_node.hpp @@ -0,0 +1,161 @@ +#pragma once + +#include "distributed_host/host_graph.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace DistributedHost +{ + /// Validated single-node configuration. Construction opens nothing. + struct SingleNodeConfig { + std::string peer_address{"127.0.0.1:0"}; + /// Required peer credential; an empty token fails closed. + std::string peer_token{}; + std::chrono::milliseconds shutdown_grace{ + std::chrono::seconds{5}}; + std::size_t max_connections{16}; + std::size_t max_append_bytes{64ULL * 1024ULL}; + /// Bounded retained peer log entries. + std::size_t max_log_entries{1024}; + + [[nodiscard]] Void::Result::Result validate() const; + }; + + /// Bounded in-memory replicated log served by the peer fixture. The + /// single-node composition owns it; durable storage arrives with the + /// multi-node reference in a later task. + class PeerLog + { + public: + + explicit PeerLog(std::size_t max_entries = 1024); + + /// Append one opaque entry. Returns the assigned index (1-based). + [[nodiscard]] Void::Result::Result + append(std::string entry); + + [[nodiscard]] std::size_t size() const; + [[nodiscard]] std::uint64_t last_index() const; + + private: + + mutable std::mutex m_mutex; + std::size_t m_max_entries; + std::vector m_entries; + }; + + /// Real authenticated peer transport over Void::Net::HttpServer. + /// + /// Routes: `GET /peer/health` (bounded status, no secrets) and + /// `POST /peer/append` (bearer-authenticated, bounded body). A missing or + /// empty configured token rejects every request. + class HttpPeerTransport final : public PeerTransport + { + public: + + HttpPeerTransport(std::string address, std::string token, + PeerLog& log, std::size_t max_connections, + std::size_t max_append_bytes); + ~HttpPeerTransport() noexcept override; + + HttpPeerTransport(const HttpPeerTransport&) = delete; + HttpPeerTransport& operator=(const HttpPeerTransport&) = delete; + + [[nodiscard]] Void::Result::Result listen() override; + [[nodiscard]] Void::Result::Result + connect_peers(const std::vector& peers) override; + void close() noexcept override; + + [[nodiscard]] std::uint16_t bound_port() const noexcept; + [[nodiscard]] std::size_t connected_peers() const noexcept + { + return m_connected_peers; + } + + private: + + [[nodiscard]] bool authorized(const Void::Net::ServerRequest& req) + const noexcept; + + std::string m_address; + std::string m_token; + PeerLog& m_log; + std::size_t m_max_connections; + std::size_t m_max_append_bytes; + std::size_t m_connected_peers{0}; + std::unique_ptr m_server{}; + }; + + /// Single-node replication adapter: a sole voter is always the leader + /// while started. Multi-node election belongs to the Coordination plan. + class SingleNodeReplication final : public ReplicationAdapter + { + public: + + [[nodiscard]] Void::Result::Result start() override; + [[nodiscard]] Role role() const noexcept override + { + return m_running ? Role::Leader : Role::Follower; + } + [[nodiscard]] bool leader_available() const noexcept override + { + return m_running; + } + void stop() noexcept override { m_running = false; } + + private: + + bool m_running{false}; + }; + + /// Single-node reference composition: the host graph wired with the + /// authenticated HTTP peer fixture and a leader-available replication + /// adapter. Startup is bounded and rolls back in reverse order. + class SingleNodeHost + { + public: + + SingleNodeHost(const SingleNodeHost&) = delete; + SingleNodeHost& operator=(const SingleNodeHost&) = delete; + /// Movable: every component the host graph points at is heap-owned, + /// so a move transfers ownership without changing addresses. + SingleNodeHost(SingleNodeHost&&) noexcept = default; + SingleNodeHost& operator=(SingleNodeHost&&) noexcept = default; + ~SingleNodeHost(); + + [[nodiscard]] static Void::Result::Result + create(SingleNodeConfig config); + + [[nodiscard]] Void::Result::Result start(); + void stop() noexcept; + + [[nodiscard]] HealthSnapshot health() const; + [[nodiscard]] std::uint16_t peer_port() const noexcept; + [[nodiscard]] const std::vector& history() const noexcept; + + private: + + struct NoopStorage final : StorageBackend { + Void::Result::Result open() override { return {}; } + Void::Result::Result recover() override { return {}; } + void close() noexcept override {} + }; + + explicit SingleNodeHost(SingleNodeConfig config); + + SingleNodeConfig m_config; + std::unique_ptr m_log; + std::unique_ptr m_storage; + std::unique_ptr m_transport; + std::unique_ptr m_replication; + std::unique_ptr m_graph; + }; +} // namespace DistributedHost diff --git a/examples/distributed/host-graph/src/single_node.cpp b/examples/distributed/host-graph/src/single_node.cpp new file mode 100644 index 0000000..8c061cc --- /dev/null +++ b/examples/distributed/host-graph/src/single_node.cpp @@ -0,0 +1,376 @@ +#include "distributed_host/single_node.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace DistributedHost +{ + namespace + { + [[nodiscard]] Void::Result::Error invalid(std::string message) + { + return Void::Result::Error{ + Void::Result::ErrorKind::invalid_argument, std::move(message)}; + } + + [[nodiscard]] Void::Result::Error conflict(std::string message) + { + return Void::Result::Error{Void::Result::ErrorKind::conflict, + std::move(message)}; + } + + [[nodiscard]] Void::Result::Error exhausted(std::string message) + { + return Void::Result::Error{Void::Result::ErrorKind::exhausted, + std::move(message)}; + } + + [[nodiscard]] bool parse_address(std::string_view address, + std::string& host, + std::uint16_t& port) noexcept + { + const auto colon = address.rfind(':'); + if (colon == std::string_view::npos || colon == 0 || + colon + 1 >= address.size()) { + return false; + } + host = std::string{address.substr(0, colon)}; + const auto digits = address.substr(colon + 1); + unsigned int value = 0; + const auto parsed = std::from_chars( + digits.data(), digits.data() + digits.size(), value); + if (parsed.ec != std::errc{} || + parsed.ptr != digits.data() + digits.size() || value > 65535U) { + return false; + } + port = static_cast(value); + return true; + } + + /// Length-independent comparison: always scans the full candidate. + [[nodiscard]] bool constant_time_equal(std::string_view a, + std::string_view b) noexcept + { + unsigned char difference = + static_cast(a.size() == b.size() ? 0 : 1); + for (std::size_t i = 0; i < b.size(); ++i) { + const unsigned char left = + i < a.size() ? static_cast(a[i]) : 0; + difference |= static_cast( + left ^ static_cast(b[i])); + } + return difference == 0; + } + + [[nodiscard]] bool iequals_ascii(std::string_view a, + std::string_view b) noexcept + { + if (a.size() != b.size()) { + return false; + } + for (std::size_t i = 0; i < a.size(); ++i) { + auto lower = [](char c) noexcept { + return c >= 'A' && c <= 'Z' ? static_cast(c - 'A' + 'a') + : c; + }; + if (lower(a[i]) != lower(b[i])) { + return false; + } + } + return true; + } + + [[nodiscard]] Void::Net::ServerResponse text_response(int status, + std::string body) + { + Void::Net::ServerResponse response; + response.status = static_cast(status); + response.headers.push_back( + Void::Net::Header{"content-type", "text/plain; charset=utf-8"}); + response.headers.push_back(Void::Net::Header{"cache-control", "no-store"}); + response.body = std::move(body); + return response; + } + } // namespace + + Void::Result::Result SingleNodeConfig::validate() const + { + std::string host; + std::uint16_t port = 0; + if (!parse_address(peer_address, host, port)) { + return std::unexpected{ + invalid("SingleNodeConfig: peer_address must be host:port")}; + } + if (peer_token.empty()) { + return std::unexpected{invalid( + "SingleNodeConfig: peer_token is required (fail closed)")}; + } + if (max_connections == 0) { + return std::unexpected{invalid( + "SingleNodeConfig: max_connections must be positive")}; + } + if (max_append_bytes == 0) { + return std::unexpected{invalid( + "SingleNodeConfig: max_append_bytes must be positive")}; + } + if (max_log_entries == 0) { + return std::unexpected{invalid( + "SingleNodeConfig: max_log_entries must be positive")}; + } + if (shutdown_grace.count() < 0) { + return std::unexpected{invalid( + "SingleNodeConfig: shutdown_grace must not be negative")}; + } + return {}; + } + + PeerLog::PeerLog(std::size_t max_entries) + : m_max_entries(max_entries) + { + } + + Void::Result::Result PeerLog::append(std::string entry) + { + std::lock_guard lock{m_mutex}; + if (m_entries.size() >= m_max_entries) { + return std::unexpected{exhausted( + "PeerLog: retained entry cap reached")}; + } + m_entries.push_back(std::move(entry)); + return static_cast(m_entries.size()); + } + + std::size_t PeerLog::size() const + { + std::lock_guard lock{m_mutex}; + return m_entries.size(); + } + + std::uint64_t PeerLog::last_index() const + { + std::lock_guard lock{m_mutex}; + return static_cast(m_entries.size()); + } + + HttpPeerTransport::HttpPeerTransport(std::string address, std::string token, + PeerLog& log, + std::size_t max_connections, + std::size_t max_append_bytes) + : m_address(std::move(address)) + , m_token(std::move(token)) + , m_log(log) + , m_max_connections(max_connections) + , m_max_append_bytes(max_append_bytes) + { + } + + HttpPeerTransport::~HttpPeerTransport() noexcept + { + close(); + } + + bool HttpPeerTransport::authorized( + const Void::Net::ServerRequest& req) const noexcept + { + if (m_token.empty()) { + return false; + } + const auto header = req.header("authorization"); + if (!header) { + return false; + } + constexpr std::string_view scheme{"bearer "}; + if (header->size() < scheme.size() || + !iequals_ascii(header->substr(0, scheme.size()), scheme)) { + return false; + } + return constant_time_equal(header->substr(scheme.size()), m_token); + } + + Void::Result::Result HttpPeerTransport::listen() + { + if (m_server) { + return std::unexpected{ + conflict("HttpPeerTransport: already listening")}; + } + std::string host; + std::uint16_t port = 0; + if (!parse_address(m_address, host, port)) { + return std::unexpected{ + invalid("HttpPeerTransport: address must be host:port")}; + } + + Void::Net::HttpServerOptions options; + options.bind_host = std::move(host); + options.port = port; + options.max_concurrent_connections = m_max_connections; + options.max_body_bytes = m_max_append_bytes; + auto server = std::make_unique(options); + + auto added = server->add_route( + Void::Net::Method::Get, "/peer/health", + [this](const Void::Net::ServerRequest& req) + -> Void::Net::RouteResult { + if (!authorized(req)) { + return Void::Result::ok( + text_response(401, "unauthorized")); + } + return Void::Result::ok(text_response( + 200, std::format("role=leader entries={} last_index={}", + m_log.size(), m_log.last_index()))); + }); + if (!added) { + return std::unexpected{std::move(added).error()}; + } + added = server->add_route( + Void::Net::Method::Post, "/peer/append", + [this](const Void::Net::ServerRequest& req) + -> Void::Net::RouteResult { + if (!authorized(req)) { + return Void::Result::ok( + text_response(401, "unauthorized")); + } + if (req.body.empty()) { + return Void::Result::ok( + text_response(400, "empty entry")); + } + if (req.body.size() > m_max_append_bytes) { + return Void::Result::ok( + text_response(413, "entry too large")); + } + auto index = m_log.append(req.body); + if (!index) { + return Void::Result::ok( + text_response(503, index.error().message())); + } + return Void::Result::ok(text_response( + 200, std::format("index={}", *index))); + }); + if (!added) { + return std::unexpected{std::move(added).error()}; + } + if (auto started = server->start(); !started) { + return started; + } + m_server = std::move(server); + return {}; + } + + Void::Result::Result + HttpPeerTransport::connect_peers(const std::vector& peers) + { + // A single-node fixture has no outgoing peer connections; the count is + // recorded for inspect and the multi-node transport is a later task. + m_connected_peers = peers.size(); + return {}; + } + + void HttpPeerTransport::close() noexcept + { + if (m_server) { + m_server->shutdown(std::chrono::seconds{2}); + m_server.reset(); + } + m_connected_peers = 0; + } + + std::uint16_t HttpPeerTransport::bound_port() const noexcept + { + return m_server ? m_server->bound_port() : 0; + } + + Void::Result::Result SingleNodeReplication::start() + { + if (m_running) { + return std::unexpected{ + conflict("SingleNodeReplication: already started")}; + } + m_running = true; + return {}; + } + + SingleNodeHost::SingleNodeHost(SingleNodeConfig config) + : m_config(std::move(config)) + , m_log(std::make_unique(m_config.max_log_entries)) + , m_storage(std::make_unique()) + { + } + + SingleNodeHost::~SingleNodeHost() + { + stop(); + } + + Void::Result::Result + SingleNodeHost::create(SingleNodeConfig config) + { + if (auto valid = config.validate(); !valid) { + return std::unexpected{std::move(valid).error()}; + } + SingleNodeHost host{std::move(config)}; + host.m_transport = std::make_unique( + host.m_config.peer_address, host.m_config.peer_token, *host.m_log, + host.m_config.max_connections, host.m_config.max_append_bytes); + host.m_replication = std::make_unique(); + + HostResources resources; + resources.storage = host.m_storage.get(); + resources.transport = host.m_transport.get(); + resources.replication = host.m_replication.get(); + + HostConfig graph_config; + graph_config.cluster = "single-node"; + graph_config.self = "node-1"; + graph_config.peers = {}; + graph_config.publish_discovery = false; + graph_config.startup_deadline = host.m_config.shutdown_grace; + + auto graph = + DistributedHostGraph::compose(resources, std::move(graph_config)); + if (!graph) { + return std::unexpected{std::move(graph).error()}; + } + host.m_graph = + std::make_unique(std::move(*graph)); + return host; + } + + Void::Result::Result SingleNodeHost::start() + { + if (!m_graph) { + return std::unexpected{ + conflict("SingleNodeHost: host was moved out")}; + } + return m_graph->start(); + } + + void SingleNodeHost::stop() noexcept + { + if (m_graph) { + m_graph->stop(); + } + } + + HealthSnapshot SingleNodeHost::health() const + { + return m_graph ? m_graph->health() : HealthSnapshot{}; + } + + std::uint16_t SingleNodeHost::peer_port() const noexcept + { + return m_transport ? m_transport->bound_port() : 0; + } + + const std::vector& SingleNodeHost::history() const noexcept + { + static const std::vector empty{}; + return m_graph ? m_graph->history() : empty; + } +} // namespace DistributedHost diff --git a/examples/distributed/host-graph/tests/single_node_test.cpp b/examples/distributed/host-graph/tests/single_node_test.cpp new file mode 100644 index 0000000..f9a4aed --- /dev/null +++ b/examples/distributed/host-graph/tests/single_node_test.cpp @@ -0,0 +1,177 @@ +#include "distributed_host/single_node.hpp" + +#include + +#include +#include +#include +#include + +#include +#include +#include + +namespace +{ + using namespace DistributedHost; + + SingleNodeConfig config() + { + SingleNodeConfig cfg; + cfg.peer_address = "127.0.0.1:0"; + cfg.peer_token = "peer-secret"; + cfg.shutdown_grace = std::chrono::seconds{2}; + return cfg; + } + + Void::Net::Header auth() + { + return Void::Net::Header{"authorization", "Bearer peer-secret"}; + } + + void config_fails_closed_without_a_token() + { + SingleNodeConfig no_token; + no_token.peer_token.clear(); + assert(!SingleNodeHost::create(no_token).has_value()); + + SingleNodeConfig bad_address; + bad_address.peer_token = "x"; + bad_address.peer_address = "not-an-address"; + assert(!SingleNodeHost::create(bad_address).has_value()); + + SingleNodeConfig zero_entries = config(); + zero_entries.max_log_entries = 0; + assert(!SingleNodeHost::create(zero_entries).has_value()); + } + + void peer_fixture_requires_authentication_and_serves_bounded_state() + { + auto host = SingleNodeHost::create(config()); + assert(host.has_value()); + // Construction opens no listener. + assert(host->peer_port() == 0); + assert(host->history().empty()); + + assert(host->start().has_value()); + assert(host->health().readiness == Readiness::WriteReady); + const std::uint16_t port = host->peer_port(); + assert(port != 0); + + Void::Net::HttpClient client; + const std::string base = + "http://127.0.0.1:" + std::to_string(port); + + // Both peer endpoints reject missing and wrong credentials. + auto anonymous_health = client.get(base + "/peer/health"); + assert(anonymous_health.has_value()); + assert(anonymous_health->status == 401); + auto wrong = client.get( + base + "/peer/health", + {Void::Net::Header{"authorization", "Bearer wrong"}}); + assert(wrong.has_value()); + assert(wrong->status == 401); + + auto health = client.get(base + "/peer/health", {auth()}); + assert(health.has_value()); + assert(health->status == 200); + assert(health->body.find("role=leader") != std::string::npos); + assert(health->body.find("entries=0") != std::string::npos); + // The credential never appears in a response. + assert(health->body.find("peer-secret") == std::string::npos); + + auto append = [&](std::string body) { + Void::Net::Request request; + request.method = Void::Net::Method::Post; + request.url = base + "/peer/append"; + request.body = std::move(body); + request.headers.push_back(auth()); + return client.send(request); + }; + + auto anonymous = client.send(Void::Net::Request{ + .method = Void::Net::Method::Post, + .url = base + "/peer/append", + .body = "entry"}); + assert(anonymous.has_value()); + assert(anonymous->status == 401); + + auto first = append("entry-one"); + assert(first.has_value()); + assert(first->status == 200); + assert(first->body == "index=1"); + + auto second = append("entry-two"); + assert(second.has_value()); + assert(second->body == "index=2"); + + auto after = client.get(base + "/peer/health", {auth()}); + assert(after.has_value()); + assert(after->body.find("entries=2") != std::string::npos); + + // Auth is required for the mutation even with a valid-looking path. + auto wrong_method = client.get(base + "/peer/append", {auth()}); + assert(wrong_method.has_value()); + assert(wrong_method->status == 405); + + host->stop(); + assert(host->peer_port() == 0); + const auto closed = client.get(base + "/peer/health", {auth()}); + assert(!closed.has_value()); + + // Idempotent. + host->stop(); + } + + void bind_failure_rolls_back_in_reverse_order() + { + // Occupy a loopback port with a raw listener. + const int fd = ::socket(AF_INET, SOCK_STREAM, 0); + assert(fd >= 0); + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = 0; + assert(::bind(fd, reinterpret_cast(&addr), sizeof(addr)) == 0); + assert(::listen(fd, 4) == 0); + socklen_t length = sizeof(addr); + assert(::getsockname(fd, reinterpret_cast(&addr), &length) == + 0); + const std::uint16_t busy_port = ntohs(addr.sin_port); + + SingleNodeConfig cfg = config(); + cfg.peer_address = "127.0.0.1:" + std::to_string(busy_port); + auto host = SingleNodeHost::create(cfg); + assert(host.has_value()); + + auto started = host->start(); + assert(!started.has_value()); + assert(host->health().readiness == Readiness::Failed); + const std::vector expected{ + "storage.open", "storage.recover", "storage.close"}; + assert(host->history() == expected); + assert(host->peer_port() == 0); + (void)::close(fd); + } + + void log_cap_is_bounded() + { + PeerLog log{2}; + assert(log.append("a").has_value()); + assert(log.append("b").has_value()); + auto rejected = log.append("c"); + assert(!rejected.has_value()); + assert(log.size() == 2); + assert(log.last_index() == 2); + } +} // namespace + +int main() +{ + config_fails_closed_without_a_token(); + peer_fixture_requires_authentication_and_serves_bounded_state(); + bind_failure_rolls_back_in_reverse_order(); + log_cap_is_bounded(); + std::puts("distributed single-node host ok"); + return 0; +}