From 23a899a892617b3e9f393398328a8064a64d1c22 Mon Sep 17 00:00:00 2001 From: "Aleksei (Faumaray) Selikhov" Date: Fri, 4 Dec 2026 10:34:33 +0300 Subject: [PATCH] DistributedApplications: three-node networked KV fixture with quorum reads, durable replies and crash histories (P-DISTRIBUTED-04) --- .../distributed/host-graph/CMakeLists.txt | 5 + .../distributed_host/cluster_fixture.hpp | 87 ++++ .../host-graph/src/cluster_fixture.cpp | 401 ++++++++++++++++++ .../host-graph/tests/cluster_fixture_test.cpp | 184 ++++++++ 4 files changed, 677 insertions(+) create mode 100644 examples/distributed/host-graph/include/distributed_host/cluster_fixture.hpp create mode 100644 examples/distributed/host-graph/src/cluster_fixture.cpp create mode 100644 examples/distributed/host-graph/tests/cluster_fixture_test.cpp diff --git a/examples/distributed/host-graph/CMakeLists.txt b/examples/distributed/host-graph/CMakeLists.txt index 75efb3d..9772352 100644 --- a/examples/distributed/host-graph/CMakeLists.txt +++ b/examples/distributed/host-graph/CMakeLists.txt @@ -10,6 +10,7 @@ set(CMAKE_CXX_EXTENSIONS OFF) find_package(Void CONFIG REQUIRED COMPONENTS Functional Net) add_library(distributed_host_graph STATIC + src/cluster_fixture.cpp src/host_graph.cpp src/replicated_kv.cpp src/single_node.cpp) @@ -25,7 +26,11 @@ target_link_libraries(distributed_single_node_test PRIVATE distributed_host_grap add_executable(distributed_replicated_kv_test tests/replicated_kv_test.cpp) target_link_libraries(distributed_replicated_kv_test PRIVATE distributed_host_graph) +add_executable(distributed_cluster_fixture_test tests/cluster_fixture_test.cpp) +target_link_libraries(distributed_cluster_fixture_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) add_test(NAME distributed_replicated_kv COMMAND distributed_replicated_kv_test) +add_test(NAME distributed_cluster_fixture COMMAND distributed_cluster_fixture_test) diff --git a/examples/distributed/host-graph/include/distributed_host/cluster_fixture.hpp b/examples/distributed/host-graph/include/distributed_host/cluster_fixture.hpp new file mode 100644 index 0000000..7276eef --- /dev/null +++ b/examples/distributed/host-graph/include/distributed_host/cluster_fixture.hpp @@ -0,0 +1,87 @@ +#pragma once + +#include "distributed_host/replicated_kv.hpp" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace DistributedHost +{ + struct ClusterFixtureConfig { + /// Required bearer token for every peer and admin route. + std::string token{"peer-secret"}; + std::size_t max_connections{8}; + std::chrono::milliseconds shutdown_grace{ + std::chrono::seconds{2}}; + }; + + /// Three-node replicated KV reference over real loopback HTTP listeners. + /// + /// Each voter owns one `Void::Net::HttpServer`. Peer routes drive the + /// deterministic replication core (elect, propose, read, heartbeat); an + /// authenticated admin route models partitions for crash/partition + /// histories. The transport is real; consensus timing is deterministic. + /// + /// Routes (all require `Authorization: Bearer `): + /// GET /peer/health role/term/commit/applied + /// POST /peer/elect become a candidate + /// PUT /peer/propose?key=K body = value + /// DELETE /peer/propose?key=K erase + /// GET /peer/read?key=K consistent quorum read + /// POST /peer/heartbeat replicate log and commit index + /// POST /admin/partition?node=X&partition=N + /// POST /admin/crash?node=X + /// POST /admin/restart?node=X + class ClusterFixture + { + public: + + ClusterFixture(const ClusterFixture&) = delete; + ClusterFixture& operator=(const ClusterFixture&) = delete; + ClusterFixture(ClusterFixture&&) = delete; + ClusterFixture& operator=(ClusterFixture&&) = delete; + ~ClusterFixture(); + + [[nodiscard]] static Void::Result::Result< + std::unique_ptr> + create(ClusterFixtureConfig config = {}); + + /// Bind and start every listener. Construction alone opens none. + [[nodiscard]] Void::Result::Result start(); + + /// Bounded, idempotent shutdown of every listener. + void stop() noexcept; + + /// `http://127.0.0.1:` for one voter, or an empty string + /// when it is unknown or not listening. + [[nodiscard]] std::string endpoint(std::string_view node) const; + + [[nodiscard]] const std::vector& voters() const noexcept; + + private: + + struct PeerServer { + std::string id; + std::unique_ptr server; + }; + + explicit ClusterFixture(ClusterFixtureConfig config); + + [[nodiscard]] Void::Result::Result + register_routes(PeerServer& peer); + + ClusterFixtureConfig m_config; + ReplicatedKvCluster m_cluster; + mutable std::mutex m_mutex; + std::vector> m_peers; + }; +} // namespace DistributedHost diff --git a/examples/distributed/host-graph/src/cluster_fixture.cpp b/examples/distributed/host-graph/src/cluster_fixture.cpp new file mode 100644 index 0000000..c410fe0 --- /dev/null +++ b/examples/distributed/host-graph/src/cluster_fixture.cpp @@ -0,0 +1,401 @@ +#include "distributed_host/cluster_fixture.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace DistributedHost +{ + namespace + { + [[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; + } + + [[nodiscard]] int status_for(const Void::Result::Error& error) noexcept + { + using Kind = Void::Result::ErrorKind; + switch (error.kind()) { + case Kind::invalid_argument: return 400; + case Kind::not_found: return 404; + case Kind::conflict: return 409; + case Kind::overloaded: return 503; + case Kind::timeout: return 504; + default: return 500; + } + } + + [[nodiscard]] bool authorized(const Void::Net::ServerRequest& request, + std::string_view token) noexcept + { + if (token.empty()) { + return false; + } + const auto header = request.header("authorization"); + if (!header) { + return false; + } + constexpr std::string_view scheme{"bearer "}; + if (header->size() <= scheme.size()) { + return false; + } + const std::string_view word = header->substr(0, scheme.size() - 1); + if (!(word == "Bearer" || word == "bearer") || + (*header)[scheme.size() - 1] != ' ') { + return false; + } + return header->substr(scheme.size()) == token; + } + + [[nodiscard]] std::optional + query_value(std::string_view query, std::string_view name) noexcept + { + std::size_t pos = 0; + while (pos <= query.size()) { + const std::size_t amp = query.find('&', pos); + const std::string_view pair = query.substr( + pos, amp == std::string_view::npos ? std::string_view::npos + : amp - pos); + const std::size_t equals = pair.find('='); + const std::string_view key = pair.substr(0, equals); + if (key == name) { + return equals == std::string_view::npos + ? std::string_view{} + : pair.substr(equals + 1); + } + if (amp == std::string_view::npos) { + break; + } + pos = amp + 1; + } + return std::nullopt; + } + + [[nodiscard]] std::string_view role_name(Role role) noexcept + { + switch (role) { + case Role::Leader: return "leader"; + case Role::Candidate: return "candidate"; + case Role::Follower: return "follower"; + } + return "follower"; + } + + [[nodiscard]] std::string_view + outcome_name(KvWriteOutcome outcome) noexcept + { + switch (outcome) { + case KvWriteOutcome::Applied: return "applied"; + case KvWriteOutcome::NoQuorum: return "no-quorum"; + case KvWriteOutcome::NotLeader: return "not-leader"; + case KvWriteOutcome::NodeDown: return "node-down"; + } + return "no-quorum"; + } + + [[nodiscard]] int outcome_status(KvWriteOutcome outcome) noexcept + { + switch (outcome) { + case KvWriteOutcome::Applied: return 200; + case KvWriteOutcome::NotLeader: return 409; + case KvWriteOutcome::NoQuorum: return 503; + case KvWriteOutcome::NodeDown: return 503; + } + return 503; + } + } // namespace + + ClusterFixture::ClusterFixture(ClusterFixtureConfig config) + : m_config(std::move(config)), m_cluster({"a", "b", "c"}) + { + } + + ClusterFixture::~ClusterFixture() + { + stop(); + } + + Void::Result::Result> + ClusterFixture::create(ClusterFixtureConfig config) + { + if (config.token.empty()) { + return std::unexpected{Void::Result::Error{ + Void::Result::ErrorKind::invalid_argument, + "ClusterFixture: a peer token is required (fail closed)"}}; + } + auto fixture = std::unique_ptr{ + new ClusterFixture{std::move(config)}}; + for (const auto& id : fixture->m_cluster.voters()) { + auto peer = std::make_unique(); + peer->id = id; + Void::Net::HttpServerOptions options; + options.bind_host = "127.0.0.1"; + options.port = 0; + options.max_concurrent_connections = + fixture->m_config.max_connections; + peer->server = std::make_unique(options); + if (auto routes = fixture->register_routes(*peer); !routes) { + return std::unexpected{std::move(routes).error()}; + } + fixture->m_peers.push_back(std::move(peer)); + } + return fixture; + } + + Void::Result::Result + ClusterFixture::register_routes(PeerServer& peer) + { + const std::string id = peer.id; + Void::Net::HttpServer& server = *peer.server; + const std::string token = m_config.token; + + auto guarded = [this, token]( + const Void::Net::ServerRequest& request) + -> std::optional { + if (!authorized(request, token)) { + return text_response(401, "unauthorized"); + } + return std::nullopt; + }; + + auto add = [&](Void::Net::Method method, const char* pattern, auto fn) + -> Void::Result::Result { + return server.add_route( + method, pattern, + [this, id, pattern, fn, guarded]( + const Void::Net::ServerRequest& request) + -> Void::Net::RouteResult { + if (auto denied = guarded(request)) { + return Void::Result::ok(std::move(*denied)); + } + std::lock_guard lock{m_mutex}; + return Void::Result::ok(fn(id, request, *this)); + }); + }; + + auto registered = add( + Void::Net::Method::Get, "/peer/health", + [](const std::string& self, + const Void::Net::ServerRequest&, + ClusterFixture& fixture) { + const auto state = fixture.m_cluster.snapshot(self); + if (!state) { + return text_response(404, "unknown node"); + } + return text_response( + 200, + std::format( + "id={} role={} term={} commit={} applied={} alive={}", + state->id, role_name(state->role), state->term, + state->commit_index, state->applied_index, + state->alive ? "true" : "false")); + }); + if (!registered) { + return registered; + } + + registered = add( + Void::Net::Method::Post, "/peer/elect", + [](const std::string& self, + const Void::Net::ServerRequest&, + ClusterFixture& fixture) { + auto elected = fixture.m_cluster.elect(self); + if (!elected) { + return text_response(status_for(elected.error()), + elected.error().message()); + } + return text_response(200, "elected"); + }); + if (!registered) { + return registered; + } + + registered = add( + Void::Net::Method::Post, "/peer/heartbeat", + [](const std::string& self, + const Void::Net::ServerRequest&, + ClusterFixture& fixture) { + auto beat = fixture.m_cluster.heartbeat(self); + if (!beat) { + return text_response(status_for(beat.error()), + beat.error().message()); + } + return text_response(200, "ok"); + }); + if (!registered) { + return registered; + } + + auto propose = [](const std::string& self, + const Void::Net::ServerRequest& request, + ClusterFixture& fixture, + std::optional value) { + const auto key = query_value(request.query, "key"); + if (!key || key->empty()) { + return text_response(400, "key required"); + } + const KvWriteReply reply = fixture.m_cluster.propose( + self, std::string{*key}, std::move(value)); + return text_response( + outcome_status(reply.outcome), + std::format("{} index={} term={}", outcome_name(reply.outcome), + reply.index, reply.term)); + }; + + registered = add( + Void::Net::Method::Put, "/peer/propose", + [propose](const std::string& self, + const Void::Net::ServerRequest& request, + ClusterFixture& fixture) { + return propose(self, request, fixture, + std::optional{request.body}); + }); + if (!registered) { + return registered; + } + + registered = add( + Void::Net::Method::Delete, "/peer/propose", + [propose](const std::string& self, + const Void::Net::ServerRequest& request, + ClusterFixture& fixture) { + return propose(self, request, fixture, std::nullopt); + }); + if (!registered) { + return registered; + } + + registered = add( + Void::Net::Method::Get, "/peer/read", + [](const std::string& self, + const Void::Net::ServerRequest& request, + ClusterFixture& fixture) { + const auto key = query_value(request.query, "key"); + if (!key || key->empty()) { + return text_response(400, "key required"); + } + auto read = + fixture.m_cluster.quorum_read(self, *key); + if (!read) { + return text_response(status_for(read.error()), + read.error().message()); + } + if (!read->has_value()) { + return text_response(404, "not found"); + } + return text_response(200, **read); + }); + if (!registered) { + return registered; + } + + registered = add( + Void::Net::Method::Post, "/admin/partition", + [](const std::string&, + const Void::Net::ServerRequest& request, + ClusterFixture& fixture) { + const auto node = query_value(request.query, "node"); + const auto partition = query_value(request.query, "partition"); + if (!node || !partition) { + return text_response(400, "node and partition required"); + } + unsigned int value = 0; + const auto parsed = std::from_chars( + partition->data(), partition->data() + partition->size(), + value); + if (parsed.ec != std::errc{}) { + return text_response(400, "invalid partition"); + } + fixture.m_cluster.set_partition(*node, + static_cast(value)); + return text_response(200, "ok"); + }); + if (!registered) { + return registered; + } + + registered = add( + Void::Net::Method::Post, "/admin/crash", + [](const std::string&, + const Void::Net::ServerRequest& request, + ClusterFixture& fixture) { + const auto node = query_value(request.query, "node"); + if (!node) { + return text_response(400, "node required"); + } + fixture.m_cluster.crash(*node); + return text_response(200, "ok"); + }); + if (!registered) { + return registered; + } + + return add( + Void::Net::Method::Post, "/admin/restart", + [](const std::string&, + const Void::Net::ServerRequest& request, + ClusterFixture& fixture) { + const auto node = query_value(request.query, "node"); + if (!node) { + return text_response(400, "node required"); + } + fixture.m_cluster.restart(*node); + return text_response(200, "ok"); + }); + } + + Void::Result::Result ClusterFixture::start() + { + std::size_t started = 0; + for (auto& peer : m_peers) { + if (auto listening = peer->server->start(); !listening) { + for (std::size_t i = 0; i < started; ++i) { + m_peers[i]->server->shutdown(m_config.shutdown_grace); + } + return listening; + } + ++started; + } + return {}; + } + + void ClusterFixture::stop() noexcept + { + for (auto& peer : m_peers) { + if (peer->server) { + peer->server->shutdown(m_config.shutdown_grace); + peer->server.reset(); + } + } + } + + std::string ClusterFixture::endpoint(std::string_view node) const + { + for (const auto& peer : m_peers) { + if (peer->id == node && peer->server && + peer->server->bound_port() != 0) { + return "http://127.0.0.1:" + + std::to_string(peer->server->bound_port()); + } + } + return {}; + } + + const std::vector& ClusterFixture::voters() const noexcept + { + return m_cluster.voters(); + } +} // namespace DistributedHost diff --git a/examples/distributed/host-graph/tests/cluster_fixture_test.cpp b/examples/distributed/host-graph/tests/cluster_fixture_test.cpp new file mode 100644 index 0000000..1c85efa --- /dev/null +++ b/examples/distributed/host-graph/tests/cluster_fixture_test.cpp @@ -0,0 +1,184 @@ +#include "distributed_host/cluster_fixture.hpp" + +#include + +#include +#include +#include +#include + +namespace +{ + using namespace DistributedHost; + + Void::Net::Header auth() + { + return Void::Net::Header{"authorization", "Bearer peer-secret"}; + } + + Void::Net::Response + send(Void::Net::HttpClient& client, Void::Net::Method method, + const std::string& url, std::string body = {}) + { + Void::Net::Request request; + request.method = method; + request.url = url; + request.body = std::move(body); + request.headers.push_back(auth()); + auto response = client.send(request); + assert(response.has_value()); + return *response; + } + + void three_real_listeners_serve_the_replicated_kv() + { + auto fixture = ClusterFixture::create(); + assert(fixture.has_value()); + // Construction opens nothing. + assert((*fixture)->endpoint("a").empty()); + assert((*fixture)->start().has_value()); + + const std::string a = (*fixture)->endpoint("a"); + const std::string b = (*fixture)->endpoint("b"); + const std::string c = (*fixture)->endpoint("c"); + assert(!a.empty() && !b.empty() && !c.empty()); + assert(a != b && b != c && a != c); + + Void::Net::HttpClient client; + // Every peer route is authenticated. + auto anonymous = client.get(a + "/peer/health"); + assert(anonymous.has_value() && anonymous->status == 401); + + assert(send(client, Void::Net::Method::Post, a + "/peer/elect").body == + "elected"); + auto proposed = send(client, Void::Net::Method::Put, + a + "/peer/propose?key=k", "value"); + assert(proposed.status == 200); + assert(proposed.body.starts_with("applied")); + + auto read = client.get(a + "/peer/read?key=k", {auth()}); + assert(read.has_value()); + assert(read->status == 200); + assert(read->body == "value"); + // The follower applied the committed entry but cannot serve a + // consistent read. + auto follower_read = client.get(b + "/peer/read?key=k", {auth()}); + assert(follower_read.has_value()); + assert(follower_read->status == 409); + auto follower_write = + send(client, Void::Net::Method::Put, b + "/peer/propose?key=k", "x"); + assert(follower_write.status == 409); + + (*fixture)->stop(); + assert((*fixture)->endpoint("a").empty()); + } + + void minority_leader_cannot_commit_or_read_over_http() + { + auto fixture = ClusterFixture::create(); + assert(fixture.has_value()); + assert((*fixture)->start().has_value()); + const std::string a = (*fixture)->endpoint("a"); + const std::string b = (*fixture)->endpoint("b"); + const std::string c = (*fixture)->endpoint("c"); + + Void::Net::HttpClient client; + assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status == + 200); + assert(send(client, Void::Net::Method::Post, + a + "/admin/partition?node=b&partition=1") + .status == 200); + assert(send(client, Void::Net::Method::Post, + a + "/admin/partition?node=c&partition=1") + .status == 200); + + auto proposed = send(client, Void::Net::Method::Put, + a + "/peer/propose?key=k", "lost"); + assert(proposed.status == 503); + assert(proposed.body.starts_with("no-quorum")); + + auto read = client.get(a + "/peer/read?key=k", {auth()}); + assert(read.has_value()); + assert(read->status == 503); + + // Heal and let the majority take over. + assert(send(client, Void::Net::Method::Post, + b + "/admin/partition?node=b&partition=0") + .status == 200); + assert(send(client, Void::Net::Method::Post, + b + "/admin/partition?node=c&partition=0") + .status == 200); + assert(send(client, Void::Net::Method::Post, b + "/peer/elect").status == + 200); + assert(send(client, Void::Net::Method::Put, + b + "/peer/propose?key=k", "kept") + .status == 200); + auto read_after = client.get(b + "/peer/read?key=k", {auth()}); + assert(read_after.has_value()); + assert(read_after->status == 200); + assert(read_after->body == "kept"); + + (*fixture)->stop(); + } + + void crash_history_keeps_committed_replies() + { + auto fixture = ClusterFixture::create(); + assert(fixture.has_value()); + assert((*fixture)->start().has_value()); + const std::string a = (*fixture)->endpoint("a"); + const std::string b = (*fixture)->endpoint("b"); + const std::string c = (*fixture)->endpoint("c"); + + Void::Net::HttpClient client; + assert(send(client, Void::Net::Method::Post, a + "/peer/elect").status == + 200); + assert(send(client, Void::Net::Method::Put, + a + "/peer/propose?key=committed", "1") + .status == 200); + + // One voter crashes: the majority still commits. + assert(send(client, Void::Net::Method::Post, a + "/admin/crash?node=c") + .status == 200); + assert(send(client, Void::Net::Method::Put, + a + "/peer/propose?key=second", "2") + .status == 200); + + // A second crash loses the majority: no durable reply. + assert(send(client, Void::Net::Method::Post, a + "/admin/crash?node=b") + .status == 200); + assert(send(client, Void::Net::Method::Put, + a + "/peer/propose?key=third", "3") + .status == 503); + + // Restart and re-elect: committed history is intact, the failed + // proposal was never applied. + assert(send(client, Void::Net::Method::Post, + b + "/admin/restart?node=b") + .status == 200); + assert(send(client, Void::Net::Method::Post, + c + "/admin/restart?node=c") + .status == 200); + assert(send(client, Void::Net::Method::Post, b + "/peer/elect").status == + 200); + auto first = client.get(b + "/peer/read?key=committed", {auth()}); + auto second = client.get(b + "/peer/read?key=second", {auth()}); + auto third = client.get(b + "/peer/read?key=third", {auth()}); + assert(first.has_value() && first->status == 200 && + first->body == "1"); + assert(second.has_value() && second->status == 200 && + second->body == "2"); + assert(third.has_value() && third->status == 404); + + (*fixture)->stop(); + } +} // namespace + +int main() +{ + three_real_listeners_serve_the_replicated_kv(); + minority_leader_cannot_commit_or_read_over_http(); + crash_history_keeps_committed_replies(); + std::puts("distributed cluster fixture ok"); + return 0; +}