DistributedApplications: replicated worker queue with inbox/outbox dedup, at-least-once retry, DLQ and consumer recovery (P-DISTRIBUTED-05)
This commit is contained in:
1 parent
23a899a892
commit
b386140899
6 files changed
+871
-18
No files matched your search
@@ -13,6 +13,7 @@ add_library(distributed_host_graph STATIC
|
|||||||
src/cluster_fixture.cpp
|
src/cluster_fixture.cpp
|
||||||
src/host_graph.cpp
|
src/host_graph.cpp
|
||||||
src/replicated_kv.cpp
|
src/replicated_kv.cpp
|
||||||
|
src/replicated_queue.cpp
|
||||||
src/single_node.cpp)
|
src/single_node.cpp)
|
||||||
target_include_directories(distributed_host_graph PUBLIC include)
|
target_include_directories(distributed_host_graph PUBLIC include)
|
||||||
target_link_libraries(distributed_host_graph PUBLIC Void::Functional Void::Net)
|
target_link_libraries(distributed_host_graph PUBLIC Void::Functional Void::Net)
|
||||||
@@ -29,8 +30,12 @@ target_link_libraries(distributed_replicated_kv_test PRIVATE distributed_host_gr
|
|||||||
add_executable(distributed_cluster_fixture_test tests/cluster_fixture_test.cpp)
|
add_executable(distributed_cluster_fixture_test tests/cluster_fixture_test.cpp)
|
||||||
target_link_libraries(distributed_cluster_fixture_test PRIVATE distributed_host_graph)
|
target_link_libraries(distributed_cluster_fixture_test PRIVATE distributed_host_graph)
|
||||||
|
|
||||||
|
add_executable(distributed_replicated_queue_test tests/replicated_queue_test.cpp)
|
||||||
|
target_link_libraries(distributed_replicated_queue_test PRIVATE distributed_host_graph)
|
||||||
|
|
||||||
enable_testing()
|
enable_testing()
|
||||||
add_test(NAME distributed_host_graph COMMAND distributed_host_graph_test)
|
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_single_node COMMAND distributed_single_node_test)
|
||||||
add_test(NAME distributed_replicated_kv COMMAND distributed_replicated_kv_test)
|
add_test(NAME distributed_replicated_kv COMMAND distributed_replicated_kv_test)
|
||||||
add_test(NAME distributed_cluster_fixture COMMAND distributed_cluster_fixture_test)
|
add_test(NAME distributed_cluster_fixture COMMAND distributed_cluster_fixture_test)
|
||||||
|
add_test(NAME distributed_replicated_queue COMMAND distributed_replicated_queue_test)
|
||||||
@@ -99,6 +99,12 @@ namespace DistributedHost
|
|||||||
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
|
[[nodiscard]] Void::Result::Result<std::optional<std::string>>
|
||||||
quorum_read(std::string_view node, std::string_view key);
|
quorum_read(std::string_view node, std::string_view key);
|
||||||
|
|
||||||
|
/// Quorum-confirmed copy of the leader's applied state. Used by
|
||||||
|
/// compositions that must enumerate keys (e.g. the worker queue).
|
||||||
|
[[nodiscard]] Void::Result::Result<
|
||||||
|
std::map<std::string, std::string, std::less<>>>
|
||||||
|
quorum_snapshot(std::string_view node);
|
||||||
|
|
||||||
/// Crash/restart keep the durable log, term and vote.
|
/// Crash/restart keep the durable log, term and vote.
|
||||||
void crash(std::string_view node);
|
void crash(std::string_view node);
|
||||||
void restart(std::string_view node);
|
void restart(std::string_view node);
|
||||||
@@ -137,6 +143,10 @@ namespace DistributedHost
|
|||||||
[[nodiscard]] static bool log_up_to_date(const Node& candidate,
|
[[nodiscard]] static bool log_up_to_date(const Node& candidate,
|
||||||
const Node& voter);
|
const Node& voter);
|
||||||
void apply_committed(Node& node);
|
void apply_committed(Node& node);
|
||||||
|
/// Majority-confirm `node` as leader in its term, then apply pending
|
||||||
|
/// committed entries. Shared by quorum reads and snapshots.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
confirm_leader(Node& node);
|
||||||
/// Copy the leader's log to one reachable follower. False when the
|
/// Copy the leader's log to one reachable follower. False when the
|
||||||
/// follower cannot be brought in line (e.g. it is in a newer term).
|
/// follower cannot be brought in line (e.g. it is in a newer term).
|
||||||
[[nodiscard]] bool replicate_to(Node& leader, Node& follower);
|
[[nodiscard]] bool replicate_to(Node& leader, Node& follower);
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "distributed_host/replicated_kv.hpp"
|
||||||
|
|
||||||
|
#include <Void/Functional/Result.hpp>
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <functional>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace DistributedHost
|
||||||
|
{
|
||||||
|
enum class JobState : std::uint8_t {
|
||||||
|
Pending,
|
||||||
|
InFlight,
|
||||||
|
Done,
|
||||||
|
Dead
|
||||||
|
};
|
||||||
|
|
||||||
|
[[nodiscard]] std::string_view job_state_name(JobState state) noexcept;
|
||||||
|
|
||||||
|
struct QueueJob {
|
||||||
|
std::string id;
|
||||||
|
std::string payload;
|
||||||
|
JobState state{JobState::Pending};
|
||||||
|
std::uint32_t attempts{0};
|
||||||
|
std::string consumer;
|
||||||
|
/// Set when the acknowledged effect still needs external
|
||||||
|
/// delivery (the outbox).
|
||||||
|
bool outbox_pending{false};
|
||||||
|
std::string reason;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct QueueConfig {
|
||||||
|
std::uint32_t max_attempts{3};
|
||||||
|
std::size_t max_jobs{1024};
|
||||||
|
std::size_t max_payload_bytes{64ULL * 1024ULL};
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Consumer-side effect delivery for dispatched outbox entries.
|
||||||
|
using OutboxSink = std::function<void(const QueueJob&)>;
|
||||||
|
|
||||||
|
/// Worker-queue reference backed by one replicated KV group.
|
||||||
|
///
|
||||||
|
/// Semantics are at-least-once by contract:
|
||||||
|
/// * `publish` is idempotent by caller key and replies only after the
|
||||||
|
/// record is majority-committed; a lost reply is retried with the
|
||||||
|
/// same key;
|
||||||
|
/// * `claim` leases one job to a consumer (attempts incremented);
|
||||||
|
/// * `ack` records the inbox outcome and the outbox entry in one
|
||||||
|
/// replicated job record, so a redelivered ack cannot duplicate the
|
||||||
|
/// effect;
|
||||||
|
/// * `nack` requeues or dead-letters after `max_attempts`;
|
||||||
|
/// * `recover_consumer` requeues or dead-letters a crashed
|
||||||
|
/// consumer's in-flight jobs;
|
||||||
|
/// * `dispatch_outbox` delivers effects externally. A crash between
|
||||||
|
/// delivery and marking duplicates the effect: consumers must dedup
|
||||||
|
/// on the job id.
|
||||||
|
class ReplicatedQueue
|
||||||
|
{
|
||||||
|
public:
|
||||||
|
|
||||||
|
ReplicatedQueue(ReplicatedKvCluster& cluster, std::string leader,
|
||||||
|
QueueConfig config = {});
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::string>
|
||||||
|
publish(std::string payload, std::string idempotency_key);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<QueueJob>>
|
||||||
|
claim(std::string_view consumer);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
ack(std::string_view consumer, std::string_view job_id);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<QueueJob>
|
||||||
|
nack(std::string_view consumer, std::string_view job_id,
|
||||||
|
std::string reason);
|
||||||
|
|
||||||
|
/// Requeue (or dead-letter) every in-flight job of a crashed
|
||||||
|
/// consumer. Returns the affected count.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||||
|
recover_consumer(std::string_view consumer);
|
||||||
|
|
||||||
|
/// Deliver pending outbox effects and mark them delivered.
|
||||||
|
/// Returns the delivered count.
|
||||||
|
[[nodiscard]] Void::Result::Result<std::size_t>
|
||||||
|
dispatch_outbox(const OutboxSink& sink);
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<std::vector<QueueJob>>
|
||||||
|
dead_letters();
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Result<QueueJob>
|
||||||
|
status(std::string_view job_id);
|
||||||
|
|
||||||
|
/// The leader endpoint used for every replicated operation.
|
||||||
|
void set_leader(std::string leader)
|
||||||
|
{
|
||||||
|
m_leader = std::move(leader);
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
[[nodiscard]] static std::string key_for(std::string_view id);
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
store(const QueueJob& job);
|
||||||
|
[[nodiscard]] Void::Result::Result<std::optional<QueueJob>>
|
||||||
|
load(std::string_view job_id);
|
||||||
|
[[nodiscard]] Void::Result::Result<
|
||||||
|
std::vector<std::pair<std::string, QueueJob>>>
|
||||||
|
all_jobs();
|
||||||
|
|
||||||
|
ReplicatedKvCluster& m_cluster;
|
||||||
|
std::string m_leader;
|
||||||
|
QueueConfig m_config;
|
||||||
|
};
|
||||||
|
} // namespace DistributedHost
|
||||||
@@ -287,32 +287,25 @@ namespace DistributedHost
|
|||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
Void::Result::Result<std::optional<std::string>>
|
Void::Result::Result<void>
|
||||||
ReplicatedKvCluster::quorum_read(std::string_view node_id,
|
ReplicatedKvCluster::confirm_leader(Node& node)
|
||||||
std::string_view key)
|
|
||||||
{
|
{
|
||||||
Node* node = find(node_id);
|
if (!node.alive) {
|
||||||
if (node == nullptr) {
|
return std::unexpected{no_quorum("ReplicatedKv: node is down")};
|
||||||
return std::unexpected{not_found("ReplicatedKv: unknown voter")};
|
|
||||||
}
|
}
|
||||||
if (!node->alive) {
|
if (node.role != Role::Leader) {
|
||||||
return std::unexpected{
|
|
||||||
no_quorum("ReplicatedKv: node is down")};
|
|
||||||
}
|
|
||||||
if (node->role != Role::Leader) {
|
|
||||||
return std::unexpected{not_leader(
|
return std::unexpected{not_leader(
|
||||||
"ReplicatedKv: consistent reads require a leader")};
|
"ReplicatedKv: consistent reads require a leader")};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Confirm leadership in this term with a majority heartbeat.
|
// Confirm leadership in this term with a majority heartbeat.
|
||||||
std::size_t acks = 1;
|
std::size_t acks = 1;
|
||||||
for (auto& peer : m_nodes) {
|
for (auto& peer : m_nodes) {
|
||||||
if (peer.id == node->id || !reachable(*node, peer)) {
|
if (peer.id == node.id || !reachable(node, peer)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (peer.term > node->term) {
|
if (peer.term > node.term) {
|
||||||
node->role = Role::Follower;
|
node.role = Role::Follower;
|
||||||
node->leader.reset();
|
node.leader.reset();
|
||||||
return std::unexpected{not_leader(
|
return std::unexpected{not_leader(
|
||||||
"ReplicatedKv: stepped down after a higher term")};
|
"ReplicatedKv: stepped down after a higher term")};
|
||||||
}
|
}
|
||||||
@@ -322,9 +315,22 @@ namespace DistributedHost
|
|||||||
return std::unexpected{no_quorum(
|
return std::unexpected{no_quorum(
|
||||||
"ReplicatedKv: no majority to confirm the read")};
|
"ReplicatedKv: no majority to confirm the read")};
|
||||||
}
|
}
|
||||||
|
|
||||||
// A quorum-confirmed leader has every committed entry; apply them.
|
// A quorum-confirmed leader has every committed entry; apply them.
|
||||||
apply_committed(*node);
|
apply_committed(node);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<std::string>>
|
||||||
|
ReplicatedKvCluster::quorum_read(std::string_view node_id,
|
||||||
|
std::string_view key)
|
||||||
|
{
|
||||||
|
Node* node = find(node_id);
|
||||||
|
if (node == nullptr) {
|
||||||
|
return std::unexpected{not_found("ReplicatedKv: unknown voter")};
|
||||||
|
}
|
||||||
|
if (auto confirmed = confirm_leader(*node); !confirmed) {
|
||||||
|
return std::unexpected{std::move(confirmed).error()};
|
||||||
|
}
|
||||||
const auto found = node->kv.find(key);
|
const auto found = node->kv.find(key);
|
||||||
if (found == node->kv.end()) {
|
if (found == node->kv.end()) {
|
||||||
return std::optional<std::string>{};
|
return std::optional<std::string>{};
|
||||||
@@ -332,6 +338,19 @@ namespace DistributedHost
|
|||||||
return std::optional<std::string>{found->second};
|
return std::optional<std::string>{found->second};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::map<std::string, std::string, std::less<>>>
|
||||||
|
ReplicatedKvCluster::quorum_snapshot(std::string_view node_id)
|
||||||
|
{
|
||||||
|
Node* node = find(node_id);
|
||||||
|
if (node == nullptr) {
|
||||||
|
return std::unexpected{not_found("ReplicatedKv: unknown voter")};
|
||||||
|
}
|
||||||
|
if (auto confirmed = confirm_leader(*node); !confirmed) {
|
||||||
|
return std::unexpected{std::move(confirmed).error()};
|
||||||
|
}
|
||||||
|
return node->kv;
|
||||||
|
}
|
||||||
|
|
||||||
void ReplicatedKvCluster::crash(std::string_view node_id)
|
void ReplicatedKvCluster::crash(std::string_view node_id)
|
||||||
{
|
{
|
||||||
if (Node* node = find(node_id); node != nullptr) {
|
if (Node* node = find(node_id); node != nullptr) {
|
||||||
|
|||||||
@@ -0,0 +1,495 @@
|
|||||||
|
#include "distributed_host/replicated_queue.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <map>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace DistributedHost
|
||||||
|
{
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
constexpr std::array<std::byte, 4> kMagic{
|
||||||
|
std::byte{'V'}, std::byte{'J'}, std::byte{'O'}, std::byte{'B'}};
|
||||||
|
constexpr std::uint32_t kVersion{1};
|
||||||
|
constexpr std::size_t kMaxIdBytes{128};
|
||||||
|
constexpr std::size_t kMaxConsumerBytes{128};
|
||||||
|
constexpr std::size_t kMaxReasonBytes{512};
|
||||||
|
constexpr std::string_view kJobPrefix{"job/"};
|
||||||
|
|
||||||
|
[[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 not_found(std::string message)
|
||||||
|
{
|
||||||
|
return Void::Result::Error{Void::Result::ErrorKind::not_found,
|
||||||
|
std::move(message)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Error exhausted(std::string message)
|
||||||
|
{
|
||||||
|
return Void::Result::Error{Void::Result::ErrorKind::exhausted,
|
||||||
|
std::move(message)};
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] Void::Result::Error corrupt(std::string message)
|
||||||
|
{
|
||||||
|
return Void::Result::Error{Void::Result::ErrorKind::corrupt,
|
||||||
|
std::move(message)};
|
||||||
|
}
|
||||||
|
|
||||||
|
void append_u32(std::vector<std::byte>& out, std::uint32_t value)
|
||||||
|
{
|
||||||
|
for (int shift = 24; shift >= 0; shift -= 8) {
|
||||||
|
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void append_u64(std::vector<std::byte>& out, std::uint64_t value)
|
||||||
|
{
|
||||||
|
for (int shift = 56; shift >= 0; shift -= 8) {
|
||||||
|
out.push_back(static_cast<std::byte>((value >> shift) & 0xFFU));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool read_u32(std::span<const std::byte> in,
|
||||||
|
std::size_t& pos, std::uint32_t& value) noexcept
|
||||||
|
{
|
||||||
|
if (pos + 4 > in.size()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
value = 0;
|
||||||
|
for (int i = 0; i < 4; ++i) {
|
||||||
|
value = (value << 8) |
|
||||||
|
std::to_integer<std::uint32_t>(in[pos + i]);
|
||||||
|
}
|
||||||
|
pos += 4;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool read_u64(std::span<const std::byte> in,
|
||||||
|
std::size_t& pos, std::uint64_t& value) noexcept
|
||||||
|
{
|
||||||
|
if (pos + 8 > in.size()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
value = 0;
|
||||||
|
for (int i = 0; i < 8; ++i) {
|
||||||
|
value = (value << 8) |
|
||||||
|
std::to_integer<std::uint64_t>(in[pos + i]);
|
||||||
|
}
|
||||||
|
pos += 8;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void append_string(std::vector<std::byte>& out, std::string_view text)
|
||||||
|
{
|
||||||
|
append_u32(out, static_cast<std::uint32_t>(text.size()));
|
||||||
|
for (const char c : text) {
|
||||||
|
out.push_back(static_cast<std::byte>(
|
||||||
|
static_cast<unsigned char>(c)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool read_string(std::span<const std::byte> in,
|
||||||
|
std::size_t& pos, std::string& out,
|
||||||
|
std::size_t max_bytes) noexcept
|
||||||
|
{
|
||||||
|
std::uint32_t length = 0;
|
||||||
|
if (!read_u32(in, pos, length) || length > max_bytes ||
|
||||||
|
pos + length > in.size()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
out.clear();
|
||||||
|
out.reserve(length);
|
||||||
|
for (std::uint32_t i = 0; i < length; ++i) {
|
||||||
|
out.push_back(static_cast<char>(
|
||||||
|
std::to_integer<unsigned char>(in[pos + i])));
|
||||||
|
}
|
||||||
|
pos += length;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::uint64_t checksum(std::span<const std::byte> bytes)
|
||||||
|
{
|
||||||
|
std::uint64_t hash = 0xCBF29CE484222325ULL;
|
||||||
|
for (const std::byte byte : bytes) {
|
||||||
|
hash ^= std::to_integer<std::uint64_t>(byte);
|
||||||
|
hash *= 0x100000001B3ULL;
|
||||||
|
}
|
||||||
|
return hash;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::vector<std::byte> encode_job(const QueueJob& job)
|
||||||
|
{
|
||||||
|
std::vector<std::byte> out;
|
||||||
|
out.insert(out.end(), kMagic.begin(), kMagic.end());
|
||||||
|
append_u32(out, kVersion);
|
||||||
|
append_string(out, job.id);
|
||||||
|
append_string(out, job.payload);
|
||||||
|
out.push_back(static_cast<std::byte>(job.state));
|
||||||
|
append_u32(out, job.attempts);
|
||||||
|
append_string(out, job.consumer);
|
||||||
|
out.push_back(std::byte{job.outbox_pending ? 1 : 0});
|
||||||
|
append_string(out, job.reason);
|
||||||
|
append_u64(out, checksum(out));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::optional<QueueJob>
|
||||||
|
decode_job(std::span<const std::byte> bytes)
|
||||||
|
{
|
||||||
|
if (bytes.size() < kMagic.size() + 4 + 8 ||
|
||||||
|
!std::equal(kMagic.begin(), kMagic.end(), bytes.begin())) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
const std::size_t payload = bytes.size() - 8;
|
||||||
|
std::uint64_t stored = 0;
|
||||||
|
{
|
||||||
|
std::size_t check_pos = payload;
|
||||||
|
if (!read_u64(bytes, check_pos, stored) ||
|
||||||
|
checksum(bytes.first(payload)) != stored) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::size_t pos = kMagic.size();
|
||||||
|
std::uint32_t version = 0;
|
||||||
|
if (!read_u32(bytes, pos, version) || version != kVersion) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
QueueJob job;
|
||||||
|
if (!read_string(bytes, pos, job.id, kMaxIdBytes) ||
|
||||||
|
!read_string(bytes, pos, job.payload, 1024ULL * 1024ULL) ||
|
||||||
|
pos >= payload) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
job.state = static_cast<JobState>(
|
||||||
|
std::to_integer<unsigned char>(bytes[pos++]));
|
||||||
|
if (job.state != JobState::Pending &&
|
||||||
|
job.state != JobState::InFlight &&
|
||||||
|
job.state != JobState::Done && job.state != JobState::Dead) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
if (!read_u32(bytes, pos, job.attempts) ||
|
||||||
|
!read_string(bytes, pos, job.consumer, kMaxConsumerBytes) ||
|
||||||
|
pos >= payload) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
job.outbox_pending = std::to_integer<unsigned char>(bytes[pos++]) != 0;
|
||||||
|
if (!read_string(bytes, pos, job.reason, kMaxReasonBytes) ||
|
||||||
|
pos != payload) {
|
||||||
|
return std::nullopt;
|
||||||
|
}
|
||||||
|
return job;
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] std::string to_string(std::span<const std::byte> bytes)
|
||||||
|
{
|
||||||
|
return std::string{
|
||||||
|
reinterpret_cast<const char*>(bytes.data()), bytes.size()};
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
std::string_view job_state_name(JobState state) noexcept
|
||||||
|
{
|
||||||
|
switch (state) {
|
||||||
|
case JobState::Pending: return "pending";
|
||||||
|
case JobState::InFlight: return "in-flight";
|
||||||
|
case JobState::Done: return "done";
|
||||||
|
case JobState::Dead: return "dead";
|
||||||
|
}
|
||||||
|
return "pending";
|
||||||
|
}
|
||||||
|
|
||||||
|
ReplicatedQueue::ReplicatedQueue(ReplicatedKvCluster& cluster,
|
||||||
|
std::string leader, QueueConfig config)
|
||||||
|
: m_cluster(cluster), m_leader(std::move(leader)), m_config(config)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string ReplicatedQueue::key_for(std::string_view id)
|
||||||
|
{
|
||||||
|
return std::string{kJobPrefix} + std::string{id};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void> ReplicatedQueue::store(const QueueJob& job)
|
||||||
|
{
|
||||||
|
const auto encoded = encode_job(job);
|
||||||
|
const KvWriteReply reply = m_cluster.propose(
|
||||||
|
m_leader, key_for(job.id), to_string(encoded));
|
||||||
|
switch (reply.outcome) {
|
||||||
|
case KvWriteOutcome::Applied:
|
||||||
|
return {};
|
||||||
|
case KvWriteOutcome::NoQuorum:
|
||||||
|
return std::unexpected{exhausted(
|
||||||
|
"ReplicatedQueue: write was not majority-committed")};
|
||||||
|
case KvWriteOutcome::NotLeader:
|
||||||
|
return std::unexpected{
|
||||||
|
conflict("ReplicatedQueue: endpoint is not the leader")};
|
||||||
|
case KvWriteOutcome::NodeDown:
|
||||||
|
return std::unexpected{exhausted(
|
||||||
|
"ReplicatedQueue: leader is down")};
|
||||||
|
}
|
||||||
|
return std::unexpected{
|
||||||
|
exhausted("ReplicatedQueue: unknown commit outcome")};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<QueueJob>>
|
||||||
|
ReplicatedQueue::load(std::string_view job_id)
|
||||||
|
{
|
||||||
|
auto stored = m_cluster.quorum_read(m_leader, key_for(job_id));
|
||||||
|
if (!stored) {
|
||||||
|
return std::unexpected{std::move(stored).error()};
|
||||||
|
}
|
||||||
|
if (!stored->has_value()) {
|
||||||
|
return std::optional<QueueJob>{};
|
||||||
|
}
|
||||||
|
const auto bytes =
|
||||||
|
std::as_bytes(std::span{(*stored)->data(), (*stored)->size()});
|
||||||
|
auto decoded = decode_job(bytes);
|
||||||
|
if (!decoded) {
|
||||||
|
return std::unexpected{corrupt("ReplicatedQueue: corrupt job record")};
|
||||||
|
}
|
||||||
|
return std::optional<QueueJob>{std::move(*decoded)};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::vector<std::pair<std::string, QueueJob>>>
|
||||||
|
ReplicatedQueue::all_jobs()
|
||||||
|
{
|
||||||
|
auto snapshot = m_cluster.quorum_snapshot(m_leader);
|
||||||
|
if (!snapshot) {
|
||||||
|
return std::unexpected{std::move(snapshot).error()};
|
||||||
|
}
|
||||||
|
std::vector<std::pair<std::string, QueueJob>> jobs;
|
||||||
|
for (const auto& [key, value] : *snapshot) {
|
||||||
|
if (!key.starts_with(kJobPrefix)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const auto bytes = std::as_bytes(std::span{value.data(), value.size()});
|
||||||
|
auto decoded = decode_job(bytes);
|
||||||
|
if (!decoded) {
|
||||||
|
return std::unexpected{
|
||||||
|
corrupt("ReplicatedQueue: corrupt job record")};
|
||||||
|
}
|
||||||
|
jobs.emplace_back(key, std::move(*decoded));
|
||||||
|
}
|
||||||
|
return jobs;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::string>
|
||||||
|
ReplicatedQueue::publish(std::string payload,
|
||||||
|
std::string idempotency_key)
|
||||||
|
{
|
||||||
|
if (idempotency_key.empty() || idempotency_key.size() > kMaxIdBytes) {
|
||||||
|
return std::unexpected{
|
||||||
|
invalid("ReplicatedQueue: invalid idempotency key")};
|
||||||
|
}
|
||||||
|
if (payload.size() > m_config.max_payload_bytes) {
|
||||||
|
return std::unexpected{
|
||||||
|
invalid("ReplicatedQueue: payload exceeds max_payload_bytes")};
|
||||||
|
}
|
||||||
|
auto jobs = all_jobs();
|
||||||
|
if (!jobs) {
|
||||||
|
return std::unexpected{std::move(jobs).error()};
|
||||||
|
}
|
||||||
|
for (const auto& [key, job] : *jobs) {
|
||||||
|
(void)key;
|
||||||
|
if (job.id == idempotency_key) {
|
||||||
|
// Deduplicated: the caller's retry resolves to the same job.
|
||||||
|
return idempotency_key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (jobs->size() >= m_config.max_jobs) {
|
||||||
|
return std::unexpected{
|
||||||
|
exhausted("ReplicatedQueue: job cap reached")};
|
||||||
|
}
|
||||||
|
QueueJob job;
|
||||||
|
job.id = idempotency_key;
|
||||||
|
job.payload = std::move(payload);
|
||||||
|
if (auto written = store(job); !written) {
|
||||||
|
return std::unexpected{std::move(written).error()};
|
||||||
|
}
|
||||||
|
return idempotency_key;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::optional<QueueJob>>
|
||||||
|
ReplicatedQueue::claim(std::string_view consumer)
|
||||||
|
{
|
||||||
|
if (consumer.empty()) {
|
||||||
|
return std::unexpected{
|
||||||
|
invalid("ReplicatedQueue: consumer must not be empty")};
|
||||||
|
}
|
||||||
|
auto jobs = all_jobs();
|
||||||
|
if (!jobs) {
|
||||||
|
return std::unexpected{std::move(jobs).error()};
|
||||||
|
}
|
||||||
|
for (auto& [key, job] : *jobs) {
|
||||||
|
(void)key;
|
||||||
|
if (job.state != JobState::Pending) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
job.state = JobState::InFlight;
|
||||||
|
job.consumer = std::string{consumer};
|
||||||
|
++job.attempts;
|
||||||
|
if (auto written = store(job); !written) {
|
||||||
|
return std::unexpected{std::move(written).error()};
|
||||||
|
}
|
||||||
|
return std::optional<QueueJob>{std::move(job)};
|
||||||
|
}
|
||||||
|
return std::optional<QueueJob>{};
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<void>
|
||||||
|
ReplicatedQueue::ack(std::string_view consumer, std::string_view job_id)
|
||||||
|
{
|
||||||
|
auto job = load(job_id);
|
||||||
|
if (!job) {
|
||||||
|
return std::unexpected{std::move(job).error()};
|
||||||
|
}
|
||||||
|
if (!job->has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
not_found("ReplicatedQueue: unknown job")};
|
||||||
|
}
|
||||||
|
if ((*job)->state == JobState::Done) {
|
||||||
|
// Duplicate delivery: the inbox already recorded the outcome and
|
||||||
|
// the outbox must not gain a second entry.
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
if ((*job)->state != JobState::InFlight ||
|
||||||
|
(*job)->consumer != consumer) {
|
||||||
|
return std::unexpected{conflict(
|
||||||
|
"ReplicatedQueue: job is not in flight for this consumer")};
|
||||||
|
}
|
||||||
|
(*job)->state = JobState::Done;
|
||||||
|
(*job)->consumer.clear();
|
||||||
|
(*job)->outbox_pending = true;
|
||||||
|
return store(**job);
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<QueueJob>
|
||||||
|
ReplicatedQueue::nack(std::string_view consumer, std::string_view job_id,
|
||||||
|
std::string reason)
|
||||||
|
{
|
||||||
|
auto job = load(job_id);
|
||||||
|
if (!job) {
|
||||||
|
return std::unexpected{std::move(job).error()};
|
||||||
|
}
|
||||||
|
if (!job->has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
not_found("ReplicatedQueue: unknown job")};
|
||||||
|
}
|
||||||
|
if ((*job)->state != JobState::InFlight ||
|
||||||
|
(*job)->consumer != consumer) {
|
||||||
|
return std::unexpected{conflict(
|
||||||
|
"ReplicatedQueue: job is not in flight for this consumer")};
|
||||||
|
}
|
||||||
|
(*job)->reason = std::move(reason);
|
||||||
|
(*job)->consumer.clear();
|
||||||
|
if ((*job)->attempts >= m_config.max_attempts) {
|
||||||
|
(*job)->state = JobState::Dead;
|
||||||
|
} else {
|
||||||
|
(*job)->state = JobState::Pending;
|
||||||
|
}
|
||||||
|
if (auto written = store(**job); !written) {
|
||||||
|
return std::unexpected{std::move(written).error()};
|
||||||
|
}
|
||||||
|
return **job;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::size_t>
|
||||||
|
ReplicatedQueue::recover_consumer(std::string_view consumer)
|
||||||
|
{
|
||||||
|
auto jobs = all_jobs();
|
||||||
|
if (!jobs) {
|
||||||
|
return std::unexpected{std::move(jobs).error()};
|
||||||
|
}
|
||||||
|
std::size_t affected = 0;
|
||||||
|
for (auto& [key, job] : *jobs) {
|
||||||
|
(void)key;
|
||||||
|
if (job.state != JobState::InFlight || job.consumer != consumer) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
job.consumer.clear();
|
||||||
|
if (job.attempts >= m_config.max_attempts) {
|
||||||
|
job.state = JobState::Dead;
|
||||||
|
job.reason = "consumer lost after final attempt";
|
||||||
|
} else {
|
||||||
|
job.state = JobState::Pending;
|
||||||
|
}
|
||||||
|
if (auto written = store(job); !written) {
|
||||||
|
return std::unexpected{std::move(written).error()};
|
||||||
|
}
|
||||||
|
++affected;
|
||||||
|
}
|
||||||
|
return affected;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::size_t>
|
||||||
|
ReplicatedQueue::dispatch_outbox(const OutboxSink& sink)
|
||||||
|
{
|
||||||
|
auto jobs = all_jobs();
|
||||||
|
if (!jobs) {
|
||||||
|
return std::unexpected{std::move(jobs).error()};
|
||||||
|
}
|
||||||
|
std::size_t delivered = 0;
|
||||||
|
for (auto& [key, job] : *jobs) {
|
||||||
|
(void)key;
|
||||||
|
if (job.state != JobState::Done || !job.outbox_pending) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (sink) {
|
||||||
|
sink(job);
|
||||||
|
}
|
||||||
|
job.outbox_pending = false;
|
||||||
|
if (auto written = store(job); !written) {
|
||||||
|
// The effect was delivered but not marked: the next dispatch
|
||||||
|
// delivers it again (at-least-once).
|
||||||
|
return std::unexpected{std::move(written).error()};
|
||||||
|
}
|
||||||
|
++delivered;
|
||||||
|
}
|
||||||
|
return delivered;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<std::vector<QueueJob>>
|
||||||
|
ReplicatedQueue::dead_letters()
|
||||||
|
{
|
||||||
|
auto jobs = all_jobs();
|
||||||
|
if (!jobs) {
|
||||||
|
return std::unexpected{std::move(jobs).error()};
|
||||||
|
}
|
||||||
|
std::vector<QueueJob> dead;
|
||||||
|
for (auto& [key, job] : *jobs) {
|
||||||
|
(void)key;
|
||||||
|
if (job.state == JobState::Dead) {
|
||||||
|
dead.push_back(std::move(job));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dead;
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Result::Result<QueueJob>
|
||||||
|
ReplicatedQueue::status(std::string_view job_id)
|
||||||
|
{
|
||||||
|
auto job = load(job_id);
|
||||||
|
if (!job) {
|
||||||
|
return std::unexpected{std::move(job).error()};
|
||||||
|
}
|
||||||
|
if (!job->has_value()) {
|
||||||
|
return std::unexpected{
|
||||||
|
not_found("ReplicatedQueue: unknown job")};
|
||||||
|
}
|
||||||
|
return **job;
|
||||||
|
}
|
||||||
|
} // namespace DistributedHost
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
#include "distributed_host/replicated_queue.hpp"
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
using namespace DistributedHost;
|
||||||
|
|
||||||
|
struct World {
|
||||||
|
ReplicatedKvCluster cluster{{"a", "b", "c"}};
|
||||||
|
QueueConfig config{.max_attempts = 2, .max_jobs = 8};
|
||||||
|
|
||||||
|
World()
|
||||||
|
{
|
||||||
|
assert(cluster.elect("a").has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
ReplicatedQueue queue()
|
||||||
|
{
|
||||||
|
return ReplicatedQueue{cluster, "a", config};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
void publish_claim_ack_dispatches_one_effect()
|
||||||
|
{
|
||||||
|
World world;
|
||||||
|
auto queue = world.queue();
|
||||||
|
auto id = queue.publish("payload", "job-1");
|
||||||
|
assert(id.has_value());
|
||||||
|
|
||||||
|
// Idempotent publish: the same key never creates a second job.
|
||||||
|
auto duplicate = queue.publish("different", "job-1");
|
||||||
|
assert(duplicate.has_value());
|
||||||
|
assert(*duplicate == *id);
|
||||||
|
|
||||||
|
auto claimed = queue.claim("worker-1");
|
||||||
|
assert(claimed.has_value() && claimed->has_value());
|
||||||
|
assert((*claimed)->id == *id);
|
||||||
|
assert((*claimed)->state == JobState::InFlight);
|
||||||
|
assert((*claimed)->consumer == "worker-1");
|
||||||
|
assert((*claimed)->attempts == 1);
|
||||||
|
|
||||||
|
// No other pending job.
|
||||||
|
auto none = queue.claim("worker-1");
|
||||||
|
assert(none.has_value() && !none->has_value());
|
||||||
|
|
||||||
|
assert(queue.ack("worker-1", *id).has_value());
|
||||||
|
const auto done = queue.status(*id);
|
||||||
|
assert(done.has_value());
|
||||||
|
assert(done->state == JobState::Done);
|
||||||
|
assert(done->outbox_pending);
|
||||||
|
|
||||||
|
// Duplicate ack: the inbox already recorded it, no second outbox row.
|
||||||
|
assert(queue.ack("worker-1", *id).has_value());
|
||||||
|
|
||||||
|
int delivered = 0;
|
||||||
|
auto dispatched = queue.dispatch_outbox([&](const QueueJob& job) {
|
||||||
|
++delivered;
|
||||||
|
assert(job.id == *id);
|
||||||
|
assert(job.payload == "payload");
|
||||||
|
});
|
||||||
|
assert(dispatched.has_value());
|
||||||
|
assert(*dispatched == 1);
|
||||||
|
assert(delivered == 1);
|
||||||
|
|
||||||
|
// The outbox entry was marked delivered.
|
||||||
|
auto redispatch = queue.dispatch_outbox(
|
||||||
|
[&](const QueueJob&) { ++delivered; });
|
||||||
|
assert(redispatch.has_value());
|
||||||
|
assert(*redispatch == 0);
|
||||||
|
assert(delivered == 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
void retries_then_dead_letters()
|
||||||
|
{
|
||||||
|
World world;
|
||||||
|
auto queue = world.queue();
|
||||||
|
auto id = queue.publish("poison", "retry-1");
|
||||||
|
assert(id.has_value());
|
||||||
|
|
||||||
|
assert(queue.claim("w").has_value());
|
||||||
|
auto retried = queue.nack("w", *id, "boom");
|
||||||
|
assert(retried.has_value());
|
||||||
|
assert(retried->state == JobState::Pending);
|
||||||
|
assert(retried->attempts == 1);
|
||||||
|
|
||||||
|
assert(queue.claim("w").has_value());
|
||||||
|
auto dead = queue.nack("w", *id, "boom again");
|
||||||
|
assert(dead.has_value());
|
||||||
|
assert(dead->state == JobState::Dead);
|
||||||
|
assert(dead->attempts == 2);
|
||||||
|
assert(dead->reason == "boom again");
|
||||||
|
|
||||||
|
auto letters = queue.dead_letters();
|
||||||
|
assert(letters.has_value());
|
||||||
|
assert(letters->size() == 1);
|
||||||
|
assert((*letters)[0].id == *id);
|
||||||
|
|
||||||
|
// Dead jobs are no longer claimable.
|
||||||
|
auto none = queue.claim("w");
|
||||||
|
assert(none.has_value() && !none->has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
void crashed_consumer_is_recovered()
|
||||||
|
{
|
||||||
|
World world;
|
||||||
|
auto queue = world.queue();
|
||||||
|
auto id = queue.publish("work", "recover-1");
|
||||||
|
assert(id.has_value());
|
||||||
|
|
||||||
|
auto claimed = queue.claim("worker-1");
|
||||||
|
assert(claimed.has_value() && claimed->has_value());
|
||||||
|
|
||||||
|
auto recovered = queue.recover_consumer("worker-1");
|
||||||
|
assert(recovered.has_value());
|
||||||
|
assert(*recovered == 1);
|
||||||
|
// Recovery is idempotent: nothing is in flight any more.
|
||||||
|
assert(*queue.recover_consumer("worker-1") == 0);
|
||||||
|
|
||||||
|
auto reclaimed = queue.claim("worker-2");
|
||||||
|
assert(reclaimed.has_value() && reclaimed->has_value());
|
||||||
|
assert((*reclaimed)->consumer == "worker-2");
|
||||||
|
assert((*reclaimed)->attempts == 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
void final_attempt_recovery_dead_letters()
|
||||||
|
{
|
||||||
|
World world;
|
||||||
|
world.config.max_attempts = 1;
|
||||||
|
auto queue = world.queue();
|
||||||
|
assert(queue.publish("work", "final-1").has_value());
|
||||||
|
assert(queue.claim("worker-1").has_value());
|
||||||
|
|
||||||
|
auto recovered = queue.recover_consumer("worker-1");
|
||||||
|
assert(recovered.has_value());
|
||||||
|
assert(*recovered == 1);
|
||||||
|
const auto job = queue.status("final-1");
|
||||||
|
assert(job.has_value());
|
||||||
|
assert(job->state == JobState::Dead);
|
||||||
|
}
|
||||||
|
|
||||||
|
void no_quorum_write_is_never_durable()
|
||||||
|
{
|
||||||
|
World world;
|
||||||
|
auto queue = world.queue();
|
||||||
|
world.cluster.set_partition("b", 1);
|
||||||
|
world.cluster.set_partition("c", 1);
|
||||||
|
|
||||||
|
auto published = queue.publish("lost", "loss-1");
|
||||||
|
assert(!published.has_value());
|
||||||
|
|
||||||
|
world.cluster.set_partition("b", 0);
|
||||||
|
world.cluster.set_partition("c", 0);
|
||||||
|
// The failed publish was never applied.
|
||||||
|
auto status = queue.status("loss-1");
|
||||||
|
assert(!status.has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
void ack_from_the_wrong_consumer_is_rejected()
|
||||||
|
{
|
||||||
|
World world;
|
||||||
|
auto queue = world.queue();
|
||||||
|
assert(queue.publish("work", "owner-1").has_value());
|
||||||
|
assert(queue.claim("worker-1").has_value());
|
||||||
|
|
||||||
|
auto wrong = queue.ack("worker-2", "owner-1");
|
||||||
|
assert(!wrong.has_value());
|
||||||
|
assert(wrong.error().kind() == Void::Result::ErrorKind::conflict);
|
||||||
|
assert(queue.ack("worker-1", "owner-1").has_value());
|
||||||
|
}
|
||||||
|
|
||||||
|
void leader_change_requires_endpoint_update()
|
||||||
|
{
|
||||||
|
World world;
|
||||||
|
auto queue = world.queue();
|
||||||
|
assert(queue.publish("work", "move-1").has_value());
|
||||||
|
|
||||||
|
world.cluster.set_partition("a", 1);
|
||||||
|
assert(world.cluster.elect("b").has_value());
|
||||||
|
// The queue still points at the old leader: explicit failure, not a
|
||||||
|
// silent write to a minority.
|
||||||
|
auto stale = queue.publish("work", "move-2");
|
||||||
|
assert(!stale.has_value());
|
||||||
|
|
||||||
|
queue.set_leader("b");
|
||||||
|
auto moved = queue.publish("work", "move-2");
|
||||||
|
assert(moved.has_value());
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
publish_claim_ack_dispatches_one_effect();
|
||||||
|
retries_then_dead_letters();
|
||||||
|
crashed_consumer_is_recovered();
|
||||||
|
final_attempt_recovery_dead_letters();
|
||||||
|
no_quorum_write_is_never_durable();
|
||||||
|
ack_from_the_wrong_consumer_is_rejected();
|
||||||
|
leader_change_requires_endpoint_update();
|
||||||
|
std::puts("distributed replicated queue ok");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user