377 lines
10 KiB
C++
377 lines
10 KiB
C++
#include "distributed_host/single_node.hpp"
|
|
|
|
#include <Void/Net/Http.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <charconv>
|
|
#include <chrono>
|
|
#include <format>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <utility>
|
|
|
|
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<std::uint16_t>(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<unsigned char>(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<unsigned char>(a[i]) : 0;
|
|
difference |= static_cast<unsigned char>(
|
|
left ^ static_cast<unsigned char>(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<char>(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<std::uint16_t>(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<void> 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<std::uint64_t> 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<std::uint64_t>(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<std::uint64_t>(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<void> 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<Void::Net::HttpServer>(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<void>
|
|
HttpPeerTransport::connect_peers(const std::vector<NodeId>& 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<void> 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<PeerLog>(m_config.max_log_entries))
|
|
, m_storage(std::make_unique<NoopStorage>())
|
|
{
|
|
}
|
|
|
|
SingleNodeHost::~SingleNodeHost()
|
|
{
|
|
stop();
|
|
}
|
|
|
|
Void::Result::Result<SingleNodeHost>
|
|
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<HttpPeerTransport>(
|
|
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<SingleNodeReplication>();
|
|
|
|
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<DistributedHostGraph>(std::move(*graph));
|
|
return host;
|
|
}
|
|
|
|
Void::Result::Result<void> 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<std::string>& SingleNodeHost::history() const noexcept
|
|
{
|
|
static const std::vector<std::string> empty{};
|
|
return m_graph ? m_graph->history() : empty;
|
|
}
|
|
} // namespace DistributedHost
|