feat(messaging): implement P3 S-MESSAGING-01..04 Messaging queue, StorageQueue/OutboxInbox, and MessagingRpc adapter
This commit is contained in:
1 parent
aaeab50758
commit
60ee28e4ca
17 files changed
+4641
No files matched your search
@@ -0,0 +1,180 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Messaging/Types.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Messaging
|
||||
{
|
||||
/// Abstract queue interface implemented by both explicitly nondurable
|
||||
/// `InMemoryQueue` and durable `MessagingStorage::StorageQueue`.
|
||||
class Queue
|
||||
{
|
||||
public:
|
||||
|
||||
virtual ~Queue() = default;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
create_queue(QueueConfig config) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
create_group(std::string_view queue, GroupConfig config) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<PublishReceipt> publish(
|
||||
std::string_view queue, Message message,
|
||||
PublishDurability durability,
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<std::optional<Delivery>>
|
||||
try_receive(std::string_view queue, std::string_view group) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<Delivery> receive(
|
||||
std::string_view queue, std::string_view group,
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void>
|
||||
ack(const Receipt& receipt,
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<void> nack(
|
||||
const Receipt& receipt,
|
||||
std::optional<std::chrono::milliseconds> delay = std::nullopt,
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<Void::Time::MonotonicClock::time_point>
|
||||
extend_visibility(
|
||||
const Receipt& receipt, std::chrono::milliseconds extension,
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
/// Quarantine an unparseable or schema-incompatible message into
|
||||
/// DLQ without falsely acknowledging it as processed.
|
||||
[[nodiscard]] virtual Result<void> quarantine_corrupt(
|
||||
const Receipt& receipt, std::string reason,
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<DeliveryState>
|
||||
query_receipt(const Receipt& receipt) const = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<std::vector<DeadLetterEntry>>
|
||||
list_dead_letters(std::string_view queue,
|
||||
std::string_view group,
|
||||
std::size_t limit = 100) const = 0;
|
||||
|
||||
[[nodiscard]] virtual std::size_t
|
||||
stuck_dlq_count(std::string_view queue,
|
||||
std::string_view group) const noexcept = 0;
|
||||
|
||||
/// Reclaim expired `InFlight` deliveries into `Pending` (with retry
|
||||
/// backoff) or atomically move exhausted messages to DLQ.
|
||||
[[nodiscard]] virtual Result<std::size_t>
|
||||
reap_expired_visibility() = 0;
|
||||
|
||||
/// Apply configured retention policy (paused when civil clock
|
||||
/// health is degraded).
|
||||
[[nodiscard]] virtual Result<std::size_t> expire_retention() = 0;
|
||||
|
||||
virtual void set_clock_healthy(bool healthy) noexcept = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<ShutdownReport> close_and_join(
|
||||
Void::Async::OperationOptions options = {}) = 0;
|
||||
|
||||
[[nodiscard]] virtual Result<QueueStats> stats() const = 0;
|
||||
};
|
||||
|
||||
struct InMemoryQueueOptions {
|
||||
QueueLimits limits{};
|
||||
const Void::Time::MonotonicClock* monotonic_clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
const Void::Time::CivilClock* civil_clock{
|
||||
&Void::Time::SystemCivilClock::instance()};
|
||||
RandomU64Fn rng{};
|
||||
};
|
||||
|
||||
/// Explicitly nondurable in-process queue implementing the full native
|
||||
/// delivery state machine (`PublishDurability::Durable` is rejected with
|
||||
/// `UnsupportedDurability`).
|
||||
class InMemoryQueue final : public Queue
|
||||
{
|
||||
public:
|
||||
|
||||
explicit InMemoryQueue(InMemoryQueueOptions options = {});
|
||||
~InMemoryQueue() noexcept override;
|
||||
|
||||
InMemoryQueue(InMemoryQueue&&) noexcept;
|
||||
InMemoryQueue& operator=(InMemoryQueue&&) noexcept;
|
||||
InMemoryQueue(const InMemoryQueue&) = delete;
|
||||
InMemoryQueue& operator=(const InMemoryQueue&) = delete;
|
||||
|
||||
[[nodiscard]] Result<void> create_queue(QueueConfig config) override;
|
||||
[[nodiscard]] Result<void>
|
||||
create_group(std::string_view queue,
|
||||
GroupConfig config) override;
|
||||
|
||||
[[nodiscard]] Result<PublishReceipt> publish(
|
||||
std::string_view queue, Message message,
|
||||
PublishDurability durability,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<std::optional<Delivery>>
|
||||
try_receive(std::string_view queue,
|
||||
std::string_view group) override;
|
||||
|
||||
[[nodiscard]] Result<Delivery> receive(
|
||||
std::string_view queue, std::string_view group,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<void>
|
||||
ack(const Receipt& receipt,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<void> nack(
|
||||
const Receipt& receipt,
|
||||
std::optional<std::chrono::milliseconds> delay = std::nullopt,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<Void::Time::MonotonicClock::time_point>
|
||||
extend_visibility(
|
||||
const Receipt& receipt, std::chrono::milliseconds extension,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<void> quarantine_corrupt(
|
||||
const Receipt& receipt, std::string reason,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<DeliveryState>
|
||||
query_receipt(const Receipt& receipt) const override;
|
||||
|
||||
[[nodiscard]] Result<std::vector<DeadLetterEntry>>
|
||||
list_dead_letters(std::string_view queue,
|
||||
std::string_view group,
|
||||
std::size_t limit = 100) const override;
|
||||
|
||||
[[nodiscard]] std::size_t
|
||||
stuck_dlq_count(std::string_view queue,
|
||||
std::string_view group) const noexcept override;
|
||||
|
||||
[[nodiscard]] Result<std::size_t>
|
||||
reap_expired_visibility() override;
|
||||
|
||||
[[nodiscard]] Result<std::size_t> expire_retention() override;
|
||||
|
||||
void set_clock_healthy(bool healthy) noexcept override;
|
||||
|
||||
[[nodiscard]] Result<ShutdownReport> close_and_join(
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Result<QueueStats> stats() const override;
|
||||
|
||||
private:
|
||||
|
||||
struct State;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
} // namespace Void::Messaging
|
||||
@@ -0,0 +1,260 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <compare>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Messaging
|
||||
{
|
||||
using Void::Result::Error;
|
||||
template <typename T> using Result = Void::Result::Result<T, Error>;
|
||||
|
||||
enum class MessagingErrorCode : std::int32_t {
|
||||
None = 0,
|
||||
InvalidArgument = 1,
|
||||
NotFound = 2,
|
||||
Conflict = 3,
|
||||
StaleReceipt = 4,
|
||||
Overloaded = 5,
|
||||
QuotaExceeded = 6,
|
||||
IdempotencyCapacityExceeded = 7,
|
||||
DlqFull = 8,
|
||||
UnsupportedDurability = 9,
|
||||
CorruptPayload = 10,
|
||||
PersistenceError = 11,
|
||||
UnknownOutcome = 12,
|
||||
Cancelled = 13,
|
||||
Timeout = 14,
|
||||
Closed = 15,
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Error make_messaging_error(MessagingErrorCode code,
|
||||
std::string message)
|
||||
{
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case MessagingErrorCode::None:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case MessagingErrorCode::InvalidArgument:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case MessagingErrorCode::NotFound:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case MessagingErrorCode::Conflict:
|
||||
case MessagingErrorCode::StaleReceipt:
|
||||
case MessagingErrorCode::UnknownOutcome:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case MessagingErrorCode::Overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case MessagingErrorCode::QuotaExceeded:
|
||||
case MessagingErrorCode::IdempotencyCapacityExceeded:
|
||||
case MessagingErrorCode::DlqFull:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case MessagingErrorCode::UnsupportedDurability:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case MessagingErrorCode::CorruptPayload:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
case MessagingErrorCode::PersistenceError:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
case MessagingErrorCode::Cancelled:
|
||||
case MessagingErrorCode::Closed:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case MessagingErrorCode::Timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
}
|
||||
return Error{kind, std::move(message),
|
||||
ErrorCode{Void::Result::kMessagingErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
/// Explicit publish durability contract. Nondurable queues must reject
|
||||
/// `PublishDurability::Durable` rather than returning a false durable OK.
|
||||
enum class PublishDurability : std::uint8_t {
|
||||
Memory = 0,
|
||||
Durable = 1,
|
||||
};
|
||||
|
||||
enum class ConsumerMode : std::uint8_t {
|
||||
Competing = 0,
|
||||
SingleActive = 1,
|
||||
};
|
||||
|
||||
enum class RetentionPolicy : std::uint8_t {
|
||||
/// Initial default: block further publish at quota rather than silently
|
||||
/// expiring unread work.
|
||||
BlockAtQuota = 0,
|
||||
/// Explicit opt-in lossy mode allowing retention expiry of unread work.
|
||||
DropOldestLossy = 1,
|
||||
};
|
||||
|
||||
enum class DeliveryState : std::uint8_t {
|
||||
Pending = 0,
|
||||
InFlight = 1,
|
||||
Acked = 2,
|
||||
DeadLetter = 3,
|
||||
};
|
||||
|
||||
struct Message {
|
||||
std::string id{};
|
||||
std::vector<std::byte> payload{};
|
||||
std::map<std::string, std::string, std::less<>> headers{};
|
||||
std::uint32_t schema_version{1};
|
||||
|
||||
[[nodiscard]] bool
|
||||
operator==(const Message&) const noexcept = default;
|
||||
};
|
||||
|
||||
struct Receipt {
|
||||
std::string queue{};
|
||||
std::string group{};
|
||||
std::string message_id{};
|
||||
std::uint64_t sequence{0};
|
||||
std::uint64_t generation{0};
|
||||
|
||||
[[nodiscard]] auto
|
||||
operator<=>(const Receipt&) const noexcept = default;
|
||||
};
|
||||
|
||||
struct PublishReceipt {
|
||||
std::string queue{};
|
||||
std::string message_id{};
|
||||
std::uint64_t sequence{0};
|
||||
PublishDurability durability{PublishDurability::Memory};
|
||||
bool deduplicated{false};
|
||||
};
|
||||
|
||||
struct Delivery {
|
||||
Message message{};
|
||||
Receipt receipt{};
|
||||
std::uint32_t attempt{1};
|
||||
Void::Time::MonotonicClock::time_point visibility_deadline{};
|
||||
};
|
||||
|
||||
struct DeadLetterEntry {
|
||||
Message message{};
|
||||
std::string queue{};
|
||||
std::string group{};
|
||||
std::uint64_t sequence{0};
|
||||
std::uint32_t attempts{0};
|
||||
std::string reason{};
|
||||
std::int64_t dead_lettered_utc_ms{0};
|
||||
};
|
||||
|
||||
struct RetryPolicy {
|
||||
std::uint32_t max_attempts{5};
|
||||
std::chrono::milliseconds base_delay{std::chrono::seconds{1}};
|
||||
std::chrono::milliseconds max_delay{std::chrono::seconds{60}};
|
||||
};
|
||||
|
||||
struct QueueLimits {
|
||||
std::size_t max_message_bytes{768ULL * 1024};
|
||||
std::size_t max_headers_bytes{8ULL * 1024};
|
||||
std::size_t max_header_count{32};
|
||||
std::size_t max_queues{1024};
|
||||
std::size_t max_groups_per_queue{32};
|
||||
std::size_t max_in_flight_per_group{64};
|
||||
std::size_t max_waiting_receives{1024};
|
||||
std::size_t max_transient_payload_bytes{64ULL * 1024 * 1024};
|
||||
std::uint64_t persistent_quota_bytes{1024ULL * 1024 * 1024};
|
||||
std::size_t max_dlq_messages{10000};
|
||||
std::chrono::milliseconds idempotency_retention{
|
||||
std::chrono::hours{24}};
|
||||
std::size_t max_idempotency_entries{100000};
|
||||
std::chrono::milliseconds default_visibility_timeout{
|
||||
std::chrono::seconds{30}};
|
||||
std::chrono::milliseconds max_visibility_extension{
|
||||
std::chrono::minutes{5}};
|
||||
std::chrono::milliseconds logical_retention{
|
||||
std::chrono::hours{24 * 7}};
|
||||
std::chrono::milliseconds shutdown_drain_timeout{
|
||||
std::chrono::seconds{10}};
|
||||
};
|
||||
|
||||
struct QueueConfig {
|
||||
std::string name{};
|
||||
RetentionPolicy retention_policy{RetentionPolicy::BlockAtQuota};
|
||||
RetryPolicy retry{};
|
||||
};
|
||||
|
||||
struct GroupConfig {
|
||||
std::string name{};
|
||||
ConsumerMode mode{ConsumerMode::Competing};
|
||||
std::chrono::milliseconds visibility_timeout{
|
||||
std::chrono::seconds{30}};
|
||||
std::size_t max_in_flight{64};
|
||||
};
|
||||
|
||||
struct QueueStats {
|
||||
std::size_t queues{0};
|
||||
std::size_t pending{0};
|
||||
std::size_t in_flight{0};
|
||||
std::size_t acked{0};
|
||||
std::size_t dead_letter{0};
|
||||
std::size_t stuck_dlq{0};
|
||||
std::uint64_t retained_bytes{0};
|
||||
std::size_t idempotency_entries{0};
|
||||
};
|
||||
|
||||
struct ShutdownReport {
|
||||
bool complete{true};
|
||||
std::size_t remaining_in_flight{0};
|
||||
};
|
||||
|
||||
using RandomU64Fn = std::function<std::uint64_t()>;
|
||||
|
||||
[[nodiscard]] Result<void>
|
||||
validate_identifier(std::string_view name, std::string_view label);
|
||||
|
||||
[[nodiscard]] Result<void> validate_message(const Message& message,
|
||||
const QueueLimits& limits);
|
||||
|
||||
[[nodiscard]] std::size_t
|
||||
estimate_message_bytes(const Message& message) noexcept;
|
||||
|
||||
[[nodiscard]] std::int64_t
|
||||
compute_retry_backoff_ms(const RetryPolicy& retry,
|
||||
std::uint32_t attempt,
|
||||
const RandomU64Fn& rng);
|
||||
|
||||
[[nodiscard]] inline std::int64_t
|
||||
to_mono_ns(Void::Time::MonotonicClock::time_point tp) noexcept
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
tp.time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::int64_t
|
||||
to_utc_ms(Void::Time::CivilClock::time_point tp) noexcept
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
tp.time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
} // namespace Void::Messaging
|
||||
@@ -0,0 +1,89 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
#include <Void/RPC/Rpc.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::MessagingRpc
|
||||
{
|
||||
inline constexpr std::uint64_t kMessagingRpcServiceId = 0x564D534752504301ULL;
|
||||
inline constexpr Void::RPC::MethodId kPublishMethod{
|
||||
kMessagingRpcServiceId, 1U};
|
||||
inline constexpr Void::RPC::MethodId kTryReceiveMethod{
|
||||
kMessagingRpcServiceId, 2U};
|
||||
inline constexpr Void::RPC::MethodId kAckMethod{
|
||||
kMessagingRpcServiceId, 3U};
|
||||
inline constexpr Void::RPC::MethodId kNackMethod{
|
||||
kMessagingRpcServiceId, 4U};
|
||||
inline constexpr Void::RPC::MethodId kQueryReceiptMethod{
|
||||
kMessagingRpcServiceId, 5U};
|
||||
|
||||
/// Mounts remote Messaging operations (`publish`, `try_receive`, `ack`,
|
||||
/// `nack`, `query_receipt`) onto a `Void::RPC::Server`.
|
||||
class RpcQueueServer final
|
||||
{
|
||||
public:
|
||||
|
||||
RpcQueueServer() = default;
|
||||
~RpcQueueServer() noexcept;
|
||||
|
||||
RpcQueueServer(RpcQueueServer&&) noexcept = default;
|
||||
RpcQueueServer& operator=(RpcQueueServer&&) noexcept = default;
|
||||
RpcQueueServer(const RpcQueueServer&) = delete;
|
||||
RpcQueueServer& operator=(const RpcQueueServer&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void>
|
||||
mount(Void::RPC::Server& server,
|
||||
Void::Messaging::Queue& queue);
|
||||
|
||||
void unmount_and_drain() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
std::vector<Void::RPC::Registration> m_registrations{};
|
||||
};
|
||||
|
||||
/// Remote client executing Messaging operations over unary `Void::RPC::Client`,
|
||||
/// propagating `UnknownOutcome` faithfully when network replies are lost.
|
||||
class RpcQueueClient final
|
||||
{
|
||||
public:
|
||||
|
||||
explicit RpcQueueClient(Void::RPC::ClientOptions options);
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::PublishReceipt>
|
||||
publish(std::string_view queue,
|
||||
const Void::Messaging::Message& message,
|
||||
Void::Messaging::PublishDurability durability,
|
||||
const Void::RPC::CallOptions& options = {});
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<
|
||||
std::optional<Void::Messaging::Delivery>>
|
||||
try_receive(std::string_view queue, std::string_view group,
|
||||
const Void::RPC::CallOptions& options = {});
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void>
|
||||
ack(const Void::Messaging::Receipt& receipt,
|
||||
const Void::RPC::CallOptions& options = {});
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void>
|
||||
nack(const Void::Messaging::Receipt& receipt,
|
||||
std::optional<std::chrono::milliseconds> delay =
|
||||
std::nullopt,
|
||||
const Void::RPC::CallOptions& options = {});
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::DeliveryState>
|
||||
query_receipt(const Void::Messaging::Receipt& receipt,
|
||||
const Void::RPC::CallOptions& options = {});
|
||||
|
||||
private:
|
||||
|
||||
Void::RPC::Client m_client;
|
||||
};
|
||||
|
||||
} // namespace Void::MessagingRpc
|
||||
@@ -0,0 +1,260 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
#include <Void/Storage/Batch.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::MessagingStorage
|
||||
{
|
||||
struct OutboxRecord {
|
||||
std::string outbox_id{};
|
||||
std::string target_queue{};
|
||||
Void::Messaging::Message message{};
|
||||
};
|
||||
|
||||
/// Atomic local-batch helpers for the Outbox and Inbox patterns over a
|
||||
/// single shared `Void::Storage::Engine`.
|
||||
///
|
||||
/// Boundary guarantee:
|
||||
/// - Business state + outbox insert (or consumer state + inbox dedup key)
|
||||
/// commit atomically ONLY within the same `Void::Storage::Batch`.
|
||||
/// - External effects (email, HTTP/RPC calls, separate databases) remain
|
||||
/// strictly outside this batch boundary and still require downstream
|
||||
/// idempotency or compensation.
|
||||
class OutboxInbox final
|
||||
{
|
||||
public:
|
||||
|
||||
static void append_outbox_in_batch(
|
||||
Void::Storage::Batch& batch, const OutboxRecord& record,
|
||||
std::string_view prefix = "outbox:v1:")
|
||||
{
|
||||
const std::string key =
|
||||
std::string{prefix} + record.outbox_id;
|
||||
batch.require_absent(key);
|
||||
batch.put(key, encode_outbox(record));
|
||||
}
|
||||
|
||||
/// Record inbox deduplication key inside the consumer's SAME
|
||||
/// `Void::Storage::Batch` as its local business mutation. If the
|
||||
/// message was already applied, the batch fails with `Conflict`
|
||||
/// (duplicate prevented atomically).
|
||||
static void apply_inbox_in_batch(
|
||||
Void::Storage::Batch& batch, std::string_view consumer_id,
|
||||
std::string_view message_id,
|
||||
std::string_view prefix = "inbox:v1:")
|
||||
{
|
||||
const std::string key = std::string{prefix} +
|
||||
std::string{consumer_id} + "\x1F" +
|
||||
std::string{message_id};
|
||||
batch.require_absent(key);
|
||||
batch.put(key, "1");
|
||||
}
|
||||
|
||||
/// Relay pending outbox entries to `queue` using stable
|
||||
/// `Message::id` (idempotent on retry) and delete confirmed entries.
|
||||
[[nodiscard]] static Void::Messaging::Result<std::size_t>
|
||||
relay_outbox(Void::Storage::Engine& engine,
|
||||
Void::Messaging::Queue& queue,
|
||||
std::string_view prefix = "outbox:v1:",
|
||||
std::size_t max_entries = 64)
|
||||
{
|
||||
auto snap = engine.snapshot();
|
||||
if (!snap.has_value()) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::PersistenceError,
|
||||
snap.error().message()));
|
||||
}
|
||||
auto cur = engine.scan(
|
||||
std::move(*snap),
|
||||
Void::Storage::ScanBounds::prefix(prefix));
|
||||
if (!cur.has_value()) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::PersistenceError,
|
||||
cur.error().message()));
|
||||
}
|
||||
|
||||
std::size_t relayed = 0;
|
||||
for (;;) {
|
||||
auto page = cur->next_page();
|
||||
if (!page.has_value()) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::
|
||||
PersistenceError,
|
||||
page.error().message()));
|
||||
}
|
||||
for (const auto& entry : page->entries) {
|
||||
if (relayed >= max_entries) {
|
||||
return relayed;
|
||||
}
|
||||
auto decoded = decode_outbox(
|
||||
Void::Storage::to_string_view(entry.value));
|
||||
if (!decoded.has_value()) {
|
||||
return Void::Result::fail(decoded.error());
|
||||
}
|
||||
auto pub = queue.publish(
|
||||
decoded->target_queue, decoded->message,
|
||||
Void::Messaging::PublishDurability::Durable);
|
||||
if (!pub.has_value()) {
|
||||
return Void::Result::fail(pub.error());
|
||||
}
|
||||
Void::Storage::Batch erase_b{};
|
||||
erase_b.require_version(entry.key, entry.version);
|
||||
erase_b.erase(entry.key);
|
||||
auto wr = engine.write(std::move(erase_b),
|
||||
Void::Storage::Durability::Sync);
|
||||
if (!wr.has_value()) {
|
||||
if (wr.error().outcome ==
|
||||
Void::Storage::Outcome::Unknown) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::
|
||||
UnknownOutcome,
|
||||
"Outbox relay delete outcome unknown"));
|
||||
}
|
||||
if (wr.error().cause.code !=
|
||||
Void::Storage::StorageErrorCode::conflict) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::
|
||||
PersistenceError,
|
||||
wr.error().cause.error.message()));
|
||||
}
|
||||
}
|
||||
++relayed;
|
||||
}
|
||||
if (!page->has_more) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return relayed;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
static void append_u32(std::string& out, std::uint32_t v)
|
||||
{
|
||||
out.push_back(static_cast<char>((v >> 24U) & 0xFFU));
|
||||
out.push_back(static_cast<char>((v >> 16U) & 0xFFU));
|
||||
out.push_back(static_cast<char>((v >> 8U) & 0xFFU));
|
||||
out.push_back(static_cast<char>(v & 0xFFU));
|
||||
}
|
||||
|
||||
static void append_str(std::string& out, std::string_view s)
|
||||
{
|
||||
append_u32(out, static_cast<std::uint32_t>(s.size()));
|
||||
out.append(s);
|
||||
}
|
||||
|
||||
[[nodiscard]] static bool read_u32(std::string_view& in,
|
||||
std::uint32_t& out) noexcept
|
||||
{
|
||||
if (in.size() < 4U) return false;
|
||||
out = (static_cast<std::uint32_t>(
|
||||
static_cast<unsigned char>(in[0]))
|
||||
<< 24U) |
|
||||
(static_cast<std::uint32_t>(
|
||||
static_cast<unsigned char>(in[1]))
|
||||
<< 16U) |
|
||||
(static_cast<std::uint32_t>(
|
||||
static_cast<unsigned char>(in[2]))
|
||||
<< 8U) |
|
||||
static_cast<std::uint32_t>(
|
||||
static_cast<unsigned char>(in[3]));
|
||||
in.remove_prefix(4U);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] static bool read_str(std::string_view& in,
|
||||
std::string& out)
|
||||
{
|
||||
std::uint32_t len = 0;
|
||||
if (!read_u32(in, len) || len > in.size()) return false;
|
||||
out.assign(in.data(), len);
|
||||
in.remove_prefix(len);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] static std::string
|
||||
encode_outbox(const OutboxRecord& r)
|
||||
{
|
||||
std::string out;
|
||||
append_u32(out, 1U);
|
||||
append_str(out, r.outbox_id);
|
||||
append_str(out, r.target_queue);
|
||||
append_str(out, r.message.id);
|
||||
append_u32(out, r.message.schema_version);
|
||||
append_u32(out,
|
||||
static_cast<std::uint32_t>(r.message.payload.size()));
|
||||
if (!r.message.payload.empty()) {
|
||||
out.append(
|
||||
reinterpret_cast<const char*>(r.message.payload.data()),
|
||||
r.message.payload.size());
|
||||
}
|
||||
append_u32(
|
||||
out, static_cast<std::uint32_t>(r.message.headers.size()));
|
||||
for (const auto& [k, v] : r.message.headers) {
|
||||
append_str(out, k);
|
||||
append_str(out, v);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
[[nodiscard]] static Void::Messaging::Result<OutboxRecord>
|
||||
decode_outbox(std::string_view raw)
|
||||
{
|
||||
std::uint32_t ver = 0;
|
||||
if (!read_u32(raw, ver) || ver != 1U) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::CorruptPayload,
|
||||
"Outbox: unsupported schema version"));
|
||||
}
|
||||
OutboxRecord r{};
|
||||
std::uint32_t plen = 0;
|
||||
std::uint32_t hcount = 0;
|
||||
if (!read_str(raw, r.outbox_id) ||
|
||||
!read_str(raw, r.target_queue) ||
|
||||
!read_str(raw, r.message.id) ||
|
||||
!read_u32(raw, r.message.schema_version) ||
|
||||
!read_u32(raw, plen) || plen > raw.size()) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::CorruptPayload,
|
||||
"Outbox: truncated payload"));
|
||||
}
|
||||
r.message.payload.resize(plen);
|
||||
if (plen > 0U) {
|
||||
std::memcpy(r.message.payload.data(), raw.data(), plen);
|
||||
raw.remove_prefix(plen);
|
||||
}
|
||||
if (!read_u32(raw, hcount)) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::CorruptPayload,
|
||||
"Outbox: truncated header count"));
|
||||
}
|
||||
for (std::uint32_t i = 0; i < hcount; ++i) {
|
||||
std::string k, v;
|
||||
if (!read_str(raw, k) || !read_str(raw, v)) {
|
||||
return Void::Result::fail(
|
||||
Void::Messaging::make_messaging_error(
|
||||
Void::Messaging::MessagingErrorCode::
|
||||
CorruptPayload,
|
||||
"Outbox: truncated header"));
|
||||
}
|
||||
r.message.headers.emplace(std::move(k), std::move(v));
|
||||
}
|
||||
return r;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace Void::MessagingStorage
|
||||
@@ -0,0 +1,121 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
namespace Void::MessagingStorage
|
||||
{
|
||||
struct StorageQueueOptions {
|
||||
Void::Messaging::QueueLimits limits{};
|
||||
std::string key_prefix{"msg:v1:"};
|
||||
const Void::Time::MonotonicClock* monotonic_clock{
|
||||
&Void::Time::SystemMonotonicClock::instance()};
|
||||
const Void::Time::CivilClock* civil_clock{
|
||||
&Void::Time::SystemCivilClock::instance()};
|
||||
Void::Messaging::RandomU64Fn rng{};
|
||||
};
|
||||
|
||||
/// Single-node durable `Void::Messaging::Queue` backed by
|
||||
/// `Void::Storage::Engine` conditional batches (`Durability::Sync` for
|
||||
/// `PublishDurability::Durable`).
|
||||
///
|
||||
/// Explicit at-least-once delivery:
|
||||
/// - On open/restart, all prior `InFlight` records are promoted to
|
||||
/// `Pending` with a bumped delivery generation so stale worker receipts
|
||||
/// fail with `StaleReceipt` while preserving attempt counters.
|
||||
/// - DLQ insertion and source delivery update execute in one atomic batch.
|
||||
class StorageQueue final : public Void::Messaging::Queue
|
||||
{
|
||||
public:
|
||||
|
||||
[[nodiscard]] static Void::Messaging::Result<StorageQueue>
|
||||
open(Void::Storage::Engine& engine,
|
||||
StorageQueueOptions options = {});
|
||||
|
||||
~StorageQueue() noexcept override;
|
||||
StorageQueue(StorageQueue&&) noexcept;
|
||||
StorageQueue& operator=(StorageQueue&&) noexcept;
|
||||
StorageQueue(const StorageQueue&) = delete;
|
||||
StorageQueue& operator=(const StorageQueue&) = delete;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void>
|
||||
create_queue(Void::Messaging::QueueConfig config) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void>
|
||||
create_group(std::string_view queue,
|
||||
Void::Messaging::GroupConfig config) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::PublishReceipt>
|
||||
publish(std::string_view queue, Void::Messaging::Message message,
|
||||
Void::Messaging::PublishDurability durability,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<
|
||||
std::optional<Void::Messaging::Delivery>>
|
||||
try_receive(std::string_view queue,
|
||||
std::string_view group) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::Delivery>
|
||||
receive(std::string_view queue, std::string_view group,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void>
|
||||
ack(const Void::Messaging::Receipt& receipt,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void> nack(
|
||||
const Void::Messaging::Receipt& receipt,
|
||||
std::optional<std::chrono::milliseconds> delay = std::nullopt,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<
|
||||
Void::Time::MonotonicClock::time_point>
|
||||
extend_visibility(
|
||||
const Void::Messaging::Receipt& receipt,
|
||||
std::chrono::milliseconds extension,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<void> quarantine_corrupt(
|
||||
const Void::Messaging::Receipt& receipt, std::string reason,
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::DeliveryState>
|
||||
query_receipt(
|
||||
const Void::Messaging::Receipt& receipt) const override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<
|
||||
std::vector<Void::Messaging::DeadLetterEntry>>
|
||||
list_dead_letters(std::string_view queue,
|
||||
std::string_view group,
|
||||
std::size_t limit = 100) const override;
|
||||
|
||||
[[nodiscard]] std::size_t
|
||||
stuck_dlq_count(std::string_view queue,
|
||||
std::string_view group) const noexcept override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<std::size_t>
|
||||
reap_expired_visibility() override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<std::size_t>
|
||||
expire_retention() override;
|
||||
|
||||
void set_clock_healthy(bool healthy) noexcept override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::ShutdownReport>
|
||||
close_and_join(
|
||||
Void::Async::OperationOptions options = {}) override;
|
||||
|
||||
[[nodiscard]] Void::Messaging::Result<Void::Messaging::QueueStats>
|
||||
stats() const override;
|
||||
|
||||
private:
|
||||
|
||||
struct State;
|
||||
explicit StorageQueue(std::shared_ptr<State> state) noexcept;
|
||||
std::shared_ptr<State> m_state;
|
||||
};
|
||||
|
||||
} // namespace Void::MessagingStorage
|
||||
Reference in new issue
Block a user