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 1ceea871d87e CAMEL-27415: camel-mongodb - the change streams consumer
resumes after the post batch resume token, and opens at the current time when
the oplog no longer has its token (#30763)
1ceea871d87e is described below
commit 1ceea871d87e1d8495549769d8219a40e698a041
Author: allthingssecurity <[email protected]>
AuthorDate: Wed Nov 25 14:43:03 2026 +0530
CAMEL-27415: camel-mongodb - the change streams consumer resumes after the
post batch resume token, and opens at the current time when the oplog no longer
has its token (#30763)
The change streams consumer kept only the token of the last event whose
exchange completed. On a quiet collection that
token falls out of the oplog window, so reopening the cursor (or starting
the route with changeStreamTokenRepository)
failed with ChangeStreamHistoryLost (286), retried for ever or failed every
route start.
The loop now reads with tryNext() and, after an empty getMore, commits the
post batch resume token when the exchange of
the last event completed. A token the oplog no longer has (286, 280, 40576)
is dropped with a WARN and the change stream
opens at the current time. Only the first failed commit of a post batch
resume token in a row goes to the exception
handler; the next ones log a WARN with the count. Upgrade guide entry for
4.24.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../camel/catalog/docs/mongodb-component.adoc | 15 +
.../src/main/docs/mongodb-component.adoc | 15 +
.../mongodb/MongoDbChangeStreamsThread.java | 113 +++-
.../MongoDbChangeStreamsInvalidateTest.java | 2 +-
.../mongodb/MongoDbChangeStreamsMocks.java | 7 +-
...ngoDbChangeStreamsPostBatchResumeTokenTest.java | 599 +++++++++++++++++++++
.../mongodb/MongoDbChangeStreamsReopenTest.java | 40 +-
.../MongoDbConsumerCursorRegenerationTest.java | 7 +-
.../component/mongodb/MongoDbConsumerStopTest.java | 5 +-
.../camel/component/mongodb/dst/FakeMongo.java | 75 ++-
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 18 +
11 files changed, 845 insertions(+), 51 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
index 724c83a6ae78..fa0761d02597 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/mongodb-component.adoc
@@ -1340,6 +1340,21 @@
from("mongodb:myDb?consumerType=changeStreams&database=flights&collection=ticket
You can use only endpoint options, only route-level resumable configuration,
or both depending on your deployment requirements.
+While no change of the collection arrives, the change stream still reads the
oplog, which the other collections of the
+replica set write. After each getMore that returns no change (MongoDB waits up
to one second for a change), the consumer
+takes the post batch resume token of the change stream: the position up to
which it has read the oplog. It stores that
+token in the `changeStreamTokenRepository`, so a new change stream resumes
after it.
+
+The consumer stores this token only when the exchange of the last change it
read completed. A change whose exchange
+failed is therefore read again by a new change stream, unless a later change
completed, as the token of that later
+change already passes the failed one.
+
+The post batch resume token is not passed to a resume strategy, which only
gets the tokens of the exchanges.
+
+If the oplog no longer has the token to resume after (MongoDB answers
ChangeStreamHistoryLost), for example because the
+route was stopped for longer than the oplog window, the consumer logs a WARN
and opens the change stream at the current
+time: the changes made since that token may not have been consumed.
+
=== Type conversions
The `MongoDbBasicConverters` type converter included with the
diff --git a/components/camel-mongodb/src/main/docs/mongodb-component.adoc
b/components/camel-mongodb/src/main/docs/mongodb-component.adoc
index 724c83a6ae78..fa0761d02597 100644
--- a/components/camel-mongodb/src/main/docs/mongodb-component.adoc
+++ b/components/camel-mongodb/src/main/docs/mongodb-component.adoc
@@ -1340,6 +1340,21 @@
from("mongodb:myDb?consumerType=changeStreams&database=flights&collection=ticket
You can use only endpoint options, only route-level resumable configuration,
or both depending on your deployment requirements.
+While no change of the collection arrives, the change stream still reads the
oplog, which the other collections of the
+replica set write. After each getMore that returns no change (MongoDB waits up
to one second for a change), the consumer
+takes the post batch resume token of the change stream: the position up to
which it has read the oplog. It stores that
+token in the `changeStreamTokenRepository`, so a new change stream resumes
after it.
+
+The consumer stores this token only when the exchange of the last change it
read completed. A change whose exchange
+failed is therefore read again by a new change stream, unless a later change
completed, as the token of that later
+change already passes the failed one.
+
+The post batch resume token is not passed to a resume strategy, which only
gets the tokens of the exchanges.
+
+If the oplog no longer has the token to resume after (MongoDB answers
ChangeStreamHistoryLost), for example because the
+route was stopped for longer than the oplog window, the consumer logs a WARN
and opens the change stream at the current
+time: the changes made since that token may not have been consumed.
+
=== Type conversions
The `MongoDbBasicConverters` type converter included with the
diff --git
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsThread.java
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsThread.java
index 02a755193ba4..799ff1b85733 100644
---
a/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsThread.java
+++
b/components/camel-mongodb/src/main/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsThread.java
@@ -22,6 +22,7 @@ import com.mongodb.MongoCommandException;
import com.mongodb.MongoException;
import com.mongodb.MongoServerException;
import com.mongodb.client.ChangeStreamIterable;
+import com.mongodb.client.MongoChangeStreamCursor;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.changestream.ChangeStreamDocument;
import com.mongodb.client.model.changestream.OperationType;
@@ -54,6 +55,9 @@ class MongoDbChangeStreamsThread extends
MongoAbstractConsumerThread {
private static final int UNKNOWN_FIELD = 40415;
private List<BsonDocument> bsonFilter;
+ // where a cursor opened again resumes: the token of the last event whose
exchange completed or, once a getMore
+ // returned no event and the exchange of the last event read before it
completed, the post batch resume token of
+ // the change stream
private BsonDocument resumeToken;
// the operation time read just before the change stream was opened
without a resume token. Until an exchange
// completed (and so there is a resume token), a cursor opened again
starts at it instead of the current time, so
@@ -64,6 +68,9 @@ class MongoDbChangeStreamsThread extends
MongoAbstractConsumerThread {
private boolean startTimeRefused;
private CommitManager commitManager;
private String resumeTokenKey;
+ // the post batch resume tokens that could not be committed in a row:
while the token repository cannot be reached,
+ // every getMore whose token moved fails the same way, so only the first
one goes to the exception handler
+ private int postBatchTokenCommitFailures;
MongoDbChangeStreamsThread(MongoDbEndpoint endpoint,
MongoDbChangeStreamsConsumer consumer,
List<BsonDocument> bsonFilter) {
@@ -93,6 +100,9 @@ class MongoDbChangeStreamsThread extends
MongoAbstractConsumerThread {
try {
return watch().resumeAfter(resumeToken).iterator();
} catch (MongoCommandException e) {
+ if (isStartNotInOplog(e.getErrorCode())) {
+ return openWithoutTokenAfterHistoryLost(e);
+ }
if (e.getErrorCode() != INVALID_RESUME_TOKEN) {
throw e;
}
@@ -104,6 +114,12 @@ class MongoDbChangeStreamsThread extends
MongoAbstractConsumerThread {
MongoCursor cursor;
try {
cursor = watch().startAfter(resumeToken).iterator();
+ } catch (MongoCommandException startAfterFailure) {
+ if (isStartNotInOplog(startAfterFailure.getErrorCode())) {
+ return openWithoutTokenAfterHistoryLost(startAfterFailure);
+ }
+ startAfterFailure.addSuppressed(e);
+ throw startAfterFailure;
} catch (RuntimeException startAfterFailure) {
startAfterFailure.addSuppressed(e);
throw startAfterFailure;
@@ -115,6 +131,23 @@ class MongoDbChangeStreamsThread extends
MongoAbstractConsumerThread {
}
}
+ /**
+ * Opens the change stream at the current time when the oplog no longer
has the resume token: it can never be
+ * resumed after it (the server answers the same for every attempt, and
for every start of the route while the token
+ * is stored), and the changes after it that the oplog still has cannot be
read either. The stored token is replaced
+ * by the next one the consumer commits.
+ */
+ private MongoCursor openWithoutTokenAfterHistoryLost(MongoCommandException
e) {
+ log.warn("The change stream of collection {} cannot be resumed after
its resume token, as the oplog no longer goes"
+ + " back that far ({}). Started a new change stream at the
current time, changes made since that token"
+ + " may not have been consumed.",
+ endpoint.getCollection(), e.getErrorMessage());
+ resumeToken = null;
+ // the start time is older than the token, so the oplog does not have
it either
+ startTime = null;
+ return openWithoutToken();
+ }
+
private MongoCursor openWithoutToken() {
if (startTime != null) {
// no exchange completed since the change stream was first opened:
start where it started
@@ -210,8 +243,27 @@ class MongoDbChangeStreamsThread extends
MongoAbstractConsumerThread {
@Override
protected void doRun() {
try {
- while (cursor.hasNext() && keepRunning) {
- ChangeStreamDocument<Document> dbObj =
(ChangeStreamDocument<Document>) cursor.next();
+ // whether the exchange of the last event this cursor returned
completed, so that the post batch resume
+ // token does not pass an event whose exchange failed. A failed
event that a later one passed is not held
+ // back: the token of the later event, committed when its exchange
completed, already passed it
+ boolean lastRouted = true;
+ while (keepRunning) {
+ // tryNext rather than hasNext: hasNext waits for the next
event across the getMores that return none, and
+ // only after one of those does the cursor give the post batch
resume token, the position up to which
+ // the change stream has read the oplog. Without an event a
getMore waits on the server for up to its
+ // maxAwaitTime
+ ChangeStreamDocument<Document> dbObj =
(ChangeStreamDocument<Document>) cursor.tryNext();
+ if (dbObj == null) {
+ if (!keepRunning || cursor.getServerCursor() == null) {
+ // the server closed the cursor (an invalidate event
ended the change stream), where hasNext
+ // returns false
+ break;
+ }
+ if (lastRouted) {
+ advanceToPostBatchResumeToken();
+ }
+ continue;
+ }
Exchange exchange =
createMongoDbExchange(dbObj.getFullDocument());
Object documentId = readDocumentId(dbObj.getDocumentKey());
@@ -237,10 +289,12 @@ class MongoDbChangeStreamsThread extends
MongoAbstractConsumerThread {
}
// a failed event does not advance the resume token
itself, but a later event that
// succeeds commits its own, so the failure is reported
rather than retried
- if (processExchange(exchange)) {
+ lastRouted = processExchange(exchange);
+ if (lastRouted) {
this.resumeToken = currentResumeToken;
commitManager.recordResumeToken(currentResumeToken);
commitManager.commit();
+ tokenCommitted();
}
} catch (Exception e) {
getExceptionHandler().handleException("Error committing
the change stream resume token", exchange, e);
@@ -249,9 +303,9 @@ class MongoDbChangeStreamsThread extends
MongoAbstractConsumerThread {
}
}
} catch (MongoException e) {
- // cursor.hasNext() opens socket and waiting for data
- // it throws exception when cursor is closed in another thread
- // there is no way to stop hasNext() before closing cursor
+ // cursor.tryNext() opens a socket and waits for data (a getMore)
+ // it throws an exception when the cursor is closed in another
thread
+ // there is no way to stop tryNext() before closing the cursor
if (keepRunning && resumeToken == null && startTime != null &&
isStartNotInOplog(e.getCode())) {
// a change stream started at the start time and failed on a
getMore because the oplog no longer goes
// back that far (should the server not have refused it in the
aggregate): the next one starts at the
@@ -266,6 +320,53 @@ class MongoDbChangeStreamsThread extends
MongoAbstractConsumerThread {
}
}
+ /**
+ * A token was committed, the one of an event or a post batch resume
token: the token repository can be reached
+ * again, so the next failure to commit a post batch resume token goes to
the exception handler again.
+ */
+ private void tokenCommitted() {
+ if (postBatchTokenCommitFailures > 0) {
+ log.info("Committed the change stream resume token again
(consecutive failures: {})",
+ postBatchTokenCommitFailures);
+ postBatchTokenCommitFailures = 0;
+ }
+ }
+
+ /**
+ * Takes the post batch resume token of the cursor after a getMore that
returned no event, as the token a cursor
+ * opened again resumes after, and commits it. On a collection that sees
no change while the rest of the replica set
+ * is written, the token of the last event soon falls out of the oplog,
and a change stream that the driver cannot
+ * resume itself (the server cannot be reached for longer than the server
selection timeout) could then no longer be
+ * resumed, while this token still can. A filter of the change stream
({@code streamFilter}) does not hold it back
+ * either: it passes the events the filter left out.
+ */
+ private void advanceToPostBatchResumeToken() {
+ BsonDocument postBatchResumeToken = cursor instanceof
MongoChangeStreamCursor<?> changeStreamCursor
+ ? changeStreamCursor.getResumeToken() : null;
+ // before the first reply with a post batch resume token (MongoDB
4.0.7 and later send one with every reply) the
+ // cursor gives the token it was opened with, or null when it was
opened without one
+ if (postBatchResumeToken == null ||
postBatchResumeToken.equals(resumeToken)) {
+ return;
+ }
+ resumeToken = postBatchResumeToken;
+ try {
+ commitManager.recordResumeToken(postBatchResumeToken);
+ commitManager.commit();
+ tokenCommitted();
+ } catch (Exception e) {
+ postBatchTokenCommitFailures++;
+ if (postBatchTokenCommitFailures == 1) {
+ getExceptionHandler().handleException("Error committing the
change stream resume token", e);
+ } else {
+ // this one repeats about once a second for as long as the
cause persists: the first failure went to the
+ // exception handler with its stack trace
+ log.warn("Error committing the change stream resume token
caused by {} ({} consecutive failures)",
+ e.getMessage(), postBatchTokenCommitFailures);
+ log.debug("Error committing the change stream resume token",
e);
+ }
+ }
+ }
+
/**
* Reads the {@code _id} out of the change event's document key.
* <p>
diff --git
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsInvalidateTest.java
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsInvalidateTest.java
index 56e7f2d7cc48..8bc5328ab276 100644
---
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsInvalidateTest.java
+++
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsInvalidateTest.java
@@ -149,7 +149,7 @@ class MongoDbChangeStreamsInvalidateTest {
* manual, "Invalidate Events" and "Resume a Change Stream"):
* <ul>
* <li>without a resume option: the insert, the drop and the invalidate
event; the server then closes the cursor, so
- * {@code hasNext()} returns false;</li>
+ * {@code tryNext()} returns null and {@code getServerCursor()} null;</li>
* <li>{@code resumeAfter} the token of the invalidate event: the
aggregate command fails with InvalidResumeToken
* (260), "Attempting to resume a change stream using 'resumeAfter' is not
allowed from an invalidate notification",
* which the driver throws from {@code iterator()} as a {@link
MongoCommandException};</li>
diff --git
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsMocks.java
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsMocks.java
index 57a35ab97d0c..2a8ddabc4a57 100644
---
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsMocks.java
+++
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsMocks.java
@@ -106,13 +106,18 @@ final class MongoDbChangeStreamsMocks {
return iterable;
}
- /** A cursor over the given events, whose {@code hasNext()} returns false
after the last one. */
+ /**
+ * A cursor over the given events whose server cursor is closed after the
last one: {@code tryNext()} then returns
+ * null and {@code getServerCursor()} null, as for a cursor that the
server closed ({@code hasNext()} returns
+ * false).
+ */
@SuppressWarnings("unchecked")
static MongoChangeStreamCursor<ChangeStreamDocument<Document>>
cursor(List<ChangeStreamDocument<Document>> events) {
Iterator<ChangeStreamDocument<Document>> it = events.iterator();
MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor =
mock(MongoChangeStreamCursor.class);
when(cursor.hasNext()).thenAnswer(i -> it.hasNext());
when(cursor.next()).thenAnswer(i -> it.next());
+ when(cursor.tryNext()).thenAnswer(i -> it.hasNext() ? it.next() :
null);
return cursor;
}
diff --git
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsPostBatchResumeTokenTest.java
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsPostBatchResumeTokenTest.java
new file mode 100644
index 000000000000..e160f576466c
--- /dev/null
+++
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsPostBatchResumeTokenTest.java
@@ -0,0 +1,599 @@
+/*
+ * 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.mongodb;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import com.mongodb.MongoCommandException;
+import com.mongodb.MongoTimeoutException;
+import com.mongodb.ReadPreference;
+import com.mongodb.ServerCursor;
+import com.mongodb.client.MongoChangeStreamCursor;
+import com.mongodb.client.MongoClient;
+import com.mongodb.client.MongoCollection;
+import com.mongodb.client.MongoDatabase;
+import com.mongodb.client.model.changestream.ChangeStreamDocument;
+import com.mongodb.client.model.changestream.OperationType;
+import org.apache.camel.CamelContext;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.mock.MockEndpoint;
+import
org.apache.camel.component.mongodb.MongoDbChangeStreamsMocks.ResumeOptions;
+import org.apache.camel.impl.DefaultCamelContext;
+import org.apache.camel.spi.ExceptionHandler;
+import org.apache.camel.support.processor.state.MemoryStateRepository;
+import org.apache.logging.log4j.Level;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.core.LogEvent;
+import org.apache.logging.log4j.core.Logger;
+import org.apache.logging.log4j.core.appender.AbstractAppender;
+import org.apache.logging.log4j.core.config.Property;
+import org.bson.BsonDocument;
+import org.bson.BsonInt32;
+import org.bson.BsonString;
+import org.bson.BsonTimestamp;
+import org.bson.Document;
+import org.bson.conversions.Bson;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static
org.apache.camel.component.mongodb.MongoDbChangeStreamsMocks.SERVER;
+import static
org.apache.camel.component.mongodb.MongoDbChangeStreamsMocks.errorReply;
+import static
org.apache.camel.component.mongodb.MongoDbChangeStreamsMocks.event;
+import static
org.apache.camel.component.mongodb.MongoDbChangeStreamsMocks.mockCollection;
+import static
org.apache.camel.component.mongodb.MongoDbChangeStreamsMocks.mockDatabase;
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * The change stream of a collection that sees no change keeps reading the
oplog, which the rest of the replica set
+ * writes: its post batch resume token moves on, while the token of the last
event of the collection falls out of the
+ * oplog. A cursor that the consumer opens again (the driver could not resume
the change stream itself), or a start of
+ * the route, must resume after the post batch resume token; and a token that
the oplog no longer has must not be tried
+ * for ever.
+ */
+class MongoDbChangeStreamsPostBatchResumeTokenTest {
+
+ private static final BsonDocument HISTORY_LOST = errorReply(286,
"ChangeStreamHistoryLost",
+ "Resume of change stream was not possible, as the resume point may
no longer be in the oplog.");
+ private static final String KEY = "mongo/events";
+
+ private final MongoClient client = mock(MongoClient.class);
+ private final MongoCollection<Document> collection = mockCollection();
+ // the next commits of a token that fail, as the token repository cannot
be reached
+ private final AtomicInteger failingCommits = new AtomicInteger();
+ // a durable store of the token (a database table): started here, so the
consumer does not stop it, as a stopped
+ // MemoryStateRepository forgets its state
+ private final MemoryStateRepository tokens = new MemoryStateRepository() {
+ @Override
+ public void setState(String key, String value) {
+ if (failingCommits.getAndUpdate(n -> Math.max(0, n - 1)) > 0) {
+ throw new IllegalStateException("token repository cannot be
reached");
+ }
+ super.setState(key, value);
+ }
+ };
+
+ // the oplog of the replica set: the entries of this collection ("events")
and of other collections. The entry at
+ // index i has the position i + 1
+ private final Object lock = new Object();
+ private final List<String[]> oplog = new ArrayList<>();
+ // the oldest position the oplog still has
+ private int historyStart = 1;
+ // positions of the entries that are invalidate events of this collection
+ private final Set<Integer> invalidates = new HashSet<>();
+ // the next getMore fails, and the driver cannot resume the change stream
(the server cannot be reached)
+ private boolean outagePending;
+ // the furthest position a change stream of the consumer read up to
+ private volatile int scanned;
+ // the getMores that returned no event
+ private final AtomicInteger emptyGetMores = new AtomicInteger();
+ // how the consumer opened change streams, and the answer
+ private final List<String> opened = Collections.synchronizedList(new
ArrayList<>());
+ // the bodies whose exchange fails, once each
+ private final Set<String> failOnce = Collections.synchronizedSet(new
HashSet<>());
+ private final List<LogEvent> logged = new CopyOnWriteArrayList<>();
+ private AbstractAppender appender;
+ private CamelContext context;
+
+ private static BsonDocument token(int position) {
+ return new BsonDocument("_data", new
BsonString(Integer.toString(position)));
+ }
+
+ @BeforeEach
+ void setUp() {
+ MongoDatabase database = mockDatabase(client, collection, this::open);
+
when(collection.getReadPreference()).thenReturn(ReadPreference.primary());
+ // runCommand reference: for read concern local, the operation time of
a command that writes nothing is the
+ // timestamp of the newest entry of the oplog; the entry at position p
has the operation time (1, p)
+ when(database.runCommand(any(Bson.class),
eq(ReadPreference.primary()), eq(BsonDocument.class)))
+ .thenAnswer(i -> {
+ synchronized (lock) {
+ return new BsonDocument("ok", new BsonInt32(1))
+ .append("operationTime", new BsonTimestamp(1,
oplog.size()));
+ }
+ });
+ // the first entry of the oplog of the replica set
+ write("other", "initiate");
+ tokens.start();
+
+ appender = new AbstractAppender("postBatchResumeToken", null, null,
true, Property.EMPTY_ARRAY) {
+ @Override
+ public void append(LogEvent event) {
+ logged.add(event.toImmutable());
+ }
+ };
+ appender.start();
+ ((Logger)
LogManager.getLogger(MongoDbChangeStreamsThread.class)).addAppender(appender);
+
+ context = new DefaultCamelContext();
+ context.getRegistry().bind("myDb", client);
+ context.getRegistry().bind("tokens", tokens);
+ }
+
+ @AfterEach
+ void tearDown() {
+ try {
+ if (context != null) {
+ context.stop();
+ }
+ } finally {
+ ((Logger)
LogManager.getLogger(MongoDbChangeStreamsThread.class)).removeAppender(appender);
+ appender.stop();
+ }
+ }
+
+ @Test
+ void
cursorOpenedAgainOnAQuietCollectionResumesAfterThePostBatchResumeToken() throws
Exception {
+ MockEndpoint mock = startRoute();
+ write("events", "a");
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
token(2).toJson().equals(tokens.getState(KEY)));
+
+ // only other collections are written; the change stream reads them
+ write("other", "x1");
+ write("other", "x2");
+ write("other", "x3");
+ awaitQuietAt(5);
+
+ synchronized (lock) {
+ // the oplog rolls past event a, and the server cannot be reached
for longer than the server selection
+ // timeout, so the driver cannot resume the change stream itself
+ historyStart = 3;
+ outagePending = true;
+ lock.notifyAll();
+ }
+
+ // on main the consumer opened the change stream after the token of a,
and the server refused it every time
+ await().atMost(10, TimeUnit.SECONDS).until(() -> opened.size() >= 2);
+ assertEquals(List.of("now 2", "resumeAfter 5 -> ok"), firstOpened(2));
+ write("events", "b");
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
bodies(mock).equals(List.of("a", "b")));
+ assertNoHistoryLostWarning();
+ }
+
+ @Test
+ void
routeStartedAgainAfterAQuietPeriodResumesAfterTheStoredPostBatchResumeToken()
throws Exception {
+ MockEndpoint mock = startRoute();
+ write("events", "a");
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
bodies(mock).equals(List.of("a")));
+ write("other", "x1");
+ write("other", "x2");
+ write("other", "x3");
+ awaitQuietAt(5);
+ context.getRouteController().stopRoute("mongo");
+
+ synchronized (lock) {
+ historyStart = 3;
+ }
+ // changed while the route is stopped
+ write("events", "b");
+
+ // on main the start failed with ChangeStreamHistoryLost, as the
stored token was the one of a
+ context.getRouteController().startRoute("mongo");
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
bodies(mock).equals(List.of("a", "b")));
+ assertEquals("resumeAfter 5 -> ok", opened.get(1));
+ assertNoHistoryLostWarning();
+ }
+
+ @Test
+ void storedTokenNoLongerInTheOplogStartsAtTheCurrentTime() throws
Exception {
+ write("events", "a");
+ write("other", "x1");
+ write("other", "x2");
+ synchronized (lock) {
+ historyStart = 3;
+ }
+ tokens.setState(KEY, token(2).toJson());
+
+ // on main the start failed with ChangeStreamHistoryLost, and so would
every later one
+ MockEndpoint mock = startRoute();
+ write("events", "b");
+
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
bodies(mock).equals(List.of("b")));
+ assertEquals(List.of("resumeAfter 2 -> 286", "now 5"), firstOpened(2));
+ assertHistoryLostWarning();
+ // the token of b replaces the one the oplog no longer has
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
token(5).toJson().equals(tokens.getState(KEY)));
+ }
+
+ @Test
+ void
tokenNoLongerInTheOplogWhenTheCursorIsOpenedAgainStartsAtTheCurrentTime()
throws Exception {
+ // every event after a fails, so the token of a stays the one to
resume after
+ failOnce.add("b");
+ MockEndpoint mock = startRoute();
+ write("events", "a");
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
token(2).toJson().equals(tokens.getState(KEY)));
+ write("events", "b");
+ write("other", "x1");
+ awaitQuietAt(4);
+
+ synchronized (lock) {
+ historyStart = 3;
+ outagePending = true;
+ lock.notifyAll();
+ }
+
+ // on main the consumer opened the change stream after the token of a
for as long as the route ran
+ await().atMost(10, TimeUnit.SECONDS).until(() -> opened.size() >= 3);
+ assertEquals(List.of("now 2", "resumeAfter 2 -> 286", "now 5"),
firstOpened(3));
+ write("events", "c");
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
bodies(mock).equals(List.of("a", "c")));
+ assertHistoryLostWarning();
+ }
+
+ @Test
+ void postBatchResumeTokenDoesNotPassAnEventWhoseExchangeFailed() throws
Exception {
+ // control, as on main: a cursor opened again resumes after the last
event whose exchange completed, so the
+ // event that failed is routed again
+ failOnce.add("b");
+ MockEndpoint mock = startRoute();
+ write("events", "a");
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
token(2).toJson().equals(tokens.getState(KEY)));
+ write("events", "b");
+ write("other", "x1");
+ awaitQuietAt(4);
+ assertEquals(token(2).toJson(), tokens.getState(KEY));
+
+ synchronized (lock) {
+ outagePending = true;
+ lock.notifyAll();
+ }
+
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
bodies(mock).equals(List.of("a", "b")));
+ assertEquals(List.of("now 2", "resumeAfter 2 -> ok"), firstOpened(2));
+ }
+
+ @Test
+ void storedInvalidateTokenNoLongerInTheOplogStartsAtTheCurrentTime()
throws Exception {
+ // the collection was dropped: its change stream ended with an
invalidate event, whose token is stored
+ write("events", "invalidate");
+ synchronized (lock) {
+ invalidates.add(2);
+ }
+ write("other", "x1");
+ write("other", "x2");
+ synchronized (lock) {
+ historyStart = 3;
+ }
+ tokens.setState(KEY, token(2).toJson());
+
+ // on main startAfter failed with ChangeStreamHistoryLost, and the
route did not start
+ MockEndpoint mock = startRoute();
+ write("events", "b");
+
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
bodies(mock).equals(List.of("b")));
+ assertEquals(List.of("resumeAfter 2 -> 260", "startAfter 2 -> 286",
"now 5"), firstOpened(3));
+ assertHistoryLostWarning();
+ }
+
+ @Test
+ void
repeatedPostBatchResumeTokenCommitFailuresReachTheExceptionHandlerOnce() throws
Exception {
+ List<String> handled = new CopyOnWriteArrayList<>();
+ context.getRegistry().bind("handler", new ExceptionHandler() {
+ @Override
+ public void handleException(Throwable exception) {
+ handled.add(exception.getMessage());
+ }
+
+ @Override
+ public void handleException(String message, Throwable exception) {
+ handled.add(message);
+ }
+
+ @Override
+ public void handleException(String message, Exchange exchange,
Throwable exception) {
+ handled.add(message);
+ }
+ });
+ MockEndpoint mock = startRoute("&exceptionHandler=#handler");
+ write("events", "a");
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
token(2).toJson().equals(tokens.getState(KEY)));
+
+ // the token repository cannot be reached while the post batch resume
token moves three times
+ failingCommits.set(3);
+ for (int i = 1; i <= 3; i++) {
+ write("other", "x" + i);
+ int left = 3 - i;
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
failingCommits.get() == left);
+ }
+ write("other", "x4");
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
token(6).toJson().equals(tokens.getState(KEY)));
+
+ String failed = "Error committing the change stream resume token";
+ String cause = failed + " caused by token repository cannot be
reached";
+ assertEquals(List.of(failed), handled);
+ assertEquals(List.of(cause + " (2 consecutive failures)", cause + " (3
consecutive failures)"),
+ messages(Level.WARN, failed));
+ assertEquals(List.of("Committed the change stream resume token again
(consecutive failures: 3)"),
+ messages(Level.INFO, "Committed the change stream resume
token"));
+
+ // a commit of the token of an event also ends a run of failures: the
next failure goes to the handler again
+ failingCommits.set(1);
+ write("other", "x5");
+ await().atMost(10, TimeUnit.SECONDS).until(() -> handled.size() == 2);
+ write("events", "b");
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
token(8).toJson().equals(tokens.getState(KEY)));
+ failingCommits.set(1);
+ write("other", "x6");
+ await().atMost(10, TimeUnit.SECONDS).until(() -> handled.size() == 3);
+ assertEquals(List.of("a", "b"), bodies(mock));
+ assertEquals(List.of(cause + " (2 consecutive failures)", cause + " (3
consecutive failures)"),
+ messages(Level.WARN, failed));
+ }
+
+ private List<String> messages(Level level, String prefix) {
+ return logged.stream().filter(e -> e.getLevel() == level)
+ .map(e -> e.getMessage().getFormattedMessage())
+ .filter(m -> m.startsWith(prefix))
+ .toList();
+ }
+
+ /** Waits until the change stream read the oplog up to the position and
then answered empty getMores. */
+ private void awaitQuietAt(int position) {
+ await().atMost(10, TimeUnit.SECONDS).until(() -> scanned == position);
+ int empty = emptyGetMores.get();
+ // the consumer asks again only once it handled the previous answer
+ await().atMost(10, TimeUnit.SECONDS).until(() -> emptyGetMores.get()
>= empty + 2);
+ }
+
+ private void assertHistoryLostWarning() {
+ assertEquals(1, historyLostWarnings().size(),
historyLostWarnings().toString());
+ }
+
+ private void assertNoHistoryLostWarning() {
+ assertEquals(List.of(), historyLostWarnings());
+ }
+
+ private List<String> historyLostWarnings() {
+ return logged.stream().filter(e -> e.getLevel() == Level.WARN)
+ .map(e -> e.getMessage().getFormattedMessage())
+ .filter(m -> m.startsWith("The change stream of collection
events cannot be resumed after its resume"
+ + " token, as the oplog no longer
goes back that far"))
+ .toList();
+ }
+
+ private void write(String coll, String text) {
+ synchronized (lock) {
+ oplog.add(new String[] { coll, text });
+ lock.notifyAll();
+ }
+ }
+
+ private List<String> firstOpened(int count) {
+ synchronized (opened) {
+ // the consumer thread may still be opening change streams
+ return List.copyOf(opened.subList(0, Math.min(count,
opened.size())));
+ }
+ }
+
+ private static List<String> bodies(MockEndpoint mock) {
+ return mock.getExchanges().stream()
+ .map(e -> e.getIn().getBody(Document.class).getString("text"))
+ .toList();
+ }
+
+ private MockEndpoint startRoute() throws Exception {
+ return startRoute("");
+ }
+
+ private MockEndpoint startRoute(String options) throws Exception {
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+
from("mongodb:myDb?database=test&collection=events&consumerType=changeStreams"
+ +
"&changeStreamTokenRepository=#tokens&cursorRegenerationDelay=100" + options)
+ .routeId("mongo")
+ .process(exchange -> {
+ String text =
exchange.getIn().getBody(Document.class).getString("text");
+ if (failOnce.remove(text)) {
+ throw new IllegalStateException("processing of
" + text + " failed");
+ }
+ })
+ .to("mock:result");
+ }
+ });
+ context.start();
+ return context.getEndpoint("mock:result", MockEndpoint.class);
+ }
+
+ /**
+ * The aggregate that opens a change stream (change streams manual,
"Resume a Change Stream"): without a resume
+ * option it starts at the current time; with {@code resumeAfter} after
the position of the token, unless the oplog
+ * no longer has that position (ChangeStreamHistoryLost, 286) or the token
is the one of an invalidate event
+ * (InvalidResumeToken, 260, "Attempting to resume a change stream using
'resumeAfter' is not allowed from an
+ * invalidate notification", checked before the oplog is read); with
{@code startAfter} after the position of the
+ * token, unless the oplog no longer has it (286).
+ */
+ private MongoChangeStreamCursor<ChangeStreamDocument<Document>>
open(ResumeOptions options) {
+ synchronized (lock) {
+ int position;
+ if (options.resumeAfter != null || options.startAfter != null) {
+ String how = options.resumeAfter != null ? "resumeAfter" :
"startAfter";
+ BsonDocument token = options.resumeAfter != null ?
options.resumeAfter : options.startAfter;
+ int t = Integer.parseInt(token.getString("_data").getValue());
+ if (options.resumeAfter != null && invalidates.contains(t)) {
+ opened.add(how + " " + t + " -> 260");
+ throw new MongoCommandException(
+ errorReply(260, "InvalidResumeToken", "Attempting
to resume a change stream using"
+ + "
'resumeAfter' is not allowed from an invalidate"
+ + "
notification."),
+ SERVER);
+ }
+ if (t < historyStart) {
+ opened.add(how + " " + t + " -> 286");
+ throw new MongoCommandException(HISTORY_LOST, SERVER);
+ }
+ opened.add(how + " " + t + " -> ok");
+ position = t;
+ return new FakeCursor(position, token).cursor;
+ } else if (options.startAtOperationTime != null) {
+ position = options.startAtOperationTime.getInc() - 1;
+ opened.add("startAtOperationTime " + (position + 1));
+ } else {
+ position = oplog.size();
+ opened.add("now " + (position + 1));
+ }
+ return new FakeCursor(position, null).cursor;
+ }
+ }
+
+ /**
+ * A change stream cursor that answers like the one of the MongoDB Java
driver 5.14 (MongoChangeStreamCursorImpl,
+ * ChangeStreamBatchCursor and CommandCursor, read with javap), one event
per batch:
+ * <ul>
+ * <li>{@code hasNext()} waits for the next event across the getMores that
return none, without changing the resume
+ * token of the cursor; {@code next()} returns the event, after which the
resume token is the post batch resume
+ * token of its batch, the token of the event;</li>
+ * <li>{@code tryNext()} returns the next event, or sends one getMore,
which waits up to its maxAwaitTime on the
+ * server (50 millis here), and returns null when it brought no event: the
resume token is then the post batch
+ * resume token of that getMore, the position up to which the change
stream read the oplog;</li>
+ * <li>before any reply the resume token is the token the cursor was
opened with, or null;</li>
+ * <li>{@code getServerCursor()} is not null until the server closes the
cursor; after {@code close()} it, and every
+ * read that starts, throws IllegalStateException; a getMore in progress
ends, and then {@code hasNext()} throws
+ * IllegalStateException while {@code tryNext()} returns null;</li>
+ * <li>a getMore that fails while the server cannot be reached, which the
driver cannot resume either, throws
+ * MongoTimeoutException.</li>
+ * </ul>
+ */
+ private final class FakeCursor {
+ @SuppressWarnings("unchecked")
+ private final MongoChangeStreamCursor<ChangeStreamDocument<Document>>
cursor = mock(MongoChangeStreamCursor.class);
+ private int position;
+ private BsonDocument resumeToken;
+ private volatile boolean closed;
+
+ private FakeCursor(int position, BsonDocument initialToken) {
+ this.position = position;
+ this.resumeToken = initialToken;
+ when(cursor.hasNext()).thenAnswer(i -> hasNext());
+ when(cursor.next()).thenAnswer(i -> next());
+ when(cursor.tryNext()).thenAnswer(i -> tryNext());
+ when(cursor.getResumeToken()).thenAnswer(i -> {
+ synchronized (lock) {
+ return resumeToken;
+ }
+ });
+ when(cursor.getServerCursor()).thenAnswer(i -> {
+ if (closed) {
+ throw new IllegalStateException("Iterator has been
closed");
+ }
+ return new ServerCursor(42, SERVER);
+ });
+ doAnswer(i -> {
+ closed = true;
+ synchronized (lock) {
+ lock.notifyAll();
+ }
+ return null;
+ }).when(cursor).close();
+ }
+
+ private boolean hasNext() throws InterruptedException {
+ synchronized (lock) {
+ while (true) {
+ if (eventReady()) {
+ return true;
+ }
+ getMore();
+ }
+ }
+ }
+
+ private ChangeStreamDocument<Document> next() {
+ synchronized (lock) {
+ String text = oplog.get(position++)[1];
+ resumeToken = token(position);
+ return event(invalidates.contains(position) ?
OperationType.INVALIDATE : OperationType.INSERT,
+ token(position), new Document("_id",
position).append("text", text));
+ }
+ }
+
+ private ChangeStreamDocument<Document> tryNext() throws
InterruptedException {
+ synchronized (lock) {
+ if (eventReady()) {
+ return next();
+ }
+ getMore();
+ if (closed) {
+ // closed while the getMore waited: the driver lets it end
and returns no event
+ return null;
+ }
+ if (eventReady()) {
+ return next();
+ }
+ resumeToken = token(position);
+ return null;
+ }
+ }
+
+ /** Reads the oplog up to the next event of the collection; true if
there is one. */
+ private boolean eventReady() {
+ if (closed) {
+ throw new IllegalStateException("Cursor has been closed");
+ }
+ while (position < oplog.size() &&
!"events".equals(oplog.get(position)[0])) {
+ position++;
+ }
+ scanned = Math.max(scanned, position);
+ return position < oplog.size();
+ }
+
+ private void getMore() throws InterruptedException {
+ if (outagePending) {
+ outagePending = false;
+ throw new MongoTimeoutException("Timed out while waiting for a
server that matches ReadPreference");
+ }
+ lock.wait(50);
+ if (!closed && !eventReady()) {
+ emptyGetMores.incrementAndGet();
+ }
+ }
+ }
+}
diff --git
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsReopenTest.java
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsReopenTest.java
index 41ecc2866bec..619b51abe1c4 100644
---
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsReopenTest.java
+++
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbChangeStreamsReopenTest.java
@@ -73,9 +73,9 @@ class MongoDbChangeStreamsReopenTest {
private final List<String> oplog = Collections.synchronizedList(new
ArrayList<>());
// the resume options of every change stream the consumer opened, in order
private final List<String> opened = Collections.synchronizedList(new
ArrayList<>());
- // what happens on the server when the consumer first calls hasNext on the
first change stream: the getMore then
- // fails, and so does the resume of the driver
- private volatile Runnable onFirstHasNext = () -> {
+ // what happens on the server when the consumer first reads from the first
change stream: the getMore then fails,
+ // and so does the resume of the driver
+ private volatile Runnable onFirstRead = () -> {
};
// a change made right after the consumer opened a change stream again
private volatile String changeAfterFirstReopen;
@@ -135,7 +135,7 @@ class MongoDbChangeStreamsReopenTest {
void
cursorOpenedAgainBeforeAnyExchangeCompletedStartsWhereTheFirstStarted() throws
Exception {
// made before the route starts, so not consumed
oplog.add("before");
- onFirstHasNext = () -> {
+ onFirstRead = () -> {
oplog.add("a");
oplog.add("b");
};
@@ -172,7 +172,7 @@ class MongoDbChangeStreamsReopenTest {
private void
assertStartNoLongerInTheOplogStartsAtTheCurrentTime(BsonDocument error) throws
Exception {
historyLost = error;
- onFirstHasNext = () -> {
+ onFirstRead = () -> {
oplog.add("a");
oplog.add("b");
// the oplog no longer has the time at which the first change
stream started
@@ -194,7 +194,7 @@ class MongoDbChangeStreamsReopenTest {
historyLost = errorReply(286, "ChangeStreamHistoryLost",
"Resume of change stream was not possible, as the resume point
may no longer be in the oplog.");
historyLostOnGetMore = true;
- onFirstHasNext = () -> {
+ onFirstRead = () -> {
oplog.add("a");
oplog.add("b");
historyStart = 2;
@@ -214,7 +214,7 @@ class MongoDbChangeStreamsReopenTest {
// a MongoDB-compatible server that does not know the option
startRefused = errorReply(40415, "Location40415",
"BSON field '$changeStream.startAtOperationTime' is an unknown
field.");
- onFirstHasNext = () -> oplog.add("a");
+ onFirstRead = () -> oplog.add("a");
changeAfterFirstReopen = "c";
MockEndpoint mock = startRoute();
@@ -230,7 +230,7 @@ class MongoDbChangeStreamsReopenTest {
@Test
void serverWithoutOperationTimeStartsAtTheCurrentTime() throws Exception {
operationTimeInReplies = false;
- onFirstHasNext = () -> oplog.add("a");
+ onFirstRead = () -> oplog.add("a");
changeAfterFirstReopen = "c";
MockEndpoint mock = startRoute();
@@ -243,7 +243,7 @@ class MongoDbChangeStreamsReopenTest {
@Test
void pingAnsweredWithAnErrorStartsAtTheCurrentTime() throws Exception {
pingFails = true;
- onFirstHasNext = () -> oplog.add("a");
+ onFirstRead = () -> oplog.add("a");
changeAfterFirstReopen = "c";
MockEndpoint mock = startRoute();
@@ -287,8 +287,9 @@ class MongoDbChangeStreamsReopenTest {
* token, with {@code startAtOperationTime} at the first change at or
after that time; a start the oplog no longer
* has fails with ChangeStreamHistoryLost (286), in the aggregate or, with
historyLostOnGetMore, in the first
* getMore; a server that does not accept startAtOperationTime fails the
aggregate with startRefused;</li>
- * <li>{@code hasNext()} returns false when there is no change, so the
consumer opens a new cursor after the
- * regeneration delay (a real change stream waits).</li>
+ * <li>{@code tryNext()} returns null and the server cursor is gone when
there is no change, as for a cursor that
+ * the server closed, so the consumer opens a new cursor after the
regeneration delay (a real change stream
+ * waits).</li>
* </ul>
*/
private MongoChangeStreamCursor<ChangeStreamDocument<Document>>
open(ResumeOptions options) {
@@ -327,7 +328,7 @@ class MongoDbChangeStreamsReopenTest {
@SuppressWarnings("unchecked")
private MongoChangeStreamCursor<ChangeStreamDocument<Document>>
historyLostCursor() {
MongoChangeStreamCursor<ChangeStreamDocument<Document>> cursor =
mock(MongoChangeStreamCursor.class);
- when(cursor.hasNext()).thenThrow(new
MongoCommandException(historyLost, SERVER));
+ when(cursor.tryNext()).thenThrow(new
MongoCommandException(historyLost, SERVER));
return cursor;
}
@@ -336,20 +337,19 @@ class MongoDbChangeStreamsReopenTest {
@SuppressWarnings("unchecked")
private final MongoChangeStreamCursor<ChangeStreamDocument<Document>>
cursor = mock(MongoChangeStreamCursor.class);
private int position;
- private boolean firstHasNextPending;
+ private boolean firstReadPending;
private FakeCursor(int position, boolean first) {
this.position = position;
- this.firstHasNextPending = first;
- when(cursor.hasNext()).thenAnswer(i -> {
- if (firstHasNextPending) {
- firstHasNextPending = false;
- onFirstHasNext.run();
+ this.firstReadPending = first;
+ when(cursor.tryNext()).thenAnswer(i -> {
+ if (firstReadPending) {
+ firstReadPending = false;
+ onFirstRead.run();
throw new MongoSocketReadException("Prematurely reached
end of stream", SERVER);
}
- return position < oplog.size();
+ return position < oplog.size() ? next() : null;
});
- when(cursor.next()).thenAnswer(i -> next());
}
private ChangeStreamDocument<Document> next() {
diff --git
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbConsumerCursorRegenerationTest.java
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbConsumerCursorRegenerationTest.java
index b0fe853f305b..b07582b000c1 100644
---
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbConsumerCursorRegenerationTest.java
+++
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/MongoDbConsumerCursorRegenerationTest.java
@@ -296,7 +296,7 @@ class MongoDbConsumerCursorRegenerationTest {
@SuppressWarnings("unchecked")
void changeStreamsConsumerOpensANewCursorAfterAFailedRegeneration() throws
Exception {
MongoChangeStreamCursor<ChangeStreamDocument<Document>> broken =
mock(MongoChangeStreamCursor.class);
- when(broken.hasNext()).thenThrow(new
MongoSocketReadException("Prematurely reached end of stream", SERVER));
+ when(broken.tryNext()).thenThrow(new
MongoSocketReadException("Prematurely reached end of stream", SERVER));
ChangeStreamDocument<Document> event =
mock(ChangeStreamDocument.class);
when(event.getFullDocument()).thenReturn(new Document("_id",
1).append("text", "after the outage"));
@@ -304,11 +304,10 @@ class MongoDbConsumerCursorRegenerationTest {
when(event.getOperationType()).thenReturn(OperationType.INSERT);
when(event.getResumeToken()).thenReturn(new BsonDocument("_data", new
BsonInt32(1)));
MongoChangeStreamCursor<ChangeStreamDocument<Document>> recovered =
mock(MongoChangeStreamCursor.class);
- when(recovered.hasNext()).thenReturn(true, false);
- when(recovered.next()).thenReturn(event);
+ // tryNext returns null once the server closed the cursor
(getServerCursor() is null then too)
+ when(recovered.tryNext()).thenReturn(event,
(ChangeStreamDocument<Document>) null);
MongoChangeStreamCursor<ChangeStreamDocument<Document>> idle =
mock(MongoChangeStreamCursor.class);
- when(idle.hasNext()).thenReturn(false);
ChangeStreamIterable<Document> watch =
mock(ChangeStreamIterable.class);
when(collection.watch()).thenReturn(watch);
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 1293cce3d662..754f2c4bdc50 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
@@ -129,7 +129,10 @@ class MongoDbConsumerStopTest {
@SuppressWarnings("unchecked")
void changeStreamsConsumerStopsWhileItsThreadIsBlockedReadingTheCursor()
throws Exception {
MongoChangeStreamCursor<?> cursor =
mock(MongoChangeStreamCursor.class);
- when(cursor.hasNext()).thenAnswer(i -> readThatDoesNotReturn());
+ when(cursor.tryNext()).thenAnswer(i -> {
+ readThatDoesNotReturn();
+ return null;
+ });
ChangeStreamIterable<Document> watch =
mock(ChangeStreamIterable.class);
when(collection.watch()).thenReturn(watch);
when(watch.fullDocument(any(FullDocument.class))).thenReturn(watch);
diff --git
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/dst/FakeMongo.java
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/dst/FakeMongo.java
index 38f4885bfddd..9031182a5140 100644
---
a/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/dst/FakeMongo.java
+++
b/components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/dst/FakeMongo.java
@@ -28,6 +28,7 @@ import com.mongodb.MongoSocketReadException;
import com.mongodb.MongoTimeoutException;
import com.mongodb.ReadPreference;
import com.mongodb.ServerAddress;
+import com.mongodb.ServerCursor;
import com.mongodb.client.ChangeStreamIterable;
import com.mongodb.client.ListCollectionNamesIterable;
import com.mongodb.client.MongoChangeStreamCursor;
@@ -64,8 +65,12 @@ import org.bson.Document;
* <p>
* Not modelled: the oplog window (a resume token that fell out of the oplog,
ChangeStreamHistoryLost), sharded
* clusters, pipelines (streamFilter), pre-images, renames and dropDatabase
(they end the change stream as a drop does),
- * transactions, batching (one event per getMore), and the post batch resume
token of an empty getMore (the driver then
- * resumes from the last event it returned, which is the same position here,
as events are never filtered).
+ * transactions, and batching (one event per getMore).
+ * <p>
+ * [A] The post batch resume token that the cursor gives after a getMore
without an event (tryNext returned null) is the
+ * token of the last event the cursor returned, and null before its first
event: events are never filtered and no other
+ * collection is written, so the change stream has read the oplog up to that
event (a real server returns a token for
+ * the start position too; null makes the consumer keep the token it has).
* <p>
* Timing (the one-stack rule of the harness): a getMore waits up to its
maxAwaitTime for an event and takes a round
* trip; writes of the other clients take effect at once and never block.
@@ -395,6 +400,8 @@ final class FakeMongo {
this.proxy = FakeMongo.this.proxy(MongoChangeStreamCursor.class,
(m, args) -> switch (m) {
case "hasNext" -> hasNext();
case "next" -> next();
+ case "tryNext" -> tryNext();
+ case "getServerCursor" -> serverCursor();
case "close" -> {
closed = true;
yield null;
@@ -419,22 +426,54 @@ final class FakeMongo {
if (position < oplog.size()) {
return true;
}
- // a getMore: waits up to maxAwaitTime (1 s by default) for an
event, then answers
- dst.awaitUntil(() -> position < oplog.size() ||
interruptRequested, 1000, "getMore");
- roundTrip("getMore");
- if (dst.now() < unreachableUntil || faults &&
dst.chance(getMoreFailRate)) {
- // [D] a resumable error (isResumableError is true for
network errors): the driver opens the change
- // stream again after its cached token
(ChangeStreamBatchCursor.resumeableOperation). The resume
- // itself is outside that retry, so what the resume throws
reaches the caller: a server selection
- // timeout, or a network error of the resume aggregate
- dst.trace("mongo: getMore fails, the driver resumes the
change stream");
- selectServer("resume the change stream");
- roundTrip("aggregate $changeStream (resume)");
- if (faults && dst.chance(0.5)) {
- // [A] the resume aggregate fails with a network error
too
- throw new MongoSocketReadException(
- "dst: the connection was reset", new
ServerAddress("fake", 27017));
- }
+ getMore();
+ }
+ }
+
+ /**
+ * [D] tryNext returns the next change, or sends one getMore and
returns null when it brought none; once the
+ * server closed the cursor it returns null without a getMore
(CommandCursor.tryHasNext of driver 5.14).
+ */
+ private ChangeStreamDocument<Document> tryNext() {
+ if (closed) {
+ violations.add("tryNext on a closed cursor");
+ throw new IllegalStateException("Cursor has been closed");
+ }
+ checkInterrupt();
+ if (invalidated) {
+ return null;
+ }
+ if (position >= oplog.size()) {
+ getMore();
+ }
+ return position < oplog.size() ? next() : null;
+ }
+
+ /** [D] the server cursor, null once the server closed it (after the
invalidate event). */
+ private ServerCursor serverCursor() {
+ if (closed) {
+ violations.add("getServerCursor on a closed cursor");
+ throw new IllegalStateException("Iterator has been closed");
+ }
+ return invalidated ? null : new ServerCursor(1, new
ServerAddress("fake", 27017));
+ }
+
+ /** A getMore: waits up to maxAwaitTime (1 s by default) for an event,
then answers. */
+ private void getMore() {
+ dst.awaitUntil(() -> position < oplog.size() ||
interruptRequested, 1000, "getMore");
+ roundTrip("getMore");
+ if (dst.now() < unreachableUntil || faults &&
dst.chance(getMoreFailRate)) {
+ // [D] a resumable error (isResumableError is true for network
errors): the driver opens the change
+ // stream again after its cached token
(ChangeStreamBatchCursor.resumeableOperation). The resume
+ // itself is outside that retry, so what the resume throws
reaches the caller: a server selection
+ // timeout, or a network error of the resume aggregate
+ dst.trace("mongo: getMore fails, the driver resumes the change
stream");
+ selectServer("resume the change stream");
+ roundTrip("aggregate $changeStream (resume)");
+ if (faults && dst.chance(0.5)) {
+ // [A] the resume aggregate fails with a network error too
+ throw new MongoSocketReadException(
+ "dst: the connection was reset", new
ServerAddress("fake", 27017));
}
}
}
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 5af95a953e6d..749cd1f0142f 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -931,6 +931,24 @@ A cql endpoint no longer closes a session given with
`session` or `beanRef` when
uses it is removed. It still closes a session it creates from its `hosts`, and
creates a new one when it is started
again. The application closes a session it gives to the endpoint, such as with
a destroy method of its bean.
+=== camel-mongodb - the change streams consumer stores the post batch resume
token
+
+While no change of its collection arrives, the change streams consumer now
takes the post batch resume token of the
+change stream after each getMore that returns no change (about once a second),
and stores it in the
+`changeStreamTokenRepository` when it differs from the stored token. A
repository is therefore also written while the
+collection sees no change, at most about once a second. Before, only the token
of the last change whose exchange
+completed was stored; on a collection that sees few changes, that token could
fall out of the oplog, and the change
+stream could then no longer be resumed.
+
+A route with a token repository that has not consumed any change yet now also
resumes after a restart: it resumes
+after the stored post batch resume token, so the changes made while the route
was stopped are routed. Before, such a
+route had nothing stored and started at the current time after a restart.
+
+A resume token that the oplog no longer has (MongoDB answers
ChangeStreamHistoryLost), such as a token stored before
+the route was stopped for longer than the oplog window, or a
`changeStreamToken` that old, no longer fails the start of
+the route, and the consumer no longer tries it again for as long as the route
runs: it logs a WARN and opens the change
+stream at the current time, so the changes made since that token are not
consumed.
+
=== camel-mina-sftp - checking whether a file exists takes one lstat request
The `mina-sftp` component now checks whether a remote file exists
(`fileExist=Ignore|Fail|Move`, `tempFileName`,