Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
};
Expand Down
8 changes: 8 additions & 0 deletions docs/doxygen.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion examples/helloworld/producer.m.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion examples/topology/headers.m.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions src/rmq/rmqa/rmqa_consumer.h
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ class Consumer {
explicit Consumer(bslma::ManagedPtr<rmqp::Consumer>& 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.
Expand Down
16 changes: 12 additions & 4 deletions src/rmq/rmqa/rmqa_messageguard.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand Down
42 changes: 37 additions & 5 deletions src/rmq/rmqa/rmqa_messageguard.h
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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;

Expand Down
4 changes: 2 additions & 2 deletions src/rmq/rmqa/rmqa_tracingmessageguard.h
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 4 additions & 0 deletions src/rmq/rmqamqp/rmqamqp_metrics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
5 changes: 5 additions & 0 deletions src/rmq/rmqamqp/rmqamqp_metrics.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
27 changes: 19 additions & 8 deletions src/rmq/rmqamqp/rmqamqp_multipleackhandler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include <rmqamqp_multipleackhandler.h>

#include <ball_log.h>
#include <bsls_assert.h>

namespace BloombergLP {
namespace rmqamqp {
Expand All @@ -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)
{
Expand All @@ -56,9 +59,11 @@ void MultipleAckHandler::process(bsl::vector<rmqt::ConsumerAck>& 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
Expand Down Expand Up @@ -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);
}
}

Expand Down
8 changes: 7 additions & 1 deletion src/rmq/rmqamqp/rmqamqp_multipleackhandler.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,11 @@ class MultipleAckHandler {
public:
typedef bsl::function<void(uint64_t, bool)> AckCallback;
typedef bsl::function<void(uint64_t, bool, bool)> NackCallback;
typedef bsl::function<void(uint64_t, bool)> 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.
Expand All @@ -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;

Expand Down
51 changes: 50 additions & 1 deletion src/rmq/rmqamqp/rmqamqp_receivechannel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<bsl::pair<bsl::string, bsl::string> > tags =
getMetricTags();
tags.push_back(
bsl::make_pair(bsl::string(Metrics::RESULT_TAG),
bsl::string(resultName(
static_cast<rmqt::ConsumerAck::Type>(type)))));
d_messageHandledTags.push_back(tags);
}
}

const rmqt::ConsumerConfig& ReceiveChannel::consumerConfig() const
Expand Down Expand Up @@ -618,6 +655,10 @@ void ReceiveChannel::consumeAckBatchFromQueue()
for (bsl::vector<rmqt::ConsumerAck>::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);
Expand Down Expand Up @@ -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)
Expand Down
15 changes: 15 additions & 0 deletions src/rmq/rmqamqp/rmqamqp_receivechannel.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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<bsl::vector<bsl::pair<bsl::string, bsl::string> > >
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
Expand Down
Loading
Loading