diff --git a/src/main/java/com/rabbitmq/client/ChannelContinuationTimeoutException.java b/src/main/java/com/rabbitmq/client/ChannelContinuationTimeoutException.java index d5bca1eeb..5ca171032 100644 --- a/src/main/java/com/rabbitmq/client/ChannelContinuationTimeoutException.java +++ b/src/main/java/com/rabbitmq/client/ChannelContinuationTimeoutException.java @@ -5,6 +5,8 @@ /** * Exception thrown when a channel times out on a continuation during a RPC call. + *

+ * 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 { diff --git a/src/main/java/com/rabbitmq/client/ConnectionFactory.java b/src/main/java/com/rabbitmq/client/ConnectionFactory.java index dfa06e25e..39bdedfeb 100644 --- a/src/main/java/com/rabbitmq/client/ConnectionFactory.java +++ b/src/main/java/com/rabbitmq/client/ConnectionFactory.java @@ -1704,6 +1704,9 @@ public ConnectionFactory useBlockingIo() { * Set the continuation timeout for RPC calls in channels. Default is 10 minutes. 0 means no * timeout. * + *

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) { diff --git a/src/main/java/com/rabbitmq/client/impl/AMQChannel.java b/src/main/java/com/rabbitmq/client/impl/AMQChannel.java index de080eca9..4fb795c63 100644 --- a/src/main/java/com/rabbitmq/client/impl/AMQChannel.java +++ b/src/main/java/com/rabbitmq/client/impl/AMQChannel.java @@ -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); } @@ -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; } } diff --git a/src/main/java/com/rabbitmq/client/impl/ChannelN.java b/src/main/java/com/rabbitmq/client/impl/ChannelN.java index e6856f768..0967956fe 100644 --- a/src/main/java/com/rabbitmq/client/impl/ChannelN.java +++ b/src/main/java/com/rabbitmq/client/impl/ChannelN.java @@ -667,6 +667,57 @@ public AMQCommand transformReply(AMQCommand command) { } } + /** + * Protected API - closes the channel after a RPC timeout. + *

+ * 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 k = new BlockingRpcContinuation() { + @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) diff --git a/src/test/java/com/rabbitmq/client/test/ChannelRpcTimeoutIntegrationTest.java b/src/test/java/com/rabbitmq/client/test/ChannelRpcTimeoutIntegrationTest.java index acb1ea1d8..5dc4fa0fa 100644 --- a/src/test/java/com/rabbitmq/client/test/ChannelRpcTimeoutIntegrationTest.java +++ b/src/test/java/com/rabbitmq/client/test/ChannelRpcTimeoutIntegrationTest.java @@ -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 { @@ -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); @@ -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) {