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
8 changes: 8 additions & 0 deletions src/main/java/com/rabbitmq/client/Channel.java
Original file line number Diff line number Diff line change
Expand Up @@ -1089,6 +1089,7 @@ void basicNack(long deliveryTag, boolean multiple, boolean requeue)
* @param callback an interface to the consumer object
* @return the consumerTag associated with the new consumer
* @throws java.io.IOException if an error is encountered
* @throws IllegalStateException if the client-provided consumer tag is already in use on this channel
* @see com.rabbitmq.client.AMQP.Basic.Consume
* @see com.rabbitmq.client.AMQP.Basic.ConsumeOk
* @see #basicConsume(String, boolean, String, boolean, boolean, Map, Consumer)
Expand All @@ -1110,6 +1111,7 @@ void basicNack(long deliveryTag, boolean multiple, boolean requeue)
* @param cancelCallback callback when the consumer is cancelled
* @return the consumerTag associated with the new consumer
* @throws java.io.IOException if an error is encountered
* @throws IllegalStateException if the client-provided consumer tag is already in use on this channel
* @see com.rabbitmq.client.AMQP.Basic.Consume
* @see com.rabbitmq.client.AMQP.Basic.ConsumeOk
* @see #basicConsume(String, boolean, String, boolean, boolean, Map, Consumer)
Expand All @@ -1132,6 +1134,7 @@ void basicNack(long deliveryTag, boolean multiple, boolean requeue)
* @param shutdownSignalCallback callback when the channel/connection is shut down
* @return the consumerTag associated with the new consumer
* @throws java.io.IOException if an error is encountered
* @throws IllegalStateException if the client-provided consumer tag is already in use on this channel
* @see com.rabbitmq.client.AMQP.Basic.Consume
* @see com.rabbitmq.client.AMQP.Basic.ConsumeOk
* @see #basicConsume(String, boolean, String, boolean, boolean, Map, Consumer)
Expand All @@ -1155,6 +1158,7 @@ void basicNack(long deliveryTag, boolean multiple, boolean requeue)
* @param shutdownSignalCallback callback when the channel/connection is shut down
* @return the consumerTag associated with the new consumer
* @throws java.io.IOException if an error is encountered
* @throws IllegalStateException if the client-provided consumer tag is already in use on this channel
* @see com.rabbitmq.client.AMQP.Basic.Consume
* @see com.rabbitmq.client.AMQP.Basic.ConsumeOk
* @see #basicConsume(String, boolean, String, boolean, boolean, Map, Consumer)
Expand All @@ -1177,6 +1181,7 @@ void basicNack(long deliveryTag, boolean multiple, boolean requeue)
* @param arguments a set of arguments for the consume
* @return the consumerTag associated with the new consumer
* @throws java.io.IOException if an error is encountered
* @throws IllegalStateException if the client-provided consumer tag is already in use on this channel
* @see com.rabbitmq.client.AMQP.Basic.Consume
* @see com.rabbitmq.client.AMQP.Basic.ConsumeOk
*/
Expand All @@ -1202,6 +1207,7 @@ void basicNack(long deliveryTag, boolean multiple, boolean requeue)
* @param cancelCallback callback when the consumer is cancelled
* @return the consumerTag associated with the new consumer
* @throws java.io.IOException if an error is encountered
* @throws IllegalStateException if the client-provided consumer tag is already in use on this channel
* @see com.rabbitmq.client.AMQP.Basic.Consume
* @see com.rabbitmq.client.AMQP.Basic.ConsumeOk
* @since 5.0
Expand All @@ -1228,6 +1234,7 @@ void basicNack(long deliveryTag, boolean multiple, boolean requeue)
* @param shutdownSignalCallback callback when the channel/connection is shut down
* @return the consumerTag associated with the new consumer
* @throws java.io.IOException if an error is encountered
* @throws IllegalStateException if the client-provided consumer tag is already in use on this channel
* @see com.rabbitmq.client.AMQP.Basic.Consume
* @see com.rabbitmq.client.AMQP.Basic.ConsumeOk
* @since 5.0
Expand Down Expand Up @@ -1255,6 +1262,7 @@ void basicNack(long deliveryTag, boolean multiple, boolean requeue)
* @param shutdownSignalCallback callback when the channel/connection is shut down
* @return the consumerTag associated with the new consumer
* @throws java.io.IOException if an error is encountered
* @throws IllegalStateException if the client-provided consumer tag is already in use on this channel
* @see com.rabbitmq.client.AMQP.Basic.Consume
* @see com.rabbitmq.client.AMQP.Basic.ConsumeOk
* @since 5.0
Expand Down
56 changes: 54 additions & 2 deletions src/main/java/com/rabbitmq/client/impl/ChannelN.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,18 @@ public class ChannelN extends AMQChannel implements com.rabbitmq.client.Channel
* from the connection's reader thread. We go to some pains to
* ensure this is the case - see the use of
* BlockingRpcContinuation to inject code into the reader thread
* in basicConsume and basicCancel.
* in basicConsume and basicCancel. It is also read from the caller
* thread in basicConsume to detect duplicate consumer tags.
*/
private final Map<String, Consumer> _consumers =
Collections.synchronizedMap(new HashMap<String, Consumer>());

