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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
void_add_module(Messaging
|
||||
INTERNAL_DEPS Core Functional Binary Time Async
|
||||
)
|
||||
@@ -0,0 +1,513 @@
|
||||
#include <Void/MessagingRpc/RpcAdapter.hpp>
|
||||
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::MessagingRpc
|
||||
{
|
||||
using namespace Void::Messaging;
|
||||
using Void::Messaging::Result;
|
||||
|
||||
namespace
|
||||
{
|
||||
void put_u8(Void::RPC::OwnedBytes& out, std::uint8_t v)
|
||||
{
|
||||
out.push_back(static_cast<std::byte>(v));
|
||||
}
|
||||
|
||||
void put_u32(Void::RPC::OwnedBytes& out, std::uint32_t v)
|
||||
{
|
||||
out.push_back(static_cast<std::byte>((v >> 24U) & 0xFFU));
|
||||
out.push_back(static_cast<std::byte>((v >> 16U) & 0xFFU));
|
||||
out.push_back(static_cast<std::byte>((v >> 8U) & 0xFFU));
|
||||
out.push_back(static_cast<std::byte>(v & 0xFFU));
|
||||
}
|
||||
|
||||
void put_u64(Void::RPC::OwnedBytes& out, std::uint64_t v)
|
||||
{
|
||||
for (int shift = 56; shift >= 0; shift -= 8) {
|
||||
out.push_back(static_cast<std::byte>((v >> shift) & 0xFFU));
|
||||
}
|
||||
}
|
||||
|
||||
void put_i64(Void::RPC::OwnedBytes& out, std::int64_t v)
|
||||
{
|
||||
put_u64(out, static_cast<std::uint64_t>(v));
|
||||
}
|
||||
|
||||
void put_str(Void::RPC::OwnedBytes& out, std::string_view s)
|
||||
{
|
||||
put_u32(out, static_cast<std::uint32_t>(s.size()));
|
||||
for (char c : s) {
|
||||
out.push_back(static_cast<std::byte>(c));
|
||||
}
|
||||
}
|
||||
|
||||
void put_bytes(Void::RPC::OwnedBytes& out,
|
||||
const std::vector<std::byte>& b)
|
||||
{
|
||||
put_u32(out, static_cast<std::uint32_t>(b.size()));
|
||||
out.insert(out.end(), b.begin(), b.end());
|
||||
}
|
||||
|
||||
void put_message(Void::RPC::OwnedBytes& out, const Message& m)
|
||||
{
|
||||
put_str(out, m.id);
|
||||
put_u32(out, m.schema_version);
|
||||
put_bytes(out, m.payload);
|
||||
put_u32(out, static_cast<std::uint32_t>(m.headers.size()));
|
||||
for (const auto& [k, v] : m.headers) {
|
||||
put_str(out, k);
|
||||
put_str(out, v);
|
||||
}
|
||||
}
|
||||
|
||||
void put_receipt(Void::RPC::OwnedBytes& out, const Receipt& r)
|
||||
{
|
||||
put_str(out, r.queue);
|
||||
put_str(out, r.group);
|
||||
put_str(out, r.message_id);
|
||||
put_u64(out, r.sequence);
|
||||
put_u64(out, r.generation);
|
||||
}
|
||||
|
||||
struct Cursor {
|
||||
std::span<const std::byte> data{};
|
||||
std::size_t pos{0};
|
||||
|
||||
[[nodiscard]] bool read_u8(std::uint8_t& v) noexcept
|
||||
{
|
||||
if (pos + 1U > data.size()) return false;
|
||||
v = std::to_integer<std::uint8_t>(data[pos++]);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_u32(std::uint32_t& v) noexcept
|
||||
{
|
||||
if (pos + 4U > data.size()) return false;
|
||||
v = (static_cast<std::uint32_t>(
|
||||
std::to_integer<std::uint8_t>(data[pos]))
|
||||
<< 24U) |
|
||||
(static_cast<std::uint32_t>(
|
||||
std::to_integer<std::uint8_t>(data[pos + 1]))
|
||||
<< 16U) |
|
||||
(static_cast<std::uint32_t>(
|
||||
std::to_integer<std::uint8_t>(data[pos + 2]))
|
||||
<< 8U) |
|
||||
static_cast<std::uint32_t>(
|
||||
std::to_integer<std::uint8_t>(data[pos + 3]));
|
||||
pos += 4U;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_u64(std::uint64_t& v) noexcept
|
||||
{
|
||||
if (pos + 8U > data.size()) return false;
|
||||
v = 0;
|
||||
for (std::size_t i = 0; i < 8U; ++i) {
|
||||
v = (v << 8U) |
|
||||
static_cast<std::uint64_t>(
|
||||
std::to_integer<std::uint8_t>(data[pos + i]));
|
||||
}
|
||||
pos += 8U;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_i64(std::int64_t& v) noexcept
|
||||
{
|
||||
std::uint64_t u = 0;
|
||||
if (!read_u64(u)) return false;
|
||||
v = static_cast<std::int64_t>(u);
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_str(std::string& s)
|
||||
{
|
||||
std::uint32_t len = 0;
|
||||
if (!read_u32(len) || pos + len > data.size()) return false;
|
||||
s.resize(len);
|
||||
if (len > 0U) {
|
||||
std::memcpy(s.data(), data.data() + pos, len);
|
||||
}
|
||||
pos += len;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_bytes(std::vector<std::byte>& b)
|
||||
{
|
||||
std::uint32_t len = 0;
|
||||
if (!read_u32(len) || pos + len > data.size()) return false;
|
||||
b.resize(len);
|
||||
if (len > 0U) {
|
||||
std::memcpy(b.data(), data.data() + pos, len);
|
||||
}
|
||||
pos += len;
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_message(Message& m)
|
||||
{
|
||||
std::uint32_t hcount = 0;
|
||||
if (!read_str(m.id) || !read_u32(m.schema_version) ||
|
||||
!read_bytes(m.payload) || !read_u32(hcount)) {
|
||||
return false;
|
||||
}
|
||||
m.headers.clear();
|
||||
for (std::uint32_t i = 0; i < hcount; ++i) {
|
||||
std::string k, v;
|
||||
if (!read_str(k) || !read_str(v)) return false;
|
||||
m.headers.emplace(std::move(k), std::move(v));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool read_receipt(Receipt& r)
|
||||
{
|
||||
return read_str(r.queue) && read_str(r.group) &&
|
||||
read_str(r.message_id) && read_u64(r.sequence) &&
|
||||
read_u64(r.generation);
|
||||
}
|
||||
|
||||
[[nodiscard]] bool eof() const noexcept
|
||||
{
|
||||
return pos == data.size();
|
||||
}
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Error
|
||||
map_rpc_err(const Void::Result::Error& err)
|
||||
{
|
||||
if (err.code().domain == Void::Result::kMessagingErrorDomain) {
|
||||
return err;
|
||||
}
|
||||
const auto status = Void::RPC::rpc_status_from_error(err);
|
||||
if (status == Void::RPC::RpcStatusCode::UnknownOutcome) {
|
||||
return make_messaging_error(MessagingErrorCode::UnknownOutcome,
|
||||
err.message());
|
||||
}
|
||||
if (status == Void::RPC::RpcStatusCode::FailedPrecondition) {
|
||||
return make_messaging_error(MessagingErrorCode::StaleReceipt,
|
||||
err.message());
|
||||
}
|
||||
if (status == Void::RPC::RpcStatusCode::NotFound) {
|
||||
return make_messaging_error(MessagingErrorCode::NotFound,
|
||||
err.message());
|
||||
}
|
||||
if (status == Void::RPC::RpcStatusCode::ResourceExhausted) {
|
||||
return make_messaging_error(MessagingErrorCode::QuotaExceeded,
|
||||
err.message());
|
||||
}
|
||||
if (status == Void::RPC::RpcStatusCode::DeadlineExceeded) {
|
||||
return make_messaging_error(MessagingErrorCode::Timeout,
|
||||
err.message());
|
||||
}
|
||||
if (status == Void::RPC::RpcStatusCode::Cancelled) {
|
||||
return make_messaging_error(MessagingErrorCode::Cancelled,
|
||||
err.message());
|
||||
}
|
||||
return make_messaging_error(MessagingErrorCode::PersistenceError,
|
||||
err.message());
|
||||
}
|
||||
} // namespace
|
||||
|
||||
RpcQueueServer::~RpcQueueServer() noexcept { unmount_and_drain(); }
|
||||
|
||||
void RpcQueueServer::unmount_and_drain() noexcept
|
||||
{
|
||||
for (auto& reg : m_registrations) {
|
||||
reg.unregister_and_drain();
|
||||
}
|
||||
m_registrations.clear();
|
||||
}
|
||||
|
||||
Result<void> RpcQueueServer::mount(Void::RPC::Server& server, Queue& queue)
|
||||
{
|
||||
auto bind_one = [&](Void::RPC::MethodId id, std::string name,
|
||||
Void::RPC::UnaryHandler handler) -> Result<void> {
|
||||
auto reg = server.bind(
|
||||
Void::RPC::MethodDescriptor{
|
||||
.id = id,
|
||||
.service_name = "void.messaging.v1",
|
||||
.method_name = std::move(name),
|
||||
.schema_version = 1,
|
||||
},
|
||||
std::move(handler));
|
||||
if (!reg.has_value()) {
|
||||
return Void::Result::fail(reg.error());
|
||||
}
|
||||
m_registrations.push_back(std::move(*reg));
|
||||
return {};
|
||||
};
|
||||
|
||||
if (auto r = bind_one(
|
||||
kPublishMethod, "publish",
|
||||
[&queue](const Void::RPC::CallContext& ctx,
|
||||
Void::RPC::OwnedBytes req)
|
||||
-> Void::Result::Result<Void::RPC::OwnedBytes> {
|
||||
Cursor c{req, 0};
|
||||
std::string qname;
|
||||
std::uint8_t dur = 0;
|
||||
Message msg{};
|
||||
if (!c.read_str(qname) || !c.read_u8(dur) ||
|
||||
!c.read_message(msg) || !c.eof()) {
|
||||
return Void::Result::fail(Void::RPC::make_rpc_error(
|
||||
Void::RPC::RpcStatusCode::InvalidArgument,
|
||||
"MessagingRpc: malformed publish request"));
|
||||
}
|
||||
Void::Async::OperationOptions opts{.stop = ctx.stop};
|
||||
auto res = queue.publish(
|
||||
qname, std::move(msg),
|
||||
static_cast<PublishDurability>(dur), opts);
|
||||
if (!res.has_value()) {
|
||||
return Void::Result::fail(res.error());
|
||||
}
|
||||
Void::RPC::OwnedBytes out;
|
||||
put_str(out, res->queue);
|
||||
put_str(out, res->message_id);
|
||||
put_u64(out, res->sequence);
|
||||
put_u8(out, static_cast<std::uint8_t>(res->durability));
|
||||
put_u8(out, res->deduplicated ? 1U : 0U);
|
||||
return out;
|
||||
});
|
||||
!r.has_value()) {
|
||||
return r;
|
||||
}
|
||||
|
||||
if (auto r = bind_one(
|
||||
kTryReceiveMethod, "try_receive",
|
||||
[&queue](const Void::RPC::CallContext&,
|
||||
Void::RPC::OwnedBytes req)
|
||||
-> Void::Result::Result<Void::RPC::OwnedBytes> {
|
||||
Cursor c{req, 0};
|
||||
std::string qname, gname;
|
||||
if (!c.read_str(qname) || !c.read_str(gname) || !c.eof()) {
|
||||
return Void::Result::fail(Void::RPC::make_rpc_error(
|
||||
Void::RPC::RpcStatusCode::InvalidArgument,
|
||||
"MessagingRpc: malformed try_receive request"));
|
||||
}
|
||||
auto res = queue.try_receive(qname, gname);
|
||||
if (!res.has_value()) {
|
||||
return Void::Result::fail(res.error());
|
||||
}
|
||||
Void::RPC::OwnedBytes out;
|
||||
if (!res->has_value()) {
|
||||
put_u8(out, 0U);
|
||||
return out;
|
||||
}
|
||||
put_u8(out, 1U);
|
||||
put_message(out, (*res)->message);
|
||||
put_receipt(out, (*res)->receipt);
|
||||
put_u32(out, (*res)->attempt);
|
||||
put_i64(out, to_mono_ns((*res)->visibility_deadline));
|
||||
return out;
|
||||
});
|
||||
!r.has_value()) {
|
||||
return r;
|
||||
}
|
||||
|
||||
if (auto r = bind_one(
|
||||
kAckMethod, "ack",
|
||||
[&queue](const Void::RPC::CallContext& ctx,
|
||||
Void::RPC::OwnedBytes req)
|
||||
-> Void::Result::Result<Void::RPC::OwnedBytes> {
|
||||
Cursor c{req, 0};
|
||||
Receipt rec{};
|
||||
if (!c.read_receipt(rec) || !c.eof()) {
|
||||
return Void::Result::fail(Void::RPC::make_rpc_error(
|
||||
Void::RPC::RpcStatusCode::InvalidArgument,
|
||||
"MessagingRpc: malformed ack request"));
|
||||
}
|
||||
auto res =
|
||||
queue.ack(rec, Void::Async::OperationOptions{.stop = ctx.stop});
|
||||
if (!res.has_value()) {
|
||||
return Void::Result::fail(res.error());
|
||||
}
|
||||
return Void::RPC::OwnedBytes{};
|
||||
});
|
||||
!r.has_value()) {
|
||||
return r;
|
||||
}
|
||||
|
||||
if (auto r = bind_one(
|
||||
kNackMethod, "nack",
|
||||
[&queue](const Void::RPC::CallContext& ctx,
|
||||
Void::RPC::OwnedBytes req)
|
||||
-> Void::Result::Result<Void::RPC::OwnedBytes> {
|
||||
Cursor c{req, 0};
|
||||
Receipt rec{};
|
||||
std::uint8_t has_delay = 0;
|
||||
std::int64_t delay_ms = 0;
|
||||
if (!c.read_receipt(rec) || !c.read_u8(has_delay) ||
|
||||
!c.read_i64(delay_ms) || !c.eof()) {
|
||||
return Void::Result::fail(Void::RPC::make_rpc_error(
|
||||
Void::RPC::RpcStatusCode::InvalidArgument,
|
||||
"MessagingRpc: malformed nack request"));
|
||||
}
|
||||
std::optional<std::chrono::milliseconds> d{};
|
||||
if (has_delay != 0U) {
|
||||
d = std::chrono::milliseconds{delay_ms};
|
||||
}
|
||||
auto res = queue.nack(
|
||||
rec, d, Void::Async::OperationOptions{.stop = ctx.stop});
|
||||
if (!res.has_value()) {
|
||||
return Void::Result::fail(res.error());
|
||||
}
|
||||
return Void::RPC::OwnedBytes{};
|
||||
});
|
||||
!r.has_value()) {
|
||||
return r;
|
||||
}
|
||||
|
||||
if (auto r = bind_one(
|
||||
kQueryReceiptMethod, "query_receipt",
|
||||
[&queue](const Void::RPC::CallContext&,
|
||||
Void::RPC::OwnedBytes req)
|
||||
-> Void::Result::Result<Void::RPC::OwnedBytes> {
|
||||
Cursor c{req, 0};
|
||||
Receipt rec{};
|
||||
if (!c.read_receipt(rec) || !c.eof()) {
|
||||
return Void::Result::fail(Void::RPC::make_rpc_error(
|
||||
Void::RPC::RpcStatusCode::InvalidArgument,
|
||||
"MessagingRpc: malformed query_receipt request"));
|
||||
}
|
||||
auto res = queue.query_receipt(rec);
|
||||
if (!res.has_value()) {
|
||||
return Void::Result::fail(res.error());
|
||||
}
|
||||
Void::RPC::OwnedBytes out;
|
||||
put_u8(out, static_cast<std::uint8_t>(*res));
|
||||
return out;
|
||||
});
|
||||
!r.has_value()) {
|
||||
return r;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
// ── RpcQueueClient ────────────────────────────────────────────────────────
|
||||
|
||||
RpcQueueClient::RpcQueueClient(Void::RPC::ClientOptions options)
|
||||
: m_client(std::move(options))
|
||||
{
|
||||
}
|
||||
|
||||
Result<PublishReceipt> RpcQueueClient::publish(
|
||||
std::string_view queue, const Message& message,
|
||||
PublishDurability durability, const Void::RPC::CallOptions& options)
|
||||
{
|
||||
Void::RPC::OwnedBytes req;
|
||||
put_str(req, queue);
|
||||
put_u8(req, static_cast<std::uint8_t>(durability));
|
||||
put_message(req, message);
|
||||
|
||||
auto resp = m_client.call(kPublishMethod, std::move(req), options);
|
||||
if (!resp.has_value()) {
|
||||
return Void::Result::fail(map_rpc_err(resp.error()));
|
||||
}
|
||||
Cursor c{*resp, 0};
|
||||
PublishReceipt pr{};
|
||||
std::uint8_t dur = 0, dedup = 0;
|
||||
if (!c.read_str(pr.queue) || !c.read_str(pr.message_id) ||
|
||||
!c.read_u64(pr.sequence) || !c.read_u8(dur) || !c.read_u8(dedup) ||
|
||||
!c.eof()) {
|
||||
return Void::Result::fail(make_messaging_error(
|
||||
MessagingErrorCode::CorruptPayload,
|
||||
"MessagingRpc: corrupt publish response"));
|
||||
}
|
||||
pr.durability = static_cast<PublishDurability>(dur);
|
||||
pr.deduplicated = (dedup != 0U);
|
||||
return pr;
|
||||
}
|
||||
|
||||
Result<std::optional<Delivery>>
|
||||
RpcQueueClient::try_receive(std::string_view queue,
|
||||
std::string_view group,
|
||||
const Void::RPC::CallOptions& options)
|
||||
{
|
||||
Void::RPC::OwnedBytes req;
|
||||
put_str(req, queue);
|
||||
put_str(req, group);
|
||||
|
||||
auto resp = m_client.call(kTryReceiveMethod, std::move(req), options);
|
||||
if (!resp.has_value()) {
|
||||
return Void::Result::fail(map_rpc_err(resp.error()));
|
||||
}
|
||||
Cursor c{*resp, 0};
|
||||
std::uint8_t present = 0;
|
||||
if (!c.read_u8(present)) {
|
||||
return Void::Result::fail(make_messaging_error(
|
||||
MessagingErrorCode::CorruptPayload,
|
||||
"MessagingRpc: corrupt try_receive response"));
|
||||
}
|
||||
if (present == 0U) {
|
||||
return std::optional<Delivery>{std::nullopt};
|
||||
}
|
||||
Delivery d{};
|
||||
std::int64_t dl_ns = 0;
|
||||
if (!c.read_message(d.message) || !c.read_receipt(d.receipt) ||
|
||||
!c.read_u32(d.attempt) || !c.read_i64(dl_ns) || !c.eof()) {
|
||||
return Void::Result::fail(make_messaging_error(
|
||||
MessagingErrorCode::CorruptPayload,
|
||||
"MessagingRpc: corrupt delivery response"));
|
||||
}
|
||||
d.visibility_deadline = Void::Time::MonotonicClock::time_point{
|
||||
std::chrono::duration_cast<
|
||||
Void::Time::MonotonicClock::time_point::duration>(
|
||||
std::chrono::nanoseconds{dl_ns})};
|
||||
return std::optional<Delivery>{std::move(d)};
|
||||
}
|
||||
|
||||
Result<void> RpcQueueClient::ack(const Receipt& receipt,
|
||||
const Void::RPC::CallOptions& options)
|
||||
{
|
||||
Void::RPC::OwnedBytes req;
|
||||
put_receipt(req, receipt);
|
||||
auto resp = m_client.call(kAckMethod, std::move(req), options);
|
||||
if (!resp.has_value()) {
|
||||
return Void::Result::fail(map_rpc_err(resp.error()));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Result<void>
|
||||
RpcQueueClient::nack(const Receipt& receipt,
|
||||
std::optional<std::chrono::milliseconds> delay,
|
||||
const Void::RPC::CallOptions& options)
|
||||
{
|
||||
Void::RPC::OwnedBytes req;
|
||||
put_receipt(req, receipt);
|
||||
put_u8(req, delay.has_value() ? 1U : 0U);
|
||||
put_i64(req, delay.has_value() ? delay->count() : 0LL);
|
||||
auto resp = m_client.call(kNackMethod, std::move(req), options);
|
||||
if (!resp.has_value()) {
|
||||
return Void::Result::fail(map_rpc_err(resp.error()));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
Result<DeliveryState>
|
||||
RpcQueueClient::query_receipt(const Receipt& receipt,
|
||||
const Void::RPC::CallOptions& options)
|
||||
{
|
||||
Void::RPC::OwnedBytes req;
|
||||
put_receipt(req, receipt);
|
||||
auto resp = m_client.call(kQueryReceiptMethod, std::move(req), options);
|
||||
if (!resp.has_value()) {
|
||||
return Void::Result::fail(map_rpc_err(resp.error()));
|
||||
}
|
||||
Cursor c{*resp, 0};
|
||||
std::uint8_t st = 0;
|
||||
if (!c.read_u8(st) || !c.eof() ||
|
||||
st > static_cast<std::uint8_t>(DeliveryState::DeadLetter)) {
|
||||
return Void::Result::fail(make_messaging_error(
|
||||
MessagingErrorCode::CorruptPayload,
|
||||
"MessagingRpc: corrupt query_receipt response"));
|
||||
}
|
||||
return static_cast<DeliveryState>(st);
|
||||
}
|
||||
|
||||
} // namespace Void::MessagingRpc
|
||||
@@ -0,0 +1,3 @@
|
||||
void_add_module(MessagingRpc
|
||||
INTERNAL_DEPS Messaging RPC
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,3 @@
|
||||
void_add_module(MessagingStorage
|
||||
INTERNAL_DEPS Messaging Storage
|
||||
)
|
||||
@@ -328,6 +328,11 @@ if(_has_scheduler)
|
||||
run_consumer(SchedulerOnly "${install_prefix}" "SchedulerOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
has_modules(_has_messaging Messaging Core Functional Binary Time Async)
|
||||
if(_has_messaging)
|
||||
run_consumer(MessagingOnly "${install_prefix}" "MessagingOnly" ${_no_external_deps})
|
||||
endif()
|
||||
|
||||
# Foundation consumer with Core-formatting bridge and zero external packages.
|
||||
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
|
||||
if(_has_foundation)
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
cmake_minimum_required(VERSION 4.0)
|
||||
project(VoidMessagingOnlyConsumer LANGUAGES CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||
|
||||
find_package(Void REQUIRED CONFIG COMPONENTS Messaging)
|
||||
|
||||
add_executable(messaging_only main.cpp)
|
||||
target_link_libraries(messaging_only PRIVATE Void::Messaging)
|
||||
|
||||
enable_testing()
|
||||
add_test(NAME messaging_only COMMAND messaging_only)
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
|
||||
int main()
|
||||
{
|
||||
Void::Messaging::InMemoryQueue q{};
|
||||
if (!q.create_queue(Void::Messaging::QueueConfig{.name = "q"}).has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (!q.create_group("q", Void::Messaging::GroupConfig{.name = "g"})
|
||||
.has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
Void::Messaging::Message m{};
|
||||
m.id = "m1";
|
||||
m.payload = {std::byte{0x41}};
|
||||
auto pub = q.publish("q", m, Void::Messaging::PublishDurability::Memory);
|
||||
if (!pub.has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
auto del = q.try_receive("q", "g");
|
||||
if (!del.has_value() || !del->has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (!q.ack((*del)->receipt).has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
if (!q.close_and_join().has_value()) {
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
Void::Messaging::Message make_msg(std::string id, std::string body)
|
||||
{
|
||||
Void::Messaging::Message m{};
|
||||
m.id = std::move(id);
|
||||
m.payload.reserve(body.size());
|
||||
for (char c : body) {
|
||||
m.payload.push_back(static_cast<std::byte>(c));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test messaging_ephemeral_durability_visibility_fencing_and_dlq()
|
||||
{
|
||||
using namespace Void::Messaging;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::Time::ManualClock mono{};
|
||||
Void::Time::ManualCivilClock civil{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
|
||||
|
||||
InMemoryQueue q{InMemoryQueueOptions{
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
.rng = []() -> std::uint64_t { return 0ULL; }, // zero retry delay
|
||||
}};
|
||||
|
||||
QueueConfig qcfg{};
|
||||
qcfg.name = "jobs";
|
||||
qcfg.retry.max_attempts = 2;
|
||||
qcfg.retry.base_delay = 1s;
|
||||
qcfg.retry.max_delay = 5s;
|
||||
Void::Testing::require(q.create_queue(qcfg).has_value());
|
||||
Void::Testing::require(
|
||||
q.create_group("jobs", GroupConfig{
|
||||
.name = "workers",
|
||||
.mode = ConsumerMode::Competing,
|
||||
.visibility_timeout = 30s,
|
||||
})
|
||||
.has_value());
|
||||
|
||||
// Explicitly nondurable queue MUST reject PublishDurability::Durable!
|
||||
auto bad_dur =
|
||||
q.publish("jobs", make_msg("m1", "hello"), PublishDurability::Durable);
|
||||
Void::Testing::expect(!bad_dur.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
bad_dur.error().code().value,
|
||||
static_cast<std::int32_t>(MessagingErrorCode::UnsupportedDurability));
|
||||
|
||||
auto pub =
|
||||
q.publish("jobs", make_msg("m1", "hello"), PublishDurability::Memory);
|
||||
Void::Testing::require(pub.has_value());
|
||||
Void::Testing::expect(pub->durability == PublishDurability::Memory);
|
||||
Void::Testing::expect(!pub->deduplicated);
|
||||
|
||||
// Idempotent duplicate publish within 24h returns same sequence.
|
||||
auto dup =
|
||||
q.publish("jobs", make_msg("m1", "hello"), PublishDurability::Memory);
|
||||
Void::Testing::require(dup.has_value());
|
||||
Void::Testing::expect(dup->deduplicated);
|
||||
Void::Testing::expect_eq(dup->sequence, pub->sequence);
|
||||
|
||||
// Receive generation 1, then advance past 30s visibility timeout.
|
||||
auto d1 = q.try_receive("jobs", "workers");
|
||||
Void::Testing::require(d1.has_value() && d1->has_value());
|
||||
Void::Testing::expect_eq((*d1)->receipt.generation, 1ULL);
|
||||
Void::Testing::expect_eq((*d1)->attempt, 1U);
|
||||
|
||||
// Extend visibility works within 5m limit, rejects >5m.
|
||||
Void::Testing::expect(
|
||||
!q.extend_visibility((*d1)->receipt, std::chrono::minutes{6})
|
||||
.has_value());
|
||||
Void::Testing::require(
|
||||
q.extend_visibility((*d1)->receipt, 20s).has_value());
|
||||
|
||||
// Advance past extended 20s visibility -> redelivery generation 2!
|
||||
Void::Testing::require(mono.advance(25s).has_value());
|
||||
auto d2 = q.try_receive("jobs", "workers");
|
||||
Void::Testing::require(d2.has_value() && d2->has_value());
|
||||
Void::Testing::expect_eq((*d2)->receipt.generation, 2ULL);
|
||||
Void::Testing::expect_eq((*d2)->attempt, 2U);
|
||||
|
||||
// Stale receipt from generation 1 MUST fail with StaleReceipt!
|
||||
auto stale_ack = q.ack((*d1)->receipt);
|
||||
Void::Testing::expect(!stale_ack.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
stale_ack.error().code().value,
|
||||
static_cast<std::int32_t>(MessagingErrorCode::StaleReceipt));
|
||||
|
||||
// Exhausting attempt 2 via nack moves atomically to DLQ.
|
||||
Void::Testing::require(q.nack((*d2)->receipt).has_value());
|
||||
auto dlq = q.list_dead_letters("jobs", "workers");
|
||||
Void::Testing::require(dlq.has_value());
|
||||
Void::Testing::require(dlq->size() == 1U);
|
||||
Void::Testing::expect_eq(dlq->front().message.id, std::string{"m1"});
|
||||
Void::Testing::expect_eq(dlq->front().attempts, 2U);
|
||||
|
||||
// Test idempotent repeat ack + SingleActive head-of-line blocking!
|
||||
Void::Testing::require(
|
||||
q.create_group("jobs", GroupConfig{
|
||||
.name = "ordered",
|
||||
.mode = ConsumerMode::SingleActive,
|
||||
.visibility_timeout = 30s,
|
||||
})
|
||||
.has_value());
|
||||
Void::Testing::require(
|
||||
q.publish("jobs", make_msg("m2", "a"), PublishDurability::Memory)
|
||||
.has_value());
|
||||
Void::Testing::require(
|
||||
q.publish("jobs", make_msg("m3", "b"), PublishDurability::Memory)
|
||||
.has_value());
|
||||
|
||||
auto s1 = q.try_receive("jobs", "ordered");
|
||||
Void::Testing::require(s1.has_value() && s1->has_value());
|
||||
Void::Testing::expect_eq((*s1)->message.id, std::string{"m1"});
|
||||
// While head is InFlight, SingleActive blocks delivery of m2!
|
||||
auto s_blocked = q.try_receive("jobs", "ordered");
|
||||
Void::Testing::require(s_blocked.has_value());
|
||||
Void::Testing::expect(!s_blocked->has_value());
|
||||
|
||||
// Ack and repeat ack of same receipt -> idempotent OK!
|
||||
Void::Testing::require(q.ack((*s1)->receipt).has_value());
|
||||
Void::Testing::require(q.ack((*s1)->receipt).has_value());
|
||||
auto st = q.query_receipt((*s1)->receipt);
|
||||
Void::Testing::require(st.has_value());
|
||||
Void::Testing::expect(*st == DeliveryState::Acked);
|
||||
|
||||
// Next delivery is strictly m2.
|
||||
auto s2 = q.try_receive("jobs", "ordered");
|
||||
Void::Testing::require(s2.has_value() && s2->has_value());
|
||||
Void::Testing::expect_eq((*s2)->message.id, std::string{"m2"});
|
||||
Void::Testing::require(q.ack((*s2)->receipt).has_value());
|
||||
|
||||
auto report = q.close_and_join();
|
||||
Void::Testing::require(report.has_value());
|
||||
Void::Testing::expect(report->complete);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
#include <Void/Messaging/Queue.hpp>
|
||||
#include <Void/MessagingRpc/RpcAdapter.hpp>
|
||||
#include <Void/RPC/Rpc.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
Void::Testing::Test messaging_rpc_remote_publish_receive_ack_and_query()
|
||||
{
|
||||
using namespace Void::Messaging;
|
||||
using namespace Void::MessagingRpc;
|
||||
|
||||
InMemoryQueue queue{};
|
||||
Void::Testing::require(
|
||||
queue.create_queue(QueueConfig{.name = "remote-q"}).has_value());
|
||||
Void::Testing::require(
|
||||
queue.create_group("remote-q", GroupConfig{.name = "g1"}).has_value());
|
||||
|
||||
Void::RPC::Server rpc_server{};
|
||||
RpcQueueServer adapter{};
|
||||
Void::Testing::require(adapter.mount(rpc_server, queue).has_value());
|
||||
Void::Testing::require(rpc_server.start().has_value());
|
||||
|
||||
RpcQueueClient client{Void::RPC::ClientOptions{
|
||||
.endpoint_base_url = rpc_server.base_url(),
|
||||
}};
|
||||
|
||||
Message msg{};
|
||||
msg.id = "rpc-msg-1";
|
||||
msg.payload = {std::byte{'h'}, std::byte{'i'}};
|
||||
msg.headers["trace"] = "abc";
|
||||
|
||||
auto pub = client.publish("remote-q", msg, PublishDurability::Memory);
|
||||
Void::Testing::require(pub.has_value());
|
||||
Void::Testing::expect_eq(pub->sequence, 1ULL);
|
||||
|
||||
auto del = client.try_receive("remote-q", "g1");
|
||||
Void::Testing::require(del.has_value() && del->has_value());
|
||||
Void::Testing::expect_eq((*del)->message.id, std::string{"rpc-msg-1"});
|
||||
Void::Testing::expect_eq((*del)->message.headers.at("trace"),
|
||||
std::string{"abc"});
|
||||
|
||||
auto st_inflight = client.query_receipt((*del)->receipt);
|
||||
Void::Testing::require(st_inflight.has_value());
|
||||
Void::Testing::expect(*st_inflight == DeliveryState::InFlight);
|
||||
|
||||
Void::Testing::require(client.ack((*del)->receipt).has_value());
|
||||
|
||||
auto st_acked = client.query_receipt((*del)->receipt);
|
||||
Void::Testing::require(st_acked.has_value());
|
||||
Void::Testing::expect(*st_acked == DeliveryState::Acked);
|
||||
|
||||
adapter.unmount_and_drain();
|
||||
rpc_server.shutdown();
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
#include <Void/MessagingStorage/OutboxInbox.hpp>
|
||||
#include <Void/MessagingStorage/StorageQueue.hpp>
|
||||
#include <Void/Storage/Engine.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
|
||||
namespace
|
||||
{
|
||||
Void::Messaging::Message make_msg(std::string id, std::string body)
|
||||
{
|
||||
Void::Messaging::Message m{};
|
||||
m.id = std::move(id);
|
||||
m.payload.reserve(body.size());
|
||||
for (char c : body) {
|
||||
m.payload.push_back(static_cast<std::byte>(c));
|
||||
}
|
||||
return m;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test messaging_storage_restart_fencing_poison_dlq_and_caps()
|
||||
{
|
||||
using namespace Void::Messaging;
|
||||
using namespace Void::MessagingStorage;
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
Void::FileSystem::TempDir tmp{"void_msg_store_"};
|
||||
Void::Time::ManualClock mono{};
|
||||
Void::Time::ManualCivilClock civil{
|
||||
std::chrono::system_clock::time_point{std::chrono::seconds{1700000000}}};
|
||||
|
||||
Receipt pre_crash_receipt{};
|
||||
{
|
||||
auto eng = Void::Storage::Engine::open(
|
||||
Void::Storage::OpenOptions{.directory = tmp.path()});
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
auto sq = StorageQueue::open(*eng, StorageQueueOptions{
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
.rng = []() { return 0ULL; },
|
||||
});
|
||||
Void::Testing::require(sq.has_value());
|
||||
|
||||
QueueConfig qcfg{};
|
||||
qcfg.name = "events";
|
||||
qcfg.retry.max_attempts = 2;
|
||||
Void::Testing::require(sq->create_queue(qcfg).has_value());
|
||||
Void::Testing::require(
|
||||
sq->create_group("events", GroupConfig{.name = "g1"}).has_value());
|
||||
|
||||
auto pub = sq->publish("events", make_msg("poison-1", "bad-data"),
|
||||
PublishDurability::Durable);
|
||||
Void::Testing::require(pub.has_value());
|
||||
Void::Testing::expect(pub->durability == PublishDurability::Durable);
|
||||
|
||||
auto d1 = sq->try_receive("events", "g1");
|
||||
Void::Testing::require(d1.has_value() && d1->has_value());
|
||||
Void::Testing::expect_eq((*d1)->attempt, 1U);
|
||||
pre_crash_receipt = (*d1)->receipt;
|
||||
|
||||
// Crash before ack!
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
|
||||
// Reopen: prior InFlight must be redelivered with bumped generation and
|
||||
// preserved attempt count (1 -> 2)! Old receipt must fail StaleReceipt!
|
||||
{
|
||||
auto eng = Void::Storage::Engine::open(
|
||||
Void::Storage::OpenOptions{.directory = tmp.path()});
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
QueueLimits lim{};
|
||||
lim.max_dlq_messages = 1;
|
||||
lim.max_idempotency_entries = 2;
|
||||
auto sq = StorageQueue::open(*eng, StorageQueueOptions{
|
||||
.limits = lim,
|
||||
.monotonic_clock = &mono,
|
||||
.civil_clock = &civil,
|
||||
.rng = []() { return 0ULL; },
|
||||
});
|
||||
Void::Testing::require(sq.has_value());
|
||||
|
||||
// Old worker receipt from before crash is fenced!
|
||||
auto stale = sq->ack(pre_crash_receipt);
|
||||
Void::Testing::expect(!stale.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
stale.error().code().value,
|
||||
static_cast<std::int32_t>(MessagingErrorCode::StaleReceipt));
|
||||
|
||||
auto d2 = sq->try_receive("events", "g1");
|
||||
Void::Testing::require(d2.has_value() && d2->has_value());
|
||||
Void::Testing::expect((*d2)->receipt.generation >
|
||||
pre_crash_receipt.generation);
|
||||
// Attempt counter survived restart!
|
||||
Void::Testing::expect_eq((*d2)->attempt, 2U);
|
||||
|
||||
// Attempt 2 nack exhausts max_attempts=2 -> atomic DLQ move!
|
||||
Void::Testing::require(sq->nack((*d2)->receipt).has_value());
|
||||
auto dlq = sq->list_dead_letters("events", "g1");
|
||||
Void::Testing::require(dlq.has_value());
|
||||
Void::Testing::require(dlq->size() == 1U);
|
||||
Void::Testing::expect_eq(dlq->front().message.id,
|
||||
std::string{"poison-1"});
|
||||
|
||||
// Second poison message hits DLQ cap (max_dlq_messages = 1) -> keeps
|
||||
// message durable and increments stuck_dlq_count without dropping data!
|
||||
Void::Testing::require(
|
||||
sq->publish("events", make_msg("poison-2", "bad2"),
|
||||
PublishDurability::Durable)
|
||||
.has_value());
|
||||
auto p2a = sq->try_receive("events", "g1");
|
||||
Void::Testing::require(p2a.has_value() && p2a->has_value());
|
||||
auto q_full = sq->quarantine_corrupt((*p2a)->receipt, "unknown schema");
|
||||
Void::Testing::expect(!q_full.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
q_full.error().code().value,
|
||||
static_cast<std::int32_t>(MessagingErrorCode::DlqFull));
|
||||
Void::Testing::expect_eq(sq->stuck_dlq_count("events", "g1"), 1ULL);
|
||||
|
||||
// Idempotency table is now at capacity (2/2 live within 24h) -> third
|
||||
// distinct publish MUST fail with IdempotencyCapacityExceeded rather
|
||||
// than silently evicting live contracts!
|
||||
auto idem_cap = sq->publish("events", make_msg("msg-3", "data"),
|
||||
PublishDurability::Durable);
|
||||
Void::Testing::expect(!idem_cap.has_value());
|
||||
Void::Testing::expect_eq(
|
||||
idem_cap.error().code().value,
|
||||
static_cast<std::int32_t>(
|
||||
MessagingErrorCode::IdempotencyCapacityExceeded));
|
||||
|
||||
// Unhealthy civil clock pauses retention expiry even after 30 days!
|
||||
sq->set_clock_healthy(false);
|
||||
Void::Testing::require(
|
||||
civil.advance(std::chrono::hours{24 * 30}).has_value());
|
||||
auto exp_paused = sq->expire_retention();
|
||||
Void::Testing::require(exp_paused.has_value());
|
||||
Void::Testing::expect_eq(*exp_paused, 0ULL);
|
||||
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
}
|
||||
|
||||
Void::Testing::Test messaging_storage_outbox_inbox_single_batch_atomicity()
|
||||
{
|
||||
using namespace Void::Messaging;
|
||||
using namespace Void::MessagingStorage;
|
||||
|
||||
Void::FileSystem::TempDir tmp{"void_msg_outbox_"};
|
||||
auto eng = Void::Storage::Engine::open(
|
||||
Void::Storage::OpenOptions{.directory = tmp.path()});
|
||||
Void::Testing::require(eng.has_value());
|
||||
|
||||
auto sq = StorageQueue::open(*eng);
|
||||
Void::Testing::require(sq.has_value());
|
||||
Void::Testing::require(
|
||||
sq->create_queue(QueueConfig{.name = "orders"}).has_value());
|
||||
Void::Testing::require(
|
||||
sq->create_group("orders", GroupConfig{.name = "ledger"}).has_value());
|
||||
|
||||
// 1. Atomic business mutation + outbox append in ONE Storage::Batch!
|
||||
{
|
||||
Void::Storage::Batch b{};
|
||||
b.put("biz:order:100", "created");
|
||||
OutboxInbox::append_outbox_in_batch(
|
||||
b, OutboxRecord{
|
||||
.outbox_id = "ob-100",
|
||||
.target_queue = "orders",
|
||||
.message = make_msg("order-100", "amount=42"),
|
||||
});
|
||||
Void::Testing::require(
|
||||
eng->write(std::move(b), Void::Storage::Durability::Sync)
|
||||
.has_value());
|
||||
}
|
||||
|
||||
// 2. Relay outbox into durable queue (idempotent publish).
|
||||
auto relayed = OutboxInbox::relay_outbox(*eng, *sq);
|
||||
Void::Testing::require(relayed.has_value());
|
||||
Void::Testing::expect_eq(*relayed, 1ULL);
|
||||
|
||||
// 3. Consumer receives message and atomically applies local effect + inbox
|
||||
// dedup key in ONE Storage::Batch!
|
||||
auto del = sq->try_receive("orders", "ledger");
|
||||
Void::Testing::require(del.has_value() && del->has_value());
|
||||
|
||||
{
|
||||
Void::Storage::Batch apply_b{};
|
||||
OutboxInbox::apply_inbox_in_batch(apply_b, "ledger-worker",
|
||||
(*del)->message.id);
|
||||
apply_b.put("biz:ledger:100", "credited");
|
||||
Void::Testing::require(
|
||||
eng->write(std::move(apply_b), Void::Storage::Durability::Sync)
|
||||
.has_value());
|
||||
}
|
||||
|
||||
// Simulate duplicate delivery (e.g. crash before ack): second apply of
|
||||
// identical inbox key in local batch fails cleanly with Conflict!
|
||||
{
|
||||
Void::Storage::Batch dup_b{};
|
||||
OutboxInbox::apply_inbox_in_batch(dup_b, "ledger-worker",
|
||||
(*del)->message.id);
|
||||
dup_b.put("biz:ledger:100", "double-credited");
|
||||
auto wr = eng->write(std::move(dup_b), Void::Storage::Durability::Sync);
|
||||
Void::Testing::expect(!wr.has_value());
|
||||
Void::Testing::expect(wr.error().cause.code ==
|
||||
Void::Storage::StorageErrorCode::conflict);
|
||||
}
|
||||
|
||||
Void::Testing::require(sq->ack((*del)->receipt).has_value());
|
||||
Void::Testing::require(eng->close().has_value());
|
||||
}
|
||||
Reference in new issue
Block a user