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 05d8408e16e5e892c11bff72a2ab5b45ae83bbbb
Author: AurĂ©lien Pupier <[email protected]>
AuthorDate: Wed Nov 25 13:42:37 2026 +0100

    CAMEL-26407: camel-mongodb - stopping a tailable cursor consumer persists 
the tail position of a consumer thread left behind
    
    MongoDbTailableCursorConsumerIT is flaky: a test reads the persisted tail
    position right after stopRoute() and sees the previous record (299 instead
    of 300, or a date one minute behind), and on the next start the last record
    is delivered again (301 messages instead of 300).
    
    The tail position was persisted only in the finally block of the tailing
    thread. stop() waits for that thread, but only up to the shutdown await
    timeout (10 seconds by default, bounded while the thread reads from 
MongoDB).
    When the thread is still blocked in a read, stop() interrupts it and returns
    without waiting, so the thread never reaches its persist before the caller
    reads the tracking document.
    
    Fix:
    - MongoAbstractConsumerThread.stop() calls a new afterStopped() hook once 
the
      thread has ended or was left behind. The default is empty.
    - MongoDbTailingThread overrides afterStopped() to persist the tail 
position.
      The persist in doRun() stays, so cursor regeneration still saves progress.
    - MongoDbChangeStreamsThread inherits the empty default: no behavior change.
    
    Tests:
    - 
MongoDbConsumerStopTest.stopPersistsTheTailPositionOfAConsumerThreadLeftBehind
      is deterministic: the consumer thread is blocked on a read that does not
      return, and the test asserts that stopRoute() persists the position. It
      fails without the fix and passes with it. No sleeps, latches and an
      explicit await bound only.
    - MongoDbTailableCursorConsumerIT passes (9/9), together with the mongodb
      unit tests (1097).
    
    Co-authored-by: Bob (AI assistant) on behalf of Aurelien Pupier
---
 .../mongodb/MongoAbstractConsumerThread.java       |  8 ++++
 .../component/mongodb/MongoDbTailingThread.java    |  9 +++++
 .../component/mongodb/MongoDbConsumerStopTest.java | 44 +++++++++++++++++++++-
 3 files changed, 60 insertions(+), 1 deletion(-)

diff --git 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoAbstractConsumerThread.java
 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoAbstractConsumerThread.java
index 511b1121ece0..68a2e4555bff 100644
--- 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoAbstractConsumerThread.java
+++ 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoAbstractConsumerThread.java
@@ -183,6 +183,7 @@ abstract class MongoAbstractConsumerThread implements 
Runnable {
             cursor.close();
         }
         awaitStopped();
