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 6e6c2cf92999 CAMEL-27173: camel-netty - an error or a message on an 
idle pooled channel no longer touches the exchange of its last request (#30356)
6e6c2cf92999 is described below

commit 6e6c2cf929993d4503f0693eaa5dabe89eac67d3
Author: allthingssecurity <[email protected]>
AuthorDate: Thu Nov 19 15:09:39 2026 +0530

    CAMEL-27173: camel-netty - an error or a message on an idle pooled channel 
no longer touches the exchange of its last request (#30356)
    
    The default correlation manager keeps the state of the last request of a 
channel
    until the channel closes, so a reset of the idle pooled channel failed that
    exchange, which had completed its call and was routing on, and a message on 
the
    idle channel replaced its message. ClientChannelHandler now handles a 
completed
    state as no state: the channel is closed, the message is ignored.
    
    CAMEL-27173: camel-netty - address review: an idle channel of a sync=false 
producer no longer touches the exchange of its last request
    
    With sync=false the write listener called the producer callback directly, so
    the state of the request was never done: a reset of the idle pooled channel
    still set the exception on the exchange that had continued, and ran the
    producer callback a second time. The listener now completes through
    state.callbackDoneOnce(false), which marks the state done.
    
    NettyProducerIdleChannelResetTest: a sync=false case next to the sync=true
    one; the route calls the producer with .to("netty:...").threads(1), and the
    server thread returns when the test does not ask for the reset.
    
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/component/netty/NettyProducer.java       |   5 +-
 .../netty/handlers/ClientChannelHandler.java       |  17 +++
 .../netty/NettyProducerIdleChannelResetTest.java   | 134 +++++++++++++++++++++
 3 files changed, 154 insertions(+), 2 deletions(-)

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 ca303308e963..d1ed0aaf0ab4 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
@@ -406,8 +406,9 @@ public class NettyProducer extends DefaultAsyncProducer {
                             NettyHelper.close(channel);
                         }
                     } finally {
-                        // signal callback to continue routing
-                        producerCallback.done(false);
+                        // signal callback to continue routing (marks the 
state done, so a later error or message on this
+                        // idle channel does not touch this exchange)
+                        state.callbackDoneOnce(false);
                     }
                 }
             }
diff --git 
a/components/camel-netty/src/main/java/org/apache/camel/component/netty/handlers/ClientChannelHandler.java
 
