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 877f60a4cd6a CAMEL-27338: camel-netty - A request that fails while it 
is set up gives its channel back to the producer pool (#30629)
877f60a4cd6a is described below

commit 877f60a4cd6a36b6f1f8af706fbbb59e1822c563
Author: allthingssecurity <[email protected]>
AuthorDate: Mon Nov 23 14:01:43 2026 +0530

    CAMEL-27338: camel-netty - A request that fails while it is set up gives 
its channel back to the producer pool (#30629)
    
    When setting up a request on its borrowed channel failed (an invalid
    CamelNettyRequestTimeout header, a missing correlation id for a
    TimeoutCorrelationManagerSupport, a pipeline without a handler), the
    exchange was completed with the exception but the channel was never
    released, so a bounded producer pool ran out of channels.
    
    The borrowed channel of the producer pool is now invalidated (closed and
    removed from the pool): activating it armed the request timeout, which
    would otherwise fire on the idle channel. The shared channel of
    producerPoolEnabled=false is released as usual. With reuseChannel nothing
    changes: the channel is left to the on-completion of the exchange.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../camel/component/netty/NettyProducer.java       | 111 ++++++++++-------
 .../netty/NettyProducerFailedSetupTest.java        | 131 +++++++++++++++++++++
 2 files changed, 202 insertions(+), 40 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 861f62b80568..fc45bdd5ef66 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
@@ -322,50 +322,62 @@ public class NettyProducer extends DefaultAsyncProducer {
             });
         }
 
