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
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

/**
* Exception thrown when a channel times out on a continuation during a RPC call.
* <p>
* The channel is closed when this exception is thrown, a new channel must be created to continue.
* @since 4.1.0
*/
public class ChannelContinuationTimeoutException extends IOException {
Expand Down
3 changes: 3 additions & 0 deletions src/main/java/com/rabbitmq/client/ConnectionFactory.java
Original file line number Diff line number Diff line change
Expand Up @@ -1704,6 +1704,9 @@ public ConnectionFactory useBlockingIo() {
* Set the continuation timeout for RPC calls in channels. Default is 10 minutes. 0 means no
* timeout.
*
* <p>A channel is closed when one of its RPC calls times out, as the late reply could otherwise
* be handed to a subsequent RPC call on the channel. A new channel must be created to continue.
*
* @param channelRpcTimeout
*/
public ConnectionFactory setChannelRpcTimeout(int channelRpcTimeout) {
Expand Down
16 changes: 13 additions & 3 deletions src/main/java/com/rabbitmq/client/impl/AMQChannel.java
Original file line number Diff line number Diff line change
Expand Up @@ -328,9 +328,19 @@ private void cleanRpcChannelState() {
}
}

/** Cleans RPC channel state after a timeout and wraps the TimeoutException in a ChannelContinuationTimeoutException */
ChannelContinuationTimeoutException wrapTimeoutException(final Method m, final TimeoutException e) {
/**
* Protected API - called when a RPC times out after its request has been sent.
* The default implementation only cleans the RPC channel state.
* @param m the request method that timed out
* @param e the timeout exception
*/
protected void handleRpcTimeout(Method m, TimeoutException e) {
cleanRpcChannelState();
}

/** Handles a RPC timeout and wraps the TimeoutException in a ChannelContinuationTimeoutException */
ChannelContinuationTimeoutException wrapTimeoutException(final Method m, final TimeoutException e) {
handleRpcTimeout(m, e);
return new ChannelContinuationTimeoutException(e, this, this._channelNumber, m);
}

Expand All @@ -350,7 +360,7 @@ private AMQCommand privateRpc(Method m, int timeout)
try {
return k.getReply(timeout);
} catch (TimeoutException e) {
cleanRpcChannelState();
handleRpcTimeout(m, e);
throw e;
}
}
Expand Down
51 changes: 51 additions & 0 deletions src/main/java/com/rabbitmq/client/impl/ChannelN.java
Original file line number Diff line number Diff line change
Expand Up @@ -667,6 +667,57 @@ public AMQCommand transformReply(AMQCommand command) {
}
}

/**
* Protected API - closes the channel after a RPC timeout.
* <p>
* AMQP 0-9-1 replies cannot be correlated with their requests, so the late reply
* of the timed out request could be handed to a subsequent RPC on this channel.
* The channel is closed without waiting for the close-ok: inbound commands are
* discarded until the close-ok arrives and the channel number is released then.
*/
@Override
protected void handleRpcTimeout(Method m, TimeoutException e) {
Channel.Close reason = new Channel.Close(AMQP.PRECONDITION_FAILED,
"Timed out waiting for an RPC reply (" + m.protocolMethodName() + ")",
0, 0);
ShutdownSignalException signal = new ShutdownSignalException(false, false, reason, this);
signal.initCause(e);
AtomicBoolean finished = new AtomicBoolean(false);
Runnable finishClose = () -> {
if (finished.compareAndSet(false, true)) {
try {
finishProcessShutdownSignal();
} catch (Exception ex) {
LOGGER.info("Error while processing shutdown signal: {}", ex.getMessage());
}
releaseChannel();
notifyListeners();
}
};
BlockingRpcContinuation<AMQCommand> k = new BlockingRpcContinuation<AMQCommand>() {
@Override
public AMQCommand transformReply(AMQCommand command) {
finishClose.run();
return command;
}
};
_channelLock.lock();
try {
if (!isOpen()) {
// the channel is already closing, the closing takes care of the clean-up
return;
}
// clears the timed out RPC continuation
startProcessShutdownSignal(signal, true, true);
quiescingRpc(reason, k);
} catch (Exception ex) {
LOGGER.warn("Error while closing channel after RPC timeout: {}", ex.getMessage());
finishClose.run();
} finally {
_channelLock.unlock();
}
}

/** Public API - {@inheritDoc} */
@Override
public void basicQos(int prefetchSize, int prefetchCount, boolean global)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,16 @@

import javax.net.SocketFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.fail;

public class ChannelRpcTimeoutIntegrationTest {
Expand Down Expand Up @@ -82,6 +87,54 @@ public void tearDown() {
}
}

@Test public void channelIsClosedAfterRpcTimeoutAndLateReplyIsDiscarded() throws Exception {
String queueA = "rpc-timeout-a-" + UUID.randomUUID();
String queueB = "rpc-timeout-b-" + UUID.randomUUID();
byte[] body = "message for queue A".getBytes(StandardCharsets.UTF_8);
FrameHandler frameHandler = createFrameHandler();
ConnectionParams params = factory.params(Executors.newFixedThreadPool(1));
params.setChannelRpcTimeout((int) (waitTimeOnSomeResponses / 5.0));
WaitingAmqConnection connection = new WaitingAmqConnection(params, frameHandler);
connection.start();
try (Connection regularConnection = factory.newConnection()) {
Channel regularChannel = regularConnection.createChannel();
regularChannel.queueDeclare(queueA, true, false, false, null);
regularChannel.queueDeclare(queueB, true, false, false, null);
regularChannel.basicPublish("", queueA, null, body);
TestUtils.waitAtMost(() -> regularChannel.messageCount(queueA) == 1);
try {
Channel channel = connection.createChannel();
CountDownLatch shutdownLatch = new CountDownLatch(1);
channel.addShutdownListener(cause -> shutdownLatch.countDown());

assertThatThrownBy(() -> channel.basicGet(queueA, false))
.isInstanceOf(ChannelContinuationTimeoutException.class);
assertThat(channel.isOpen()).isFalse();
ShutdownSignalException closeReason = channel.getCloseReason();
assertThat(closeReason.isHardError()).isFalse();
assertThat(closeReason.isInitiatedByApplication()).isFalse();
assertThat(closeReason.getCause()).isInstanceOf(TimeoutException.class);
assertThatThrownBy(() -> channel.basicGet(queueB, true))
.isInstanceOf(AlreadyClosedException.class);

// the late reply is discarded and the close-ok eventually arrives
assertThat(shutdownLatch.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(connection.isOpen()).isTrue();

// the unacknowledged message is requeued when the channel is closed
TestUtils.waitAtMost(() -> regularChannel.messageCount(queueA) == 1);
GetResponse response = regularChannel.basicGet(queueA, true);
assertThat(response.getBody()).isEqualTo(body);
assertThat(regularChannel.basicGet(queueB, true)).isNull();
} finally {
regularChannel.queueDelete(queueA);
regularChannel.queueDelete(queueB);
}
} finally {
connection.close(10_000);
}
}

private FrameHandler createFrameHandler() throws IOException {
SocketFrameHandlerFactory socketFrameHandlerFactory = new SocketFrameHandlerFactory(ConnectionFactory.DEFAULT_CONNECTION_TIMEOUT,
SocketFactory.getDefault(), SocketConfigurators.defaultConfigurator(), false, null);
Expand All @@ -96,7 +149,8 @@ public WaitingChannel(AMQConnection connection, int channelNumber, ConsumerWorkS

@Override
public void handleCompleteInboundCommand(AMQCommand command) throws IOException {
if(command.getMethod() instanceof AMQImpl.Queue.DeclareOk) {
if(command.getMethod() instanceof AMQImpl.Queue.DeclareOk
|| command.getMethod() instanceof AMQImpl.Basic.GetOk) {
try {
Thread.sleep(waitTimeOnSomeResponses);
} catch (InterruptedException e) {
Expand Down
Loading