/**
* Client-provided consumer tags of in-flight basic.consume calls.
* Guarded by the {@link #_consumers} monitor.
*/
private final Set<String> leasedConsumerTags = new HashSet<>();

/* All listeners collections are in CopyOnWriteArrayList objects */
/** The ReturnListener collection. */
private final Collection<ReturnListener> returnListeners = new CopyOnWriteArrayList<ReturnListener>();
Expand Down Expand Up @@ -1444,6 +1451,21 @@ public String basicConsume(String queue, final boolean autoAck, String consumerT
boolean noLocal, boolean exclusive, Map<String, Object> arguments,
final Consumer callback)
throws IOException
{
final boolean leased = leaseConsumerTag(consumerTag);
try {
return doBasicConsume(queue, autoAck, consumerTag, noLocal, exclusive, arguments, callback);
} finally {
if (leased) {
releaseConsumerTag(consumerTag);
}
}
}

private String doBasicConsume(String queue, final boolean autoAck, String consumerTag,
boolean noLocal, boolean exclusive, Map<String, Object> arguments,
final Consumer callback)
throws IOException
{
final Method m = new Basic.Consume.Builder()
.queue(queue)
Expand All @@ -1458,7 +1480,10 @@ public String basicConsume(String queue, final boolean autoAck, String consumerT
public String transformReply(AMQCommand replyCommand) {
String actualConsumerTag = ((Basic.ConsumeOk) replyCommand.getMethod()).getConsumerTag();
Consumer wrappedCallback = observationCollector.basicConsume(queue, consumerTag, callback);
_consumers.put(actualConsumerTag, wrappedCallback);
synchronized (_consumers) {
_consumers.put(actualConsumerTag, wrappedCallback);
leasedConsumerTags.remove(consumerTag);
}

// need to register consumer in stats before it actually starts consuming
metricsCollector.basicConsume(ChannelN.this, actualConsumerTag, autoAck);
Expand Down Expand Up @@ -1486,6 +1511,33 @@ public String transformReply(AMQCommand replyCommand) {
}
}

private boolean leaseConsumerTag(String consumerTag) {
if (consumerTag == null || consumerTag.isEmpty()) {
return false;
}
synchronized (_consumers) {
if (_consumers.containsKey(consumerTag) || leasedConsumerTags.contains(consumerTag)) {
throw new IllegalStateException(
"Consumer tag '" + consumerTag + "' is already in use on channel " + getChannelNumber());
}
leasedConsumerTags.add(consumerTag);
return true;
}
}

private void releaseConsumerTag(String consumerTag) {
synchronized (_consumers) {
leasedConsumerTags.remove(consumerTag);
}
}

/**
* Whether a consumer with this tag is registered (consume-ok received) on this channel.
*/
public boolean hasConsumer(String consumerTag) {
return _consumers.containsKey(consumerTag);
}

private Consumer consumerFromDeliverCancelCallbacks(final DeliverCallback deliverCallback, final CancelCallback cancelCallback) {
return new Consumer() {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import com.rabbitmq.client.*;
import com.rabbitmq.client.impl.AMQConnection;
import com.rabbitmq.client.impl.ChannelN;
import com.rabbitmq.client.impl.ConnectionParams;
import com.rabbitmq.client.impl.FrameHandlerFactory;
import com.rabbitmq.client.impl.NetworkConnection;
Expand Down Expand Up @@ -883,6 +884,13 @@ void recoverConsumer(final String tag, RecordedConsumer consumer) throws Excepti

private void internalRecoverConsumer(final String tag, RecordedConsumer consumer, boolean retry) throws Exception {
if (this.topologyRecoveryFilter.filterConsumer(consumer)) {
Channel delegateChannel = consumer.getDelegateChannel();
if (tag != null && delegateChannel instanceof ChannelN
&& ((ChannelN) delegateChannel).hasConsumer(tag)) {
// the application registered a consumer with this tag on the new channel already
LOGGER.debug("Not recovering {}, consumer tag already in use on the channel", consumer);
return;
}
LOGGER.debug("Recovering {}", consumer);
String newTag = null;
if (retry) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,18 @@
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
Expand All @@ -30,6 +39,65 @@ public class BasicConsume extends BrokerTestCase {
assertTrue(nbOfExpectedMessagesHasBeenConsumed, "Not all the messages have been received");
}

@Test public void basicConsumeWithDuplicateTagShouldFailOnClientSide() throws IOException {
String q = channel.queueDeclare("", false, true, false, null).getQueue();
String tag = UUID.randomUUID().toString();
channel.basicConsume(q, false, tag, new DefaultConsumer(channel));
assertThatThrownBy(() -> channel.basicConsume(q, false, tag, new DefaultConsumer(channel)))
.isInstanceOf(IllegalStateException.class);
assertThat(channel.isOpen()).isTrue();
assertThat(channel.consumerCount(q)).isEqualTo(1);

channel.basicCancel(tag);
assertThat(channel.basicConsume(q, false, tag, new DefaultConsumer(channel))).isEqualTo(tag);
assertThat(channel.consumerCount(q)).isEqualTo(1);
}

@Test public void concurrentBasicConsumeWithSameTagShouldRegisterOnlyOneConsumer() throws Exception {
String q = channel.queueDeclare("", false, true, false, null).getQueue();
int attempts = 50;
ExecutorService executor = Executors.newFixedThreadPool(8);
try {
for (int i = 0; i < 10; i++) {
String tag = UUID.randomUUID().toString();
AtomicInteger successes = new AtomicInteger();
AtomicInteger rejections = new AtomicInteger();
CountDownLatch start = new CountDownLatch(1);
List<Future<?>> futures = new ArrayList<>();
for (int j = 0; j < attempts; j++) {
futures.add(executor.submit(() -> {
start.await();
try {
channel.basicConsume(q, false, tag, new DefaultConsumer(channel));
successes.incrementAndGet();
} catch (IllegalStateException e) {
rejections.incrementAndGet();
}
return null;
}));
}
start.countDown();
for (Future<?> f : futures) {
f.get(10, TimeUnit.SECONDS);
}
assertThat(successes.get()).isEqualTo(1);
assertThat(rejections.get()).isEqualTo(attempts - 1);
assertThat(channel.isOpen()).isTrue();
channel.basicCancel(tag);
}
} finally {
executor.shutdownNow();
}
}

@Test public void basicConsumeWithServerGeneratedTagsShouldNotBeRestricted() throws IOException {
String q = channel.queueDeclare().getQueue();
String tag1 = channel.basicConsume(q, false, "", new DefaultConsumer(channel));
String tag2 = channel.basicConsume(q, false, "", new DefaultConsumer(channel));
assertThat(tag1).isNotEqualTo(tag2);
assertThat(channel.consumerCount(q)).isEqualTo(2);
}

static class CountDownLatchConsumer extends DefaultConsumer {

private final CountDownLatch latch;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,42 @@ private void testClientNamedQueueRecoveryWith(String q, boolean noWait) throws I
}
}

@Test public void consumerRecoveryIsSkippedIfTagAlreadyRegisteredByApplication() throws IOException, InterruptedException {
String q = channel.queueDeclare(UUID.randomUUID().toString(), true, false, false, null).getQueue();
String tag = UUID.randomUUID().toString();
try {
channel.basicConsume(q, false, tag, new DefaultConsumer(channel));
assertConsumerCount(1, q);
AtomicReference<Exception> consumeException = new AtomicReference<>();
RecoveryListener listener = new RecoveryListener() {
@Override
public void handleRecovery(Recoverable recoverable) {
// channel recovery listeners are called before topology recovery
try {
channel.basicConsume(q, false, tag, new DefaultConsumer(channel));
} catch (Exception e) {
consumeException.set(e);
}
}

@Override
public void handleRecoveryStarted(Recoverable recoverable) { }
};
((Recoverable) channel).addRecoveryListener(listener);
closeAndWaitForRecovery();
((Recoverable) channel).removeRecoveryListener(listener);
assertThat(consumeException.get()).isNull();
expectChannelRecovery(channel);
assertConsumerCount(1, q);

closeAndWaitForRecovery();
expectChannelRecovery(channel);
assertConsumerCount(1, q);
} finally {
channel.queueDelete(q);
}
}

@Test public void consumerRecoveryWithManyConsumers() throws IOException, InterruptedException {
String q = channel.queueDeclare(UUID.randomUUID().toString(), true, false, false, null).getQueue();
try {
Expand Down
Loading