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 3908b67bdd4c CAMEL-27335: camel-netty - stopping a producer with a 
TimeoutCorrelationManagerSupport completes its pending requests (#30628)
3908b67bdd4c is described below

commit 3908b67bdd4c25ae819ffcc14338c7525f8850f4
Author: allthingssecurity <[email protected]>
AuthorDate: Mon Nov 23 14:01:32 2026 +0530

    CAMEL-27335: camel-netty - stopping a producer with a 
TimeoutCorrelationManagerSupport completes its pending requests (#30628)
    
    The timeout map of TimeoutCorrelationManagerSupport was cleared on stop
    without evicting its entries, and channelInactive gets no state from this
    manager, so a request still waiting for its reply when the producer stopped
    was never completed. The map now evicts every entry before it stops, so they
    complete as timed out on the worker pool before the pool is shut down. An
    eviction that finds the worker pool shut down, missing or rejecting (such as
    one the purge task removed while the producer stopped) runs in the calling
    thread; markDone keeps the completion at most once.
    
    Found with a TLA+ model.
    
    camel-netty - test a timeout discarded by a shut-down CallerRuns worker pool
    
    A shut-down ThreadPoolExecutor with the CallerRunsPolicy (the default
    rejection policy of Camel thread pools) discards a task without throwing,
    so submit returns normally and the task never runs. The existing test only
    covers a pool that throws (AbortPolicy). The new test fails if onEviction
    returns right after a successful submit. Clarify the comment above the
    isShutdown check.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
 .../netty/TimeoutCorrelationManagerSupport.java    |  44 ++++-
 .../NettyTimeoutCorrelationManagerStopTest.java    | 218 +++++++++++++++++++++
 2 files changed, 258 insertions(+), 4 deletions(-)

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 5f98dd614265..d8ec96311a83 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
@@ -17,6 +17,7 @@
 package org.apache.camel.component.netty;
 
 import java.util.concurrent.ExecutorService;
+import java.util.concurrent.RejectedExecutionException;
 import java.util.concurrent.ScheduledExecutorService;
 
 import io.netty.channel.Channel;
@@ -186,7 +187,7 @@ public abstract class TimeoutCorrelationManagerSupport 
extends ServiceSupport
             stopWorkerPool = true;
         }
 
-        map = new DefaultTimeoutMap<>(scheduledExecutorService, 
timeoutChecker);
+        map = new CorrelationTimeoutMap(scheduledExecutorService, 
timeoutChecker);
         map.addListener(this::onEviction);
 
         ServiceHelper.startService(map);
@@ -220,15 +221,33 @@ public abstract class TimeoutCorrelationManagerSupport 
extends ServiceSupport
         }
     }
 
+    /**
+     * The timeout map of the pending requests. When it stops (the producer 
stops), the requests still waiting for a
+     * reply are evicted, so they complete as if they timed out: the worker 
pool runs them before it is shut down.
+     */
+    private static final class CorrelationTimeoutMap extends 
DefaultTimeoutMap<String, NettyCamelState> {
+
+        CorrelationTimeoutMap(ScheduledExecutorService executor, long 
requestMapPollTimeMillis) {
+            super(executor, requestMapPollTimeMillis);
+        }
+
+        @Override
+        protected void doStop() throws Exception {
+            drainAndEvictAll();
+            super.doStop();
+        }
+    }
+
     private void onEviction(Type type, String key, NettyCamelState value) {
         if (type != Type.Evict) {
             return;
         }
 
-        workerPool.submit(() -> {
+        Runnable task = () -> {
             Exchange exchange = value.getExchange();
             AsyncCallback callback = value.getCallback();
-            // the exchange may have been completed meanwhile (the write 
failed), then it must not be touched
+            // the exchange may have been completed meanwhile (the write 
failed, or this task already ran), then it
+            // must not be touched
             if (exchange != null && callback != null && value.markDone()) {
                 timeoutLogger.log("Timeout of correlation id: " + key);
                 Object timeoutBody = getTimeoutResponse(key, 
exchange.getMessage().getBody());
@@ -239,6 +258,23 @@ public abstract class TimeoutCorrelationManagerSupport 
extends ServiceSupport
                 }
                 callback.done(false);
             }
-        });
+        };
+        ExecutorService pool = workerPool;
+        if (pool != null) {
+            try {
+                pool.submit(task);
+            } catch (RejectedExecutionException e) {
+                LOG.debug("The worker pool rejected the timeout of correlation 
id: {}. Running it in this thread.", key);
+                task.run();
+                return;
+            }
+        }
+        if (pool == null || pool.isShutdown()) {
+            // the manager is stopping (an entry the purge task evicted while 
the producer stopped). A shut-down pool
+            // with the CallerRunsPolicy (the default rejection policy of 
Camel thread pools) discards the task without
+            // throwing, so submit can return normally while the task never 
runs. Run it here as well: markDone makes
+            // sure the exchange is completed at most once
+            task.run();
+        }
     }
 }