b/components/camel-netty/src/main/java/org/apache/camel/component/netty/handlers/ClientChannelHandler.java
index b9cdc6735d12..f084826cb926 100644
--- 
a/components/camel-netty/src/main/java/org/apache/camel/component/netty/handlers/ClientChannelHandler.java
+++ 
b/components/camel-netty/src/main/java/org/apache/camel/component/netty/handlers/ClientChannelHandler.java
@@ -76,6 +76,15 @@ public class ClientChannelHandler extends 
SimpleChannelInboundHandler<Object> {
         Exchange exchange = null;
 
         NettyCamelState state = getState(ctx, cause);
+        if (state != null && state.isDone()) {
+            // no request on this channel waits for a reply: the channel is 
idle in the producer pool (the server reset
+            // it, for example), and the exchange of its last request is 
completed, and may still be routing, so it
+            // must not get this exception
+            LOG.debug("Closing channel: {} as an exception was thrown from 
Netty while no request was waiting for a reply",
+                    ctx.channel(), cause);
+            NettyHelper.close(ctx.channel());
+            return;
+        }
         if (state != null) {
             state.onExceptionCaught();
             exchange = state.getExchange();
@@ -177,6 +186,14 @@ public class ClientChannelHandler extends 
SimpleChannelInboundHandler<Object> {
             // we just ignore the received message as the channel is closed
             return;
         }
+        if (state.isDone()) {
+            // the exchange of the last request on this channel is completed 
(and may still be routing): a message the
+            // server sends now is not its reply, and must not replace its 
message
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Ignoring message received on channel: {} as no 
request is waiting for a reply", ctx.channel());
+            }
+            return;
+        }
 
         Message message;
         try {
diff --git 
a/components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyProducerIdleChannelResetTest.java
 
b/components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyProducerIdleChannelResetTest.java
new file mode 100644
index 000000000000..3bc447666a5b
--- /dev/null
+++ 
b/components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyProducerIdleChannelResetTest.java
@@ -0,0 +1,134 @@
+/*
+ * 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.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+
+/**
+ * The server resets the connection after the call, while the channel is idle 
in the producer pool and the exchange of
+ * that call is still routing (on another thread): the exchange is not failed 
by that reset.
+ */
+class NettyProducerIdleChannelResetTest extends BaseNettyTest {
+
+    private final CountDownLatch resetNow = new CountDownLatch(1);
+    private ServerSocket server;
+
+    @AfterEach
+    void stopServer() throws Exception {
+        resetNow.countDown();
+        if (server != null) {
+            server.close();
+        }
+    }
+
+    @Test
+    void testResetOfIdleChannelDoesNotFailTheExchange() throws Exception {
+        startServer(true);
+
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        mock.expectedBodiesReceived("Bye World");
+
+        String out = template.requestBody("direct:sync", "Hello World", 
String.class);
+        assertEquals("Bye World", out);
+        mock.assertIsSatisfied();
+    }
+
+    @Test
+    void testResetOfIdleChannelDoesNotFailTheExchangeWhenNotSync() throws 
Exception {
+        startServer(false);
+
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        mock.expectedBodiesReceived("Hello World");
+
+        Exchange out = template.send("direct:async", e -> 
e.getIn().setBody("Hello World"));
+        assertNull(out.getException());
+        mock.assertIsSatisfied();
+    }
+
+    private void startServer(boolean reply) throws Exception {
+        server = new ServerSocket(getPort());
+        Thread serverThread = new Thread(() -> 
serveOneRequestThenReset(reply), "reset-server");
+        serverThread.setDaemon(true);
+        serverThread.start();
+    }
+
+    private void serveOneRequestThenReset(boolean reply) {
+        try (Socket socket = server.accept()) {
+            BufferedReader in = new BufferedReader(new 
InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
+            in.readLine();
+            if (reply) {
+                OutputStream out = socket.getOutputStream();
+                out.write("Bye World\n".getBytes(StandardCharsets.UTF_8));
+                out.flush();
+            }
+            // reset the connection (RST) once the call is done and the 
exchange routes on
+            if (!resetNow.await(20, TimeUnit.SECONDS)) {
+                return;
+            }
+            socket.setSoLinger(true, 0);
+        } catch (Exception e) {
+            // the test ended
+        }
+    }
+
+    private void resetAndWaitUntilChannelClosed(Exchange exchange) {
+        // the next step of the route runs (on another thread than the event 
loop of the channel) while the server
+        // resets the channel of the call, which is back in the producer pool
+        resetNow.countDown();
+        // until the producer closed the channel, or the reset failed this 
exchange
+        await().atMost(10, TimeUnit.SECONDS).until(
+                () -> exchange.getException() != null
+                        || 
context.hasServices(NettyProducer.class).stream().allMatch(p -> 
p.getAllChannels().isEmpty()));
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:sync")
+                        
.to("netty:tcp://localhost:{{port}}?textline=true&sync=true")
+                        .threads(1)
+                        .process(exchange -> 
resetAndWaitUntilChannelClosed(exchange))
+                        .to("mock:result");
+
+                from("direct:async")
+                        
.to("netty:tcp://localhost:{{port}}?textline=true&sync=false")
+                        .threads(1)
+                        .process(exchange -> 
resetAndWaitUntilChannelClosed(exchange))
+                        .to("mock:result");
+            }
+        };
+    }
+}

Reply via email to