// Out-of-process voter agent for the multi-process acceptance harness. // // Each agent owns one directory and durably persists its Raft-style state // (current term, vote, log, commit index) before replying to any RPC. The // parent harness drives elections and replication over authenticated HTTP; // killing an agent loses nothing acknowledged, and a restarted agent // recovers from disk. // // distributed_voter_agent --dir --port --token // // The bound port is written to `/port` once the listener is up. // Keys and values are restricted to [A-Za-z0-9_.-] so the durable text format // stays unambiguous. #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { using Entry = std::pair; // term, index struct LogEntry { std::uint64_t term{0}; std::uint64_t index{0}; std::string key; std::string value; [[nodiscard]] bool operator==(const LogEntry&) const noexcept = default; }; [[nodiscard]] bool safe_token(std::string_view text) { return !text.empty() && std::ranges::all_of(text, [](char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '.' || c == '-'; }); } void sync_directory(const std::filesystem::path& directory) { const int fd = ::open(directory.c_str(), O_RDONLY | O_DIRECTORY); if (fd >= 0) { (void)::fsync(fd); (void)::close(fd); } } /// Durable voter state. Every mutation is persisted (write, fsync, rename, /// directory fsync) before the RPC returns success. class VoterStore { public: explicit VoterStore(std::filesystem::path directory) : m_directory(std::move(directory)) , m_path(m_directory / "voter.state") { } [[nodiscard]] bool load() { std::lock_guard lock{m_mutex}; if (!std::filesystem::exists(m_path)) { return std::filesystem::create_directories(m_directory) || std::filesystem::exists(m_directory); } std::ifstream in{m_path}; if (!in.is_open()) { return false; } std::string line; while (std::getline(in, line)) { std::istringstream fields{line}; std::string tag; fields >> tag; if (tag == "term") { std::uint64_t term = 0; std::string voted; if (!(fields >> term >> voted)) { return false; } m_term = term; m_voted_for = voted == "-" ? std::nullopt : std::optional{voted}; } else if (tag == "entry") { LogEntry entry; if (!(fields >> entry.term >> entry.index >> entry.key >> entry.value)) { return false; } m_log.push_back(std::move(entry)); } else if (tag == "commit") { if (!(fields >> m_commit)) { return false; } } else { return false; } } reapply(); return true; } [[nodiscard]] std::uint64_t term() const { std::lock_guard lock{m_mutex}; return m_term; } [[nodiscard]] std::uint64_t last_index() const { std::lock_guard lock{m_mutex}; return m_log.empty() ? 0 : m_log.back().index; } [[nodiscard]] std::uint64_t last_term() const { std::lock_guard lock{m_mutex}; return m_log.empty() ? 0 : m_log.back().term; } [[nodiscard]] std::uint64_t commit() const { std::lock_guard lock{m_mutex}; return m_commit; } [[nodiscard]] std::size_t log_size() const { std::lock_guard lock{m_mutex}; return m_log.size(); } [[nodiscard]] std::string voted_for() const { std::lock_guard lock{m_mutex}; return m_voted_for.value_or("-"); } /// Grant a vote when the term allows it and the candidate's log is /// at least as up to date. [[nodiscard]] bool vote(std::uint64_t term, std::string_view candidate, std::uint64_t candidate_last_index, std::uint64_t candidate_last_term) { std::lock_guard lock{m_mutex}; if (term < m_term) { return false; } if (term > m_term) { m_term = term; m_voted_for.reset(); if (!persist()) { return false; } } if (m_voted_for.has_value() && *m_voted_for != candidate) { return false; } const std::uint64_t self_index = m_log.empty() ? 0 : m_log.back().index; const std::uint64_t self_term = m_log.empty() ? 0 : m_log.back().term; const bool up_to_date = candidate_last_term > self_term || (candidate_last_term == self_term && candidate_last_index >= self_index); if (!up_to_date) { return false; } m_voted_for = std::string{candidate}; return persist(); } /// AppendEntries: returns the matched index on success. [[nodiscard]] std::optional append( std::uint64_t term, std::uint64_t prev_index, std::uint64_t prev_term, std::uint64_t leader_commit, const std::vector& entries) { std::lock_guard lock{m_mutex}; if (term < m_term) { return std::nullopt; } if (term > m_term) { m_term = term; m_voted_for.reset(); } const std::uint64_t local_last = m_log.empty() ? 0 : m_log.back().index; if (prev_index > local_last) { return std::nullopt; } const std::uint64_t local_term = prev_index == 0 ? 0 : m_log[prev_index - 1].term; if (local_term != prev_term) { return std::nullopt; } std::size_t position = static_cast(prev_index); for (const auto& entry : entries) { if (position < m_log.size() && m_log[position] == entry) { ++position; continue; } m_log.resize(position); m_log.push_back(entry); ++position; } if (leader_commit > m_commit) { m_commit = std::min(leader_commit, m_log.empty() ? 0 : m_log.back().index); } reapply(); if (!persist()) { return std::nullopt; } return m_log.empty() ? 0 : m_log.back().index; } [[nodiscard]] std::vector entries_from( std::uint64_t index) const { std::lock_guard lock{m_mutex}; std::vector out; for (const auto& entry : m_log) { if (entry.index >= index) { out.push_back(entry); } } return out; } [[nodiscard]] std::optional value( std::string_view key) const { std::lock_guard lock{m_mutex}; const auto found = m_kv.find(key); if (found == m_kv.end()) { return std::nullopt; } return found->second; } private: void reapply() { m_kv.clear(); for (const auto& entry : m_log) { if (entry.index > m_commit) { break; } if (entry.value == "-") { m_kv.erase(entry.key); } else { m_kv.insert_or_assign(entry.key, entry.value); } } } [[nodiscard]] bool persist() { std::string text; text += "term " + std::to_string(m_term) + " " + m_voted_for.value_or("-") + "\n"; for (const auto& entry : m_log) { text += "entry " + std::to_string(entry.term) + " " + std::to_string(entry.index) + " " + entry.key + " " + entry.value + "\n"; } text += "commit " + std::to_string(m_commit) + "\n"; const auto temporary = m_path.string() + ".tmp"; { std::ofstream out{temporary, std::ios::trunc}; if (!out.is_open()) { return false; } out << text; out.flush(); if (!out.good()) { return false; } } const int fd = ::open(temporary.c_str(), O_RDONLY); if (fd < 0) { return false; } (void)::fsync(fd); (void)::close(fd); if (std::rename(temporary.c_str(), m_path.c_str()) != 0) { return false; } sync_directory(m_directory); return true; } mutable std::mutex m_mutex; std::filesystem::path m_directory; std::filesystem::path m_path; std::uint64_t m_term{0}; std::optional m_voted_for; std::vector m_log; std::uint64_t m_commit{0}; std::map> m_kv; }; [[nodiscard]] std::optional query(std::string_view text, std::string_view name) { std::size_t pos = 0; while (pos <= text.size()) { const std::size_t amp = text.find('&', pos); const std::string_view pair = text.substr(pos, amp == std::string_view::npos ? std::string_view::npos : amp - pos); const std::size_t eq = pair.find('='); if (pair.substr(0, eq) == name) { return eq == std::string_view::npos ? std::string_view{} : pair.substr(eq + 1); } if (amp == std::string_view::npos) { break; } pos = amp + 1; } return std::nullopt; } [[nodiscard]] std::optional number(std::string_view text) { if (text.empty()) { return std::nullopt; } std::uint64_t value = 0; const auto parsed = std::from_chars(text.data(), text.data() + text.size(), value); if (parsed.ec != std::errc{}) { return std::nullopt; } return value; } [[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.body = std::move(body); return response; } } // namespace int main(int argc, char** argv) { std::filesystem::path directory; std::uint16_t port = 0; std::string token; long long parent{0}; for (int i = 1; i < argc; ++i) { const std::string_view arg{argv[i]}; if (arg == "--dir" && i + 1 < argc) { directory = argv[++i]; } else if (arg == "--parent" && i + 1 < argc) { parent = std::strtoll(argv[++i], nullptr, 10); } else if (arg == "--port" && i + 1 < argc) { unsigned int value = 0; const auto parsed = std::from_chars(argv[i + 1], argv[i + 1] + std::strlen(argv[i + 1]), value); if (parsed.ec != std::errc{} || value > 65535U) { std::fprintf(stderr, "invalid --port\n"); return 2; } port = static_cast(value); ++i; } else if (arg == "--token" && i + 1 < argc) { token = argv[++i]; } } if (directory.empty() || token.empty()) { std::fprintf(stderr, "usage: distributed_voter_agent --dir " "--port --token \n"); return 2; } VoterStore store{directory}; if (!store.load()) { std::fprintf(stderr, "voter agent: failed to load durable state\n"); return 3; } Void::Net::HttpServerOptions options; options.bind_host = "127.0.0.1"; options.port = port; options.max_concurrent_connections = 8; options.max_body_bytes = 64ULL * 1024ULL; Void::Net::HttpServer server{options}; auto guarded = [token](const Void::Net::ServerRequest& request) -> std::optional { const auto header = request.header("authorization"); const std::string expected = "Bearer " + token; if (!header || *header != expected) { return text_response(401, "unauthorized"); } return std::nullopt; }; auto add = [&](Void::Net::Method method, const char* pattern, auto fn) { return server.add_route( method, pattern, [guarded, fn](const Void::Net::ServerRequest& request) -> Void::Net::RouteResult { if (auto denied = guarded(request)) { return Void::Result::ok(std::move(*denied)); } return Void::Result::ok(fn(request)); }); }; auto registered = add( Void::Net::Method::Get, "/voter/state", [&store](const Void::Net::ServerRequest&) { return text_response( 200, "term=" + std::to_string(store.term()) + " voted=" + store.voted_for() + " last_index=" + std::to_string(store.last_index()) + " last_term=" + std::to_string(store.last_term()) + " commit=" + std::to_string(store.commit()) + " entries=" + std::to_string(store.log_size())); }); if (!registered) { return 4; } registered = add( Void::Net::Method::Post, "/voter/vote", [&store](const Void::Net::ServerRequest& request) { const auto term = number(query(request.query, "term").value_or("")); const auto last_index = number(query(request.query, "last_index").value_or("")); const auto last_term = number(query(request.query, "last_term").value_or("")); const auto candidate = query(request.query, "candidate"); if (!term || !last_index || !last_term || !candidate || !safe_token(*candidate)) { return text_response(400, "bad vote request"); } if (!store.vote(*term, *candidate, *last_index, *last_term)) { return text_response(409, "vote rejected"); } return text_response(200, "granted"); }); if (!registered) { return 4; } registered = add( Void::Net::Method::Post, "/voter/append", [&store](const Void::Net::ServerRequest& request) { const auto term = number(query(request.query, "term").value_or("")); const auto prev_index = number(query(request.query, "prev_index").value_or("")); const auto prev_term = number(query(request.query, "prev_term").value_or("")); const auto commit = number(query(request.query, "commit").value_or("")); if (!term || !prev_index || !prev_term || !commit) { return text_response(400, "bad append request"); } std::vector entries; std::size_t pos = 0; while (pos < request.body.size()) { const std::size_t end = request.body.find('\n', pos); const std::string_view line = std::string_view{request.body}.substr( pos, end == std::string::npos ? std::string::npos : end - pos); if (!line.empty()) { LogEntry entry; std::string key; std::string value; const std::size_t first = line.find(','); const std::size_t second = first == std::string_view::npos ? std::string_view::npos : line.find(',', first + 1); const std::size_t third = second == std::string_view::npos ? std::string_view::npos : line.find(',', second + 1); if (first == std::string_view::npos || second == std::string_view::npos || third == std::string_view::npos) { return text_response(400, "bad entry"); } const auto entry_term = number(line.substr(0, first)); const auto entry_index = number(line.substr(first + 1, second - first - 1)); key = line.substr(second + 1, third - second - 1); value = line.substr(third + 1); if (!entry_term || !entry_index || !safe_token(key) || !(safe_token(value) || value == "-")) { return text_response(400, "bad entry"); } entry.term = *entry_term; entry.index = *entry_index; entry.key = key; entry.value = value; entries.push_back(std::move(entry)); } if (end == std::string::npos) { break; } pos = end + 1; } const auto matched = store.append(*term, *prev_index, *prev_term, *commit, entries); if (!matched) { return text_response(409, "append rejected"); } return text_response(200, "matched=" + std::to_string(*matched)); }); if (!registered) { return 4; } registered = add( Void::Net::Method::Get, "/voter/value", [&store](const Void::Net::ServerRequest& request) { const auto key = query(request.query, "key"); if (!key) { return text_response(400, "key required"); } const auto value = store.value(*key); if (!value) { return text_response(404, "not found"); } return text_response(200, *value); }); if (!registered) { return 4; } registered = add( Void::Net::Method::Get, "/voter/entries", [&store](const Void::Net::ServerRequest& request) { const auto from = number(query(request.query, "from").value_or("1")); if (!from) { return text_response(400, "from required"); } std::string body; for (const auto& entry : store.entries_from(*from)) { body += std::to_string(entry.term) + "," + std::to_string(entry.index) + "," + entry.key + "," + entry.value + "\n"; } return text_response(200, std::move(body)); }); if (!registered) { return 4; } if (auto started = server.start(); !started) { std::fprintf(stderr, "voter agent: failed to bind listener\n"); return 5; } { const auto port_path = directory / "port"; std::ofstream out{port_path, std::ios::trunc}; out << server.bound_port() << "\n"; } // Serve until the parent kills this process. An agent whose supervising // parent disappeared exits on its own so it can never orphan and hold the // harness's output pipes open. while (parent == 0 || ::getppid() == parent) { std::this_thread::sleep_for(std::chrono::milliseconds{200}); } return 0; }