diff --git a/README.md b/README.md index e7c47b0f..2af85532 100644 --- a/README.md +++ b/README.md @@ -160,8 +160,10 @@ class MessageConsumer { messageGuard.ack(); } else { - messageGuard.nack(); - // Would automatically nack if it goes out of scope + // Reject and requeue, counting the failed attempt towards the + // queue's delivery-limit + messageGuard.reject(); + // Would automatically reject with requeue if it goes out of scope } } }; diff --git a/docs/doxygen.md b/docs/doxygen.md index 6e351225..31f7850a 100644 --- a/docs/doxygen.md +++ b/docs/doxygen.md @@ -207,6 +207,14 @@ class MessageConsumer { **Important** -- messages should be acknowledged only after completely processing them. For example, if the consumer logic sends received messages to some RabbitMQ exchange, the message should be acknowledged only after receiving the publisher confirm of the send operation. A premature call to `ack()` followed by a failure of the user's consumer logic can result in a dropped message. +### Returning a message: `reject` vs `nack` + +`reject` and `nack` both return a delivered message to the broker, for it to discard or requeue, but from RabbitMQ 4.3 they are not counted the same way. Only `basic.reject` increments the broker's `delivery-count`, which is what a quorum queue's `delivery-limit` is measured against. Use `reject` when processing a message failed, so that a message which always fails is eventually dead lettered or dropped rather than redelivered forever. `nack` is kept because `basic.nack` is part of the protocol. + +If a `MessageGuard` is destroyed without `ack`, `nack` or `reject` being called, such as when the consumer callback throws, the library rejects it with requeue. + +See [Negative Acknowledgements](https://www.rabbitmq.com/docs/nack) and the broker's table of [when delivery count is incremented](https://www.rabbitmq.com/docs/quorum-queues#when-is-delivery-count-incremented). + ## Shutting down diff --git a/examples/helloworld/producer.m.cpp b/examples/helloworld/producer.m.cpp index e2d18332..5bb7657c 100644 --- a/examples/helloworld/producer.m.cpp +++ b/examples/helloworld/producer.m.cpp @@ -89,7 +89,7 @@ int main(int argc, char** argv) // triggered this publish } else { - // Send error response, rollback transaction, nack message + // Send error response, rollback transaction, reject message // and/or raise an alarm for investigation - your message is not // delivered to all (or perhaps any) of the queues it was // intended for. diff --git a/examples/topology/headers.m.cpp b/examples/topology/headers.m.cpp index 7f0efaf4..65b051fc 100644 --- a/examples/topology/headers.m.cpp +++ b/examples/topology/headers.m.cpp @@ -101,7 +101,7 @@ int main(int argc, char** argv) // triggered this publish } else { - // Send error response, rollback transaction, nack message + // Send error response, rollback transaction, reject message // and/or raise an alarm for investigation - your message is not // delivered to all (or perhaps any) of the queues it was // intended for. diff --git a/src/rmq/rmqa/rmqa_consumer.h b/src/rmq/rmqa/rmqa_consumer.h index 98158415..6cbd2299 100644 --- a/src/rmq/rmqa/rmqa_consumer.h +++ b/src/rmq/rmqa/rmqa_consumer.h @@ -50,8 +50,8 @@ class Consumer { explicit Consumer(bslma::ManagedPtr& impl); /// \brief Tells the broker to stop delivering messages to this consumer. - /// it's still possible to nack/ack messages from callbacks after cancel is - /// called + /// it's still possible to ack/reject/nack messages from callbacks after + /// cancel is called void cancel(); /// \brief Tells the broker to stop delivering messages to this consumer. diff --git a/src/rmq/rmqa/rmqa_messageguard.cpp b/src/rmq/rmqa/rmqa_messageguard.cpp index cf70c557..19798095 100644 --- a/src/rmq/rmqa/rmqa_messageguard.cpp +++ b/src/rmq/rmqa/rmqa_messageguard.cpp @@ -76,12 +76,13 @@ MessageGuard& MessageGuard::operator=(const MessageGuard& other) MessageGuard::~MessageGuard() { if (d_state == READY) { - BALL_LOG_ERROR << "Unacked message, explicitly nacking. Message guid: " + BALL_LOG_ERROR << "Unresolved message, explicitly rejecting with " + "requeue. Message guid: " << d_message.guid() << ", payload size: " << d_message.payloadSize(); try { - d_ackCallback( - rmqt::ConsumerAck(d_envelope, rmqt::ConsumerAck::REQUEUE)); + d_ackCallback(rmqt::ConsumerAck( + d_envelope, rmqt::ConsumerAck::REJECT_REQUEUE_TRUE)); } catch (bsl::exception& e) { BALL_LOG_ERROR @@ -107,7 +108,14 @@ void MessageGuard::ack() { resolve(rmqt::ConsumerAck::ACK); } void MessageGuard::nack(bool requeue) { - resolve(requeue ? rmqt::ConsumerAck::REQUEUE : rmqt::ConsumerAck::REJECT); + resolve(requeue ? rmqt::ConsumerAck::NACK_REQUEUE_TRUE + : rmqt::ConsumerAck::NACK_REQUEUE_FALSE); +} + +void MessageGuard::reject(bool requeue) +{ + resolve(requeue ? rmqt::ConsumerAck::REJECT_REQUEUE_TRUE + : rmqt::ConsumerAck::REJECT_REQUEUE_FALSE); } void MessageGuard::resolve(rmqt::ConsumerAck::Type ackOption) diff --git a/src/rmq/rmqa/rmqa_messageguard.h b/src/rmq/rmqa/rmqa_messageguard.h index 1bfb2621..cb354ff0 100644 --- a/src/rmq/rmqa/rmqa_messageguard.h +++ b/src/rmq/rmqa/rmqa_messageguard.h @@ -39,8 +39,10 @@ namespace rmqa { /// A MessageGuard is passed to the rmqa::Consumer callback function /// (defined in rmqp::Consumer) for each message. The object allows /// acknowledging either positively or negatively, with options to requeue. If a -/// MessageGuard object is allowed to destruct before ack/nack is called a nack -/// with requeue is automatically signaled to the broker. +/// MessageGuard object is allowed to destruct before ack/nack/reject is called +/// - for example because the consumer callback threw - a reject with requeue is +/// automatically signaled to the broker. The delivery is therefore counted as a +/// failed attempt and is subject to the queue's delivery-limit, if one is set. class MessageGuard : public rmqp::MessageGuard { public: @@ -69,8 +71,8 @@ class MessageGuard : public rmqp::MessageGuard { /// to (n)ack. MessageGuard(const MessageGuard& obj); - /// If not processed (`ack()`/`nack()` called), message will be nacked - /// automatically. + /// If not processed (`ack()`/`nack()`/`reject()` called), message will be + /// rejected with requeue automatically. ~MessageGuard() BSLS_KEYWORD_OVERRIDE; /// Access the received message @@ -87,13 +89,43 @@ class MessageGuard : public rmqp::MessageGuard { /// redelivered to another consumer. void ack() BSLS_KEYWORD_OVERRIDE; - /// Negative acknowledge the received message. Callable only once. + /// Return the received message to the broker without counting this + /// delivery as a failed processing attempt (`basic.nack`). Callable only + /// once. /// \param requeue `true` /// requeues the message on the broker for redelivery , if /// `false`, then the message will be either dead lettered (if a /// dead letter exchange is specified) or dropped if not. + /// + /// \warning Consider `reject` instead. From RabbitMQ 4.3 a quorum queue's + /// delivery-limit is measured against the broker's + /// delivery-count, which `nack` does not increment, so a message + /// returned with `nack(true)` never reaches the limit. See the + /// documentation below. + /// + /// \see https://www.rabbitmq.com/docs/nack + /// \see + /// https://www.rabbitmq.com/docs/quorum-queues#when-is-delivery-count-incremented void nack(bool requeue = true) BSLS_KEYWORD_OVERRIDE; + /// Reject the received message, counting this delivery as a failed + /// processing attempt (`basic.reject`). Callable only once. + /// + /// Use this when processing a message failed. Unlike `nack`, it + /// increments the broker's delivery-count, so from RabbitMQ 4.3 the + /// delivery counts towards a quorum queue's delivery-limit, where one is + /// set, and the message is eventually dead lettered or dropped rather + /// than redelivered forever. + /// + /// \param requeue `true` requeues the message on the broker for + /// redelivery. If `false`, the message will be either dead lettered (if a + /// dead letter exchange is specified) or dropped if not. + /// + /// \see https://www.rabbitmq.com/docs/nack + /// \see + /// https://www.rabbitmq.com/docs/quorum-queues#when-is-delivery-count-incremented + void reject(bool requeue = true) BSLS_KEYWORD_OVERRIDE; + /// Pointer to the Consumer, e.g. to cancel the message flow virtual rmqp::Consumer* consumer() const BSLS_KEYWORD_OVERRIDE; diff --git a/src/rmq/rmqa/rmqa_tracingmessageguard.h b/src/rmq/rmqa/rmqa_tracingmessageguard.h index df3d2b71..5c606401 100644 --- a/src/rmq/rmqa/rmqa_tracingmessageguard.h +++ b/src/rmq/rmqa/rmqa_tracingmessageguard.h @@ -40,8 +40,8 @@ namespace rmqa { /// context is created from the thread that will process the message callback, /// and the context will be bound to the messageGuard. The object allows /// acknowledging either positively or negatively, with options to requeue. If a -/// MessageGuard object is allowed to destruct before ack/nack is called a nack -/// with requeue is automatically signaled to the broker. +/// MessageGuard object is allowed to destruct before ack/nack/reject is called +/// a reject with requeue is automatically signaled to the broker. class TracingMessageGuard : public rmqa::MessageGuard { public: diff --git a/src/rmq/rmqamqp/rmqamqp_metrics.cpp b/src/rmq/rmqamqp/rmqamqp_metrics.cpp index 646a4261..cb44b149 100644 --- a/src/rmq/rmqamqp/rmqamqp_metrics.cpp +++ b/src/rmq/rmqamqp/rmqamqp_metrics.cpp @@ -20,6 +20,10 @@ namespace rmqamqp { const char* Metrics::VHOST_TAG = "rmqVhostName"; const char* Metrics::CHANNELTYPE_TAG = "rmqChannelType"; +const char* Metrics::RESULT_TAG = "rmqResult"; + +// Consumer metrics +const char* Metrics::CONSUMER_MESSAGE_HANDLED = "consumer_message_handled"; // Pause/Resume metrics const char* Metrics::CONSUMER_PAUSE_TOTAL = "consumer_pause_total"; diff --git a/src/rmq/rmqamqp/rmqamqp_metrics.h b/src/rmq/rmqamqp/rmqamqp_metrics.h index f4aa658d..2ef7cd94 100644 --- a/src/rmq/rmqamqp/rmqamqp_metrics.h +++ b/src/rmq/rmqamqp/rmqamqp_metrics.h @@ -30,6 +30,11 @@ class Metrics { static const char* NAMESPACE; static const char* VHOST_TAG; static const char* CHANNELTYPE_TAG; + static const char* RESULT_TAG; + + // Consumer metrics + /// How the application resolved a delivery, tagged by RESULT_TAG + static const char* CONSUMER_MESSAGE_HANDLED; // Pause/Resume metrics static const char* CONSUMER_PAUSE_TOTAL; diff --git a/src/rmq/rmqamqp/rmqamqp_multipleackhandler.cpp b/src/rmq/rmqamqp/rmqamqp_multipleackhandler.cpp index eee5ddca..246fe926 100644 --- a/src/rmq/rmqamqp/rmqamqp_multipleackhandler.cpp +++ b/src/rmq/rmqamqp/rmqamqp_multipleackhandler.cpp @@ -16,6 +16,7 @@ #include #include +#include namespace BloombergLP { namespace rmqamqp { @@ -30,9 +31,11 @@ bool compare(const rmqt::ConsumerAck& a, const rmqt::ConsumerAck& b) } // namespace MultipleAckHandler::MultipleAckHandler(const AckCallback& ackCb, - const NackCallback& nackCb) + const NackCallback& nackCb, + const RejectCallback& rejectCb) : d_onAck(ackCb) , d_onNack(nackCb) +, d_onReject(rejectCb) , d_totalAcked(0) , d_maxProcessedTag(0) { @@ -56,9 +59,11 @@ void MultipleAckHandler::process(bsl::vector& acks) const rmqt::ConsumerAck::Type type = acks[i].type(); // We can only batch the next ack if we have already processed all - // messages in the interval [1 .. n] and the next message has the tag - // n+1 - if (d_totalAcked == d_maxProcessedTag && tag == d_maxProcessedTag + 1) { + // messages in the interval [1 .. n], the next message has the tag + // n+1, and the resolution is one the broker lets us batch (basic.ack + // and basic.nack have a `multiple` field, basic.reject does not) + if (d_totalAcked == d_maxProcessedTag && tag == d_maxProcessedTag + 1 && + rmqt::ConsumerAck::supportsMultiple(type)) { // If this ack has a different type than the pending batch, the // batch is closed and can be acked to the broker @@ -107,16 +112,22 @@ void MultipleAckHandler::sendAck(uint64_t deliveryTag, { const bool multiple = (batchSize > 1); - BALL_LOG_TRACE << (type == rmqt::ConsumerAck::ACK ? "Acking: " - : "Nacking: ") - << deliveryTag << ", type = " << type + BALL_LOG_TRACE << "Resolving: " << deliveryTag << ", type = " << type << ", batch size = " << batchSize; if (type == rmqt::ConsumerAck::ACK) { d_onAck(deliveryTag, multiple); } + else if (rmqt::ConsumerAck::usesBasicReject(type)) { + // Rejects are always sent one delivery at a time, as + // supportsMultiple() keeps them out of batches + BSLS_ASSERT(!multiple); + d_onReject(deliveryTag, type == rmqt::ConsumerAck::REJECT_REQUEUE_TRUE); + } else { - d_onNack(deliveryTag, type == rmqt::ConsumerAck::REQUEUE, multiple); + d_onNack(deliveryTag, + type == rmqt::ConsumerAck::NACK_REQUEUE_TRUE, + multiple); } } diff --git a/src/rmq/rmqamqp/rmqamqp_multipleackhandler.h b/src/rmq/rmqamqp/rmqamqp_multipleackhandler.h index 8d407f06..53316027 100644 --- a/src/rmq/rmqamqp/rmqamqp_multipleackhandler.h +++ b/src/rmq/rmqamqp/rmqamqp_multipleackhandler.h @@ -35,8 +35,11 @@ class MultipleAckHandler { public: typedef bsl::function AckCallback; typedef bsl::function NackCallback; + typedef bsl::function RejectCallback; - MultipleAckHandler(const AckCallback& ackCb, const NackCallback& nackCb); + MultipleAckHandler(const AckCallback& ackCb, + const NackCallback& nackCb, + const RejectCallback& rejectCb); ~MultipleAckHandler(); /// Batches and acknowledges the given acks. @@ -57,6 +60,9 @@ class MultipleAckHandler { /// Callback for sending basic.nack to the broker NackCallback d_onNack; + /// Callback for sending basic.reject to the broker + RejectCallback d_onReject; + /// Total number of messages acknowledged uint64_t d_totalAcked; diff --git a/src/rmq/rmqamqp/rmqamqp_receivechannel.cpp b/src/rmq/rmqamqp/rmqamqp_receivechannel.cpp index 1b2a8680..1fc066ff 100644 --- a/src/rmq/rmqamqp/rmqamqp_receivechannel.cpp +++ b/src/rmq/rmqamqp/rmqamqp_receivechannel.cpp @@ -67,6 +67,30 @@ void publishLatencyIfTracked( } } +/// Value for Metrics::RESULT_TAG describing how a message was resolved. +/// Deliberately has no `default` case, so that adding an +/// rmqt::ConsumerAck::Type without naming it here is a compiler warning. +const char* resultName(rmqt::ConsumerAck::Type type) +{ + switch (type) { + case rmqt::ConsumerAck::ACK: + return "ack"; + case rmqt::ConsumerAck::NACK_REQUEUE_FALSE: + return "nack_requeue_false"; + case rmqt::ConsumerAck::NACK_REQUEUE_TRUE: + return "nack_requeue_true"; + case rmqt::ConsumerAck::REJECT_REQUEUE_FALSE: + return "reject_requeue_false"; + case rmqt::ConsumerAck::REJECT_REQUEUE_TRUE: + return "reject_requeue_true"; + } + + return "unknown"; +} + +/// Number of distinct rmqt::ConsumerAck::Type values +const size_t HANDLED_RESULT_COUNT = rmqt::ConsumerAck::REJECT_REQUEUE_TRUE + 1; + } // namespace class ReceiveChannel::Consumer { @@ -387,14 +411,27 @@ ReceiveChannel::ReceiveChannel( , d_ackQueue(ackQueue) , d_multipleAckHandler( bdlf::BindUtil::bind(&ReceiveChannel::sendAck, this, _1, _2), - bdlf::BindUtil::bind(&ReceiveChannel::sendNack, this, _1, _2, _3)) + bdlf::BindUtil::bind(&ReceiveChannel::sendNack, this, _1, _2, _3), + bdlf::BindUtil::bind(&ReceiveChannel::sendReject, this, _1, _2)) , d_consumeFuturePair() , d_cancelFuturePair() , d_drainFuture() , d_channelPausedOnOpen(channelPausedOnOpen) , d_pauseStartTime() , d_resumeStartTime() +, d_messageHandledTags() +, d_messageHandledMetricName(Metrics::CONSUMER_MESSAGE_HANDLED) { + d_messageHandledTags.reserve(HANDLED_RESULT_COUNT); + for (size_t type = 0; type < HANDLED_RESULT_COUNT; ++type) { + bsl::vector > tags = + getMetricTags(); + tags.push_back( + bsl::make_pair(bsl::string(Metrics::RESULT_TAG), + bsl::string(resultName( + static_cast(type))))); + d_messageHandledTags.push_back(tags); + } } const rmqt::ConsumerConfig& ReceiveChannel::consumerConfig() const @@ -618,6 +655,10 @@ void ReceiveChannel::consumeAckBatchFromQueue() for (bsl::vector::iterator it = valid; it < acks.end(); ++it) { if (it->envelope().channelLifetimeId() == lifetimeId()) { + d_metricPublisher->publishCounter(d_messageHandledMetricName, + 1, + d_messageHandledTags[it->type()]); + // Avoid unnecessary copying to the same vector index if (it != valid) { (*valid) = (*it); @@ -1084,6 +1125,14 @@ void ReceiveChannel::sendNack(uint64_t deliveryTag, bool requeue, bool multiple) multiple); } +void ReceiveChannel::sendReject(uint64_t deliveryTag, bool requeue) +{ + sendAckOrNack( + rmqamqpt::BasicMethod(rmqamqpt::BasicReject(deliveryTag, requeue)), + deliveryTag, + false); +} + void ReceiveChannel::sendAckOrNack(const rmqamqpt::BasicMethod& basicMethod, uint64_t deliveryTag, bool multiple) diff --git a/src/rmq/rmqamqp/rmqamqp_receivechannel.h b/src/rmq/rmqamqp/rmqamqp_receivechannel.h index 754e6be0..da0a549c 100644 --- a/src/rmq/rmqamqp/rmqamqp_receivechannel.h +++ b/src/rmq/rmqamqp/rmqamqp_receivechannel.h @@ -159,6 +159,9 @@ class ReceiveChannel : public Channel { void sendAck(uint64_t deliveryTag, bool multiple = false); void sendNack(uint64_t deliveryTag, bool requeue = true, bool multiple = false); + /// basic.reject has no `multiple` field, so this always resolves a single + /// delivery + void sendReject(uint64_t deliveryTag, bool requeue = true); void sendAckOrNack(const rmqamqpt::BasicMethod& basicMethod, uint64_t deliveryTag, bool multiple); @@ -184,6 +187,18 @@ class ReceiveChannel : public Channel { bool d_channelPausedOnOpen; bsls::TimeInterval d_pauseStartTime; bsls::TimeInterval d_resumeStartTime; + + /// Metric tags for Metrics::CONSUMER_MESSAGE_HANDLED, indexed by + /// rmqt::ConsumerAck::Type. Built once in the constructor so that + /// resolving a delivery, which happens per message on the event loop + /// thread, allocates nothing. + bsl::vector > > + d_messageHandledTags; + + /// Held rather than converted from Metrics::CONSUMER_MESSAGE_HANDLED on + /// every publish: it is too long for the short-string optimisation, so + /// each conversion would allocate + bsl::string d_messageHandledMetricName; }; } // namespace rmqamqp diff --git a/src/rmq/rmqamqpt/CMakeLists.txt b/src/rmq/rmqamqpt/CMakeLists.txt index fb6bc0ac..be2a9627 100644 --- a/src/rmq/rmqamqpt/CMakeLists.txt +++ b/src/rmq/rmqamqpt/CMakeLists.txt @@ -11,6 +11,7 @@ add_library(rmqamqpt OBJECT rmqamqpt_basicpublish.cpp rmqamqpt_basicqos.cpp rmqamqpt_basicqosok.cpp + rmqamqpt_basicreject.cpp rmqamqpt_basicreturn.cpp rmqamqpt_buffer.cpp rmqamqpt_channelclose.cpp diff --git a/src/rmq/rmqamqpt/rmqamqpt_basicmethod.cpp b/src/rmq/rmqamqpt/rmqamqpt_basicmethod.cpp index c6942f14..f8aee4f5 100644 --- a/src/rmq/rmqamqpt/rmqamqpt_basicmethod.cpp +++ b/src/rmq/rmqamqpt/rmqamqpt_basicmethod.cpp @@ -53,6 +53,7 @@ bool decodeBasicMethodPayload(BasicMethod* basicMethod, DECODE_METHOD(BasicDeliver) DECODE_METHOD(BasicNack) DECODE_METHOD(BasicPublish) + DECODE_METHOD(BasicReject) DECODE_METHOD(BasicReturn) DECODE_METHOD(BasicQoS) DECODE_METHOD(BasicQoSOk) diff --git a/src/rmq/rmqamqpt/rmqamqpt_basicmethod.h b/src/rmq/rmqamqpt/rmqamqpt_basicmethod.h index 2ed5685f..40df59df 100644 --- a/src/rmq/rmqamqpt/rmqamqpt_basicmethod.h +++ b/src/rmq/rmqamqpt/rmqamqpt_basicmethod.h @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -48,6 +49,7 @@ typedef bdlb::Variant SupportedBasicMethods; diff --git a/src/rmq/rmqamqpt/rmqamqpt_basicreject.cpp b/src/rmq/rmqamqpt/rmqamqpt_basicreject.cpp new file mode 100644 index 00000000..a1184b9a --- /dev/null +++ b/src/rmq/rmqamqpt/rmqamqpt_basicreject.cpp @@ -0,0 +1,80 @@ +// Copyright 2026 Bloomberg Finance L.P. +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include + +#include + +#include +#include + +namespace BloombergLP { +namespace rmqamqpt { + +namespace { +/// Basic.Reject's bitmask holds a single bit, `requeue`, at bit 0 +const uint8_t BITMASK_BIT_0 = (1 << 0); +} // namespace + +BasicReject::BasicReject(bsl::uint64_t dt, bool requeue) +: d_deliveryTag(dt) +, d_requeue(requeue) +{ +} + +BasicReject::BasicReject() +: d_deliveryTag() +, d_requeue() +{ +} + +bool BasicReject::decode(BasicReject* reject, + const uint8_t* data, + bsl::size_t dataLength) +{ + rmqamqpt::Buffer buffer(data, dataLength); + + uint8_t bitmask = 0; + if (!buffer.copy(&reject->d_deliveryTag) || + !buffer.copy(&bitmask)) { + return false; + } + + reject->d_requeue = bitmask & BITMASK_BIT_0; + + return true; +} + +void BasicReject::encode(Writer& output, const BasicReject& reject) +{ + Types::write(output, bdlb::BigEndianUint64::make(reject.d_deliveryTag)); + + uint8_t bitmask = 0; + if (reject.d_requeue) { + bitmask |= BITMASK_BIT_0; + } + + Types::write(output, bitmask); +} + +bsl::ostream& operator<<(bsl::ostream& os, const BasicReject& reject) +{ + return os << "BasicReject:" + << "[ delivery-tag: " << reject.deliveryTag() + << ", requeue: " << reject.requeue() << "]"; +} + +} // namespace rmqamqpt +} // namespace BloombergLP diff --git a/src/rmq/rmqamqpt/rmqamqpt_basicreject.h b/src/rmq/rmqamqpt/rmqamqpt_basicreject.h new file mode 100644 index 00000000..7cd9d2bf --- /dev/null +++ b/src/rmq/rmqamqpt/rmqamqpt_basicreject.h @@ -0,0 +1,78 @@ +// Copyright 2026 Bloomberg Finance L.P. +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef INCLUDED_RMQAMQPT_BASICREJECT +#define INCLUDED_RMQAMQPT_BASICREJECT + +#include +#include +#include + +#include +#include + +namespace BloombergLP { +namespace rmqamqpt { + +/// \brief Provide basic REJECT method +/// +/// This method allows a client to reject a single incoming message. It signals +/// to the broker that processing the message failed, and is the AMQP 0-9-1 +/// method for returning an untreatable message to its original queue. +/// +/// Unlike BasicNack, this method carries no `multiple` flag, so each rejected +/// delivery requires its own frame. +/// +/// Brokers which implement poison message handling count a reject as a failed +/// delivery attempt, where a nack is not counted. + +class BasicReject { + public: + static const rmqamqpt::Constants::AMQPMethodId METHOD_ID = + rmqamqpt::Constants::BASIC_REJECT; + + explicit BasicReject(bsl::uint64_t dt, bool requeue = true); + BasicReject(); + + size_t encodedSize() const { return sizeof(uint64_t) + sizeof(uint8_t); } + + /// The server-assigned and channel-specific delivery tag + /// The delivery tag is valid only within the channel from which the message + /// was received. I.e. a client MUST NOT receive a message on one channel + /// and then acknowledge it on another. The server MUST NOT use a zero value + /// for delivery tags. Zero is reserved for client use, meaning "all + /// messages so far received". + bsl::uint64_t deliveryTag() const { return d_deliveryTag; } + + /// If requeue is true, the server will attempt to requeue the message. If + /// requeue is false or the requeue attempt fails the messages are discarded + /// or dead-lettered. + bool requeue() const { return d_requeue; } + + static bool decode(BasicReject*, const uint8_t*, bsl::size_t); + + static void encode(Writer&, const BasicReject&); + + private: + Types::DeliveryTag d_deliveryTag; + bool d_requeue; +}; + +bsl::ostream& operator<<(bsl::ostream& os, const BasicReject&); + +} // namespace rmqamqpt +} // namespace BloombergLP + +#endif diff --git a/src/rmq/rmqp/rmqp_messageguard.h b/src/rmq/rmqp/rmqp_messageguard.h index 7936d0f9..0f1a90a9 100644 --- a/src/rmq/rmqp/rmqp_messageguard.h +++ b/src/rmq/rmqp/rmqp_messageguard.h @@ -52,12 +52,41 @@ class MessageGuard { /// Should only be called _after_ the message has been fully processed virtual void ack() = 0; - /// Negative acknowledge the received message. Callable only once. - /// by default requeues the message on the broker for redelivery, if + /// Return the received message to the broker without counting this + /// delivery as a failed processing attempt (`basic.nack`). Callable only + /// once. By default requeues the message on the broker for redelivery, if /// requeue is false, then the message will be either dead lettered (if a /// dead letter exchange is specified) or dropped if not. + /// + /// \warning Consider `reject` instead. From RabbitMQ 4.3 a quorum queue's + /// delivery-limit is measured against the broker's + /// delivery-count, which `nack` does not increment, so a message + /// returned with `nack(true)` never reaches the limit. See the + /// documentation below. + /// + /// \see https://www.rabbitmq.com/docs/nack + /// \see + /// https://www.rabbitmq.com/docs/quorum-queues#when-is-delivery-count-incremented virtual void nack(bool requeue = true) = 0; + /// Reject the received message, counting this delivery as a failed + /// processing attempt (`basic.reject`). Callable only once. + /// + /// Use this when processing a message failed. Unlike `nack`, it + /// increments the broker's delivery-count, so from RabbitMQ 4.3 the + /// delivery counts towards a quorum queue's delivery-limit, where one is + /// set, and the message is eventually dead lettered or dropped rather + /// than redelivered forever. + /// + /// \param requeue if `true` the broker returns the message to the queue + /// for redelivery. If `false` the message is dead lettered (if a + /// dead letter exchange is specified) or dropped if not. + /// + /// \see https://www.rabbitmq.com/docs/nack + /// \see + /// https://www.rabbitmq.com/docs/quorum-queues#when-is-delivery-count-incremented + virtual void reject(bool requeue = true) = 0; + /// Reference to the Consumer virtual Consumer* consumer() const = 0; diff --git a/src/rmq/rmqt/rmqt_consumerack.cpp b/src/rmq/rmqt/rmqt_consumerack.cpp index 1b199b30..c1d3ed29 100644 --- a/src/rmq/rmqt/rmqt_consumerack.cpp +++ b/src/rmq/rmqt/rmqt_consumerack.cpp @@ -17,9 +17,15 @@ #include +#include + namespace BloombergLP { namespace rmqt { +// Until REJECT and REQUEUE can be retired +BSLMF_ASSERT(ConsumerAck::REJECT == ConsumerAck::NACK_REQUEUE_FALSE); +BSLMF_ASSERT(ConsumerAck::REQUEUE == ConsumerAck::NACK_REQUEUE_TRUE); + ConsumerAck::ConsumerAck(const Envelope& envelope, Type type) : d_envelope(envelope) , d_type(type) @@ -28,5 +34,29 @@ ConsumerAck::ConsumerAck(const Envelope& envelope, Type type) ConsumerAck::~ConsumerAck() {} +bool ConsumerAck::usesBasicReject(Type type) +{ + return type == REJECT_REQUEUE_FALSE || type == REJECT_REQUEUE_TRUE; +} + +bool ConsumerAck::supportsMultiple(Type type) { return !usesBasicReject(type); } + +bsl::ostream& operator<<(bsl::ostream& os, ConsumerAck::Type type) +{ + switch (type) { + case ConsumerAck::ACK: + return os << "ACK"; + case ConsumerAck::NACK_REQUEUE_FALSE: + return os << "NACK_REQUEUE_FALSE"; + case ConsumerAck::NACK_REQUEUE_TRUE: + return os << "NACK_REQUEUE_TRUE"; + case ConsumerAck::REJECT_REQUEUE_FALSE: + return os << "REJECT_REQUEUE_FALSE"; + case ConsumerAck::REJECT_REQUEUE_TRUE: + return os << "REJECT_REQUEUE_TRUE"; + } + return os << "UNKNOWN(" << static_cast(type) << ")"; +} + } // namespace rmqt } // namespace BloombergLP diff --git a/src/rmq/rmqt/rmqt_consumerack.h b/src/rmq/rmqt/rmqt_consumerack.h index 53f5726c..f53ed39f 100644 --- a/src/rmq/rmqt/rmqt_consumerack.h +++ b/src/rmq/rmqt/rmqt_consumerack.h @@ -18,12 +18,45 @@ #include +#include + namespace BloombergLP { namespace rmqt { class ConsumerAck { public: - enum Type { ACK, REJECT, REQUEUE }; + /// How a consumer resolved a delivery. + /// + /// Each value names the AMQP method it sends and the value of that + /// method's `requeue` flag. Only `basic.reject` counts the delivery as a + /// failed attempt; `basic.nack` does not. + /// + /// Values are fixed and must not be renumbered. + /// + /// \see https://www.rabbitmq.com/docs/nack + /// \see + /// https://www.rabbitmq.com/docs/quorum-queues#when-is-delivery-count-incremented + enum Type { + /// `basic.ack` + ACK = 0, + /// `basic.nack` with requeue=false + NACK_REQUEUE_FALSE = 1, + /// `basic.nack` with requeue=true + NACK_REQUEUE_TRUE = 2, + /// `basic.reject` with requeue=false + REJECT_REQUEUE_FALSE = 3, + /// `basic.reject` with requeue=true + REJECT_REQUEUE_TRUE = 4, + + /// \deprecated Use `NACK_REQUEUE_FALSE`. This name predates support + /// for `basic.reject` and is misleading: it sends + /// `basic.nack`, so the delivery is not counted as a + /// failed attempt. + REJECT = NACK_REQUEUE_FALSE, + /// \deprecated Use `NACK_REQUEUE_TRUE`. This name predates support + /// for `basic.reject`. + REQUEUE = NACK_REQUEUE_TRUE + }; ConsumerAck(const Envelope& envelope, Type type); ~ConsumerAck(); @@ -31,11 +64,30 @@ class ConsumerAck { const Envelope& envelope() const { return d_envelope; } Type type() const { return d_type; } + /// RETURN `true` if `type` sends `basic.reject` rather than + /// `basic.nack`. Note this is `false` for the deprecated `REJECT`, which + /// sends `basic.nack`. + static bool usesBasicReject(Type type); + + /// RETURN `true` if the AMQP method that `type` sends carries a + /// `multiple` flag, and so may resolve every unresolved delivery up to + /// and including its delivery tag in one frame. + /// + /// `basic.ack` and `basic.nack` carry it, `basic.reject` does not, so a + /// reject is always sent one frame per delivery. Combining rejects would + /// resolve only the highest delivery tag and leave the rest outstanding. + /// + /// \see https://www.rabbitmq.com/amqp-0-9-1-reference#basic.reject + static bool supportsMultiple(Type type); + private: Envelope d_envelope; Type d_type; }; +/// Stream out +bsl::ostream& operator<<(bsl::ostream& os, ConsumerAck::Type type); + } // namespace rmqt } // namespace BloombergLP diff --git a/src/rmqtestmocks/rmqtestmocks_mockmessageguard.h b/src/rmqtestmocks/rmqtestmocks_mockmessageguard.h index 5c67b6a8..05751ce6 100644 --- a/src/rmqtestmocks/rmqtestmocks_mockmessageguard.h +++ b/src/rmqtestmocks/rmqtestmocks_mockmessageguard.h @@ -34,6 +34,7 @@ class MockMessageGuard : public rmqp::MessageGuard { MOCK_CONST_METHOD0(envelope, const rmqt::Envelope&()); MOCK_METHOD0(ack, void()); MOCK_METHOD1(nack, void(bool)); + MOCK_METHOD1(reject, void(bool)); MOCK_CONST_METHOD0(consumer, rmqp::Consumer*()); MOCK_METHOD0(transferOwnership, rmqp::TransferrableMessageGuard()); diff --git a/src/tests/integration/consumemessages/librmq_consumemessages.m.cpp b/src/tests/integration/consumemessages/librmq_consumemessages.m.cpp index 036fac8a..e63a15a3 100644 --- a/src/tests/integration/consumemessages/librmq_consumemessages.m.cpp +++ b/src/tests/integration/consumemessages/librmq_consumemessages.m.cpp @@ -125,20 +125,28 @@ class MessageConsumer { guard.ack(); } else if (input == "N") { - BALL_LOG_INFO << "Sending NACK (reject)..."; + BALL_LOG_INFO << "Sending NACK (discard)..."; guard.nack(false); } else if (input == "R") { BALL_LOG_INFO << "Sending NACK (requeue)..."; guard.nack(true); } + else if (input == "D") { + BALL_LOG_INFO << "Sending REJECT (discard)..."; + guard.reject(false); + } + else if (input == "Q") { + BALL_LOG_INFO << "Sending REJECT (requeue)..."; + guard.reject(true); + } else if (input == "I") { BALL_LOG_INFO << "IGNORING..."; return; } else { - BALL_LOG_ERROR << "Unsuported ack type (A/N/R)"; - guard.nack(true); + BALL_LOG_ERROR << "Unsuported ack type (A/N/R/D/Q/I)"; + guard.reject(true); } } else { diff --git a/src/tests/rmqa/rmqa_messageguard.t.cpp b/src/tests/rmqa/rmqa_messageguard.t.cpp index 94c8c9a3..4cfa5762 100644 --- a/src/tests/rmqa/rmqa_messageguard.t.cpp +++ b/src/tests/rmqa/rmqa_messageguard.t.cpp @@ -83,6 +83,9 @@ TEST_F(MessageGuardTest, ackCallsCallback) EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::ACK); } +// The two nack tests below pin NACK_REQUEUE_*, not just "some negative +// outcome": nack must never be silently upgraded to a reject. An application +// asking for an uncounted return has to keep getting one. TEST_F(MessageGuardTest, nackRequeueCallsCallback) { rmqa::MessageGuard mg( @@ -92,7 +95,7 @@ TEST_F(MessageGuardTest, nackRequeueCallsCallback) &d_consumer); mg.nack(); EXPECT_TRUE(d_acked); - EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::REQUEUE); + EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::NACK_REQUEUE_TRUE); } TEST_F(MessageGuardTest, nackRejectCallsCallback) @@ -104,7 +107,31 @@ TEST_F(MessageGuardTest, nackRejectCallsCallback) &d_consumer); mg.nack(false); EXPECT_TRUE(d_acked); - EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::REJECT); + EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::NACK_REQUEUE_FALSE); +} + +TEST_F(MessageGuardTest, rejectRequeueCallsCallback) +{ + rmqa::MessageGuard mg( + rmqt::Message(), + rmqt::Envelope(0, 0, "consumerTag", "exchange", "routing-key", false), + callback(), + &d_consumer); + mg.reject(); + EXPECT_TRUE(d_acked); + EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::REJECT_REQUEUE_TRUE); +} + +TEST_F(MessageGuardTest, rejectDiscardCallsCallback) +{ + rmqa::MessageGuard mg( + rmqt::Message(), + rmqt::Envelope(0, 0, "consumerTag", "exchange", "routing-key", false), + callback(), + &d_consumer); + mg.reject(false); + EXPECT_TRUE(d_acked); + EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::REJECT_REQUEUE_FALSE); } TEST_F(MessageGuardTest, onlyFirstAckApplies) @@ -134,10 +161,12 @@ TEST_F(MessageGuardTest, onlyFirstNackApplies) mg.ack(); mg.nack(false); EXPECT_TRUE(d_acked); - EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::REQUEUE); + EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::NACK_REQUEUE_TRUE); } -TEST_F(MessageGuardTest, destructorCallsNack) +// A guard destroyed without being resolved - the uncaught exception path - +// rejects with requeue so that the delivery counts towards delivery-limit. +TEST_F(MessageGuardTest, destructorCallsReject) { { rmqa::MessageGuard mg( @@ -148,7 +177,7 @@ TEST_F(MessageGuardTest, destructorCallsNack) &d_consumer); } EXPECT_TRUE(d_acked); - EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::REQUEUE); + EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::REJECT_REQUEUE_TRUE); } TEST_F(MessageGuardTest, copyingInvalidatesOriginalAndNoNackCalled) @@ -167,8 +196,10 @@ TEST_F(MessageGuardTest, copyingInvalidatesOriginalAndNoNackCalled) EXPECT_FALSE(d_acked); } } + // mg2 took ownership and was itself destroyed unresolved, so the guard + // rejects with requeue EXPECT_TRUE(d_acked); - EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::REQUEUE); + EXPECT_EQ(d_ack_state, rmqt::ConsumerAck::REJECT_REQUEUE_TRUE); } TEST_F(MessageGuardTest, copiedObjectIsvalidAndCanAck) diff --git a/src/tests/rmqamqp/rmqamqp_multipleackhandler.t.cpp b/src/tests/rmqamqp/rmqamqp_multipleackhandler.t.cpp index a0517ca9..74726118 100644 --- a/src/tests/rmqamqp/rmqamqp_multipleackhandler.t.cpp +++ b/src/tests/rmqamqp/rmqamqp_multipleackhandler.t.cpp @@ -31,12 +31,14 @@ class Callbacks { public: virtual void ack(uint64_t, bool) = 0; virtual void nack(uint64_t, bool, bool) = 0; + virtual void reject(uint64_t, bool) = 0; }; class MockCallbacks : public Callbacks { public: MOCK_METHOD2(ack, void(uint64_t, bool)); MOCK_METHOD3(nack, void(uint64_t, bool, bool)); + MOCK_METHOD2(reject, void(uint64_t, bool)); }; Sequence seq; @@ -50,7 +52,8 @@ class MultipleAckHandlerTests : public ::testing::Test { MultipleAckHandlerTests() : d_handler(bdlf::BindUtil::bind(&Callbacks::ack, &d_cb, _1, _2), - bdlf::BindUtil::bind(&Callbacks::nack, &d_cb, _1, _2, _3)) + bdlf::BindUtil::bind(&Callbacks::nack, &d_cb, _1, _2, _3), + bdlf::BindUtil::bind(&Callbacks::reject, &d_cb, _1, _2)) { } @@ -67,7 +70,17 @@ class MultipleAckHandlerTests : public ::testing::Test { d_acks.push_back(rmqt::ConsumerAck( rmqt::Envelope( dt, 0, "consumerTag", "exchange", "routing-key", false), - requeue ? rmqt::ConsumerAck::REQUEUE : rmqt::ConsumerAck::REJECT)); + requeue ? rmqt::ConsumerAck::NACK_REQUEUE_TRUE + : rmqt::ConsumerAck::NACK_REQUEUE_FALSE)); + } + + void reject(uint64_t dt, bool requeue) + { + d_acks.push_back(rmqt::ConsumerAck( + rmqt::Envelope( + dt, 0, "consumerTag", "exchange", "routing-key", false), + requeue ? rmqt::ConsumerAck::REJECT_REQUEUE_TRUE + : rmqt::ConsumerAck::REJECT_REQUEUE_FALSE)); } void expectAck(uint64_t tag, bool multiple) @@ -80,6 +93,11 @@ class MultipleAckHandlerTests : public ::testing::Test { EXPECT_CALL(d_cb, nack(tag, requeue, multiple)).InSequence(seq); } + void expectReject(uint64_t tag, bool requeue) + { + EXPECT_CALL(d_cb, reject(tag, requeue)).InSequence(seq); + } + void process() { d_handler.process(d_acks); @@ -103,13 +121,27 @@ TEST_F(MultipleAckHandlerTests, SingleRequeue) process(); } -TEST_F(MultipleAckHandlerTests, SingleReject) +TEST_F(MultipleAckHandlerTests, SingleNackDiscard) { nack(1, false); expectNack(1, false, false); process(); } +TEST_F(MultipleAckHandlerTests, SingleRejectRequeue) +{ + reject(1, true); + expectReject(1, true); + process(); +} + +TEST_F(MultipleAckHandlerTests, SingleRejectDiscard) +{ + reject(1, false); + expectReject(1, false); + process(); +} + TEST_F(MultipleAckHandlerTests, MultiAck) { ack(2); @@ -189,3 +221,80 @@ TEST_F(MultipleAckHandlerTests, DifferentTypes) expectAck(6, false); process(); } + +// basic.reject has no `multiple` field, so a run of consecutive rejects must +// never be collapsed into one frame. Batching them would resolve only the +// highest delivery tag and silently leak the rest. +TEST_F(MultipleAckHandlerTests, ConsecutiveRejectsAreNotBatched) +{ + reject(1, true); + reject(2, true); + reject(3, true); + expectReject(1, true); + expectReject(2, true); + expectReject(3, true); + process(); +} + +TEST_F(MultipleAckHandlerTests, ConsecutiveRejectDiscardsAreNotBatched) +{ + reject(1, false); + reject(2, false); + reject(3, false); + expectReject(1, false); + expectReject(2, false); + expectReject(3, false); + process(); +} + +// A reject in the middle of a contiguous run must close the pending ack batch +// and must not stop the acks after it from batching again. +TEST_F(MultipleAckHandlerTests, RejectInterleavedWithAcks) +{ + ack(1); + ack(2); + reject(3, true); + ack(4); + ack(5); + expectAck(2, true); + expectReject(3, true); + expectAck(5, true); + process(); +} + +TEST_F(MultipleAckHandlerTests, RejectsAndNacksAreNotConflated) +{ + nack(1, true); + reject(2, true); + nack(3, false); + reject(4, false); + expectNack(1, true, false); + expectReject(2, true); + expectNack(3, false, false); + expectReject(4, false); + process(); +} + +// All three resolutions in one contiguous run. Each batchable type batches +// only with its own kind, a reject always stands alone, and a reject in the +// middle does not stop the run after it batching again. +TEST_F(MultipleAckHandlerTests, AcksNacksAndRejectsMixed) +{ + ack(1); + ack(2); + nack(3, true); + nack(4, true); + reject(5, true); + reject(6, false); + nack(7, false); + ack(8); + ack(9); + + expectAck(2, true); // 1-2 batched + expectNack(4, true, true); // 3-4 batched, different type closed the ack + expectReject(5, true); // rejects never batch, not even with each + expectReject(6, false); // other + expectNack(7, false, false); + expectAck(9, true); // 8-9 batch again after the rejects + process(); +} diff --git a/src/tests/rmqamqp/rmqamqp_receivechannel.t.cpp b/src/tests/rmqamqp/rmqamqp_receivechannel.t.cpp index 266080b5..95601403 100644 --- a/src/tests/rmqamqp/rmqamqp_receivechannel.t.cpp +++ b/src/tests/rmqamqp/rmqamqp_receivechannel.t.cpp @@ -33,6 +33,7 @@ #include #include #include +#include #include @@ -152,8 +153,18 @@ class ReceiveChannelTests : public rmqamqp::ChannelTests { { ackOrNackMessage(rc, id, - requeue ? rmqt::ConsumerAck::REQUEUE - : rmqt::ConsumerAck::REJECT); + requeue ? rmqt::ConsumerAck::NACK_REQUEUE_TRUE + : rmqt::ConsumerAck::NACK_REQUEUE_FALSE); + } + + void rejectMessage(rmqamqp::ReceiveChannel& rc, + const rmqt::Envelope& id, + bool requeue = true) + { + ackOrNackMessage(rc, + id, + requeue ? rmqt::ConsumerAck::REJECT_REQUEUE_TRUE + : rmqt::ConsumerAck::REJECT_REQUEUE_FALSE); } void setupConsumerNoReply(rmqamqp::ReceiveChannel& rc, @@ -813,6 +824,67 @@ TEST_F(ReceiveChannelTests, NackMessage) EXPECT_THAT(receiveChannel->inFlight(), Eq(0)); } +TEST_F(ReceiveChannelTests, RejectMessage) +{ + bsl::shared_ptr receiveChannel = makeReceiveChannel(1); + + makeReady(*receiveChannel); + EXPECT_THAT(receiveChannel->state(), Eq(rmqamqp::Channel::READY)); + + setupConsumer(*receiveChannel, "consumer1"); + EXPECT_TRUE(receiveChannel->consumerIsActive()); + + const uint64_t deliveryTag = 41; + rmqt::Envelope id_reject(deliveryTag, + receiveChannel->lifetimeId(), + "consumer1", + "exchange", + "routing-key", + false); + receiveMessage(*receiveChannel, id_reject.deliveryTag(), "consumer1"); + + EXPECT_THAT(receiveChannel->inFlight(), Eq(1)); + + rmqamqpt::BasicReject basicReject(id_reject.deliveryTag(), true); + EXPECT_CALL(d_callback, + onAsyncWrite( + ::testing::Pointee(MessageEq(rmqamqp::Message( + rmqamqpt::Method(rmqamqpt::BasicMethod(basicReject))))), + _)) + .WillOnce(InvokeArgument<1>()); + + rejectMessage(*receiveChannel, id_reject); + EXPECT_THAT(receiveChannel->inFlight(), Eq(0)); +} + +TEST_F(ReceiveChannelTests, RejectMessageNoRequeue) +{ + bsl::shared_ptr receiveChannel = makeReceiveChannel(1); + + makeReady(*receiveChannel); + setupConsumer(*receiveChannel, "consumer1"); + + const uint64_t deliveryTag = 41; + rmqt::Envelope id_reject(deliveryTag, + receiveChannel->lifetimeId(), + "consumer1", + "exchange", + "routing-key", + false); + receiveMessage(*receiveChannel, id_reject.deliveryTag(), "consumer1"); + + rmqamqpt::BasicReject basicReject(id_reject.deliveryTag(), false); + EXPECT_CALL(d_callback, + onAsyncWrite( + ::testing::Pointee(MessageEq(rmqamqp::Message( + rmqamqpt::Method(rmqamqpt::BasicMethod(basicReject))))), + _)) + .WillOnce(InvokeArgument<1>()); + + rejectMessage(*receiveChannel, id_reject, false); + EXPECT_THAT(receiveChannel->inFlight(), Eq(0)); +} + TEST_F(ReceiveChannelTests, WrongChannelLifetimeId) { bsl::shared_ptr receiveChannel = makeReceiveChannel(1); @@ -970,6 +1042,144 @@ TEST_F(ReceiveChannelTests, ReceivedMsgPublishesMetric) receiveMessage(*receiveChannel, deliveryTag, "consumer1"); } +MATCHER_P(HasResultTag, expected, "") +{ + for (size_t i = 0; i < arg.size(); ++i) { + if (arg[i].first == Metrics::RESULT_TAG) { + return arg[i].second == expected; + } + } + return false; +} + +/// The result name is a `const char*`, and the pair is named rather than +/// deduced: Sun's `std::pair` will not decay a string literal, so +/// `bsl::make_pair(type, "ack")` gives `second` an array type there. +typedef bsl::pair MetricResultParam; + +class MessageHandledMetricTests +: public ReceiveChannelTests, + public ::testing::WithParamInterface {}; + +TEST_P(MessageHandledMetricTests, PublishesOnePerResolution) +{ + const rmqt::ConsumerAck::Type type = GetParam().first; + const bsl::string result(GetParam().second); + + bsl::shared_ptr receiveChannel = makeReceiveChannel(1); + makeReady(*receiveChannel); + setupConsumer(*receiveChannel, "consumer1"); + + const uint64_t deliveryTag = 40; + const rmqt::Envelope id(deliveryTag, + receiveChannel->lifetimeId(), + "consumer1", + "exchange", + "routingKey", + false); + receiveMessage(*receiveChannel, deliveryTag, "consumer1"); + + // The frame itself is covered by the Ack/Nack/RejectMessage tests + EXPECT_CALL(d_callback, onAsyncWrite(_, _)) + .WillRepeatedly(InvokeArgument<1>()); + + EXPECT_CALL(*d_metricPublisher, publishCounter(_, _, _)).Times(AnyNumber()); + EXPECT_CALL(*d_metricPublisher, publishDistribution(_, _, _)) + .Times(AnyNumber()); + EXPECT_CALL(*d_metricPublisher, + publishCounter(bsl::string("consumer_message_handled"), + 1, + HasResultTag(result))); + + ackOrNackMessage(*receiveChannel, id, type); +} + +RMQTESTUTIL_TESTSUITE_P( + AllResults, + MessageHandledMetricTests, + ::testing::Values(MetricResultParam(rmqt::ConsumerAck::ACK, "ack"), + MetricResultParam(rmqt::ConsumerAck::NACK_REQUEUE_FALSE, + "nack_requeue_false"), + MetricResultParam(rmqt::ConsumerAck::NACK_REQUEUE_TRUE, + "nack_requeue_true"), + MetricResultParam(rmqt::ConsumerAck::REJECT_REQUEUE_FALSE, + "reject_requeue_false"), + MetricResultParam(rmqt::ConsumerAck::REJECT_REQUEUE_TRUE, + "reject_requeue_true"))); + +TEST_F(ReceiveChannelTests, MessageHandledMetricPublishesPerMessage) +{ + bsl::shared_ptr receiveChannel = makeReceiveChannel(1); + makeReady(*receiveChannel); + setupConsumer(*receiveChannel, "consumer1"); + + bsl::shared_ptr batch = + bsl::make_shared(); + + // Two acks and one reject, resolved in the same batch + for (uint64_t tag = 1; tag <= 3; ++tag) { + receiveMessage(*receiveChannel, tag, "consumer1"); + batch->addAck( + rmqt::ConsumerAck(rmqt::Envelope(tag, + receiveChannel->lifetimeId(), + "consumer1", + "exchange", + "routingKey", + false), + tag == 3 ? rmqt::ConsumerAck::REJECT_REQUEUE_TRUE + : rmqt::ConsumerAck::ACK)); + } + + EXPECT_CALL(d_callback, onAsyncWrite(_, _)) + .WillRepeatedly(InvokeArgument<1>()); + + EXPECT_CALL(*d_metricPublisher, publishCounter(_, _, _)).Times(AnyNumber()); + EXPECT_CALL(*d_metricPublisher, publishDistribution(_, _, _)) + .Times(AnyNumber()); + // One counter increment per message, never aggregated over the batch + EXPECT_CALL(*d_metricPublisher, + publishCounter(bsl::string("consumer_message_handled"), + 1, + HasResultTag(bsl::string("ack")))) + .Times(2); + EXPECT_CALL( + *d_metricPublisher, + publishCounter(bsl::string("consumer_message_handled"), + 1, + HasResultTag(bsl::string("reject_requeue_true")))); + + d_ackQueue->pushBack(batch); + receiveChannel->consumeAckBatchFromQueue(); +} + +TEST_F(ReceiveChannelTests, MessageHandledMetricSkipsStaleLifetime) +{ + bsl::shared_ptr receiveChannel = makeReceiveChannel(1); + makeReady(*receiveChannel); + setupConsumer(*receiveChannel, "consumer1"); + + const uint64_t deliveryTag = 40; + receiveMessage(*receiveChannel, deliveryTag, "consumer1"); + + // Resolution for a channel generation which has since been reset. It is + // dropped before the metric is published, so nothing is counted. + const rmqt::Envelope stale(deliveryTag, + receiveChannel->lifetimeId() - 1, + "consumer1", + "exchange", + "routingKey", + false); + + EXPECT_CALL(*d_metricPublisher, publishCounter(_, _, _)).Times(AnyNumber()); + EXPECT_CALL(*d_metricPublisher, publishDistribution(_, _, _)) + .Times(AnyNumber()); + EXPECT_CALL(*d_metricPublisher, + publishCounter(bsl::string("consumer_message_handled"), _, _)) + .Times(0); + + ackOrNackMessage(*receiveChannel, stale, rmqt::ConsumerAck::ACK); +} + TEST_F(ReceiveChannelTests, Cancel) { bsl::shared_ptr receiveChannel = makeReceiveChannel(1); diff --git a/src/tests/rmqamqpt/CMakeLists.txt b/src/tests/rmqamqpt/CMakeLists.txt index 57a30bcc..3dc0e528 100644 --- a/src/tests/rmqamqpt/CMakeLists.txt +++ b/src/tests/rmqamqpt/CMakeLists.txt @@ -11,6 +11,7 @@ add_executable(rmqamqpt_tests rmqamqpt_basicpublish.t.cpp rmqamqpt_basicqos.t.cpp rmqamqpt_basicqosok.t.cpp + rmqamqpt_basicreject.t.cpp rmqamqpt_basicreturn.t.cpp rmqamqpt_buffer.t.cpp rmqamqpt_channelclose.t.cpp diff --git a/src/tests/rmqamqpt/rmqamqpt_basicreject.t.cpp b/src/tests/rmqamqpt/rmqamqpt_basicreject.t.cpp new file mode 100644 index 00000000..031d6176 --- /dev/null +++ b/src/tests/rmqamqpt/rmqamqpt_basicreject.t.cpp @@ -0,0 +1,165 @@ +// Copyright 2026 Bloomberg Finance L.P. +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include + +#include +#include +#include + +#include +#include + +#include +#include + +using namespace BloombergLP; +using namespace ::testing; + +namespace { + +rmqamqpt::BasicReject roundTrip(const rmqamqpt::BasicReject& sent) +{ + rmqamqp::Framer framer; + uint16_t channel = 1; + + rmqamqpt::Frame frame; + rmqamqp::Framer::makeMethodFrame( + &frame, channel, rmqamqpt::BasicMethod(sent)); + + rmqamqp::Message received; + EXPECT_THAT(framer.appendFrame(&channel, &received, frame), + Eq(rmqamqp::Framer::OK)); + + EXPECT_TRUE(received.is()); + const rmqamqpt::Method& m = received.the(); + + EXPECT_TRUE(m.is()); + const rmqamqpt::BasicMethod& bm = m.the(); + + EXPECT_TRUE(bm.is()); + return bm.the(); +} + +bsl::vector encode(const rmqamqpt::BasicReject& reject) +{ + bsl::vector storage; + rmqamqpt::Writer writer(&storage); + rmqamqpt::BasicReject::encode(writer, reject); + return storage; +} + +} // namespace + +TEST(Methods_BasicReject, RejectRequeueEncodeDecode) +{ + const rmqamqpt::BasicReject decoded = + roundTrip(rmqamqpt::BasicReject(1337, true)); + + EXPECT_EQ(decoded.deliveryTag(), 1337); + EXPECT_EQ(decoded.requeue(), true); +} + +TEST(Methods_BasicReject, RejectNoRequeueEncodeDecode) +{ + const rmqamqpt::BasicReject decoded = + roundTrip(rmqamqpt::BasicReject(42, false)); + + EXPECT_EQ(decoded.deliveryTag(), 42); + EXPECT_EQ(decoded.requeue(), false); +} + +TEST(Methods_BasicReject, DefaultConstructedRoundTrips) +{ + const rmqamqpt::BasicReject decoded = roundTrip(rmqamqpt::BasicReject()); + + EXPECT_EQ(decoded.deliveryTag(), 0); + EXPECT_EQ(decoded.requeue(), false); +} + +TEST(Methods_BasicReject, EncodedSize) +{ + EXPECT_EQ(rmqamqpt::BasicReject(1337, true).encodedSize(), 9); + EXPECT_EQ(encode(rmqamqpt::BasicReject(1337, true)).size(), 9); +} + +TEST(Methods_BasicReject, ExactWireFormat) +{ + // Basic.Reject carries a big-endian 64 bit delivery-tag followed by a + // single bitmask octet whose bit 0 is `requeue`. Basic.Nack has + // `multiple` in that position instead, so pin the bytes here to stop the + // two drifting together. + const bsl::vector requeued = + encode(rmqamqpt::BasicReject(1, true)); + + ASSERT_EQ(requeued.size(), 9u); + EXPECT_THAT(requeued, + ElementsAre(0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, // delivery-tag = 1 + 0x01 // requeue = true (bit 0) + )); + + const bsl::vector discarded = + encode(rmqamqpt::BasicReject(1, false)); + + ASSERT_EQ(discarded.size(), 9u); + EXPECT_THAT(discarded, + ElementsAre(0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x01, // delivery-tag = 1 + 0x00 // requeue = false + )); +} + +TEST(Methods_BasicReject, DecodeRejectsTruncatedPayload) +{ + // delivery-tag present, bitmask octet missing + const uint8_t truncated[] = {0, 0, 0, 0, 0, 0, 0, 1}; + + rmqamqpt::BasicReject reject; + EXPECT_FALSE( + rmqamqpt::BasicReject::decode(&reject, truncated, sizeof(truncated))); +} + +TEST(Methods_BasicReject, DecodeReadsRequeueFromBitZeroOnly) +{ + // Basic.Nack puts `multiple` at bit 0 and `requeue` at bit 1. + // Basic.Reject has no `multiple`: bit 0 is `requeue`, and nothing else + // in the octet may be read as one. + const uint8_t bitOneSet[] = {0, 0, 0, 0, 0, 0, 0, 7, 0x02}; + + rmqamqpt::BasicReject reject; + ASSERT_TRUE( + rmqamqpt::BasicReject::decode(&reject, bitOneSet, sizeof(bitOneSet))); + EXPECT_EQ(reject.deliveryTag(), 7u); + EXPECT_FALSE(reject.requeue()); + + const uint8_t bitZeroSet[] = {0, 0, 0, 0, 0, 0, 0, 7, 0x01}; + + ASSERT_TRUE( + rmqamqpt::BasicReject::decode(&reject, bitZeroSet, sizeof(bitZeroSet))); + EXPECT_TRUE(reject.requeue()); +} diff --git a/src/tests/rmqt/CMakeLists.txt b/src/tests/rmqt/CMakeLists.txt index 4fd8f4aa..1e5fc06e 100644 --- a/src/tests/rmqt/CMakeLists.txt +++ b/src/tests/rmqt/CMakeLists.txt @@ -1,5 +1,6 @@ add_executable(rmqt_tests rmqt.m.cpp + rmqt_consumerack.t.cpp rmqt_consumerconfig.t.cpp rmqt_envelope.t.cpp rmqt_exchange.t.cpp diff --git a/src/tests/rmqt/rmqt_consumerack.t.cpp b/src/tests/rmqt/rmqt_consumerack.t.cpp new file mode 100644 index 00000000..883ac753 --- /dev/null +++ b/src/tests/rmqt/rmqt_consumerack.t.cpp @@ -0,0 +1,124 @@ +// Copyright 2020-2023 Bloomberg Finance L.P. +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include + +#include + +#include +#include + +#include +#include + +using namespace BloombergLP; +using namespace ::testing; + +namespace { + +bsl::string toString(rmqt::ConsumerAck::Type type) +{ + bsl::ostringstream os; + os << type; + return os.str(); +} + +} // namespace + +// The values are the stable part of this enum: they go in no wire frame, but +// the deprecated aliases only remain compatible while they keep the value +// their old name had. +TEST(ConsumerAckTests, ValuesAreFixed) +{ + EXPECT_EQ(rmqt::ConsumerAck::ACK, 0); + EXPECT_EQ(rmqt::ConsumerAck::NACK_REQUEUE_FALSE, 1); + EXPECT_EQ(rmqt::ConsumerAck::NACK_REQUEUE_TRUE, 2); + EXPECT_EQ(rmqt::ConsumerAck::REJECT_REQUEUE_FALSE, 3); + EXPECT_EQ(rmqt::ConsumerAck::REJECT_REQUEUE_TRUE, 4); +} + +// REJECT and REQUEUE predate support for basic.reject and both send +// basic.nack. They have to keep meaning exactly what they meant before. +TEST(ConsumerAckTests, DeprecatedAliasesAreUnchanged) +{ + EXPECT_EQ(rmqt::ConsumerAck::REJECT, rmqt::ConsumerAck::NACK_REQUEUE_FALSE); + EXPECT_EQ(rmqt::ConsumerAck::REQUEUE, rmqt::ConsumerAck::NACK_REQUEUE_TRUE); +} + +TEST(ConsumerAckTests, UsesBasicReject) +{ + EXPECT_FALSE(rmqt::ConsumerAck::usesBasicReject(rmqt::ConsumerAck::ACK)); + EXPECT_FALSE(rmqt::ConsumerAck::usesBasicReject( + rmqt::ConsumerAck::NACK_REQUEUE_FALSE)); + EXPECT_FALSE(rmqt::ConsumerAck::usesBasicReject( + rmqt::ConsumerAck::NACK_REQUEUE_TRUE)); + EXPECT_TRUE(rmqt::ConsumerAck::usesBasicReject( + rmqt::ConsumerAck::REJECT_REQUEUE_FALSE)); + EXPECT_TRUE(rmqt::ConsumerAck::usesBasicReject( + rmqt::ConsumerAck::REJECT_REQUEUE_TRUE)); +} + +// The deprecated REJECT sends basic.nack, so it must not be reported as a +// basic.reject however much its name suggests otherwise. +TEST(ConsumerAckTests, DeprecatedRejectDoesNotUseBasicReject) +{ + EXPECT_FALSE(rmqt::ConsumerAck::usesBasicReject(rmqt::ConsumerAck::REJECT)); +} + +// basic.ack and basic.nack carry a `multiple` flag, basic.reject does not. +// Batching a reject would resolve only the highest delivery tag in the batch +// and silently leave the rest outstanding. +TEST(ConsumerAckTests, SupportsMultiple) +{ + EXPECT_TRUE(rmqt::ConsumerAck::supportsMultiple(rmqt::ConsumerAck::ACK)); + EXPECT_TRUE(rmqt::ConsumerAck::supportsMultiple( + rmqt::ConsumerAck::NACK_REQUEUE_FALSE)); + EXPECT_TRUE(rmqt::ConsumerAck::supportsMultiple( + rmqt::ConsumerAck::NACK_REQUEUE_TRUE)); + EXPECT_FALSE(rmqt::ConsumerAck::supportsMultiple( + rmqt::ConsumerAck::REJECT_REQUEUE_FALSE)); + EXPECT_FALSE(rmqt::ConsumerAck::supportsMultiple( + rmqt::ConsumerAck::REJECT_REQUEUE_TRUE)); +} + +TEST(ConsumerAckTests, StreamOut) +{ + EXPECT_EQ(toString(rmqt::ConsumerAck::ACK), "ACK"); + EXPECT_EQ(toString(rmqt::ConsumerAck::NACK_REQUEUE_FALSE), + "NACK_REQUEUE_FALSE"); + EXPECT_EQ(toString(rmqt::ConsumerAck::NACK_REQUEUE_TRUE), + "NACK_REQUEUE_TRUE"); + EXPECT_EQ(toString(rmqt::ConsumerAck::REJECT_REQUEUE_FALSE), + "REJECT_REQUEUE_FALSE"); + EXPECT_EQ(toString(rmqt::ConsumerAck::REJECT_REQUEUE_TRUE), + "REJECT_REQUEUE_TRUE"); +} + +TEST(ConsumerAckTests, StreamOutUnknown) +{ + EXPECT_EQ(toString(static_cast(99)), + "UNKNOWN(99)"); +} + +TEST(ConsumerAckTests, CheckMembers) +{ + const rmqt::Envelope envelope( + 1, 2, "consumerTag", "exchange", "routingKey", true); + const rmqt::ConsumerAck ack(envelope, + rmqt::ConsumerAck::REJECT_REQUEUE_TRUE); + + EXPECT_EQ(ack.type(), rmqt::ConsumerAck::REJECT_REQUEUE_TRUE); + EXPECT_EQ(ack.envelope().deliveryTag(), 1u); +}