+        afterStopped();
 
         if (log.isInfoEnabled()) {
             log.info("Stopped MongoDB Tailable Cursor consumer, bound to 
collection: {}",
@@ -190,6 +191,13 @@ abstract class MongoAbstractConsumerThread implements 
Runnable {
         }
     }
 
+    /**
+     * Called by {@link #stop()} once the thread has ended, or has been left 
behind by {@link #awaitStopped()}. Runs on
+     * the thread that stops the consumer, so that the work is done before 
{@code stop()} returns.
+     */
+    protected void afterStopped() {
+    }
+
     /**
      * Waits for the thread to end.
      * <p>
diff --git 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbTailingThread.java
 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbTailingThread.java
index c9249704d3d6..322edaad5445 100644
--- 
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbTailingThread.java
+++ 
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbTailingThread.java
@@ -148,6 +148,15 @@ class MongoDbTailingThread extends 
MongoAbstractConsumerThread {
         }
     }
 
+    /**
+     * Persists the tail position once the thread has ended, so that a test or 
caller reading the tracking document
+     * right after {@code stopRoute} sees the last routed record.
+     */
+    @Override
+    protected void afterStopped() {
+        tailTracking.persistToStore();
+    }
+
     Exchange createMongoDbExchange(Document dbObj) {
         // released by doRun once the outcome has been read, as an 
auto-released exchange may already be reset by then
         Exchange exchange = consumer.createExchange(false);
diff --git 
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbConsumerStopTest.java
 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbConsumerStopTest.java
index 754f2c4bdc50..f695d7fe216d 100644
--- 
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbConsumerStopTest.java
+++ 
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbConsumerStopTest.java
@@ -36,6 +36,7 @@ import com.mongodb.client.model.changestream.FullDocument;
 import org.apache.camel.CamelContext;
 import org.apache.camel.ServiceStatus;
 import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
 import org.apache.camel.impl.DefaultCamelContext;
 import org.apache.logging.log4j.Level;
 import org.apache.logging.log4j.LogManager;
@@ -56,6 +57,7 @@ import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 /**
@@ -67,6 +69,7 @@ import static org.mockito.Mockito.when;
 class MongoDbConsumerStopTest {
 
     private final MongoClient client = mock(MongoClient.class);
+    private final MongoDatabase database = mock(MongoDatabase.class);
     private final MongoCollection<Document> collection = mockCollection();
     // the consumer thread is in the read of the cursor
     private final CountDownLatch reading = new CountDownLatch(1);
@@ -83,7 +86,6 @@ class MongoDbConsumerStopTest {
     @BeforeEach
     @SuppressWarnings("unchecked")
     void setUp() {
-        MongoDatabase database = mock(MongoDatabase.class);
         ListCollectionNamesIterable names = 
mock(ListCollectionNamesIterable.class);
         when(names.spliterator()).thenAnswer(i -> 
List.of("events").spliterator());
         when(database.listCollectionNames()).thenReturn(names);
@@ -143,6 +145,46 @@ class MongoDbConsumerStopTest {
                 MongoDbChangeStreamsThread.class);
     }
 
+    @Test
+    @SuppressWarnings("unchecked")
+    void stopPersistsTheTailPositionOfAConsumerThreadLeftBehind() throws 
Exception {
+        // the tracking collection, which holds the position of the consumer, 
the only record routed being increasing=1
+        MongoCollection<Document> tracking = mock(MongoCollection.class);
+        
when(database.getCollection(MongoDbTailTrackingConfig.DEFAULT_COLLECTION, 
Document.class)).thenReturn(tracking);
+        FindIterable<Document> trackingFind = mock(FindIterable.class);
+        when(tracking.find(any(Bson.class))).thenReturn(trackingFind);
+        when(trackingFind.first()).thenReturn(new Document("_id", 
"tracking").append("persistentId", "darwin"));
+
+        MongoCursor<Document> cursor = mock(MongoCursor.class);
+        // one record, then a read that does not return while the route is 
stopped
+        when(cursor.hasNext()).thenReturn(true).thenAnswer(i -> 
readThatDoesNotReturn());
+        when(cursor.next()).thenReturn(new Document("increasing", 1));
+        FindIterable<Document> find = mock(FindIterable.class);
+        when(collection.find()).thenReturn(find);
+        when(find.cursorType(CursorType.TailableAwait)).thenReturn(find);
+        when(find.iterator()).thenReturn(cursor);
+
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                
from("mongodb:myDb?database=test&collection=events&tailTrackIncreasingField=increasing"
+                     + "&persistentTailTracking=true&persistentId=darwin")
+                        .routeId("mongo").to("mock:result");
+            }
+        });
+        MockEndpoint result = context.getEndpoint("mock:result", 
MockEndpoint.class);
+        result.expectedMessageCount(1);
+        context.start();
+        result.assertIsSatisfied();
+        assertTrue(reading.await(10, TimeUnit.SECONDS), "the consumer thread 
reads from the cursor");
+
+        stopRouteInAnotherThread(new CountDownLatch(1), new 
AtomicReference<>());
+        // the position is persisted by the stop itself: the consumer thread 
is blocked and never gets to its own persist
+        await().atMost(10, TimeUnit.SECONDS)
+                .until(() -> 
context.getRouteController().getRouteStatus("mongo") == ServiceStatus.Stopped);
+        verify(tracking).updateOne(any(Bson.class), any(Bson.class));
+    }
+
     @Test
     @SuppressWarnings("unchecked")
     void stopWaitsForTheRouteWithoutInterruptingIt() throws Exception {

Reply via email to