diff --git 
a/components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyTimeoutCorrelationManagerStopTest.java
 
b/components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyTimeoutCorrelationManagerStopTest.java
new file mode 100644
index 000000000000..570e54617b3e
--- /dev/null
+++ 
b/components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyTimeoutCorrelationManagerStopTest.java
@@ -0,0 +1,218 @@
+/*
+ * 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.net.ServerSocket;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.util.List;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.camel.AsyncProducer;
+import org.apache.camel.BindToRegistry;
+import org.apache.camel.CamelExchangeException;
+import org.apache.camel.Exchange;
+import org.apache.camel.ExchangePattern;
+import org.apache.camel.ExchangeTimedOutException;
+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.assertTrue;
+
+/**
+ * A request still waiting for its reply when the producer stops must be 
completed, also with a correlation manager that
+ * extends TimeoutCorrelationManagerSupport (whose timeout map would otherwise 
be cleared without completing it).
+ */
+class NettyTimeoutCorrelationManagerStopTest extends CamelTestSupport {
+
+    @BindToRegistry("myManager")
+    private final MyCorrelationManager myManager = new 
MyCorrelationManager(60000);
+
+    @BindToRegistry("rejectingManager")
+    private final MyCorrelationManager rejectingManager = new 
MyCorrelationManager(300);
+
+    private final List<Socket> accepted = new CopyOnWriteArrayList<>();
+    private ServerSocket server;
+    private AsyncProducer producer;
+
+    @AfterEach
+    void cleanup() throws Exception {
+        ServiceHelper.stopService(producer);
+        for (Socket socket : accepted) {
+            socket.close();
+        }
+        if (server != null) {
+            server.close();
+        }
+    }
+
+    @Test
+    void testStopCompletesPendingRequestOfTimeoutCorrelationManager() throws 
Exception {
+        List<Exchange> exchanges = 
sendAndStop("&correlationManager=#myManager", "abc-hello");
+
+        assertInstanceOf(ExchangeTimedOutException.class, 
exchanges.get(0).getException());
+    }
+
+    @Test
+    void testStopCompletesPendingRequestsOnSharedChannel() throws Exception {
+        // producerPoolEnabled=false: both requests wait on the one channel, 
and the manager correlates the replies
+        List<Exchange> exchanges
+                = 
sendAndStop("&correlationManager=#myManager&producerPoolEnabled=false", 
"abc-hello", "def-hello");
+
+        assertInstanceOf(ExchangeTimedOutException.class, 
exchanges.get(0).getException());
+        assertInstanceOf(ExchangeTimedOutException.class, 
exchanges.get(1).getException());
+    }
+
+    @Test
+    void testStopCompletesPendingRequestOfDefaultCorrelationManager() throws 
Exception {
+        List<Exchange> exchanges = sendAndStop("", "abc-hello");
+
+        assertInstanceOf(CamelExchangeException.class, 
exchanges.get(0).getException());
+    }
+
+    @Test
+    void testTimeoutRejectedByTheWorkerPoolCompletesTheRequest() throws 
Exception {
+        // a worker pool that no longer takes tasks (as an owned pool after 
the producer stopped): the timeout is
+        // completed in the thread that evicted it
+        ExecutorService workerPool = Executors.newSingleThreadExecutor();
+        workerPool.shutdown();
+        rejectingManager.setWorkerPool(workerPool);
+        CountDownLatch requestsReceived = new CountDownLatch(1);
+        startSilentServer(requestsReceived);
+        producer = context.getEndpoint("netty:tcp://localhost:" + 
server.getLocalPort()
+                                       + 
"?textline=true&sync=true&correlationManager=#rejectingManager")
+                .createAsyncProducer();
+        ServiceHelper.startService(producer);
+
+        Exchange exchange = new DefaultExchange(context, 
ExchangePattern.InOut);
+        exchange.getMessage().setBody("abc-hello");
+        CountDownLatch done = new CountDownLatch(1);
+        producer.process(exchange, doneSync -> done.countDown());
+
+        assertTrue(done.await(10, TimeUnit.SECONDS), "the request should be 
completed by its timeout");
+        assertInstanceOf(ExchangeTimedOutException.class, 
exchange.getException());
+    }
+
+    @Test
+    void 
testTimeoutDiscardedByShutDownCallerRunsWorkerPoolCompletesTheRequest() throws 
Exception {
+        // a shut-down pool with the CallerRunsPolicy (the default of Camel 
thread pools) does not throw: it silently
+        // discards the task, so the timeout must still be completed in the 
thread that evicted it
+        ExecutorService workerPool = new ThreadPoolExecutor(
+                1, 1, 0, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), 
new ThreadPoolExecutor.CallerRunsPolicy());
+        workerPool.shutdown();
+        rejectingManager.setWorkerPool(workerPool);
+        CountDownLatch requestsReceived = new CountDownLatch(1);
+        startSilentServer(requestsReceived);
+        producer = context.getEndpoint("netty:tcp://localhost:" + 
server.getLocalPort()
+                                       + 
"?textline=true&sync=true&correlationManager=#rejectingManager")
+                .createAsyncProducer();
+        ServiceHelper.startService(producer);
+
+        Exchange exchange = new DefaultExchange(context, 
ExchangePattern.InOut);
+        exchange.getMessage().setBody("abc-hello");
+        CountDownLatch done = new CountDownLatch(1);
+        producer.process(exchange, doneSync -> done.countDown());
+
+        assertTrue(done.await(10, TimeUnit.SECONDS), "the request should be 
completed by its timeout");
+        assertInstanceOf(ExchangeTimedOutException.class, 
exchange.getException());
+    }
+
+    private List<Exchange> sendAndStop(String options, String... bodies) 
throws Exception {
+        CountDownLatch requestsReceived = new CountDownLatch(bodies.length);
+        startSilentServer(requestsReceived);
+        producer = context.getEndpoint("netty:tcp://localhost:" + 
server.getLocalPort() + "?textline=true&sync=true"
+                                       + options)
+                .createAsyncProducer();
+        ServiceHelper.startService(producer);
+
+        List<Exchange> exchanges = new CopyOnWriteArrayList<>();
+        CountDownLatch done = new CountDownLatch(bodies.length);
+        for (String body : bodies) {
+            Exchange exchange = new DefaultExchange(context, 
ExchangePattern.InOut);
+            exchange.getMessage().setBody(body);
+            exchanges.add(exchange);
+            producer.process(exchange, doneSync -> done.countDown());
+        }
+        assertTrue(requestsReceived.await(5, TimeUnit.SECONDS), "the server 
should get the requests");
+
+        // the server never replies, and the timeout of the correlation 
manager is 60 seconds
+        ServiceHelper.stopService(producer);
+
+        assertTrue(done.await(10, TimeUnit.SECONDS), "the pending exchanges 
should be completed by the stop");
+        assertEquals(bodies.length, exchanges.size());
+        return exchanges;
+    }
+
+    private void startSilentServer(CountDownLatch requestsReceived) 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));
+                            while (in.readLine() != null) {
+                                requestsReceived.countDown();
+                            }
+                        } catch (Exception e) {
+                            // the socket was closed
+                        }
+                    }, "NettyTimeoutCorrelationManagerStopTestReader");
+                    reader.setDaemon(true);
+                    reader.start();
+                }
+            } catch (Exception e) {
+                // the server socket was closed
+            }
+        }, "NettyTimeoutCorrelationManagerStopTestServer");
+        thread.setDaemon(true);
+        thread.start();
+    }
+
+    private static final class MyCorrelationManager extends 
TimeoutCorrelationManagerSupport {
+        MyCorrelationManager(long timeout) {
+            setTimeout(timeout);
+            setTimeoutChecker(100);
+        }
+
+        @Override
+        public String getRequestCorrelationId(Object request) {
+            return request.toString().substring(0, 3);
+        }
+
+        @Override
+        public String getResponseCorrelationId(Object response) {
+            return response.toString().substring(0, 3);
+        }
+    }
+}

Reply via email to