1076 lines
32 KiB
C++
1076 lines
32 KiB
C++
#include <Void/Messaging/Queue.hpp>
|
|
|
|
#include <algorithm>
|
|
#include <condition_variable>
|
|
#include <deque>
|
|
#include <map>
|
|
#include <mutex>
|
|
#include <random>
|
|
#include <stop_token>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace Void::Messaging
|
|
{
|
|
Result<void> validate_identifier(std::string_view name,
|
|
std::string_view label)
|
|
{
|
|
if (name.empty() || name.size() > 256U) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::InvalidArgument,
|
|
"Messaging: invalid " + std::string{label} + " length"));
|
|
}
|
|
for (unsigned char c : name) {
|
|
if (c < 0x21U || c > 0x7EU) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::InvalidArgument,
|
|
"Messaging: invalid character in " + std::string{label}));
|
|
}
|
|
}
|
|
return {};
|
|
}
|
|
|
|
Result<void> validate_message(const Message& message,
|
|
const QueueLimits& limits)
|
|
{
|
|
if (auto id_ok = validate_identifier(message.id, "message.id");
|
|
!id_ok.has_value()) {
|
|
return id_ok;
|
|
}
|
|
if (message.payload.size() > limits.max_message_bytes) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::InvalidArgument,
|
|
"Messaging: message payload exceeds max_message_bytes"));
|
|
}
|
|
if (message.headers.size() > limits.max_header_count) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::InvalidArgument,
|
|
"Messaging: header count exceeds max_header_count"));
|
|
}
|
|
std::size_t hbytes = 0;
|
|
for (const auto& [k, v] : message.headers) {
|
|
if (k.empty()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::InvalidArgument,
|
|
"Messaging: header key must not be empty"));
|
|
}
|
|
for (unsigned char c : k) {
|
|
if (c < 0x20U || c > 0x7EU) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::InvalidArgument,
|
|
"Messaging: invalid header key character"));
|
|
}
|
|
}
|
|
for (unsigned char c : v) {
|
|
if (c < 0x20U || c > 0x7EU) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::InvalidArgument,
|
|
"Messaging: invalid header value character"));
|
|
}
|
|
}
|
|
hbytes += k.size() + v.size();
|
|
if (hbytes > limits.max_headers_bytes) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::InvalidArgument,
|
|
"Messaging: headers exceed max_headers_bytes"));
|
|
}
|
|
}
|
|
return {};
|
|
}
|
|
|
|
std::size_t estimate_message_bytes(const Message& message) noexcept
|
|
{
|
|
std::size_t total = message.id.size() + message.payload.size() + 64U;
|
|
for (const auto& [k, v] : message.headers) {
|
|
total += k.size() + v.size() + 16U;
|
|
}
|
|
return total;
|
|
}
|
|
|
|
std::int64_t compute_retry_backoff_ms(const RetryPolicy& retry,
|
|
std::uint32_t attempt,
|
|
const RandomU64Fn& rng)
|
|
{
|
|
const std::int64_t base_ms =
|
|
std::max<std::int64_t>(0LL, retry.base_delay.count());
|
|
const std::int64_t max_ms =
|
|
std::max<std::int64_t>(base_ms, retry.max_delay.count());
|
|
if (max_ms == 0LL) {
|
|
return 0LL;
|
|
}
|
|
std::int64_t cap = base_ms;
|
|
for (std::uint32_t i = 1U; i < attempt; ++i) {
|
|
if (cap > max_ms / 2LL) {
|
|
cap = max_ms;
|
|
break;
|
|
}
|
|
cap *= 2LL;
|
|
}
|
|
cap = std::min(cap, max_ms);
|
|
if (cap <= 0LL) {
|
|
return 0LL;
|
|
}
|
|
const std::uint64_t r = rng ? rng() : 0ULL;
|
|
return static_cast<std::int64_t>(
|
|
r % (static_cast<std::uint64_t>(cap) + 1ULL));
|
|
}
|
|
|
|
namespace
|
|
{
|
|
struct StoredMsg {
|
|
std::uint64_t sequence{0};
|
|
Message message{};
|
|
std::int64_t published_utc_ms{0};
|
|
std::size_t bytes{0};
|
|
};
|
|
|
|
struct DeliverySlot {
|
|
std::uint64_t sequence{0};
|
|
std::string message_id{};
|
|
DeliveryState state{DeliveryState::Pending};
|
|
std::uint64_t generation{0};
|
|
std::uint32_t attempt{0};
|
|
Void::Time::MonotonicClock::time_point available_at{};
|
|
Void::Time::MonotonicClock::time_point visibility_deadline{};
|
|
bool stuck_dlq{false};
|
|
};
|
|
|
|
struct GroupState {
|
|
GroupConfig config{};
|
|
std::map<std::uint64_t, DeliverySlot> slots{};
|
|
std::vector<DeadLetterEntry> dlq{};
|
|
std::size_t in_flight{0};
|
|
std::size_t stuck_dlq{0};
|
|
};
|
|
|
|
struct IdempotencyEntry {
|
|
std::uint64_t sequence{0};
|
|
std::int64_t published_utc_ms{0};
|
|
};
|
|
|
|
struct QueueData {
|
|
QueueConfig config{};
|
|
std::uint64_t next_sequence{1};
|
|
std::map<std::uint64_t, StoredMsg> messages{};
|
|
std::map<std::string, GroupState, std::less<>> groups{};
|
|
std::map<std::string, IdempotencyEntry, std::less<>>
|
|
idempotency{};
|
|
};
|
|
} // namespace
|
|
|
|
struct InMemoryQueue::State {
|
|
QueueLimits limits{};
|
|
const Void::Time::MonotonicClock* mono{
|
|
&Void::Time::SystemMonotonicClock::instance()};
|
|
const Void::Time::CivilClock* civil{
|
|
&Void::Time::SystemCivilClock::instance()};
|
|
RandomU64Fn rng{};
|
|
|
|
mutable std::mutex mu{};
|
|
std::condition_variable cv{};
|
|
bool closing{false};
|
|
bool clock_healthy{true};
|
|
std::size_t waiting_receives{0};
|
|
std::size_t transient_bytes{0};
|
|
std::map<std::string, QueueData, std::less<>> queues{};
|
|
|
|
[[nodiscard]] std::size_t total_dlq_locked() const noexcept
|
|
{
|
|
std::size_t n = 0;
|
|
for (const auto& [qn, qd] : queues) {
|
|
(void)qn;
|
|
for (const auto& [gn, gs] : qd.groups) {
|
|
(void)gn;
|
|
n += gs.dlq.size();
|
|
}
|
|
}
|
|
return n;
|
|
}
|
|
|
|
[[nodiscard]] std::size_t total_idem_locked() const noexcept
|
|
{
|
|
std::size_t n = 0;
|
|
for (const auto& [qn, qd] : queues) {
|
|
(void)qn;
|
|
n += qd.idempotency.size();
|
|
}
|
|
return n;
|
|
}
|
|
|
|
void gc_expired_idempotency_locked(std::int64_t now_utc_ms)
|
|
{
|
|
if (!clock_healthy) {
|
|
return;
|
|
}
|
|
const std::int64_t cutoff =
|
|
now_utc_ms - limits.idempotency_retention.count();
|
|
for (auto& [qn, qd] : queues) {
|
|
(void)qn;
|
|
for (auto it = qd.idempotency.begin();
|
|
it != qd.idempotency.end();) {
|
|
if (it->second.published_utc_ms <= cutoff) {
|
|
it = qd.idempotency.erase(it);
|
|
} else {
|
|
++it;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
Result<void> move_to_dlq_locked(QueueData& qd, GroupState& gs,
|
|
DeliverySlot& slot,
|
|
std::string reason)
|
|
{
|
|
if (total_dlq_locked() >= limits.max_dlq_messages) {
|
|
if (!slot.stuck_dlq) {
|
|
slot.stuck_dlq = true;
|
|
++gs.stuck_dlq;
|
|
}
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::DlqFull,
|
|
"Messaging: DLQ capacity full; message retained"));
|
|
}
|
|
auto mit = qd.messages.find(slot.sequence);
|
|
Message msg{};
|
|
if (mit != qd.messages.end()) {
|
|
msg = mit->second.message;
|
|
} else {
|
|
msg.id = slot.message_id;
|
|
}
|
|
DeadLetterEntry dle{};
|
|
dle.message = std::move(msg);
|
|
dle.queue = qd.config.name;
|
|
dle.group = gs.config.name;
|
|
dle.sequence = slot.sequence;
|
|
dle.attempts = slot.attempt;
|
|
dle.reason = std::move(reason);
|
|
dle.dead_lettered_utc_ms = to_utc_ms(civil->now());
|
|
gs.dlq.push_back(std::move(dle));
|
|
if (slot.stuck_dlq) {
|
|
slot.stuck_dlq = false;
|
|
if (gs.stuck_dlq > 0U) {
|
|
--gs.stuck_dlq;
|
|
}
|
|
}
|
|
if (slot.state == DeliveryState::InFlight && gs.in_flight > 0U) {
|
|
--gs.in_flight;
|
|
}
|
|
slot.state = DeliveryState::DeadLetter;
|
|
return {};
|
|
}
|
|
|
|
std::size_t reap_expired_locked()
|
|
{
|
|
const auto now = mono->now();
|
|
std::size_t reaped = 0;
|
|
for (auto& [qn, qd] : queues) {
|
|
(void)qn;
|
|
for (auto& [gn, gs] : qd.groups) {
|
|
(void)gn;
|
|
for (auto& [seq, slot] : gs.slots) {
|
|
(void)seq;
|
|
if (slot.state != DeliveryState::InFlight) {
|
|
continue;
|
|
}
|
|
if (now < slot.visibility_deadline) {
|
|
continue;
|
|
}
|
|
if (slot.attempt >= qd.config.retry.max_attempts) {
|
|
auto mr = move_to_dlq_locked(
|
|
qd, gs, slot,
|
|
"visibility timeout retry exhaustion");
|
|
if (mr.has_value()) {
|
|
++reaped;
|
|
}
|
|
} else {
|
|
const std::int64_t backoff_ms =
|
|
compute_retry_backoff_ms(
|
|
qd.config.retry, slot.attempt, rng);
|
|
slot.state = DeliveryState::Pending;
|
|
if (gs.in_flight > 0U) {
|
|
--gs.in_flight;
|
|
}
|
|
slot.available_at =
|
|
now + std::chrono::milliseconds{backoff_ms};
|
|
++reaped;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (reaped > 0U) {
|
|
cv.notify_all();
|
|
}
|
|
return reaped;
|
|
}
|
|
|
|
Result<std::optional<Delivery>>
|
|
try_receive_locked(std::string_view queue,
|
|
std::string_view group)
|
|
{
|
|
auto qit = queues.find(queue);
|
|
if (qit == queues.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound,
|
|
"Messaging: queue not found: " + std::string{queue}));
|
|
}
|
|
auto& qd = qit->second;
|
|
auto git = qd.groups.find(group);
|
|
if (git == qd.groups.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound,
|
|
"Messaging: consumer group not found: " +
|
|
std::string{group}));
|
|
}
|
|
auto& gs = git->second;
|
|
|
|
const std::size_t eff_cap =
|
|
gs.config.mode == ConsumerMode::SingleActive
|
|
? 1U
|
|
: std::min(gs.config.max_in_flight,
|
|
limits.max_in_flight_per_group);
|
|
if (gs.in_flight >= eff_cap) {
|
|
return std::optional<Delivery>{std::nullopt};
|
|
}
|
|
|
|
const auto now = mono->now();
|
|
for (auto& [seq, slot] : gs.slots) {
|
|
if (slot.state == DeliveryState::Acked ||
|
|
slot.state == DeliveryState::DeadLetter) {
|
|
continue;
|
|
}
|
|
if (gs.config.mode == ConsumerMode::SingleActive) {
|
|
// Head-of-line order: block group head if head is
|
|
// InFlight or waiting on retry backoff.
|
|
if (slot.state == DeliveryState::InFlight ||
|
|
slot.available_at > now) {
|
|
return std::optional<Delivery>{std::nullopt};
|
|
}
|
|
}
|
|
if (slot.state != DeliveryState::Pending ||
|
|
slot.available_at > now) {
|
|
continue;
|
|
}
|
|
auto mit = qd.messages.find(seq);
|
|
if (mit == qd.messages.end()) {
|
|
continue;
|
|
}
|
|
|
|
slot.state = DeliveryState::InFlight;
|
|
slot.generation += 1U;
|
|
slot.attempt += 1U;
|
|
slot.visibility_deadline =
|
|
now + gs.config.visibility_timeout;
|
|
gs.in_flight += 1U;
|
|
|
|
Delivery d{};
|
|
d.message = mit->second.message;
|
|
d.receipt = Receipt{
|
|
.queue = qd.config.name,
|
|
.group = gs.config.name,
|
|
.message_id = slot.message_id,
|
|
.sequence = seq,
|
|
.generation = slot.generation,
|
|
};
|
|
d.attempt = slot.attempt;
|
|
d.visibility_deadline = slot.visibility_deadline;
|
|
return std::optional<Delivery>{std::move(d)};
|
|
}
|
|
return std::optional<Delivery>{std::nullopt};
|
|
}
|
|
};
|
|
|
|
InMemoryQueue::InMemoryQueue(InMemoryQueueOptions options)
|
|
: m_state(std::make_shared<State>())
|
|
{
|
|
m_state->limits = options.limits;
|
|
m_state->mono =
|
|
options.monotonic_clock != nullptr
|
|
? options.monotonic_clock
|
|
: &Void::Time::SystemMonotonicClock::instance();
|
|
m_state->civil = options.civil_clock != nullptr
|
|
? options.civil_clock
|
|
: &Void::Time::SystemCivilClock::instance();
|
|
if (options.rng) {
|
|
m_state->rng = std::move(options.rng);
|
|
} else {
|
|
auto prng = std::make_shared<std::mt19937_64>(0xD1B54A32D192ED03ULL);
|
|
auto pmu = std::make_shared<std::mutex>();
|
|
m_state->rng = [prng, pmu]() -> std::uint64_t {
|
|
std::lock_guard lk{*pmu};
|
|
return (*prng)();
|
|
};
|
|
}
|
|
}
|
|
|
|
InMemoryQueue::~InMemoryQueue() noexcept
|
|
{
|
|
if (m_state) {
|
|
{
|
|
std::lock_guard lk{m_state->mu};
|
|
m_state->closing = true;
|
|
}
|
|
m_state->cv.notify_all();
|
|
}
|
|
}
|
|
|
|
InMemoryQueue::InMemoryQueue(InMemoryQueue&&) noexcept = default;
|
|
InMemoryQueue& InMemoryQueue::operator=(InMemoryQueue&&) noexcept = default;
|
|
|
|
Result<void> InMemoryQueue::create_queue(QueueConfig config)
|
|
{
|
|
if (auto ok = validate_identifier(config.name, "queue"); !ok.has_value()) {
|
|
return ok;
|
|
}
|
|
if (config.retry.max_attempts == 0U ||
|
|
config.retry.base_delay < std::chrono::milliseconds{0} ||
|
|
config.retry.max_delay < config.retry.base_delay) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::InvalidArgument,
|
|
"Messaging: invalid RetryPolicy"));
|
|
}
|
|
std::lock_guard lk{m_state->mu};
|
|
if (m_state->closing) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Closed, "Messaging queue is closed"));
|
|
}
|
|
if (m_state->queues.contains(config.name)) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Conflict,
|
|
"Messaging: queue already exists: " + config.name));
|
|
}
|
|
if (m_state->queues.size() >= m_state->limits.max_queues) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Overloaded,
|
|
"Messaging: max_queues cap reached"));
|
|
}
|
|
QueueData qd{};
|
|
qd.config = std::move(config);
|
|
m_state->queues.emplace(qd.config.name, std::move(qd));
|
|
return {};
|
|
}
|
|
|
|
Result<void> InMemoryQueue::create_group(std::string_view queue,
|
|
GroupConfig config)
|
|
{
|
|
if (auto ok = validate_identifier(config.name, "group"); !ok.has_value()) {
|
|
return ok;
|
|
}
|
|
if (config.visibility_timeout <= std::chrono::milliseconds{0} ||
|
|
config.max_in_flight == 0U) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::InvalidArgument,
|
|
"Messaging: group visibility_timeout and max_in_flight must be "
|
|
"positive"));
|
|
}
|
|
std::lock_guard lk{m_state->mu};
|
|
if (m_state->closing) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Closed, "Messaging queue is closed"));
|
|
}
|
|
auto qit = m_state->queues.find(queue);
|
|
if (qit == m_state->queues.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound,
|
|
"Messaging: queue not found: " + std::string{queue}));
|
|
}
|
|
auto& qd = qit->second;
|
|
if (qd.groups.contains(config.name)) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Conflict,
|
|
"Messaging: group already exists: " + config.name));
|
|
}
|
|
if (qd.groups.size() >= m_state->limits.max_groups_per_queue) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Overloaded,
|
|
"Messaging: max_groups_per_queue reached"));
|
|
}
|
|
GroupState gs{};
|
|
gs.config = std::move(config);
|
|
// Materialize pending delivery slots for existing unacknowledged
|
|
// messages in this queue.
|
|
const auto now = m_state->mono->now();
|
|
for (const auto& [seq, msg] : qd.messages) {
|
|
gs.slots.emplace(seq, DeliverySlot{
|
|
.sequence = seq,
|
|
.message_id = msg.message.id,
|
|
.state = DeliveryState::Pending,
|
|
.generation = 0,
|
|
.attempt = 0,
|
|
.available_at = now,
|
|
});
|
|
}
|
|
qd.groups.emplace(gs.config.name, std::move(gs));
|
|
m_state->cv.notify_all();
|
|
return {};
|
|
}
|
|
|
|
Result<PublishReceipt>
|
|
InMemoryQueue::publish(std::string_view queue, Message message,
|
|
PublishDurability durability,
|
|
Void::Async::OperationOptions options)
|
|
{
|
|
if (options.stop.stop_requested()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Cancelled, "Messaging::publish cancelled"));
|
|
}
|
|
if (durability == PublishDurability::Durable) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::UnsupportedDurability,
|
|
"InMemoryQueue is explicitly nondurable and cannot satisfy "
|
|
"PublishDurability::Durable"));
|
|
}
|
|
if (auto vm = validate_message(message, m_state->limits);
|
|
!vm.has_value()) {
|
|
return Void::Result::fail(vm.error());
|
|
}
|
|
|
|
std::lock_guard lk{m_state->mu};
|
|
if (m_state->closing) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Closed, "Messaging queue is closed"));
|
|
}
|
|
auto qit = m_state->queues.find(queue);
|
|
if (qit == m_state->queues.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound,
|
|
"Messaging: queue not found: " + std::string{queue}));
|
|
}
|
|
auto& qd = qit->second;
|
|
const std::int64_t now_utc = to_utc_ms(m_state->civil->now());
|
|
m_state->gc_expired_idempotency_locked(now_utc);
|
|
|
|
// Check bounded idempotency ledger.
|
|
if (auto iit = qd.idempotency.find(message.id);
|
|
iit != qd.idempotency.end()) {
|
|
return PublishReceipt{
|
|
.queue = qd.config.name,
|
|
.message_id = message.id,
|
|
.sequence = iit->second.sequence,
|
|
.durability = PublishDurability::Memory,
|
|
.deduplicated = true,
|
|
};
|
|
}
|
|
if (m_state->total_idem_locked() >=
|
|
m_state->limits.max_idempotency_entries) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::IdempotencyCapacityExceeded,
|
|
"Messaging: idempotency ledger at capacity; refusing silent "
|
|
"eviction"));
|
|
}
|
|
|
|
const std::size_t msg_bytes = estimate_message_bytes(message);
|
|
if (m_state->transient_bytes + msg_bytes >
|
|
m_state->limits.max_transient_payload_bytes) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::QuotaExceeded,
|
|
"Messaging: transient payload budget exceeded"));
|
|
}
|
|
|
|
const std::uint64_t seq = qd.next_sequence++;
|
|
const auto now_mono = m_state->mono->now();
|
|
const std::string msg_id = message.id;
|
|
|
|
qd.messages.emplace(seq, StoredMsg{
|
|
.sequence = seq,
|
|
.message = std::move(message),
|
|
.published_utc_ms = now_utc,
|
|
.bytes = msg_bytes,
|
|
});
|
|
qd.idempotency.emplace(msg_id, IdempotencyEntry{
|
|
.sequence = seq,
|
|
.published_utc_ms = now_utc,
|
|
});
|
|
m_state->transient_bytes += msg_bytes;
|
|
|
|
for (auto& [gn, gs] : qd.groups) {
|
|
(void)gn;
|
|
gs.slots.emplace(seq, DeliverySlot{
|
|
.sequence = seq,
|
|
.message_id = msg_id,
|
|
.state = DeliveryState::Pending,
|
|
.generation = 0,
|
|
.attempt = 0,
|
|
.available_at = now_mono,
|
|
});
|
|
}
|
|
|
|
m_state->cv.notify_all();
|
|
return PublishReceipt{
|
|
.queue = qd.config.name,
|
|
.message_id = msg_id,
|
|
.sequence = seq,
|
|
.durability = PublishDurability::Memory,
|
|
.deduplicated = false,
|
|
};
|
|
}
|
|
|
|
Result<std::optional<Delivery>>
|
|
InMemoryQueue::try_receive(std::string_view queue,
|
|
std::string_view group)
|
|
{
|
|
std::lock_guard lk{m_state->mu};
|
|
if (m_state->closing) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Closed, "Messaging queue is closed"));
|
|
}
|
|
m_state->reap_expired_locked();
|
|
return m_state->try_receive_locked(queue, group);
|
|
}
|
|
|
|
Result<Delivery> InMemoryQueue::receive(
|
|
std::string_view queue, std::string_view group,
|
|
Void::Async::OperationOptions options)
|
|
{
|
|
std::unique_lock lk{m_state->mu};
|
|
if (m_state->closing) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Closed, "Messaging queue is closed"));
|
|
}
|
|
if (options.stop.stop_requested()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Cancelled, "Messaging::receive cancelled"));
|
|
}
|
|
|
|
m_state->reap_expired_locked();
|
|
auto immediate = m_state->try_receive_locked(queue, group);
|
|
if (!immediate.has_value()) {
|
|
return Void::Result::fail(immediate.error());
|
|
}
|
|
if (immediate->has_value()) {
|
|
return std::move(**immediate);
|
|
}
|
|
|
|
if (m_state->waiting_receives >= m_state->limits.max_waiting_receives) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Overloaded,
|
|
"Messaging: max_waiting_receives cap reached"));
|
|
}
|
|
|
|
++m_state->waiting_receives;
|
|
struct WaitGuard {
|
|
std::size_t& counter;
|
|
~WaitGuard() noexcept { --counter; }
|
|
} wguard{m_state->waiting_receives};
|
|
|
|
std::stop_callback stop_cb(options.stop,
|
|
[this] { m_state->cv.notify_all(); });
|
|
|
|
for (;;) {
|
|
if (m_state->closing) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Closed,
|
|
"Messaging queue closed while waiting to receive"));
|
|
}
|
|
if (options.stop.stop_requested()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Cancelled,
|
|
"Messaging::receive cancelled while waiting"));
|
|
}
|
|
m_state->reap_expired_locked();
|
|
auto polled = m_state->try_receive_locked(queue, group);
|
|
if (!polled.has_value()) {
|
|
return Void::Result::fail(polled.error());
|
|
}
|
|
if (polled->has_value()) {
|
|
return std::move(**polled);
|
|
}
|
|
if (options.deadline.has_value()) {
|
|
const auto rem = Void::Time::remaining_until(
|
|
*m_state->mono, *options.deadline);
|
|
if (rem <= std::chrono::nanoseconds{0}) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Timeout,
|
|
"Messaging::receive deadline expired"));
|
|
}
|
|
const auto slice =
|
|
std::min(rem, std::chrono::duration_cast<
|
|
std::chrono::nanoseconds>(
|
|
std::chrono::milliseconds{5}));
|
|
m_state->cv.wait_for(lk, slice);
|
|
} else {
|
|
m_state->cv.wait_for(lk, std::chrono::milliseconds{5});
|
|
}
|
|
}
|
|
}
|
|
|
|
Result<void> InMemoryQueue::ack(const Receipt& receipt,
|
|
Void::Async::OperationOptions options)
|
|
{
|
|
if (options.stop.stop_requested()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Cancelled, "Messaging::ack cancelled"));
|
|
}
|
|
std::lock_guard lk{m_state->mu};
|
|
auto qit = m_state->queues.find(receipt.queue);
|
|
if (qit == m_state->queues.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: queue not found"));
|
|
}
|
|
auto git = qit->second.groups.find(receipt.group);
|
|
if (git == qit->second.groups.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: group not found"));
|
|
}
|
|
auto sit = git->second.slots.find(receipt.sequence);
|
|
if (sit == git->second.slots.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: receipt not found"));
|
|
}
|
|
auto& slot = sit->second;
|
|
// Repeat ack of the same already-acknowledged receipt is idempotent OK!
|
|
if (slot.state == DeliveryState::Acked &&
|
|
slot.generation == receipt.generation) {
|
|
return {};
|
|
}
|
|
if (slot.state != DeliveryState::InFlight ||
|
|
slot.generation != receipt.generation) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::StaleReceipt,
|
|
"Messaging::ack receipt generation is stale"));
|
|
}
|
|
slot.state = DeliveryState::Acked;
|
|
if (git->second.in_flight > 0U) {
|
|
--git->second.in_flight;
|
|
}
|
|
m_state->cv.notify_all();
|
|
return {};
|
|
}
|
|
|
|
Result<void> InMemoryQueue::nack(
|
|
const Receipt& receipt, std::optional<std::chrono::milliseconds> delay,
|
|
Void::Async::OperationOptions options)
|
|
{
|
|
if (options.stop.stop_requested()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Cancelled, "Messaging::nack cancelled"));
|
|
}
|
|
std::lock_guard lk{m_state->mu};
|
|
auto qit = m_state->queues.find(receipt.queue);
|
|
if (qit == m_state->queues.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: queue not found"));
|
|
}
|
|
auto& qd = qit->second;
|
|
auto git = qd.groups.find(receipt.group);
|
|
if (git == qd.groups.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: group not found"));
|
|
}
|
|
auto& gs = git->second;
|
|
auto sit = gs.slots.find(receipt.sequence);
|
|
if (sit == gs.slots.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: receipt not found"));
|
|
}
|
|
auto& slot = sit->second;
|
|
if (slot.state != DeliveryState::InFlight ||
|
|
slot.generation != receipt.generation) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::StaleReceipt,
|
|
"Messaging::nack receipt generation is stale"));
|
|
}
|
|
|
|
if (slot.attempt >= qd.config.retry.max_attempts) {
|
|
auto dlq_res = m_state->move_to_dlq_locked(
|
|
qd, gs, slot, "nack retry exhaustion");
|
|
m_state->cv.notify_all();
|
|
return dlq_res;
|
|
}
|
|
|
|
const std::int64_t wait_ms =
|
|
delay.has_value()
|
|
? std::max<std::int64_t>(0LL, delay->count())
|
|
: compute_retry_backoff_ms(qd.config.retry, slot.attempt,
|
|
m_state->rng);
|
|
slot.state = DeliveryState::Pending;
|
|
if (gs.in_flight > 0U) {
|
|
--gs.in_flight;
|
|
}
|
|
slot.available_at =
|
|
m_state->mono->now() + std::chrono::milliseconds{wait_ms};
|
|
m_state->cv.notify_all();
|
|
return {};
|
|
}
|
|
|
|
Result<Void::Time::MonotonicClock::time_point>
|
|
InMemoryQueue::extend_visibility(const Receipt& receipt,
|
|
std::chrono::milliseconds extension,
|
|
Void::Async::OperationOptions options)
|
|
{
|
|
if (options.stop.stop_requested()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Cancelled,
|
|
"Messaging::extend_visibility cancelled"));
|
|
}
|
|
if (extension <= std::chrono::milliseconds{0} ||
|
|
extension > m_state->limits.max_visibility_extension) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::InvalidArgument,
|
|
"Messaging::extend_visibility must be in (0, "
|
|
"max_visibility_extension]"));
|
|
}
|
|
std::lock_guard lk{m_state->mu};
|
|
auto qit = m_state->queues.find(receipt.queue);
|
|
if (qit == m_state->queues.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: queue not found"));
|
|
}
|
|
auto git = qit->second.groups.find(receipt.group);
|
|
if (git == qit->second.groups.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: group not found"));
|
|
}
|
|
auto sit = git->second.slots.find(receipt.sequence);
|
|
if (sit == git->second.slots.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: receipt not found"));
|
|
}
|
|
auto& slot = sit->second;
|
|
if (slot.state != DeliveryState::InFlight ||
|
|
slot.generation != receipt.generation) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::StaleReceipt,
|
|
"Messaging::extend_visibility receipt generation is stale"));
|
|
}
|
|
slot.visibility_deadline = m_state->mono->now() + extension;
|
|
return slot.visibility_deadline;
|
|
}
|
|
|
|
Result<void> InMemoryQueue::quarantine_corrupt(
|
|
const Receipt& receipt, std::string reason,
|
|
Void::Async::OperationOptions options)
|
|
{
|
|
if (options.stop.stop_requested()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::Cancelled,
|
|
"Messaging::quarantine_corrupt cancelled"));
|
|
}
|
|
std::lock_guard lk{m_state->mu};
|
|
auto qit = m_state->queues.find(receipt.queue);
|
|
if (qit == m_state->queues.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: queue not found"));
|
|
}
|
|
auto& qd = qit->second;
|
|
auto git = qd.groups.find(receipt.group);
|
|
if (git == qd.groups.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: group not found"));
|
|
}
|
|
auto& gs = git->second;
|
|
auto sit = gs.slots.find(receipt.sequence);
|
|
if (sit == gs.slots.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: receipt not found"));
|
|
}
|
|
auto& slot = sit->second;
|
|
if (slot.state != DeliveryState::InFlight ||
|
|
slot.generation != receipt.generation) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::StaleReceipt,
|
|
"Messaging::quarantine_corrupt receipt generation is stale"));
|
|
}
|
|
auto res = m_state->move_to_dlq_locked(
|
|
qd, gs, slot,
|
|
reason.empty() ? std::string{"corrupt payload"} : std::move(reason));
|
|
m_state->cv.notify_all();
|
|
return res;
|
|
}
|
|
|
|
Result<DeliveryState>
|
|
InMemoryQueue::query_receipt(const Receipt& receipt) const
|
|
{
|
|
std::lock_guard lk{m_state->mu};
|
|
auto qit = m_state->queues.find(receipt.queue);
|
|
if (qit == m_state->queues.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: queue not found"));
|
|
}
|
|
auto git = qit->second.groups.find(receipt.group);
|
|
if (git == qit->second.groups.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: group not found"));
|
|
}
|
|
auto sit = git->second.slots.find(receipt.sequence);
|
|
if (sit == git->second.slots.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: receipt not found"));
|
|
}
|
|
return sit->second.state;
|
|
}
|
|
|
|
Result<std::vector<DeadLetterEntry>>
|
|
InMemoryQueue::list_dead_letters(std::string_view queue,
|
|
std::string_view group,
|
|
std::size_t limit) const
|
|
{
|
|
std::lock_guard lk{m_state->mu};
|
|
auto qit = m_state->queues.find(queue);
|
|
if (qit == m_state->queues.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: queue not found"));
|
|
}
|
|
auto git = qit->second.groups.find(group);
|
|
if (git == qit->second.groups.end()) {
|
|
return Void::Result::fail(make_messaging_error(
|
|
MessagingErrorCode::NotFound, "Messaging: group not found"));
|
|
}
|
|
const auto& dlq = git->second.dlq;
|
|
const std::size_t n = std::min(limit, dlq.size());
|
|
return std::vector<DeadLetterEntry>(dlq.begin(),
|
|
dlq.begin() +
|
|
static_cast<std::ptrdiff_t>(n));
|
|
}
|
|
|
|
std::size_t InMemoryQueue::stuck_dlq_count(std::string_view queue,
|
|
std::string_view group) const
|
|
noexcept
|
|
{
|
|
std::lock_guard lk{m_state->mu};
|
|
auto qit = m_state->queues.find(queue);
|
|
if (qit == m_state->queues.end()) return 0;
|
|
auto git = qit->second.groups.find(group);
|
|
if (git == qit->second.groups.end()) return 0;
|
|
return git->second.stuck_dlq;
|
|
}
|
|
|
|
Result<std::size_t> InMemoryQueue::reap_expired_visibility()
|
|
{
|
|
std::lock_guard lk{m_state->mu};
|
|
return m_state->reap_expired_locked();
|
|
}
|
|
|
|
Result<std::size_t> InMemoryQueue::expire_retention()
|
|
{
|
|
std::lock_guard lk{m_state->mu};
|
|
if (!m_state->clock_healthy) {
|
|
// Pause retention expiry when civil clock health is degraded!
|
|
return 0U;
|
|
}
|
|
const std::int64_t cutoff =
|
|
to_utc_ms(m_state->civil->now()) -
|
|
m_state->limits.logical_retention.count();
|
|
std::size_t expired = 0;
|
|
|
|
for (auto& [qn, qd] : m_state->queues) {
|
|
(void)qn;
|
|
for (auto mit = qd.messages.begin(); mit != qd.messages.end();) {
|
|
if (mit->second.published_utc_ms > cutoff) {
|
|
++mit;
|
|
continue;
|
|
}
|
|
const std::uint64_t seq = mit->first;
|
|
bool all_terminal = true;
|
|
bool any_in_flight = false;
|
|
for (const auto& [gn, gs] : qd.groups) {
|
|
(void)gn;
|
|
auto sit = gs.slots.find(seq);
|
|
if (sit != gs.slots.end()) {
|
|
if (sit->second.state == DeliveryState::InFlight) {
|
|
any_in_flight = true;
|
|
all_terminal = false;
|
|
} else if (sit->second.state == DeliveryState::Pending) {
|
|
all_terminal = false;
|
|
}
|
|
}
|
|
}
|
|
const bool can_drop =
|
|
!any_in_flight &&
|
|
(all_terminal ||
|
|
qd.config.retention_policy ==
|
|
RetentionPolicy::DropOldestLossy);
|
|
if (can_drop) {
|
|
for (auto& [gn, gs] : qd.groups) {
|
|
(void)gn;
|
|
gs.slots.erase(seq);
|
|
}
|
|
if (m_state->transient_bytes >= mit->second.bytes) {
|
|
m_state->transient_bytes -= mit->second.bytes;
|
|
} else {
|
|
m_state->transient_bytes = 0;
|
|
}
|
|
mit = qd.messages.erase(mit);
|
|
++expired;
|
|
} else {
|
|
++mit;
|
|
}
|
|
}
|
|
}
|
|
return expired;
|
|
}
|
|
|
|
void InMemoryQueue::set_clock_healthy(bool healthy) noexcept
|
|
{
|
|
std::lock_guard lk{m_state->mu};
|
|
m_state->clock_healthy = healthy;
|
|
}
|
|
|
|
Result<ShutdownReport>
|
|
InMemoryQueue::close_and_join(Void::Async::OperationOptions options)
|
|
{
|
|
std::unique_lock lk{m_state->mu};
|
|
m_state->closing = true;
|
|
m_state->cv.notify_all();
|
|
|
|
auto count_in_flight = [&]() {
|
|
std::size_t n = 0;
|
|
for (const auto& [qn, qd] : m_state->queues) {
|
|
(void)qn;
|
|
for (const auto& [gn, gs] : qd.groups) {
|
|
(void)gn;
|
|
n += gs.in_flight;
|
|
}
|
|
}
|
|
return n;
|
|
};
|
|
|
|
const auto deadline =
|
|
options.deadline.value_or(m_state->mono->now() +
|
|
m_state->limits.shutdown_drain_timeout);
|
|
while (count_in_flight() > 0U || m_state->waiting_receives > 0U) {
|
|
const auto rem = Void::Time::remaining_until(*m_state->mono, deadline);
|
|
if (rem <= std::chrono::nanoseconds{0}) {
|
|
const std::size_t live = count_in_flight();
|
|
return ShutdownReport{
|
|
.complete = (live == 0U && m_state->waiting_receives == 0U),
|
|
.remaining_in_flight = live,
|
|
};
|
|
}
|
|
const auto slice =
|
|
std::min(rem, std::chrono::duration_cast<
|
|
std::chrono::nanoseconds>(
|
|
std::chrono::milliseconds{5}));
|
|
m_state->cv.wait_for(lk, slice);
|
|
}
|
|
return ShutdownReport{.complete = true, .remaining_in_flight = 0};
|
|
}
|
|
|
|
Result<QueueStats> InMemoryQueue::stats() const
|
|
{
|
|
std::lock_guard lk{m_state->mu};
|
|
QueueStats s{};
|
|
s.queues = m_state->queues.size();
|
|
s.retained_bytes = m_state->transient_bytes;
|
|
for (const auto& [qn, qd] : m_state->queues) {
|
|
(void)qn;
|
|
s.idempotency_entries += qd.idempotency.size();
|
|
for (const auto& [gn, gs] : qd.groups) {
|
|
(void)gn;
|
|
s.dead_letter += gs.dlq.size();
|
|
s.stuck_dlq += gs.stuck_dlq;
|
|
for (const auto& [seq, slot] : gs.slots) {
|
|
(void)seq;
|
|
switch (slot.state) {
|
|
case DeliveryState::Pending: ++s.pending; break;
|
|
case DeliveryState::InFlight: ++s.in_flight; break;
|
|
case DeliveryState::Acked: ++s.acked; break;
|
|
case DeliveryState::DeadLetter: break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return s;
|
|
}
|
|
|
|
} // namespace Void::Messaging
|