This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new 61ef2366d7d6 CAMEL-27518: camel-netty - a
TimeoutCorrelationManagerSupport refuses a correlation id used by a request
that waits for its reply (#30913)
61ef2366d7d6 is described below
commit 61ef2366d7d6b4e76ac8e734dc29746766efaf8b
Author: allthingssecurity <[email protected]>
AuthorDate: Fri Nov 27 12:42:44 2026 +0530
CAMEL-27518: camel-netty - a TimeoutCorrelationManagerSupport refuses a
correlation id used by a request that waits for its reply (#30913)
putState put the state of a request in the timeout map under its
correlation id, which replaced the state of another request with the same
id that still waited for its reply. That request was then in no map: no
reply and no timeout completed it, and its exchange waited forever. A
reply to it could be set on the new exchange.
The timeout map now refuses a correlation id held by a state that is not
done: the new request fails with an IllegalStateException and is not
sent, and the waiting request keeps its reply and its timeout. A done
state (left in the map by a failed write until it expires) is replaced as
before. The check and the put hold the lock of the map, which the map is
now created with.
With sync=false no reply is waited for, so the producer no longer puts its
requests in a TimeoutCorrelationManagerSupport, where they only waited to
expire; otherwise two such requests with the same id would be refused
while the first write is not complete. Other correlation managers still
get the state. As getRequestCorrelationId is then not called either, a
sync=false request without a correlation id is now sent, where it failed
with an IllegalArgumentException before; the upgrade guide says so.
The rule is documented on the component page (and its catalog copy), in
the class javadoc and in the 4.24 upgrade guide.
Found with a TLA+ model.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../apache/camel/catalog/docs/netty-component.adoc | 5 +
.../camel-netty/src/main/docs/netty-component.adoc | 5 +
.../camel/component/netty/NettyProducer.java | 7 +-
.../netty/TimeoutCorrelationManagerSupport.java | 39 ++-
...tyTimeoutCorrelationManagerDuplicateIdTest.java | 266 +++++++++++++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 15 ++
6 files changed, 335 insertions(+), 2 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/netty-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/netty-component.adoc
index ed702da67011..978b812138d5 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/netty-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/netty-component.adoc
@@ -571,6 +571,11 @@ correlate the replies to the Camel callback that is
responsible for continue pro
To do this, you need to implement `NettyCamelStateCorrelationManager` as
correlation manager and configure
it via the `correlationManager=#myManager` option.
+A correlation id must not be used by two requests that wait for their reply at
the same time: a
+`TimeoutCorrelationManagerSupport` fails the second request with an
`IllegalStateException`, as the reply could not be
+told apart. With `sync=false` no reply is waited for, and the producer does
not put its requests in a
+`TimeoutCorrelationManagerSupport`.
+
[NOTE]
====
We recommend extending the `TimeoutCorrelationManagerSupport` when you build
custom correlation managers.
diff --git a/components/camel-netty/src/main/docs/netty-component.adoc
b/components/camel-netty/src/main/docs/netty-component.adoc
index ed702da67011..978b812138d5 100644
--- a/components/camel-netty/src/main/docs/netty-component.adoc
+++ b/components/camel-netty/src/main/docs/netty-component.adoc
@@ -571,6 +571,11 @@ correlate the replies to the Camel callback that is
responsible for continue pro
To do this, you need to implement `NettyCamelStateCorrelationManager` as
correlation manager and configure
it via the `correlationManager=#myManager` option.
+A correlation id must not be used by two requests that wait for their reply at
the same time: a
+`TimeoutCorrelationManagerSupport` fails the second request with an
`IllegalStateException`, as the reply could not be
+told apart. With `sync=false` no reply is waited for, and the producer does
not put its requests in a
+`TimeoutCorrelationManagerSupport`.
+
[NOTE]
====
We recommend extending the `TimeoutCorrelationManagerSupport` when you build
custom correlation managers.
diff --git
a/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyProducer.java
b/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyProducer.java
index 5ac0581de648..260c4fb1972a 100644
---
a/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyProducer.java
+++
b/components/camel-netty/src/main/java/org/apache/camel/component/netty/NettyProducer.java
@@ -389,7 +389,12 @@ public class NettyProducer extends DefaultAsyncProducer {
// setup state as attachment on the channel, so we can access the
state later when needed
state = new NettyCamelState(producerCallback, exchange);
- channelCorrelationManager.putState(channel, state);
+ if (configuration.isSync() || !(channelCorrelationManager
instanceof TimeoutCorrelationManagerSupport)) {
+ // with sync=false no reply is waited for: a
TimeoutCorrelationManagerSupport would only keep the state
+ // until it expires, and refuse another request with the same
correlation id while the write of this
+ // one is not complete
+ channelCorrelationManager.putState(channel, state);
+ }
} catch (RuntimeException e) {
if (!configuration.isReuseChannel()) {
// with reuseChannel the channel is left to the on-completion
of the exchange
diff --git
a/components/camel-netty/src/main/java/org/apache/camel/component/netty/TimeoutCorrelationManagerSupport.java
b/components/camel-netty/src/main/java/org/apache/camel/component/netty/TimeoutCorrelationManagerSupport.java
index 74537e6362b2..1d82b492d7d7 100644
---
a/components/camel-netty/src/main/java/org/apache/camel/component/netty/TimeoutCorrelationManagerSupport.java
+++
b/components/camel-netty/src/main/java/org/apache/camel/component/netty/TimeoutCorrelationManagerSupport.java
@@ -19,6 +19,8 @@ package org.apache.camel.component.netty;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
@@ -40,6 +42,9 @@ import org.slf4j.LoggerFactory;
/**
* A base class for using {@link NettyCamelStateCorrelationManager} that
supports timeout.
+ * <p/>
+ * The correlation id of a request must not be used by another request that
still waits for its reply: such a request
+ * fails with an {@link IllegalStateException}, as its reply could not be told
apart from the reply of the other one.
*/
public abstract class TimeoutCorrelationManagerSupport extends ServiceSupport
implements CamelContextAware, NettyCamelStateCorrelationManager {
@@ -291,8 +296,40 @@ public abstract class TimeoutCorrelationManagerSupport
extends ServiceSupport
*/
private static final class CorrelationTimeoutMap extends
DefaultTimeoutMap<String, NettyCamelState> {
+ // the lock of the map, also held while a state is put, so that the
check of the state that holds its correlation
+ // id and the put are atomic
+ private final Lock mapLock;
+
CorrelationTimeoutMap(ScheduledExecutorService executor, long
requestMapPollTimeMillis) {
- super(executor, requestMapPollTimeMillis);
+ this(executor, requestMapPollTimeMillis, new ReentrantLock());
+ }
+
+ private CorrelationTimeoutMap(ScheduledExecutorService executor, long
requestMapPollTimeMillis, Lock mapLock) {
+ super(executor, requestMapPollTimeMillis, mapLock);
+ this.mapLock = mapLock;
+ }
+
+ /**
+ * Puts the state of a request, unless its correlation id is held by a
request that still waits for its reply:
+ * the reply could not be told apart, and the state of that request,
if replaced, would never be completed. A
+ * state that is done (the write of its request failed) only waits to
expire, and is replaced.
+ */
+ @Override
+ public NettyCamelState put(String key, NettyCamelState value, long
timeoutMillis) {
+ mapLock.lock();
+ try {
+ NettyCamelState held = super.putIfAbsent(key, value,
timeoutMillis);
+ if (held == null) {
+ return null;
+ }
+ if (!held.isDone()) {
+ throw new IllegalStateException(
+ "Correlation id: " + key + " is used by another
request that waits for its reply");
+ }
+ return super.put(key, value, timeoutMillis);
+ } finally {
+ mapLock.unlock();
+ }
}
@Override
diff --git
a/components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyTimeoutCorrelationManagerDuplicateIdTest.java
b/components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyTimeoutCorrelationManagerDuplicateIdTest.java
new file mode 100644
index 000000000000..b846857964c5
--- /dev/null
+++
b/components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyTimeoutCorrelationManagerDuplicateIdTest.java
@@ -0,0 +1,266 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.netty;
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import io.netty.channel.Channel;
+import io.netty.channel.embedded.EmbeddedChannel;
+import org.apache.camel.AsyncProducer;
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePattern;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.service.ServiceHelper;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * With a TimeoutCorrelationManagerSupport, a request whose correlation id is
used by another request that still waits
+ * for its reply fails, rather than replace the state of the other request
(which would then never be completed).
+ */
+class NettyTimeoutCorrelationManagerDuplicateIdTest extends CamelTestSupport {
+
+ @BindToRegistry("myManager")
+ private final CountingCorrelationManager myManager = new
CountingCorrelationManager();
+
+ private final List<Socket> accepted = new CopyOnWriteArrayList<>();
+ private final BlockingQueue<Request> received = new
LinkedBlockingQueue<>();
+ private ServerSocket server;
+ private AsyncProducer producer;
+
+ private record Request(String line, Socket socket) {
+ }
+
+ private static final class Sent {
+ final Exchange exchange;
+ final CountDownLatch done = new CountDownLatch(1);
+
+ Sent(Exchange exchange) {
+ this.exchange = exchange;
+ }
+ }
+
+ @AfterEach
+ void cleanup() throws Exception {
+ ServiceHelper.stopService(producer);
+ for (Socket socket : accepted) {
+ socket.close();
+ }
+ if (server != null) {
+ server.close();
+ }
+ }
+
+ @Test
+ void testSecondRequestWithTheIdOfAWaitingRequestFails() throws Exception {
+ // producerPoolEnabled=false: both requests use the one channel, and
the manager correlates the replies
+ startProducer("&sync=true&producerPoolEnabled=false");
+
+ Sent first = send("abc-first");
+ Request request = received.poll(5, TimeUnit.SECONDS);
+ assertNotNull(request, "the server should get the first request");
+
+ Sent second = send("abc-second");
+ assertTrue(second.done.await(10, TimeUnit.SECONDS), "the second
request should fail");
+ assertInstanceOf(IllegalStateException.class,
second.exchange.getException());
+ assertEquals(1, first.done.getCount(), "the first request should still
wait for its reply");
+
+ reply(request, "abc-reply");
+ assertTrue(first.done.await(10, TimeUnit.SECONDS), "the first request
should get its reply");
+ assertNull(first.exchange.getException());
+ assertEquals("abc-reply",
first.exchange.getMessage().getBody(String.class));
+ assertEquals(2, myManager.puts.get());
+ }
+
+ @Test
+ void testRequestsWithoutReplyAreNotPut() throws Exception {
+ startProducer("&sync=false");
+
+ Sent first = send("abc-first");
+ Sent second = send("abc-second");
+
+ assertTrue(first.done.await(10, TimeUnit.SECONDS), "the first request
should be sent");
+ assertTrue(second.done.await(10, TimeUnit.SECONDS), "the second
request should be sent");
+ assertNull(first.exchange.getException());
+ assertNull(second.exchange.getException());
+ assertEquals(0, myManager.puts.get(), "no reply is waited for, so no
state should be put in the manager");
+ }
+
+ @Test
+ void testRequestWithoutReplyIsSentWithoutCorrelationId() throws Exception {
+ // with sync=false the correlation id is not read, so a request
without one is sent (it was refused before)
+ startProducer("&sync=false");
+
+ Sent sent = send("ab");
+ assertTrue(sent.done.await(10, TimeUnit.SECONDS), "the request should
be sent");
+ assertNull(sent.exchange.getException());
+ Request request = received.poll(5, TimeUnit.SECONDS);
+ assertNotNull(request, "the server should get the request");
+ assertEquals("ab", request.line());
+ }
+
+ @Test
+ void testPutRefusesTheIdOfAStateThatIsNotDone() {
+ CountingCorrelationManager manager = startManager();
+ Channel channel = new EmbeddedChannel();
+ try {
+ NettyCamelState waiting = state("abc-first");
+ manager.putState(channel, waiting);
+
+ assertThrows(IllegalStateException.class, () ->
manager.putState(channel, state("abc-second")));
+ // the reply still finds the state of the request that waits for it
+ assertSame(waiting, manager.getState(null, channel, (Object)
"abc-reply"));
+ } finally {
+ channel.close();
+ ServiceHelper.stopService(manager);
+ }
+ }
+
+ @Test
+ void testPutReplacesTheIdOfAStateThatIsDone() {
+ // a state stays in the map after its write failed (done), until it
expires: its id can be used again
+ CountingCorrelationManager manager = startManager();
+ Channel channel = new EmbeddedChannel();
+ try {
+ NettyCamelState failed = state("abc-first");
+ manager.putState(channel, failed);
+ assertTrue(failed.markDone());
+
+ NettyCamelState next = state("abc-second");
+ manager.putState(channel, next);
+ assertSame(next, manager.getState(null, channel, (Object)
"abc-reply"));
+ } finally {
+ channel.close();
+ ServiceHelper.stopService(manager);
+ }
+ }
+
+ private CountingCorrelationManager startManager() {
+ CountingCorrelationManager manager = new CountingCorrelationManager();
+ manager.setCamelContext(context);
+ ServiceHelper.startService(manager);
+ return manager;
+ }
+
+ private NettyCamelState state(String body) {
+ Exchange exchange = new DefaultExchange(context,
ExchangePattern.InOut);
+ exchange.getMessage().setBody(body);
+ return new NettyCamelState(doneSync -> {
+ }, exchange);
+ }
+
+ private void startProducer(String options) throws Exception {
+ startServer();
+ producer = context.getEndpoint("netty:tcp://localhost:" +
server.getLocalPort()
+ +
"?textline=true&correlationManager=#myManager" + options)
+ .createAsyncProducer();
+ ServiceHelper.startService(producer);
+ }
+
+ private Sent send(String body) {
+ Exchange exchange = new DefaultExchange(context,
ExchangePattern.InOut);
+ exchange.getMessage().setBody(body);
+ Sent sent = new Sent(exchange);
+ producer.process(exchange, doneSync -> sent.done.countDown());
+ return sent;
+ }
+
+ private static void reply(Request request, String line) throws Exception {
+ OutputStream out = request.socket().getOutputStream();
+ out.write((line + "\n").getBytes(StandardCharsets.UTF_8));
+ out.flush();
+ }
+
+ private void startServer() throws Exception {
+ server = new ServerSocket(0);
+ Thread thread = new Thread(() -> {
+ try {
+ while (!server.isClosed()) {
+ Socket socket = server.accept();
+ accepted.add(socket);
+ Thread reader = new Thread(() -> {
+ try {
+ BufferedReader in = new BufferedReader(
+ new
InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
+ String line;
+ while ((line = in.readLine()) != null) {
+ received.add(new Request(line, socket));
+ }
+ } catch (Exception e) {
+ // the socket was closed
+ }
+ }, "NettyTimeoutCorrelationManagerDuplicateIdTestReader");
+ reader.setDaemon(true);
+ reader.start();
+ }
+ } catch (Exception e) {
+ // the server socket was closed
+ }
+ }, "NettyTimeoutCorrelationManagerDuplicateIdTestServer");
+ thread.setDaemon(true);
+ thread.start();
+ }
+
+ private static final class CountingCorrelationManager extends
TimeoutCorrelationManagerSupport {
+ final AtomicInteger puts = new AtomicInteger();
+
+ CountingCorrelationManager() {
+ setTimeout(60000);
+ setTimeoutChecker(100);
+ }
+
+ @Override
+ public void putState(Channel channel, NettyCamelState state) {
+ puts.incrementAndGet();
+ super.putState(channel, state);
+ }
+
+ @Override
+ public String getRequestCorrelationId(Object request) {
+ // a body shorter than 3 characters has no correlation id
+ String body = request.toString();
+ return body.length() < 3 ? null : body.substring(0, 3);
+ }
+
+ @Override
+ public String getResponseCorrelationId(Object response) {
+ return response.toString().substring(0, 3);
+ }
+ }
+}
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 6c7eb1cc4d7e..05f97dfc39a2 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -5718,6 +5718,21 @@ Before, a receiver with an object decoder silently
reconstructed the exchange ev
In addition, the legacy two-argument methods
`NettyPayloadHelper.setIn(Exchange, Object)` and `setOut(Exchange, Object)` are
deprecated and no longer unmarshal `DefaultExchangeHolder` payloads. Callers
should migrate to the three-argument overloads passing the `NettyEndpoint`.
+=== camel-netty - a correlation id used by two requests that wait for their
reply
+
+With a correlation manager that extends `TimeoutCorrelationManagerSupport`, a
request whose correlation id is used by
+another request that still waits for its reply now fails with an
`IllegalStateException` and is not sent. Before, it
+replaced the state of the other request, which was then never completed (no
reply, no timeout), and the reply to the
+other request could be set on it. Give each request that waits for a reply a
correlation id of its own. A correlation id
+is free again once its request got its reply or its write failed, or once the
manager completed it with its timeout:
+timeouts are checked every `timeoutChecker` millis (1 second by default), so
this can be up to that long after the
+timeout itself.
+
+With `sync=false` the producer no longer puts its requests in a
`TimeoutCorrelationManagerSupport`, as no reply is
+waited for. Before, each request stayed in the timeout map until its timeout.
`getRequestCorrelationId` is then not
+called either, so a request without a correlation id (or whose id cannot be
read) is now sent, where before it failed
+with an `IllegalArgumentException` ("CorrelationID is missing").
+
=== camel-netty-http - a response that cannot be built
When no HTTP response can be built from the reply of the route (for example
the body cannot be converted), the consumer