-        // Get appropriate correlation manager.
-        // If we reuse channel then get it from channel. 
CORRELATION_MANAGER_ATTR should be set at this point.
-        // Otherwise use correlation manager for this producer.
-        final NettyCamelStateCorrelationManager channelCorrelationManager
-                = 
Optional.ofNullable(channel.attr(CORRELATION_MANAGER_ATTR).get()).orElse(correlationManager);
-
-        if (exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT) 
!= null) {
-            long timeoutInMs = 
exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT, Long.class);
-            ChannelHandler oldHandler = channel.pipeline().get("timeout");
-            ReadTimeoutHandler newHandler = new 
ReadTimeoutHandler(timeoutInMs, TimeUnit.MILLISECONDS);
-            if (oldHandler == null) {
-                channel.pipeline().addBefore("handler", "timeout", newHandler);
-            } else {
-                channel.pipeline().replace(oldHandler, "timeout", newHandler);
-            }
-        } else if (configuration.isSync() && configuration.getRequestTimeout() 
> 0
-                && channel.pipeline().get("timeout") == null) {
-            // the reply to the previous request on this channel removed the 
timeout (ClientChannelHandler), and only a
-            // borrow from the producer pool adds it again (activateObject): a 
channel that is used again without a
-            // borrow (producerPoolEnabled=false, or reuseChannel=true) needs 
it added here, or the request never times out
-            LOG.trace("Adding the request timeout of {} millis to channel: 
{}", configuration.getRequestTimeout(), channel);
-            try {
-                channel.pipeline().addBefore("handler", "timeout",
-                        new 
ReadTimeoutHandler(configuration.getRequestTimeout(), TimeUnit.MILLISECONDS));
-            } catch (IllegalArgumentException e) {
-                // another request on this shared channel 
(producerPoolEnabled=false) added it meanwhile
-                LOG.trace("The request timeout was added to channel: {} 
meanwhile", channel);
+        // the request is not sent if setting it up fails (such as an invalid 
request timeout header, a missing correlation
+        // id, or a pipeline without a handler)
+        final NettyCamelState state;
+        try {
+            // Get appropriate correlation manager.
+            // If we reuse channel then get it from channel. 
CORRELATION_MANAGER_ATTR should be set at this point.
+            // Otherwise use correlation manager for this producer.
+            final NettyCamelStateCorrelationManager channelCorrelationManager
+                    = 
Optional.ofNullable(channel.attr(CORRELATION_MANAGER_ATTR).get()).orElse(correlationManager);
+
+            if 
(exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT) != null) {
+                long timeoutInMs = 
exchange.getIn().getHeader(NettyConstants.NETTY_REQUEST_TIMEOUT, Long.class);
+                ChannelHandler oldHandler = channel.pipeline().get("timeout");
+                ReadTimeoutHandler newHandler = new 
ReadTimeoutHandler(timeoutInMs, TimeUnit.MILLISECONDS);
+                if (oldHandler == null) {
+                    channel.pipeline().addBefore("handler", "timeout", 
newHandler);
+                } else {
+                    channel.pipeline().replace(oldHandler, "timeout", 
newHandler);
+                }
+            } else if (configuration.isSync() && 
configuration.getRequestTimeout() > 0
+                    && channel.pipeline().get("timeout") == null) {
+                // the reply to the previous request on this channel removed 
the timeout (ClientChannelHandler), and only a
+                // borrow from the producer pool adds it again 
(activateObject): a channel that is used again without a
+                // borrow (producerPoolEnabled=false, or reuseChannel=true) 
needs it added here, or the request never times out
+                LOG.trace("Adding the request timeout of {} millis to channel: 
{}", configuration.getRequestTimeout(),
+                        channel);
+                try {
+                    channel.pipeline().addBefore("handler", "timeout",
+                            new 
ReadTimeoutHandler(configuration.getRequestTimeout(), TimeUnit.MILLISECONDS));
+                } catch (IllegalArgumentException e) {
+                    // another request on this shared channel 
(producerPoolEnabled=false) added it meanwhile
+                    LOG.trace("The request timeout was added to channel: {} 
meanwhile", channel);
+                }
             }
-        }
 
-        //This will refer to original callback since netty will release body 
by itself
-        final AsyncCallback producerCallback;
+            //This will refer to original callback since netty will release 
body by itself
+            final AsyncCallback producerCallback;
 
-        if (configuration.isReuseChannel()) {
-            // use callback as-is because we should not put it back in the 
pool as NettyProducerCallback would do
-            // as when reuse channel is enabled it will put the channel back 
in the pool when exchange is done using on completion
-            producerCallback = callback.getOriginalCallback();
-        } else {
-            producerCallback = new NettyProducerCallback(channelFuture, 
callback.getOriginalCallback());
-        }
+            if (configuration.isReuseChannel()) {
+                // use callback as-is because we should not put it back in the 
pool as NettyProducerCallback would do
+                // as when reuse channel is enabled it will put the channel 
back in the pool when exchange is done using on completion
+                producerCallback = callback.getOriginalCallback();
+            } else {
+                producerCallback = new NettyProducerCallback(channelFuture, 
callback.getOriginalCallback());
+            }
 
-        // setup state as attachment on the channel, so we can access the 
state later when needed
-        final NettyCamelState state = new NettyCamelState(producerCallback, 
exchange);
-        channelCorrelationManager.putState(channel, state);
+            // 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);
+        } catch (RuntimeException e) {
+            if (!configuration.isReuseChannel()) {
+                // with reuseChannel the channel is left to the on-completion 
of the exchange
+                discardChannel(channelFuture);
+            }
+            throw e;
+        }
         // here we need to setup the remote address information here
         InetSocketAddress remoteAddress = null;
         if (!isTcp()) {
@@ -594,6 +606,25 @@ public class NettyProducer extends DefaultAsyncProducer {
         }
     }
 
+    /**
+     * Gives a borrowed channel back to the pool when its request could not be 
set up: the request timeout that
+     * activating the channel added would otherwise fire on the idle channel, 
and the pipeline may have been changed, so
+     * a channel of the producer pool is closed and removed from the pool.
+     */
+    private void discardChannel(ChannelFuture channelFuture) {
+        if (!configuration.isProducerPoolEnabled()) {
+            // the shared channel is used by the other requests too
+            releaseChannel(channelFuture);
+            return;
+        }
+        try {
+            LOG.trace("Invalidating channel from pool {}", 
channelFuture.channel());
+            pool.invalidateObject(channelFuture);
+        } catch (Exception e) {
+            LOG.warn("Error invalidating channel in pool {}. This exception 
will be ignored.", channelFuture.channel(), e);
+        }
+    }
+
     protected void releaseChannel(ChannelFuture channelFuture) {
         Channel channel = channelFuture.channel();
         try {
diff --git 
a/components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyProducerFailedSetupTest.java
 
b/components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyProducerFailedSetupTest.java
new file mode 100644
index 000000000000..ce860b021b0b
--- /dev/null
+++ 
b/components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyProducerFailedSetupTest.java
@@ -0,0 +1,131 @@
+/*
+ * 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.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.AsyncProducer;
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePattern;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.support.service.ServiceHelper;
+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.assertTrue;
+
+/**
+ * A request that fails while it is set up on its channel (before it is sent) 
must give the channel it borrowed back, so
+ * the next request can borrow one from the producer pool.
+ */
+class NettyProducerFailedSetupTest extends BaseNettyTest {
+
+    @BindToRegistry("myManager")
+    private final MyCorrelationManager myManager = new MyCorrelationManager();
+
+    private AsyncProducer producer;
+
+    @AfterEach
+    void stopProducer() {
+        ServiceHelper.stopService(producer);
+    }
+
+    @Test
+    void testInvalidRequestTimeoutHeader() throws Exception {
+        
startProducer("producerPoolMaxTotal=1&producerPoolMaxWait=2000&requestTimeout=5000");
+
+        Exchange bad = send("abc-hello", "not a number");
+        assertNotNull(bad.getException(), "The request with an invalid timeout 
should fail");
+
+        Exchange good = send("abc-hello", null);
+        assertNull(good.getException(), "The next request should get a channel 
from the pool");
+        assertEquals("abc-hello Bye", good.getMessage().getBody(String.class));
+    }
+
+    @Test
+    void testMissingCorrelationId() throws Exception {
+        
startProducer("correlationManager=#myManager&producerPoolMaxTotal=1&producerPoolMaxWait=2000");
+
+        // no correlation id: the correlation manager does not accept the 
request
+        Exchange bad = send("", null);
+        assertInstanceOf(IllegalArgumentException.class, bad.getException());
+
+        Exchange good = send("abc-hello", null);
+        assertNull(good.getException(), "The next request should get a channel 
from the pool");
+        assertEquals("abc-hello Bye", good.getMessage().getBody(String.class));
+    }
+
+    @Test
+    void testInvalidRequestTimeoutHeaderWithSharedChannel() throws Exception {
+        startProducer("producerPoolEnabled=false");
+
+        Exchange bad = send("abc-hello", "not a number");
+        assertNotNull(bad.getException(), "The request with an invalid timeout 
should fail");
+
+        Exchange good = send("abc-hello", null);
+        assertNull(good.getException(), "The next request should use the 
shared channel");
+        assertEquals("abc-hello Bye", good.getMessage().getBody(String.class));
+    }
+
+    private void startProducer(String options) throws Exception {
+        producer = 
context.getEndpoint("netty:tcp://localhost:{{port}}?textline=true&sync=true&" + 
options)
+                .createAsyncProducer();
+        ServiceHelper.startService(producer);
+    }
+
+    private Exchange send(String body, String requestTimeout) throws 
InterruptedException {
+        Exchange exchange = new DefaultExchange(context, 
ExchangePattern.InOut);
+        exchange.getMessage().setBody(body);
+        if (requestTimeout != null) {
+            
exchange.getMessage().setHeader(NettyConstants.NETTY_REQUEST_TIMEOUT, 
requestTimeout);
+        }
+        CountDownLatch done = new CountDownLatch(1);
+        producer.process(exchange, doneSync -> done.countDown());
+        assertTrue(done.await(10, TimeUnit.SECONDS), "The exchange should be 
completed");
+        return exchange;
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() {
+        return new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("netty:tcp://localhost:{{port}}?textline=true&sync=true").transform(body().append("
 Bye"));
+            }
+        };
+    }
+
+    private static final class MyCorrelationManager extends 
TimeoutCorrelationManagerSupport {
+        @Override
+        public String getRequestCorrelationId(Object request) {
+            String s = request.toString();
+            return s.length() >= 3 ? s.substring(0, 3) : null;
+        }
+
+        @Override
+        public String getResponseCorrelationId(Object response) {
+            return response.toString().substring(0, 3);
+        }
+    }
+}

Reply via email to