This is an automated email from the ASF dual-hosted git repository.

apupier pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git

commit 7ad4be9ae5025dd823b2dabf6340cf5fcab7b4b2
Author: AurĂ©lien Pupier <[email protected]>
AuthorDate: Wed Nov 25 13:40:23 2026 +0100

    CAMEL-26366: camel-nats - NatsConsumerPushConsumerDeletedTest no longer 
disconnects before the consumer listens to the connection
    
    NatsConsumerPushConsumerDeletedTest is still flaky on CI after the first
    fix (apache/camel#28614). The failures seen:
    
    - mock://result Received message count. Expected: <1|2> but was: <0> in
      consumesAgainAfterTheServerDeletedTheEphemeralConsumer,
      resumesAnEphemeralConsumerThatStartedAtATime and
      consumesAStreamCreatedAgainFromItsStart
    - "the consumer keeps checking, 0 ==> expected: <true> but was: <false>"
      in keepsCheckingUntilTheStreamIsCreatedAgain
    - "the subscription made while the route stopped is ended ==> expected:
      <true> but was: <false>" in endsTheSubscriptionItMadeWhileTheRouteStopped
    
    Cause: the consumer subscribes on its own executor (doStart() submits the
    task), and NatsJetStreamPushConsumerKeeper registers its connection
    listener only once that subscribe returned. The test route consumes the
    first message from the dispatcher thread, which can happen before that,
    so mock.assertIsSatisfied() of the first message can pass while the
    keeper is not listening yet. The test then calls FakeServer.disconnect()
    and reconnect():
    
    - disconnect() marks the consumers deleted, including the one that is
      still being subscribed, and
    - reconnect() fires RESUBSCRIBED to an empty listener list, so no keeper
      checks the consumer and nobody subscribes again.
    
    The test then waits for messages (or for checks of the consumer) that
    never come, and times out. This is a race of the test, not of the
    production code: with a real connection jnats keeps the listeners
    registered, and the keeper always sees the reconnect once it is started.
    The first fix waited for the listener only in two tests; every other test
    that calls disconnect() had the same race.
    
    Fix (test only, no production change): FakeServer.disconnect() waits,
    with an Awaitility wait with an explicit atMost of 30 seconds, until a
    connection listener is registered before it disconnects, so that every
    test that disconnects is covered. The state change moves to the private
    doDisconnect(). Nothing changes for a test where the listener is there
    already.
    
    New test aDisconnectWaitsUntilTheConsumerListensToTheConnection forces
    the race instead of hoping for a slow machine: a beforeAddListener hook
    of the fake connection holds the consumer between its subscribe and the
    registration of its listener, on a latch. The test then disconnects on
    another thread, checks that the disconnect waits (the server is still
    connected), releases the latch, and checks that after publish and
    reconnect the message is consumed, i.e. the keeper checked the consumer.
    
    Verification (mvn -o test -Dtest=NatsConsumerPushConsumerDeletedTest in
    components/camel-nats on the local machine):
    
    - the race could not be reproduced by repeating the tests on an idle
      machine, so it was widened: a 2 second sleep in addConnectionListener
      of the fake connection (temporary, not committed).
      - without the fix: 10 of the 13 tests failed (8 failures and 2 errors,
        the same on the surefire rerun), with the messages above, in about
        218 seconds
      - with the fix: 13 of 13 passed
    - new test without the wait in disconnect(): fails with a
      ConditionTimeout, as the disconnect does not wait for the listener
    - with the fix: 14 of 14 tests passed in 3 runs on an idle machine, in
      3 runs with every CPU busy (13 tests at that time), and in 2 more runs
      after the last change
    
    Co-authored-by: IBM Bob 2.2.1
    Signed-off-by: AurĂ©lien Pupier <[email protected]>
---
 .../nats/NatsConsumerPushConsumerDeletedTest.java  | 63 +++++++++++++++++++++-
 1 file changed, 62 insertions(+), 1 deletion(-)

diff --git 
a/components/camel-nats/src/test/java/org/apache/camel/component/nats/NatsConsumerPushConsumerDeletedTest.java
 
b/components/camel-nats/src/test/java/org/apache/camel/component/nats/NatsConsumerPushConsumerDeletedTest.java
index fa70205f05d1..ed5cf58ddefb 100644
--- 
a/components/camel-nats/src/test/java/org/apache/camel/component/nats/NatsConsumerPushConsumerDeletedTest.java
+++ 
b/components/camel-nats/src/test/java/org/apache/camel/component/nats/NatsConsumerPushConsumerDeletedTest.java
@@ -26,6 +26,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
@@ -63,6 +64,7 @@ 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.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertInstanceOf;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
@@ -251,6 +253,47 @@ class NatsConsumerPushConsumerDeletedTest extends 
CamelTestSupport {
                 () -> assertEquals(List.of(), server.listeners, "no keeper 
listens to the connection after the stop"));
     }
 
+    @Test
+    void aDisconnectWaitsUntilTheConsumerListensToTheConnection() throws 
Exception {
+        // the consumer subscribes on its own executor and listens to the 
connection once the subscribe returned: hold
+        // that back, to force what a busy CI machine does (a disconnect while 
the consumer is still subscribing)
+        CountDownLatch subscribed = new CountDownLatch(1);
+        CountDownLatch release = new CountDownLatch(1);
+        // the route of the test may still be subscribing: wait for it, so 
that the hook below applies to the route
+        // that replaces it
+        await().atMost(10, TimeUnit.SECONDS).until(() -> 
!server.listeners.isEmpty());
+        server.beforeAddListener = () -> {
+            server.beforeAddListener = null;
+            subscribed.countDown();
+            try {
+                release.await(30, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+            }
+        };
+        consumeWith("exceptionHandler=#handler");
+        assertTrue(subscribed.await(30, TimeUnit.SECONDS), "the consumer 
subscribed");
+
+        Thread disconnecting = new Thread(server::disconnect, "disconnecting");
+        disconnecting.start();
+        // the disconnect must wait for the listener, else it deletes the 
consumer that is being subscribed and the
+        // reconnect reaches nobody
+        await().atMost(10, TimeUnit.SECONDS)
+                .until(() -> disconnecting.getState() == 
Thread.State.TIMED_WAITING);
+        assertTrue(server.isConnected(), "not disconnected while the consumer 
does not listen");
+
+        release.countDown();
+        disconnecting.join(30_000);
+        assertFalse(disconnecting.isAlive(), "the disconnect went on once the 
consumer listens");
+        server.publish("order-1");
+        server.reconnect();
+
+        MockEndpoint mock = getMockEndpoint("mock:result");
+        mock.expectedBodiesReceived("order-1");
+        mock.setResultWaitTime(20_000);
+        mock.assertIsSatisfied();
+    }
+
     /**
      * Replaces the route of the test by one consuming with the given options.
      */
@@ -540,6 +583,8 @@ class NatsConsumerPushConsumerDeletedTest extends 
CamelTestSupport {
         int consumersCreated;
         // runs on the thread that subscribes, before the subscription is made
         volatile Runnable beforeSubscribe;
+        // runs on the thread that adds a connection listener, before the 
listener is added
+        volatile Runnable beforeAddListener;
         Connection connection;
 
         final class FakeConsumer {
@@ -588,7 +633,15 @@ class NatsConsumerPushConsumerDeletedTest extends 
CamelTestSupport {
             notifyAll();
         }
 
-        synchronized void disconnect() {
+        void disconnect() {
+            // the consumer subscribes on its own executor and listens to the 
connection only once the subscribe
+            // returned, which can be after it delivered its first message: a 
disconnect before that deletes the
+            // consumer that is being subscribed, and the reconnect reaches no 
keeper, so nothing checks the consumer
+            await().atMost(30, TimeUnit.SECONDS).until(() -> 
!listeners.isEmpty());
+            doDisconnect();
+        }
+
+        private synchronized void doDisconnect() {
             connected = false;
             for (FakeConsumer c : consumers) {
                 c.deleted = true;
@@ -596,6 +649,10 @@ class NatsConsumerPushConsumerDeletedTest extends 
CamelTestSupport {
             notifyAll();
         }
 
+        synchronized boolean isConnected() {
+            return connected;
+        }
+
         synchronized void awaitDisconnected() throws InterruptedException {
             long deadline = System.currentTimeMillis() + 20_000;
             while (connected && System.currentTimeMillis() < deadline) {
@@ -643,6 +700,10 @@ class NatsConsumerPushConsumerDeletedTest extends 
CamelTestSupport {
                 case "jetStream" -> js;
                 case "createDispatcher" -> dispatcher();
                 case "addConnectionListener" -> {
+                    Runnable addHook = beforeAddListener;
+                    if (addHook != null) {
+                        addHook.run();
+                    }
                     listenersAdded.incrementAndGet();
                     yield listeners.add((ConnectionListener) args[0]);
                 }

Reply via email to