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
16 changes: 15 additions & 1 deletion src/main/java/com/rabbitmq/client/impl/AMQCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,13 @@ public class AMQCommand implements Command {
private final CommandAssembler assembler;
private final Lock assemblerLock = new ReentrantLock();
private final WriteListener writeListener;
private final Runnable onEncoded;

/** Construct a command for inbound frame assembly with a max body length. */
AMQCommand(int maxBodyLength) {
this.assembler = new CommandAssembler(null, null, maxBodyLength);
this.writeListener = null;
this.onEncoded = null;
}

/** Construct a command ready to fill in by reading frames. */
Expand All @@ -68,6 +70,7 @@ public AMQCommand() {
public AMQCommand(com.rabbitmq.client.Method method) {
this.assembler = new CommandAssembler((Method) method, null, Integer.MAX_VALUE);
this.writeListener = null;
this.onEncoded = null;
}

/**
Expand All @@ -89,8 +92,15 @@ public AMQCommand(com.rabbitmq.client.Method method, AMQContentHeader contentHea
*/
public AMQCommand(com.rabbitmq.client.Method method, AMQContentHeader contentHeader, ByteBuffer body,
WriteListener writeListener) {
this(method, contentHeader, body, writeListener, null);
}

/** Construct a command that runs {@code onEncoded} once it is encoded, right before its first frame is written. */
AMQCommand(com.rabbitmq.client.Method method, AMQContentHeader contentHeader, ByteBuffer body,
WriteListener writeListener, Runnable onEncoded) {
this.assembler = new CommandAssembler((Method) method, contentHeader, body);
this.writeListener = writeListener;
this.onEncoded = onEncoded;
}

/** Public API - {@inheritDoc} */
Expand Down Expand Up @@ -141,7 +151,11 @@ public void transmit(AMQChannel channel) throws IOException {
String msg = String.format("Content headers exceeded max frame size: %d > %d", headerFrame.size(), frameMax);
throw new IllegalArgumentException(msg);
}
connection.writeFrame(m.toFrame(channelNumber));
Frame methodFrame = m.toFrame(channelNumber);
if (onEncoded != null) {
onEncoded.run();
}
connection.writeFrame(methodFrame);
connection.writeFrame(headerFrame);

if (body != null) {
Expand Down
21 changes: 11 additions & 10 deletions src/main/java/com/rabbitmq/client/impl/ChannelN.java
Original file line number Diff line number Diff line change
Expand Up @@ -790,14 +790,6 @@ public void basicPublish(String exchange, String routingKey,
WriteListener listener)
throws IOException
{
final long deliveryTag;
if (nextPublishSeqNo > 0) {
deliveryTag = getNextPublishSeqNo();
unconfirmedSet.add(deliveryTag);
nextPublishSeqNo++;
} else {
deliveryTag = 0;
}
if (props == null) {
props = MessageProperties.MINIMAL_BASIC;
}
Expand All @@ -807,17 +799,26 @@ public void basicPublish(String exchange, String routingKey,
.mandatory(mandatory)
.immediate(immediate)
.build();
// the number is taken once the message is encoded, as the broker only counts messages it receives
final long[] deliveryTag = new long[1];
Runnable takeDeliveryTag = () -> {
if (nextPublishSeqNo > 0) {
deliveryTag[0] = getNextPublishSeqNo();
unconfirmedSet.add(deliveryTag[0]);
nextPublishSeqNo++;
}
};
try {
ObservationCollector.PublishCall publishCall = properties -> {
AMQCommand command = new AMQCommand(publish, properties, body, listener);
AMQCommand command = new AMQCommand(publish, properties, body, listener, takeDeliveryTag);
transmit(command);
};
observationCollector.publish(publishCall, publish, props, body, this.connectionInfo());
} catch (IOException | AlreadyClosedException e) {
metricsCollector.basicPublishFailure(this, e);
throw e;
}
metricsCollector.basicPublish(this, deliveryTag);
metricsCollector.basicPublish(this, deliveryTag[0]);
}

/** Public API - {@inheritDoc} */
Expand Down
69 changes: 69 additions & 0 deletions src/test/java/com/rabbitmq/client/test/ChannelNTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,22 @@
import com.rabbitmq.client.Command;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Method;
import com.rabbitmq.client.NoOpMetricsCollector;
import com.rabbitmq.client.TrafficListener;
import com.rabbitmq.client.impl.*;
import com.rabbitmq.client.observation.ObservationCollector;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;
import java.util.stream.Stream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertNotNull;

Expand Down Expand Up @@ -156,6 +162,69 @@ public void confirmSelectOnlySendsRPCCallOnce() throws Exception {
Mockito.verify(trafficListener, Mockito.times(1)).write(Mockito.any(Command.class));
}

@Test
public void publishFailingBeforeSendingDoesNotConsumeSequenceNumber() throws Exception {
ChannelN channel = channelInConfirmMode(ObservationCollector.NO_OP);

AMQP.BasicProperties unsupportedHeader = new AMQP.BasicProperties.Builder()
.headers(Collections.singletonMap("id", UUID.randomUUID()))
.build();
assertThatThrownBy(() -> channel.basicPublish("", "q", unsupportedHeader, new byte[0]))
.isInstanceOf(IllegalArgumentException.class);
assertThat(channel.getNextPublishSeqNo()).isEqualTo(1);
assertThat(channel.waitForConfirms(100)).isTrue();

assertThatThrownBy(() -> channel.basicPublish("", null, null, new byte[0]))
.isInstanceOf(IllegalStateException.class);
assertThat(channel.getNextPublishSeqNo()).isEqualTo(1);

String overlongRoutingKey = String.join("", Collections.nCopies(256, "a"));
assertThatThrownBy(() -> channel.basicPublish("", overlongRoutingKey, null, new byte[0]))
.isInstanceOf(IllegalArgumentException.class);
assertThat(channel.getNextPublishSeqNo()).isEqualTo(1);

channel.basicPublish("", "q", null, new byte[0]);
channel.handleCompleteInboundCommand(new AMQCommand(new AMQImpl.Basic.Ack(1, false)));
assertThat(channel.waitForConfirms(1000)).isTrue();
}

@Test
public void publishFailingAfterSendingKeepsSequenceNumber() throws Exception {
ObservationCollector observationCollector = Mockito.mock(ObservationCollector.class);
Mockito.doAnswer(invocation -> {
ObservationCollector.PublishCall call = invocation.getArgument(0);
call.publish(invocation.getArgument(2));
throw new IllegalArgumentException("failure after the message was sent");
}).when(observationCollector).publish(
Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any());
ChannelN channel = channelInConfirmMode(observationCollector);

assertThatThrownBy(() -> channel.basicPublish("", "q", null, new byte[0]))
.isInstanceOf(IllegalArgumentException.class);
assertThat(channel.getNextPublishSeqNo()).isEqualTo(2);
assertThatThrownBy(() -> channel.waitForConfirms(100)).isInstanceOf(TimeoutException.class);

channel.handleCompleteInboundCommand(new AMQCommand(new AMQImpl.Basic.Ack(1, false)));
assertThat(channel.waitForConfirms(1000)).isTrue();
}

private ChannelN channelInConfirmMode(ObservationCollector observationCollector) throws Exception {
AMQConnection connection = Mockito.mock(AMQConnection.class);
TrafficListener trafficListener = Mockito.mock(TrafficListener.class);
Mockito.when(connection.getTrafficListener()).thenReturn(trafficListener);
ChannelN channel = new ChannelN(connection, 1, consumerWorkService,
new NoOpMetricsCollector(), observationCollector);
Mockito.doAnswer(invocation -> {
Command command = invocation.getArgument(0);
if (command.getMethod() instanceof AMQP.Confirm.Select) {
channel.handleCompleteInboundCommand(new AMQCommand(new AMQImpl.Confirm.SelectOk()));
}
return null;
}).when(trafficListener).write(Mockito.any(Command.class));
channel.confirmSelect();
return channel;
}

private AMQConnection connectionAcceptingConsumerCancelOk(
boolean accepts, TrafficListener trafficListener) {
AMQConnection connection = Mockito.mock(AMQConnection.class);
Expand Down
Loading