From 5bdea8476e1c6b6296619ac9a14f36755eae2c83 Mon Sep 17 00:00:00 2001 From: Valentin Kovalenko Date: Mon, 26 Oct 2026 16:56:34 -0600 Subject: [PATCH 01/11] JAVA-6350 Refactor `ChangeStreamProseTest` to support reactive prose tests Also move the sync & reactive test from `AbstractChangeSteamFunctionalTest` to `ChangeStreamProseTest`. This effectively matches the instructions that were left in `AbstractChangeSteamFunctionalTest`. JAVA-6350 --- ...reamOperationProseTestSpecification.groovy | 6 +- .../client/ChangeStreamFunctionalTest.java | 29 ---- .../client/ChangeStreamProseTest.java | 96 +++++++++++ .../client/syncadapter/SyncMongoCursor.java | 5 +- .../AbstractChangeSteamFunctionalTest.java | 105 ------------ .../client/ChangeSteamFunctionalTest.java | 27 --- .../mongodb/client/ChangeStreamProseTest.java | 158 +++++++++++++----- 7 files changed, 220 insertions(+), 206 deletions(-) delete mode 100644 driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamFunctionalTest.java create mode 100644 driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java delete mode 100644 driver-sync/src/test/functional/com/mongodb/client/AbstractChangeSteamFunctionalTest.java delete mode 100644 driver-sync/src/test/functional/com/mongodb/client/ChangeSteamFunctionalTest.java diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationProseTestSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationProseTestSpecification.groovy index c7d3314b5b7..0a62db77821 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationProseTestSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationProseTestSpecification.groovy @@ -40,7 +40,11 @@ import static com.mongodb.ClusterFixture.isStandalone import static com.mongodb.internal.connection.ServerHelper.waitForLastRelease import static java.util.Arrays.asList -// See https://github.com/mongodb/specifications/tree/master/source/change-streams/tests/README.md#prose-tests +/** + * See Prose Tests. + *

+ * New tests should be added to {@link com.mongodb.client.ChangeStreamProseTest}. + */ @IgnoreIf({ isStandalone() }) class ChangeStreamOperationProseTestSpecification extends OperationFunctionalSpecification { diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamFunctionalTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamFunctionalTest.java deleted file mode 100644 index 3b204150019..00000000000 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamFunctionalTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed 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 com.mongodb.reactivestreams.client; - -import com.mongodb.MongoClientSettings; -import com.mongodb.client.AbstractChangeSteamFunctionalTest; -import com.mongodb.client.MongoClient; -import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient; - -public class ChangeStreamFunctionalTest extends AbstractChangeSteamFunctionalTest { - @Override - protected MongoClient createMongoClient(final MongoClientSettings mongoClientSettings) { - return new SyncMongoClient(mongoClientSettings); - } -} diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java new file mode 100644 index 00000000000..702c579609a --- /dev/null +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java @@ -0,0 +1,96 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed 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 com.mongodb.reactivestreams.client; + +import com.mongodb.MongoClientSettings; +import com.mongodb.client.MongoClient; +import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient.disableWaitForBatchCursorCreation; +import static com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient.enableWaitForBatchCursorCreation; + +/** + * Many of the tests from {@link com.mongodb.client.ChangeStreamProseTest} fail when run using {@link SyncMongoClient}, + * because it does not have all the necessary implementations. Such tests are disabled. + */ +final class ChangeStreamProseTest extends com.mongodb.client.ChangeStreamProseTest { + @BeforeEach + void beforeEach() { + enableWaitForBatchCursorCreation(); + } + + @AfterEach + void afterEach() { + disableWaitForBatchCursorCreation(); + } + + @Override + protected MongoClient createClient(final MongoClientSettings settings) { + return new SyncMongoClient(settings); + } + + @Test + @Disabled + @Override + protected void test07CursorNotClosed() { + } + + @Test + @Disabled + @Override + protected void test11GetResumeTokenReturnsPostBatchResumeToken() { + } + + @Test + @Disabled + @Override + protected void test13GetResumeTokenEqualsIdOfPreviousDocument() { + } + + @Test + @Disabled + @Override + protected void test14GetResumeTokenReturnsStartAfter() { + } + + @Test + @Disabled + @Override + protected void test14GetResumeTokenReturnsResumeAfter() { + } + + @Test + @Disabled + @Override + protected void test15GetResumeTokenReturnsPostBatchResumeTokenAfterGetMore() { + } + + @Test + @Disabled + @Override + protected void test19SplitChangeStreamEvents() { + } + + @Test + @Disabled + @Override + protected void testNameSpaceTypeAbsentChangeStreamEvents() { + } +} diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCursor.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCursor.java index 4e0159f90d0..1f2481421fe 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCursor.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCursor.java @@ -106,7 +106,6 @@ public void onComplete() { } if (isWaitForBatchCursorCreationEnabled()) { batchCursorCompletableFuture.get(TIMEOUT, TimeUnit.SECONDS); - Hooks.resetOnEachOperator(); } sleep(getSleepAfterCursorOpen()); } catch (InterruptedException e) { @@ -117,6 +116,10 @@ public void onComplete() { throw (RuntimeException) cause; } throw new RuntimeException(e); + } finally { + if (isWaitForBatchCursorCreationEnabled()) { + Hooks.resetOnEachOperator(); + } } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractChangeSteamFunctionalTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractChangeSteamFunctionalTest.java deleted file mode 100644 index b982f762f07..00000000000 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractChangeSteamFunctionalTest.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed 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 com.mongodb.client; - -import com.mongodb.ClusterFixture; -import com.mongodb.MongoClientSettings; -import com.mongodb.MongoNamespace; -import com.mongodb.client.model.changestream.ChangeStreamDocument; -import com.mongodb.client.test.CollectionHelper; -import org.bson.BsonDocument; -import org.bson.BsonTimestamp; -import org.bson.Document; -import org.bson.codecs.BsonDocumentCodec; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -import java.time.Instant; -import java.util.concurrent.atomic.AtomicInteger; - -import static com.mongodb.client.Fixture.getDefaultDatabaseName; -import static java.lang.String.format; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * The {@link ChangeStreamProseTest}, which is defined only for sync driver, should be migrated to this class. - * Once this done, this class should be renamed to ChangeStreamProseTest. - */ -public abstract class AbstractChangeSteamFunctionalTest { - - private static final String FAIL_COMMAND_NAME = "failCommand"; - private static final MongoNamespace NAMESPACE = new MongoNamespace(getDefaultDatabaseName(), "test"); - private final CollectionHelper collectionHelper = new CollectionHelper<>(new BsonDocumentCodec(), NAMESPACE); - - protected abstract MongoClient createMongoClient(MongoClientSettings mongoClientSettings); - - @Test - public void shouldDoOneServerSelectionForResumeAttempt() { - //given - assumeTrue(ClusterFixture.isDiscoverableReplicaSet()); - AtomicInteger serverSelectionCounter = new AtomicInteger(); - BsonTimestamp startTime = new BsonTimestamp((int) Instant.now().getEpochSecond(), 0); - try (MongoClient mongoClient = createMongoClient(Fixture.getMongoClientSettingsBuilder() - .applyToClusterSettings(builder -> builder.serverSelector(clusterDescription -> { - serverSelectionCounter.incrementAndGet(); - return clusterDescription.getServerDescriptions(); - })).build())) { - - MongoCollection collection = mongoClient - .getDatabase(NAMESPACE.getDatabaseName()) - .getCollection(NAMESPACE.getCollectionName()); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"" + FAIL_COMMAND_NAME + "\"," - + " mode: {" - + " times: 1" - + " }," - + " data: {" - + " failCommands: ['getMore']," - + " errorCode: 9001," - + " errorLabels: ['ResumableChangeStreamError']" - + " }" - + "}"); - // We insert document here, because async cursor performs aggregate and getMore right after we call cursor() - collection.insertOne(Document.parse("{ x: 1 }")); - serverSelectionCounter.set(0); - - try (MongoChangeStreamCursor> cursor = collection.watch() - .batchSize(0) - .startAtOperationTime(startTime) - .cursor()) { - - //when - ChangeStreamDocument changeStreamDocument = cursor.next(); - //then - assertNotNull(changeStreamDocument); - int actualCountOfServerSelections = serverSelectionCounter.get(); - assertEquals(2, actualCountOfServerSelections, - format("Expected 2 server selections (initial aggregate command + resume attempt aggregate command), but there were %s", - actualCountOfServerSelections)); - } - } - } - - @AfterEach - public void tearDown() throws InterruptedException { - ClusterFixture.disableFailPoint(FAIL_COMMAND_NAME); - collectionHelper.drop(); - } -} diff --git a/driver-sync/src/test/functional/com/mongodb/client/ChangeSteamFunctionalTest.java b/driver-sync/src/test/functional/com/mongodb/client/ChangeSteamFunctionalTest.java deleted file mode 100644 index c4ec6286ce2..00000000000 --- a/driver-sync/src/test/functional/com/mongodb/client/ChangeSteamFunctionalTest.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed 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 com.mongodb.client; - -import com.mongodb.MongoClientSettings; - -public class ChangeSteamFunctionalTest extends AbstractChangeSteamFunctionalTest { - - @Override - protected MongoClient createMongoClient(final MongoClientSettings mongoClientSettings) { - return MongoClients.create(mongoClientSettings); - } -} diff --git a/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamProseTest.java index 7273d4246e4..fc764a6642b 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamProseTest.java @@ -17,8 +17,10 @@ package com.mongodb.client; import com.mongodb.MongoChangeStreamException; +import com.mongodb.MongoClientSettings; import com.mongodb.MongoCommandException; import com.mongodb.MongoInterruptedException; +import com.mongodb.MongoNamespace; import com.mongodb.MongoQueryException; import com.mongodb.assertions.Assertions; import com.mongodb.client.internal.MongoChangeStreamCursorImpl; @@ -29,21 +31,31 @@ import com.mongodb.client.model.changestream.FullDocumentBeforeChange; import com.mongodb.client.model.changestream.SplitEvent; import com.mongodb.internal.operation.AggregateResponseBatchCursor; +import com.mongodb.internal.operation.ChangeStreamOperationProseTestSpecification; import org.bson.BsonArray; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.BsonString; +import org.bson.BsonTimestamp; import org.bson.Document; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.lang.reflect.Field; +import java.time.Instant; +import java.util.concurrent.atomic.AtomicInteger; import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; import static com.mongodb.ClusterFixture.serverVersionAtLeast; import static com.mongodb.client.CrudTestHelper.repeat; +import static com.mongodb.client.Fixture.getMongoClientSettings; +import static com.mongodb.client.Fixture.getMongoClientSettingsBuilder; +import static com.mongodb.client.Fixture.getPrimary; import static com.mongodb.client.model.Updates.set; -import static java.util.Arrays.asList; +import static java.lang.Math.toIntExact; +import static java.lang.String.format; +import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -52,17 +64,36 @@ import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeTrue; +/** + * See Prose Tests. + *

+ * See also {@link ChangeStreamOperationProseTestSpecification}. + */ +public class ChangeStreamProseTest { + private static final MongoNamespace NAMESPACE = new MongoNamespace(ChangeStreamProseTest.class.getSimpleName(), "test"); -// See https://github.com/mongodb/specifications/tree/master/source/change-streams/tests/README.md#prose-tests -public class ChangeStreamProseTest extends DatabaseTestCase { - private BsonDocument failPointDocument; + private MongoClient client; + private MongoDatabase database; + private MongoCollection collection; @BeforeEach - @Override - public void setUp() { + void beforeEach() { assumeTrue(canRunTests()); - super.setUp(); - collection.insertOne(Document.parse("{ _id : 0 }")); + client = createClient(getMongoClientSettings()); + database = client.getDatabase(NAMESPACE.getDatabaseName()); + database.drop(); + collection = database.getCollection(NAMESPACE.getCollectionName()); + } + + @AfterEach + void afterEach() { + if (client != null) { + client.close(); + } + } + + protected MongoClient createClient(final MongoClientSettings settings) { + return MongoClients.create(settings); } static class ChangeStreamWatcher implements Runnable { @@ -84,7 +115,7 @@ public void run() { } } - public boolean getInterruptedExceptionOccurred() { + boolean getInterruptedExceptionOccurred() { return interruptedExceptionOccurred; } } @@ -93,7 +124,7 @@ public boolean getInterruptedExceptionOccurred() { // Test that MongoInterruptedException is not retryable so that a thread can be interrupted. // @Test - public void testThreadInterrupted() throws InterruptedException { + void testThreadInterrupted() throws InterruptedException { ChangeStreamWatcher watcher = new ChangeStreamWatcher(collection.watch().cursor()); Thread t = new Thread(watcher); t.start(); @@ -106,7 +137,7 @@ public void testThreadInterrupted() throws InterruptedException { // Test that the ChangeStream continuously tracks the last seen resumeToken. // @Test - public void test01ChangeStreamTracksResumeToken() { + void test01ChangeStreamTracksResumeToken() { try (MongoCursor> cursor = collection.watch().iterator()) { collection.insertOne(Document.parse("{x: 1}")); @@ -124,8 +155,8 @@ public void test01ChangeStreamTracksResumeToken() { // Test that the ChangeStream will throw an exception if the server response is missing the resume token (if wire version is < 8). // @Test - public void test02MissingResumeTokenThrowsException() { - try (MongoCursor> cursor = collection.watch(asList(Aggregates.project(Document.parse("{ _id : 0 }")))) + void test02MissingResumeTokenThrowsException() { + try (MongoCursor> cursor = collection.watch(singletonList(Aggregates.project(Document.parse("{ _id : 0 }")))) .iterator()) { collection.insertOne(Document.parse("{ x: 1 }")); cursor.next(); @@ -139,13 +170,16 @@ public void test02MissingResumeTokenThrowsException() { // with the initial pipeline and options, except for the addition/update of a resumeToken. // @Test - public void test03ResumeOneTimeOnError() { - try (MongoChangeStreamCursor> cursor = collection.watch().cursor()) { + void test03ResumeOneTimeOnError() throws Exception { + BsonDocument configureFailPoint = new BsonDocument("configureFailPoint", new BsonString("failCommand")) + .append("mode", new BsonDocument("times", new BsonInt32(1))) + .append("data", new BsonDocument("failCommands", new BsonArray(singletonList(new BsonString("getMore")))) + .append("errorCode", new BsonInt32(10107)) + .append("errorLabels", new BsonArray(singletonList(new BsonString("ResumableChangeStreamError"))))); + try (FailPoint ignored = FailPoint.enable(configureFailPoint, getPrimary()); + MongoChangeStreamCursor> cursor = collection.watch().cursor()) { collection.insertOne(Document.parse("{ x: 1 }")); - setFailPoint("getMore", 10107); assertNotNull(cursor.next()); - } finally { - disableFailPoint(); } } @@ -153,13 +187,13 @@ public void test03ResumeOneTimeOnError() { // Test that ChangeStream will not attempt to resume on any error encountered while executing an aggregate command. // @Test - public void test04NoResumeForAggregateErrors() { + protected void test04NoResumeForAggregateErrors() { boolean exceptionFound = false; MongoChangeStreamCursor> cursor = null; //noinspection TryFinallyCanBeTryWithResources try { - cursor = collection.watch(asList(Document.parse("{ $unsupportedStage: { _id : 0 } }"))).cursor(); + cursor = collection.watch(singletonList(Document.parse("{ $unsupportedStage: { _id : 0 } }"))).cursor(); } catch (MongoCommandException e) { exceptionFound = true; } finally { @@ -175,7 +209,7 @@ public void test04NoResumeForAggregateErrors() { // is not closed on the driver side. // @Test - public void test07CursorNotClosed() { + protected void test07CursorNotClosed() { MongoCursor> cursor = collection.watch().iterator(); assertNotNull(cursor.getServerCursor()); cursor.close(); @@ -189,7 +223,7 @@ public void test07CursorNotClosed() { // getResumeToken must return the postBatchResumeToken from the current command response. // @Test - public void test11GetResumeTokenReturnsPostBatchResumeToken() throws NoSuchFieldException, IllegalAccessException { + protected void test11GetResumeTokenReturnsPostBatchResumeToken() throws NoSuchFieldException, IllegalAccessException { MongoChangeStreamCursor> cursor = collection.watch().cursor(); assertNull(cursor.getResumeToken()); collection.insertOne(Document.parse("{ _id: 42, x: 1 }")); @@ -212,7 +246,7 @@ public void test11GetResumeTokenReturnsPostBatchResumeToken() throws NoSuchField // getResumeToken must return the _id of the previous document returned. // @Test - public void test13GetResumeTokenEqualsIdOfPreviousDocument() { + protected void test13GetResumeTokenEqualsIdOfPreviousDocument() { try (MongoChangeStreamCursor> cursor = collection.watch().batchSize(3).cursor()) { collection.insertOne(Document.parse("{ _id: 42, x: 1 }")); collection.insertOne(Document.parse("{ _id: 43, x: 1 }")); @@ -232,7 +266,7 @@ public void test13GetResumeTokenEqualsIdOfPreviousDocument() { // If startAfter is not specified, the getResumeToken result must be empty. // @Test - public void test14GetResumeTokenReturnsStartAfter() { + protected void test14GetResumeTokenReturnsStartAfter() { BsonDocument resumeToken; MongoChangeStreamCursor> cursor = collection.watch().cursor(); collection.insertOne(Document.parse("{ _id: 42, x: 1 }")); @@ -268,7 +302,7 @@ public void test14GetResumeTokenReturnsStartAfter() { // If resumeAfter is not specified, the getResumeToken result must be empty. // @Test - public void test14GetResumeTokenReturnsResumeAfter() { + protected void test14GetResumeTokenReturnsResumeAfter() { BsonDocument resumeAfterResumeToken; MongoChangeStreamCursor> cursor = collection.watch().cursor(); collection.insertOne(Document.parse("{ _id: 42, x: 1 }")); @@ -304,7 +338,7 @@ public void test14GetResumeTokenReturnsResumeAfter() { // getResumeToken must return the postBatchResumeToken from the previous command response. // @Test - public void test15GetResumeTokenReturnsPostBatchResumeTokenAfterGetMore() + protected void test15GetResumeTokenReturnsPostBatchResumeTokenAfterGetMore() throws NoSuchFieldException, IllegalAccessException { try (MongoChangeStreamCursor> cursor = collection.watch().cursor()) { collection.insertOne(Document.parse("{ _id: 42, x: 1 }")); @@ -322,11 +356,11 @@ public void test15GetResumeTokenReturnsPostBatchResumeTokenAfterGetMore() } @Test - public void test19SplitChangeStreamEvents() { + protected void test19SplitChangeStreamEvents() { assumeTrue(serverVersionAtLeast(6, 0)); collection.drop(); database.createCollection( - getClass().getName(), + collection.getNamespace().getCollectionName(), new CreateCollectionOptions().changeStreamPreAndPostImagesOptions( new ChangeStreamPreAndPostImagesOptions(true))); @@ -337,7 +371,7 @@ public void test19SplitChangeStreamEvents() { // #. Create a change stream _S_ by calling ``watch`` on _C_ with // pipeline ``[{ "$changeStreamSplitLargeEvent": {} }]`` and ``fullDocumentBeforeChange=required``. ChangeStreamIterable changeStream = collection - .watch(asList(Document.parse("{ $changeStreamSplitLargeEvent: {} }"))) + .watch(singletonList(Document.parse("{ $changeStreamSplitLargeEvent: {} }"))) .fullDocumentBeforeChange(FullDocumentBeforeChange.REQUIRED); try (MongoChangeStreamCursor> cursor = changeStream.cursor()) { @@ -350,8 +384,8 @@ public void test19SplitChangeStreamEvents() { ChangeStreamDocument e2 = Assertions.assertNotNull(cursor.tryNext()); // #. Assert that the events collected have ``splitEvent`` fields ..., in that order. - assertEquals(e1.getSplitEvent(), new SplitEvent(1, 2)); - assertEquals(e2.getSplitEvent(), new SplitEvent(2, 2)); + assertEquals(new SplitEvent(1, 2), e1.getSplitEvent()); + assertEquals(new SplitEvent(2, 2), e2.getSplitEvent()); } } @@ -359,7 +393,7 @@ public void test19SplitChangeStreamEvents() { * Not a prose spec test. However, it is additional test case for better coverage. */ @Test - public void testNameSpaceTypeAbsentChangeStreamEvents() { + protected void testNameSpaceTypeAbsentChangeStreamEvents() { assumeTrue(serverVersionAtLeast(8, 1)); collection.drop(); @@ -378,17 +412,55 @@ public void testNameSpaceTypeAbsentChangeStreamEvents() { } } - private void setFailPoint(final String command, final int errCode) { - failPointDocument = new BsonDocument("configureFailPoint", new BsonString("failCommand")) - .append("mode", new BsonDocument("times", new BsonInt32(1))) - .append("data", new BsonDocument("failCommands", new BsonArray(asList(new BsonString(command)))) - .append("errorCode", new BsonInt32(errCode)) - .append("errorLabels", new BsonArray(asList(new BsonString("ResumableChangeStreamError"))))); - getCollectionHelper().runAdminCommand(failPointDocument); - } - - private void disableFailPoint() { - getCollectionHelper().runAdminCommand(failPointDocument.append("mode", new BsonString("off"))); + /** + * Not a prose spec test. + */ + @Test + void shouldDoOneServerSelectionForResumeAttempt() throws Exception { + //given + AtomicInteger serverSelectionCounter = new AtomicInteger(); + BsonTimestamp startTime = new BsonTimestamp(toIntExact(Instant.now().getEpochSecond()), 0); + try (MongoClient mongoClient = createClient(getMongoClientSettingsBuilder() + .applyToClusterSettings(builder -> builder.serverSelector(clusterDescription -> { + serverSelectionCounter.incrementAndGet(); + return clusterDescription.getServerDescriptions(); + })).build())) { + + MongoCollection collection = mongoClient + .getDatabase(NAMESPACE.getDatabaseName()) + .getCollection(NAMESPACE.getCollectionName()); + + BsonDocument configureFailPoint = BsonDocument.parse("{" + + " configureFailPoint: 'failCommand'," + + " mode: {" + + " times: 1" + + " }," + + " data: {" + + " failCommands: ['getMore']," + + " errorCode: 9001," + + " errorLabels: ['ResumableChangeStreamError']" + + " }" + + "}"); + // We insert document here, because async cursor performs aggregate and getMore right after we call cursor() + collection.insertOne(Document.parse("{ x: 1 }")); + serverSelectionCounter.set(0); + + try (FailPoint ignored = FailPoint.enable(configureFailPoint, getPrimary()); + MongoChangeStreamCursor> cursor = collection.watch() + .batchSize(0) + .startAtOperationTime(startTime) + .cursor()) { + + //when + ChangeStreamDocument changeStreamDocument = cursor.next(); + //then + assertNotNull(changeStreamDocument); + int actualCountOfServerSelections = serverSelectionCounter.get(); + assertEquals(2, actualCountOfServerSelections, + format("Expected 2 server selections (initial aggregate command + resume attempt aggregate command), but there were %s", + actualCountOfServerSelections)); + } + } } private boolean canRunTests() { From 208acd6824f5ee6da549c40a496b5bd37dd163f0 Mon Sep 17 00:00:00 2001 From: Valentin Kovalenko Date: Tue, 27 Oct 2026 00:44:49 -0600 Subject: [PATCH 02/11] JAVA-6351 Correctly handle batch size on `ChangeStreamIterable`/`ChangeStreamPublisher.withDocumentClass` JAVA-6351 --- .../client/internal/BatchCursorPublisher.java | 13 +--- .../internal/ChangeStreamPublisherImpl.java | 13 +++- .../client/ChangeStreamProseTest.java | 13 ++++ .../internal/ChangeStreamIterableImpl.java | 33 +++++++--- .../client/internal/MongoIterableImpl.java | 3 + .../mongodb/client/ChangeStreamProseTest.java | 61 +++++++++++++++++++ .../ChangeStreamIterableSpecification.groovy | 10 +-- 7 files changed, 120 insertions(+), 26 deletions(-) diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java index 1d68eb0e56a..6a869838529 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java @@ -42,20 +42,17 @@ @VisibleForTesting(otherwise = VisibleForTesting.AccessModifier.PROTECTED) public abstract class BatchCursorPublisher implements Publisher { + @Nullable private final ClientSession clientSession; private final MongoOperationPublisher mongoOperationPublisher; + @Nullable private Integer batchSize; + @Nullable private TimeoutMode timeoutMode; BatchCursorPublisher(@Nullable final ClientSession clientSession, final MongoOperationPublisher mongoOperationPublisher) { - this(clientSession, mongoOperationPublisher, null); - } - - BatchCursorPublisher(@Nullable final ClientSession clientSession, final MongoOperationPublisher mongoOperationPublisher, - @Nullable final Integer batchSize) { this.clientSession = clientSession; this.mongoOperationPublisher = notNull("mongoOperationPublisher", mongoOperationPublisher); - this.batchSize = batchSize; } abstract ReadOperationCursor asReadOperation(int initialBatchSize); @@ -90,10 +87,6 @@ CodecRegistry getCodecRegistry() { return mongoOperationPublisher.getCodecRegistry(); } - boolean getRetryReads() { - return mongoOperationPublisher.getRetryReads(); - } - Class getDocumentClass() { return mongoOperationPublisher.getDocumentClass(); } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java index b00dfb85952..d29d78214ea 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java @@ -134,8 +134,7 @@ public ChangeStreamPublisher collation(@Nullable final Collation collation) { @Override public Publisher withDocumentClass(final Class clazz) { - return new BatchCursorPublisher(getClientSession(), getMongoOperationPublisher().withDocumentClass(clazz), - getBatchSize()) { + return new BatchCursorPublisher(getClientSession(), getMongoOperationPublisher().withDocumentClass(clazz)) { @Override ReadOperationCursor asReadOperation(final int initialBatchSize) { return createChangeStreamOperation(getMongoOperationPublisher().getCodecRegistry().get(clazz), initialBatchSize); @@ -145,6 +144,16 @@ ReadOperationCursor asReadOperation(final int initialBatchSize) { Function, TimeoutSettings> getTimeoutSettings() { return (operations -> operations.createTimeoutSettings(0, maxAwaitTimeMS)); } + + @Nullable + @Override + public Integer getBatchSize() { + Integer batchSize = super.getBatchSize(); + if (batchSize == null) { + batchSize = ChangeStreamPublisherImpl.this.getBatchSize(); + } + return batchSize; + } }; } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java index 702c579609a..bd3d5d3cc49 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java @@ -17,6 +17,7 @@ import com.mongodb.MongoClientSettings; import com.mongodb.client.MongoClient; +import com.mongodb.reactivestreams.client.internal.BatchCursorPublisher; import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -93,4 +94,16 @@ protected void test19SplitChangeStreamEvents() { @Override protected void testNameSpaceTypeAbsentChangeStreamEvents() { } + + /** + * Not a prose spec test. + *

+ * {@link ChangeStreamPublisher#withDocumentClass(Class)} returns a new {@link BatchCursorPublisher}, + * which must handle batch size correctly. + */ + @Test + @Override + protected void batchSizeWorksForWithDocumentClass() { + super.batchSizeWorksForWithDocumentClass(); + } } diff --git a/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java index c0f9aaec8af..04b4c920667 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java @@ -47,6 +47,7 @@ import java.util.List; import java.util.concurrent.TimeUnit; +import static com.mongodb.assertions.Assertions.fail; import static com.mongodb.assertions.Assertions.notNull; /** @@ -139,19 +140,28 @@ public MongoCursor iterator() { @Override public MongoChangeStreamCursor cursor() { - return new MongoChangeStreamCursorImpl<>(execute(), codecRegistry.get(clazz), initialResumeToken()); + return new MongoChangeStreamCursorImpl<>(execute(getBatchSize()), codecRegistry.get(clazz), initialResumeToken()); } @Override public ReadOperationCursor asReadOperation() { - throw new UnsupportedOperationException(); + throw fail(); } @Override - protected OperationExecutor getExecutor() { return ChangeStreamIterableImpl.this.getExecutor(); } + + @Nullable + @Override + public Integer getBatchSize() { + Integer batchSize = super.getBatchSize(); + if (batchSize == null) { + batchSize = ChangeStreamIterableImpl.this.getBatchSize(); + } + return batchSize; + } }; } @@ -193,7 +203,7 @@ public MongoCursor> iterator() { @Override public MongoChangeStreamCursor> cursor() { - return new MongoChangeStreamCursorImpl<>(execute(), codec, initialResumeToken()); + return new MongoChangeStreamCursorImpl<>(execute(getBatchSize()), codec, initialResumeToken()); } @Nullable @@ -209,7 +219,7 @@ public ChangeStreamDocument first() { @Override public ReadOperationCursor> asReadOperation() { - throw new UnsupportedOperationException(); + throw fail(); } @@ -217,13 +227,18 @@ protected OperationExecutor getExecutor() { return getExecutor(operations.createTimeoutSettings(0, maxAwaitTimeMS)); } - private ReadOperationCursor createChangeStreamOperation() { + private ReadOperationCursor createChangeStreamOperation(@Nullable final Integer batchSize) { return operations.changeStream(fullDocument, fullDocumentBeforeChange, pipeline, new RawBsonDocumentCodec(), changeStreamLevel, - getBatchSize(), collation, comment, resumeToken, startAtOperationTime, startAfter, showExpandedEvents); + batchSize, collation, comment, resumeToken, startAtOperationTime, startAfter, showExpandedEvents); } - private BatchCursor execute() { - return getExecutor().execute(createChangeStreamOperation(), getReadPreference(), getReadConcern(), getClientSession()); + /** + * @param batchSize This parameter exists to allow both {@code this} {@link ChangeStreamIterableImpl}, + * and the {@link MongoIterable} created and returned by {@link withDocumentClass} + * to pass their own {@link #getBatchSize()}. + */ + private BatchCursor execute(@Nullable final Integer batchSize) { + return getExecutor().execute(createChangeStreamOperation(batchSize), getReadPreference(), getReadConcern(), getClientSession()); } private BsonDocument initialResumeToken() { diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java index b642f0f1189..c5d90cd6b56 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java @@ -39,13 +39,16 @@ *

This class is not part of the public API and may be removed or changed at any time

*/ public abstract class MongoIterableImpl implements MongoIterable { + @Nullable private final ClientSession clientSession; private final ReadConcern readConcern; private final OperationExecutor executor; private final ReadPreference readPreference; private final boolean retryReads; private final TimeoutSettings timeoutSettings; + @Nullable private Integer batchSize; + @Nullable private TimeoutMode timeoutMode; public MongoIterableImpl(@Nullable final ClientSession clientSession, final OperationExecutor executor, final ReadConcern readConcern, diff --git a/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamProseTest.java index fc764a6642b..fd9d11fd68f 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamProseTest.java @@ -29,7 +29,10 @@ import com.mongodb.client.model.CreateCollectionOptions; import com.mongodb.client.model.changestream.ChangeStreamDocument; import com.mongodb.client.model.changestream.FullDocumentBeforeChange; +import com.mongodb.client.model.changestream.OperationType; import com.mongodb.client.model.changestream.SplitEvent; +import com.mongodb.event.CommandStartedEvent; +import com.mongodb.internal.connection.TestCommandListener; import com.mongodb.internal.operation.AggregateResponseBatchCursor; import com.mongodb.internal.operation.ChangeStreamOperationProseTestSpecification; import org.bson.BsonArray; @@ -44,7 +47,9 @@ import java.lang.reflect.Field; import java.time.Instant; +import java.util.List; import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; import static com.mongodb.ClusterFixture.serverVersionAtLeast; @@ -55,7 +60,10 @@ import static com.mongodb.client.model.Updates.set; import static java.lang.Math.toIntExact; import static java.lang.String.format; +import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; +import static java.util.stream.Collectors.toList; +import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -463,6 +471,59 @@ void shouldDoOneServerSelectionForResumeAttempt() throws Exception { } } + /** + * Not a prose spec test. + *

+ * {@link ChangeStreamIterable#withDocumentClass(Class)} returns a new {@link MongoIterable}, + * which must handle batch size correctly. + */ + @Test + protected void batchSizeWorksForWithDocumentClass() { + assertAll( + () -> assertBatchSizeWorksForWithDocumentClass(true, true), + () -> assertBatchSizeWorksForWithDocumentClass(true, false), + () -> assertBatchSizeWorksForWithDocumentClass(false, true), + () -> assertBatchSizeWorksForWithDocumentClass(false, false)); + } + + private void assertBatchSizeWorksForWithDocumentClass(final boolean chaining, final boolean batchSizeBeforeWithDocumentClass) { + TestCommandListener commandListener = new TestCommandListener(singletonList("commandStartedEvent"), emptyList()); + try (MongoClient client = createClient(getMongoClientSettingsBuilder().addCommandListener(commandListener).build())) { + MongoCollection collection = client + .getDatabase(NAMESPACE.getDatabaseName()) + .getCollection(NAMESPACE.getCollectionName()); + int batchSize = 3; + int batchCount = 2; + ChangeStreamIterable changeStreamIterable = collection.watch(); + MongoIterable configuredChangeStreamIterable; + if (chaining) { + if (batchSizeBeforeWithDocumentClass) { + configuredChangeStreamIterable = changeStreamIterable.batchSize(batchSize).withDocumentClass(Document.class); + } else { + configuredChangeStreamIterable = changeStreamIterable.withDocumentClass(Document.class).batchSize(batchSize); + } + } else { + if (batchSizeBeforeWithDocumentClass) { + changeStreamIterable.batchSize(batchSize); + configuredChangeStreamIterable = changeStreamIterable.withDocumentClass(Document.class); + } else { + configuredChangeStreamIterable = changeStreamIterable.withDocumentClass(Document.class); + changeStreamIterable.batchSize(batchSize); + } + } + try (MongoCursor changeStreamCursor = configuredChangeStreamIterable.cursor()) { + List insertedDocuments = Stream.generate(Document::new).limit(batchSize * batchCount).collect(toList()); + collection.insertMany(insertedDocuments); + for (int i = 0; i < insertedDocuments.size(); i++) { + assertEquals(OperationType.INSERT.getValue(), changeStreamCursor.next().get("operationType")); + } + commandListener.getCommandStartedEvents("getMore").stream() + .map(CommandStartedEvent::getCommand) + .forEach(command -> assertEquals(batchSize, command.getInt32("batchSize").intValue())); + } + } + } + private boolean canRunTests() { return isDiscoverableReplicaSet(); } diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/ChangeStreamIterableSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/internal/ChangeStreamIterableSpecification.groovy index 9915f8109eb..1b961cf4318 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/ChangeStreamIterableSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/ChangeStreamIterableSpecification.groovy @@ -67,11 +67,11 @@ class ChangeStreamIterableSpecification extends Specification { changeStreamIterable.iterator() def codec = new RawBsonDocumentCodec() - def operation = executor.getReadOperation() as ChangeStreamOperation + def operation = executor.getReadOperation() as ChangeStreamOperation def readPreference = executor.getReadPreference() then: - expect operation, isTheSameAs(new ChangeStreamOperation(namespace, + expect operation, isTheSameAs(new ChangeStreamOperation(namespace, FullDocument.DEFAULT, FullDocumentBeforeChange.DEFAULT, [BsonDocument.parse('{$match: 1}')], codec, ChangeStreamLevel.COLLECTION, null) .retryReads(true)) @@ -87,10 +87,10 @@ class ChangeStreamIterableSpecification extends Specification { .resumeAfter(resumeToken).startAtOperationTime(startAtOperationTime) .startAfter(resumeToken).iterator() - operation = executor.getReadOperation() as ChangeStreamOperation + operation = executor.getReadOperation() as ChangeStreamOperation then: 'should use the overrides' - expect operation, isTheSameAs(new ChangeStreamOperation(namespace, + expect operation, isTheSameAs(new ChangeStreamOperation(namespace, FullDocument.UPDATE_LOOKUP, FullDocumentBeforeChange.WHEN_AVAILABLE, [BsonDocument.parse('{$match: 1}')], codec, ChangeStreamLevel.COLLECTION, null) .retryReads(true) @@ -169,7 +169,7 @@ class ChangeStreamIterableSpecification extends Specification { def results = mongoIterable.first() then: - results.getResumeToken().equals(cannedResults[0].getDocument('_id')) + results.getResumeToken() == cannedResults[0].getDocument('_id') when: mongoIterable.forEach(new Consumer>() { From e4a83851271ed92b24f575d170b964b99eb31ca3 Mon Sep 17 00:00:00 2001 From: Valentin Kovalenko Date: Fri, 30 Oct 2026 11:57:34 -0600 Subject: [PATCH 03/11] JAVA-5068 ListCollectionsIterable/Publisher JAVA-5068 --- .../client/ListCollectionNamesPublisher.java | 4 + .../client/ListCollectionsPublisher.java | 4 + .../ListCollectionNamesPublisherTest.java | 34 +++++++++ .../client/ListCollectionNamesIterable.java | 4 + .../client/ListCollectionsIterable.java | 4 + .../ListCollectionNamesIterableTest.java | 73 +++++++++++++++++++ 6 files changed, 123 insertions(+) create mode 100644 driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/ListCollectionNamesPublisherTest.java create mode 100644 driver-sync/src/test/unit/com/mongodb/client/ListCollectionNamesIterableTest.java diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionNamesPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionNamesPublisher.java index a28fcff1030..157ea8f3542 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionNamesPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionNamesPublisher.java @@ -29,6 +29,10 @@ * @since 5.0 * @mongodb.driver.manual reference/command/listCollections/ listCollections */ +/* + * This interface should declare almost the same set of methods as `ListCollectionsPublisher`. + * See `com.mongodb.reactivestreams.client.ListCollectionNamesPublisherTest`. + */ public interface ListCollectionNamesPublisher extends Publisher { /** * Sets the query filter to apply to the query. diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionsPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionsPublisher.java index 50808928172..d5e391d4f25 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionsPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionsPublisher.java @@ -33,6 +33,10 @@ * @since 1.0 * @mongodb.driver.manual reference/command/listCollections/ listCollections */ +/* + * This interface should declare almost the same set of methods as `ListCollectionNamesPublisher`. + * See `com.mongodb.reactivestreams.client.ListCollectionNamesPublisherTest`. + */ public interface ListCollectionsPublisher extends Publisher { /** diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/ListCollectionNamesPublisherTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/ListCollectionNamesPublisherTest.java new file mode 100644 index 00000000000..3139ed48025 --- /dev/null +++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/ListCollectionNamesPublisherTest.java @@ -0,0 +1,34 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed 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 com.mongodb.reactivestreams.client; + +import org.junit.jupiter.api.Test; + +import static com.mongodb.client.ListCollectionNamesIterableTest.EXPECTED_EXTRA_METHODS; +import static com.mongodb.client.ListCollectionNamesIterableTest.EXPECTED_MISSING_METHODS; +import static com.mongodb.client.ListCollectionNamesIterableTest.assertDeclaredMethodsMatch; + +final class ListCollectionNamesPublisherTest { + @Test + void declaredMethodsMatchListCollectionsPublisher() { + assertDeclaredMethodsMatch( + ListCollectionsPublisher.class, + EXPECTED_EXTRA_METHODS, + EXPECTED_MISSING_METHODS, + ListCollectionNamesPublisher.class); + } +} diff --git a/driver-sync/src/main/com/mongodb/client/ListCollectionNamesIterable.java b/driver-sync/src/main/com/mongodb/client/ListCollectionNamesIterable.java index 94cfd7c52e3..9c49465ec7e 100644 --- a/driver-sync/src/main/com/mongodb/client/ListCollectionNamesIterable.java +++ b/driver-sync/src/main/com/mongodb/client/ListCollectionNamesIterable.java @@ -28,6 +28,10 @@ * @since 5.0 * @mongodb.driver.manual reference/command/listCollections/ listCollections */ +/* + * This interface should declare almost the same set of methods as `ListCollectionsIterable`. + * See `com.mongodb.client.ListCollectionNamesIterableTest`. + */ public interface ListCollectionNamesIterable extends MongoIterable { /** * Sets the query filter to apply to the query. diff --git a/driver-sync/src/main/com/mongodb/client/ListCollectionsIterable.java b/driver-sync/src/main/com/mongodb/client/ListCollectionsIterable.java index 421fbcaa674..355033e7885 100644 --- a/driver-sync/src/main/com/mongodb/client/ListCollectionsIterable.java +++ b/driver-sync/src/main/com/mongodb/client/ListCollectionsIterable.java @@ -32,6 +32,10 @@ * @since 3.0 * @mongodb.driver.manual reference/command/listCollections/ listCollections */ +/* + * This interface should declare almost the same set of methods as `ListCollectionNamesIterable`. + * See `com.mongodb.client.ListCollectionNamesIterableTest`. + */ public interface ListCollectionsIterable extends MongoIterable { /** diff --git a/driver-sync/src/test/unit/com/mongodb/client/ListCollectionNamesIterableTest.java b/driver-sync/src/test/unit/com/mongodb/client/ListCollectionNamesIterableTest.java new file mode 100644 index 00000000000..309fdd1c466 --- /dev/null +++ b/driver-sync/src/test/unit/com/mongodb/client/ListCollectionNamesIterableTest.java @@ -0,0 +1,73 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed 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 com.mongodb.client; + +import org.junit.jupiter.api.Test; + +import java.util.Set; +import java.util.TreeSet; + +import static java.lang.String.format; +import static java.util.Arrays.stream; +import static java.util.Collections.singleton; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toCollection; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public final class ListCollectionNamesIterableTest { + public static final Set EXPECTED_EXTRA_METHODS = singleton("authorizedCollections(boolean)"); + public static final Set EXPECTED_MISSING_METHODS = singleton("timeoutMode(com.mongodb.client.cursor.TimeoutMode)"); + + @Test + void declaredMethodsMatchListCollectionsIterable() { + assertDeclaredMethodsMatch( + ListCollectionsIterable.class, + EXPECTED_EXTRA_METHODS, + EXPECTED_MISSING_METHODS, + ListCollectionNamesIterable.class); + } + + public static void assertDeclaredMethodsMatch( + final Class expectedClass, + final Set expectedExtraMethods, + final Set expectedMissingMethods, + final Class actualClass) { + Set expected = declaredMethodSignatures(expectedClass); + for (String expectedExtraMethod : expectedExtraMethods) { + assertFalse(expected.contains(expectedExtraMethod), + () -> format("%s declares %s, remove it from expected extra methods", expectedClass, expectedExtraMethod)); + } + for (String expectedMissingMethod : expectedMissingMethods) { + assertTrue(expected.contains(expectedMissingMethod), + () -> format("%s does not declare %s, remove it from expected missing methods", expectedClass, expectedMissingMethod)); + } + expected.addAll(expectedExtraMethods); + expected.removeAll(expectedMissingMethods); + assertEquals(expected, declaredMethodSignatures(actualClass)); + } + + private static Set declaredMethodSignatures(final Class klass) { + return stream(klass.getDeclaredMethods()) + .map(method -> stream(method.getParameterTypes()) + .map(Class::getTypeName) + .collect(joining(", ", method.getName() + "(", ")"))) + // `TreeSet` results in the alphabetic order of signatures in `toString`, improving assertion messages + .collect(toCollection(TreeSet::new)); + } +} From 81c3b36ff330af38a5ad1fbc426fa352e3aef18c Mon Sep 17 00:00:00 2001 From: Valentin Kovalenko Date: Mon, 2 Nov 2026 11:25:16 -0600 Subject: [PATCH 04/11] JAVA-5068 `MongoIterable` and cursor publisher JAVA-5068 --- .../internal/AggregatePublisherImpl.java | 3 +- .../internal/ChangeStreamPublisherImpl.java | 2 +- .../internal/DistinctPublisherImpl.java | 3 +- .../client/internal/FindPublisherImpl.java | 3 +- .../InternalCommonBatchCursorPublisher.java | 132 +++++++++++ .../ListCollectionNamesPublisherImpl.java | 2 +- .../ListCollectionsPublisherImpl.java | 3 +- .../internal/ListDatabasesPublisherImpl.java | 3 +- .../internal/ListIndexesPublisherImpl.java | 3 +- .../ListSearchIndexesPublisherImpl.java | 3 +- .../internal/MapReducePublisherImpl.java | 3 +- .../gridfs/GridFSFindPublisherImpl.java | 3 +- ...nternalCommonBatchCursorPublisherTest.java | 142 ++++++++++++ .../client/gridfs/GridFSFindIterableImpl.java | 3 +- .../internal/AggregateIterableImpl.java | 3 +- .../internal/ChangeStreamIterableImpl.java | 2 +- .../client/internal/DistinctIterableImpl.java | 3 +- .../client/internal/FindIterableImpl.java | 3 +- .../internal/InternalCommonIterable.java | 124 +++++++++++ .../ListCollectionNamesIterableImpl.java | 2 +- .../internal/ListCollectionsIterableImpl.java | 3 +- .../internal/ListDatabasesIterableImpl.java | 3 +- .../internal/ListIndexesIterableImpl.java | 3 +- .../ListSearchIndexesIterableImpl.java | 3 +- .../internal/MapReduceIterableImpl.java | 3 +- .../ListCollectionNamesIterableTest.java | 11 +- .../internal/InternalCommonIterableTest.java | 206 ++++++++++++++++++ .../MongoDatabaseSpecification.groovy | 3 +- 28 files changed, 654 insertions(+), 26 deletions(-) create mode 100644 driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisher.java create mode 100644 driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisherTest.java create mode 100644 driver-sync/src/main/com/mongodb/client/internal/InternalCommonIterable.java create mode 100644 driver-sync/src/test/unit/com/mongodb/client/internal/InternalCommonIterableTest.java diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java index e37f536a4f7..703985fed42 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java @@ -43,7 +43,8 @@ import static com.mongodb.assertions.Assertions.notNull; -final class AggregatePublisherImpl extends BatchCursorPublisher implements AggregatePublisher { +final class AggregatePublisherImpl extends BatchCursorPublisher + implements InternalCommonBatchCursorPublisher, AggregatePublisher { private final List pipeline; private final AggregationLevel aggregationLevel; private Boolean allowDiskUse; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java index d29d78214ea..e8fa3c84a2b 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java @@ -43,7 +43,7 @@ final class ChangeStreamPublisherImpl extends BatchCursorPublisher> - implements ChangeStreamPublisher { + implements InternalCommonBatchCursorPublisher>, ChangeStreamPublisher { private final List pipeline; private final Codec> codec; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/DistinctPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/DistinctPublisherImpl.java index e17b37bf959..ff62f2378b4 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/DistinctPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/DistinctPublisherImpl.java @@ -33,7 +33,8 @@ import static com.mongodb.assertions.Assertions.notNull; -final class DistinctPublisherImpl extends BatchCursorPublisher implements DistinctPublisher { +final class DistinctPublisherImpl extends BatchCursorPublisher + implements InternalCommonBatchCursorPublisher, DistinctPublisher { private final String fieldName; private Bson filter; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java index e223b9daea9..4256c252130 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java @@ -38,7 +38,8 @@ import static com.mongodb.assertions.Assertions.notNull; -final class FindPublisherImpl extends BatchCursorPublisher implements FindPublisher { +final class FindPublisherImpl extends BatchCursorPublisher + implements InternalCommonBatchCursorPublisher, FindPublisher { private final FindOptions findOptions; private Bson filter; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisher.java new file mode 100644 index 00000000000..76f78b38a74 --- /dev/null +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisher.java @@ -0,0 +1,132 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed 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 com.mongodb.reactivestreams.client.internal; + +import com.mongodb.ExplainVerbosity; +import com.mongodb.client.cursor.TimeoutMode; +import com.mongodb.client.model.Collation; +import com.mongodb.lang.Nullable; +import org.bson.BsonValue; +import org.bson.Document; +import org.bson.conversions.Bson; +import org.reactivestreams.Publisher; + +import java.util.concurrent.TimeUnit; + +import static com.mongodb.assertions.Assertions.fail; + +/** + * The purpose of this interface is to ensure that all cursor publisher API interfaces that share methods + * have the signatures of those methods the same, and to help a maintainer to see which methods are shared. + * See {@code com.mongodb.reactivestreams.client.internal.InternalCommonBatchCursorPublisherTest}. + * This is a reactive counterpart to {@code com.mongodb.client.internal.InternalCommonIterable}. + *

+ * This class is not part of the public API and may be removed or changed at any time. + */ +public interface InternalCommonBatchCursorPublisher extends Publisher { + default Publisher first() { + throw fail(); + } + + default Publisher batchSize(int batchSize) { + throw fail(); + } + + default Publisher timeoutMode(TimeoutMode timeoutMode) { + throw fail(); + } + + default Publisher toCollection() { + throw fail(); + } + + default Publisher filter(@Nullable Bson filter) { + throw fail(); + } + + default Publisher limit(int limit) { + throw fail(); + } + + default Publisher skip(int skip) { + throw fail(); + } + + default Publisher maxTime(long maxTime, TimeUnit timeUnit) { + throw fail(); + } + + default Publisher maxAwaitTime(long maxAwaitTime, TimeUnit timeUnit) { + throw fail(); + } + + default Publisher collation(@Nullable Collation collation) { + throw fail(); + } + + default Publisher sort(@Nullable Bson sort) { + throw fail(); + } + + default Publisher noCursorTimeout(boolean noCursorTimeout) { + throw fail(); + } + + default Publisher comment(@Nullable String comment) { + throw fail(); + } + + default Publisher comment(@Nullable BsonValue comment) { + throw fail(); + } + + default Publisher hint(@Nullable Bson hint) { + throw fail(); + } + + default Publisher hintString(@Nullable String hint) { + throw fail(); + } + + default Publisher let(@Nullable Bson variables) { + throw fail(); + } + + default Publisher allowDiskUse(@Nullable Boolean allowDiskUse) { + throw fail(); + } + + default Publisher explain() { + throw fail(); + } + + default Publisher explain(ExplainVerbosity verbosity) { + throw fail(); + } + + default Publisher explain(Class explainResultClass) { + throw fail(); + } + + default Publisher explain(Class explainResultClass, ExplainVerbosity verbosity) { + throw fail(); + } + + default Publisher bypassDocumentValidation(@Nullable Boolean bypassDocumentValidation) { + throw fail(); + } +} diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionNamesPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionNamesPublisherImpl.java index f07379d568c..17bc9bf4743 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionNamesPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionNamesPublisherImpl.java @@ -32,7 +32,7 @@ import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; -public final class ListCollectionNamesPublisherImpl implements ListCollectionNamesPublisher { +public final class ListCollectionNamesPublisherImpl implements InternalCommonBatchCursorPublisher, ListCollectionNamesPublisher { private final ListCollectionsPublisherImpl wrapped; private final Flux wrappedWithMapping; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionsPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionsPublisherImpl.java index 1f1e5f9d00a..f5920f7ead7 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionsPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionsPublisherImpl.java @@ -35,7 +35,8 @@ import static com.mongodb.assertions.Assertions.notNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; -final class ListCollectionsPublisherImpl extends BatchCursorPublisher implements ListCollectionsPublisher { +final class ListCollectionsPublisherImpl extends BatchCursorPublisher + implements InternalCommonBatchCursorPublisher, ListCollectionsPublisher { private final boolean collectionNamesOnly; private boolean authorizedCollections; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListDatabasesPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListDatabasesPublisherImpl.java index 5c7b408ef3f..39f30b1fe04 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListDatabasesPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListDatabasesPublisherImpl.java @@ -33,7 +33,8 @@ import static com.mongodb.assertions.Assertions.notNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; -final class ListDatabasesPublisherImpl extends BatchCursorPublisher implements ListDatabasesPublisher { +final class ListDatabasesPublisherImpl extends BatchCursorPublisher + implements InternalCommonBatchCursorPublisher, ListDatabasesPublisher { private long maxTimeMS; private Bson filter; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListIndexesPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListIndexesPublisherImpl.java index 851c56fcc54..8b193e93a59 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListIndexesPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListIndexesPublisherImpl.java @@ -32,7 +32,8 @@ import static com.mongodb.assertions.Assertions.notNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; -final class ListIndexesPublisherImpl extends BatchCursorPublisher implements ListIndexesPublisher { +final class ListIndexesPublisherImpl extends BatchCursorPublisher + implements InternalCommonBatchCursorPublisher, ListIndexesPublisher { private long maxTimeMS; private BsonValue comment; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListSearchIndexesPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListSearchIndexesPublisherImpl.java index c4c703e9774..456ee3ce72e 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListSearchIndexesPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListSearchIndexesPublisherImpl.java @@ -34,7 +34,8 @@ import static com.mongodb.assertions.Assertions.notNull; -final class ListSearchIndexesPublisherImpl extends BatchCursorPublisher implements ListSearchIndexesPublisher { +final class ListSearchIndexesPublisherImpl extends BatchCursorPublisher + implements InternalCommonBatchCursorPublisher, ListSearchIndexesPublisher { @Nullable private Boolean allowDiskUse; private long maxTimeMS; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java index 1e8e7fa223b..fdc3fc82964 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java @@ -48,7 +48,8 @@ import static com.mongodb.assertions.Assertions.notNull; @SuppressWarnings("deprecation") -final class MapReducePublisherImpl extends BatchCursorPublisher implements com.mongodb.reactivestreams.client.MapReducePublisher { +final class MapReducePublisherImpl extends BatchCursorPublisher + implements InternalCommonBatchCursorPublisher, com.mongodb.reactivestreams.client.MapReducePublisher { private final String mapFunction; private final String reduceFunction; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSFindPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSFindPublisherImpl.java index 41ee872c05e..47c4d24a957 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSFindPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSFindPublisherImpl.java @@ -21,6 +21,7 @@ import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.FindPublisher; import com.mongodb.reactivestreams.client.gridfs.GridFSFindPublisher; +import com.mongodb.reactivestreams.client.internal.InternalCommonBatchCursorPublisher; import org.bson.conversions.Bson; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; @@ -32,7 +33,7 @@ /** *

This class is not part of the public API and may be removed or changed at any time

*/ -public final class GridFSFindPublisherImpl implements GridFSFindPublisher { +public final class GridFSFindPublisherImpl implements InternalCommonBatchCursorPublisher, GridFSFindPublisher { private final FindPublisher wrapped; GridFSFindPublisherImpl(final FindPublisher wrapped) { diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisherTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisherTest.java new file mode 100644 index 00000000000..cc9fd7275cc --- /dev/null +++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisherTest.java @@ -0,0 +1,142 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed 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 com.mongodb.reactivestreams.client.internal; + +import com.mongodb.client.ListCollectionNamesIterableTest; +import com.mongodb.client.internal.InternalCommonIterableTest; +import com.mongodb.reactivestreams.client.AggregatePublisher; +import com.mongodb.reactivestreams.client.ChangeStreamPublisher; +import com.mongodb.reactivestreams.client.DistinctPublisher; +import com.mongodb.reactivestreams.client.FindPublisher; +import com.mongodb.reactivestreams.client.ListCollectionNamesPublisher; +import com.mongodb.reactivestreams.client.ListCollectionsPublisher; +import com.mongodb.reactivestreams.client.ListDatabasesPublisher; +import com.mongodb.reactivestreams.client.ListIndexesPublisher; +import com.mongodb.reactivestreams.client.ListSearchIndexesPublisher; +import com.mongodb.reactivestreams.client.gridfs.GridFSFindPublisher; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.reactivestreams.Publisher; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Stream; + +import static com.mongodb.client.internal.InternalCommonIterableTest.IS_PUBLIC_API; +import static com.mongodb.client.internal.InternalCommonIterableTest.assertEachApiInterfaceImplMustImplementInternalCommonInterface; +import static com.mongodb.client.internal.InternalCommonIterableTest.assertEachApiInterfaceMethodSharedWithAnotherApiInterfaceMustBeInInternalCommonInterface; +import static com.mongodb.client.internal.InternalCommonIterableTest.assertEachInternalCommonInterfaceMethodMustBeInAtLeastTwoApiInterfaces; +import static com.mongodb.client.internal.InternalCommonIterableTest.findClasses; +import static com.mongodb.client.internal.InternalCommonIterableTest.methodSignatures; +import static java.util.Arrays.stream; +import static java.util.Comparator.comparing; +import static java.util.stream.Collectors.toCollection; +import static org.junit.jupiter.api.Assertions.assertEquals; + +final class InternalCommonBatchCursorPublisherTest { + /** + * The relevant cursor publisher API interfaces. Implementations of most, but not all of them extend {@link BatchCursorPublisher}. + */ + @SuppressWarnings("deprecation") + private static final Set> API_INTERFACES = Stream.of( + AggregatePublisher.class, + ChangeStreamPublisher.class, + DistinctPublisher.class, + FindPublisher.class, + ListCollectionsPublisher.class, + ListCollectionNamesPublisher.class, + ListDatabasesPublisher.class, + ListIndexesPublisher.class, + ListSearchIndexesPublisher.class, + com.mongodb.reactivestreams.client.MapReducePublisher.class, + GridFSFindPublisher.class). + collect(toCollection(() -> new TreeSet<>(comparing(Class::getName)))); + private static Path codeSourcePath; + + @BeforeAll + static void beforeAll() throws Exception { + codeSourcePath = Paths.get(BatchCursorPublisher.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + } + + /** + * The relevant cursor publisher API interfaces must be listed explicitly in {@link #API_INTERFACES}. + *

+ * An interface is relevant if all the following is true: + *

    + *
  1. + * it is {@code public};
  2. + *
  3. + * it is not in an internal package;
  4. + *
  5. + * it is subinterface of {@link Publisher}, but not {@link Publisher} itself;
  6. + *
  7. + * it has a {@code public} method with the signature of a {@code public} method in {@link BatchCursorPublisher}, + * excluding the {@link Publisher} and {@link Object} methods.
  8. + *
+ */ + @Test + void relevantApiInterfacesAreListedExplicitly() { + Set publisherMethodSignatures = methodSignatures(Publisher.class); + Set objectMethodSignatures = methodSignatures(Object.class); + Set cursorPublisherMarkingMethods = stream(BatchCursorPublisher.class.getMethods()) + .map(ListCollectionNamesIterableTest::signature) + .filter(signature -> !publisherMethodSignatures.contains(signature) && !objectMethodSignatures.contains(signature)) + .collect(toCollection(TreeSet::new)); + assertEquals(API_INTERFACES, findClasses(codeSourcePath, IS_PUBLIC_API + .and(klass -> klass.isInterface()) + .and(klass -> Publisher.class.isAssignableFrom(klass)) + .and(klass -> methodSignatures(klass).stream().anyMatch(cursorPublisherMarkingMethods::contains))), + "Either the explicit set of relevant interfaces or the code detecting them must be updated"); + } + + @Test + void relevantApiInterfacesMatchTheSyncInterfaces() { + Set expectedApiInterfaceSimpleNames = InternalCommonIterableTest.API_INTERFACES.stream() + .map(Class::getSimpleName) + .map(syncApiInterfaceName -> syncApiInterfaceName.substring(0, syncApiInterfaceName.length() - "Iterable".length()) + "Publisher") + .collect(toCollection(TreeSet::new)); + Set actualApiInterfaceSimpleNames = API_INTERFACES.stream().map(Class::getSimpleName).collect(toCollection(TreeSet::new)); + assertEquals(expectedApiInterfaceSimpleNames, actualApiInterfaceSimpleNames, + "The explicit set of relevant reactive interfaces must match that of the synchronous ones"); + } + + /** + * Each cursor publisher API interface implementation must implement {@link InternalCommonBatchCursorPublisher}. + */ + @Test + void eachApiInterfaceImplMustImplementInternalCommonBatchCursorPublisher() { + assertEachApiInterfaceImplMustImplementInternalCommonInterface(codeSourcePath, API_INTERFACES, InternalCommonBatchCursorPublisher.class); + } + + /** + * Each {@link InternalCommonBatchCursorPublisher} method must be in at least two cursor publisher API interfaces. + */ + @Test + void eachInternalCommonBatchCursorPublisherMethodMustBeInAtLeastTwoApiInterfaces() { + assertEachInternalCommonInterfaceMethodMustBeInAtLeastTwoApiInterfaces(API_INTERFACES, InternalCommonBatchCursorPublisher.class); + } + + /** + * Each cursor publisher API interface method shared with another cursor publisher API interface must be in {@link InternalCommonBatchCursorPublisher}. + */ + @Test + void eachApiInterfaceMethodSharedWithAnotherApiInterfaceMustBeInInternalCommonBatchCursorPublisher() { + assertEachApiInterfaceMethodSharedWithAnotherApiInterfaceMustBeInInternalCommonInterface(API_INTERFACES, InternalCommonBatchCursorPublisher.class); + } +} diff --git a/driver-sync/src/main/com/mongodb/client/gridfs/GridFSFindIterableImpl.java b/driver-sync/src/main/com/mongodb/client/gridfs/GridFSFindIterableImpl.java index 80bfb498e12..b570c56ab26 100644 --- a/driver-sync/src/main/com/mongodb/client/gridfs/GridFSFindIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/gridfs/GridFSFindIterableImpl.java @@ -21,6 +21,7 @@ import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoIterable; import com.mongodb.client.gridfs.model.GridFSFile; +import com.mongodb.client.internal.InternalCommonIterable; import com.mongodb.client.model.Collation; import com.mongodb.lang.Nullable; import org.bson.conversions.Bson; @@ -29,7 +30,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; -class GridFSFindIterableImpl implements GridFSFindIterable { +class GridFSFindIterableImpl implements InternalCommonIterable, GridFSFindIterable { private final FindIterable underlying; GridFSFindIterableImpl(final FindIterable underlying) { diff --git a/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java index 841d2532312..f7077c59285 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java @@ -44,7 +44,8 @@ import static com.mongodb.assertions.Assertions.notNull; -class AggregateIterableImpl extends MongoIterableImpl implements AggregateIterable { +class AggregateIterableImpl extends MongoIterableImpl + implements InternalCommonIterable, AggregateIterable { private final Operations operations; private final MongoNamespace namespace; private final Class documentClass; diff --git a/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java index 04b4c920667..824104797e0 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java @@ -54,7 +54,7 @@ *

This class is not part of the public API and may be removed or changed at any time

*/ public class ChangeStreamIterableImpl extends MongoIterableImpl> - implements ChangeStreamIterable { + implements InternalCommonIterable>, ChangeStreamIterable { private final CodecRegistry codecRegistry; private final List pipeline; private final Codec> codec; diff --git a/driver-sync/src/main/com/mongodb/client/internal/DistinctIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/DistinctIterableImpl.java index 5108d1849e4..5e7837b5795 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/DistinctIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/DistinctIterableImpl.java @@ -36,7 +36,8 @@ import static com.mongodb.assertions.Assertions.notNull; -class DistinctIterableImpl extends MongoIterableImpl implements DistinctIterable { +class DistinctIterableImpl extends MongoIterableImpl + implements InternalCommonIterable, DistinctIterable { private final Operations operations; private final Class resultClass; diff --git a/driver-sync/src/main/com/mongodb/client/internal/FindIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/FindIterableImpl.java index 5524ca8c145..ba0cf0d1629 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/FindIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/FindIterableImpl.java @@ -43,7 +43,8 @@ /** * This class is not part of the public API and may be removed or changed at any time. */ -public class FindIterableImpl extends MongoIterableImpl implements FindIterable { +public class FindIterableImpl extends MongoIterableImpl + implements InternalCommonIterable, FindIterable { private final Operations operations; diff --git a/driver-sync/src/main/com/mongodb/client/internal/InternalCommonIterable.java b/driver-sync/src/main/com/mongodb/client/internal/InternalCommonIterable.java new file mode 100644 index 00000000000..f1279a1a4ca --- /dev/null +++ b/driver-sync/src/main/com/mongodb/client/internal/InternalCommonIterable.java @@ -0,0 +1,124 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed 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 com.mongodb.client.internal; + +import com.mongodb.ExplainVerbosity; +import com.mongodb.client.MongoIterable; +import com.mongodb.client.cursor.TimeoutMode; +import com.mongodb.client.model.Collation; +import com.mongodb.lang.Nullable; +import org.bson.BsonValue; +import org.bson.Document; +import org.bson.conversions.Bson; + +import java.util.concurrent.TimeUnit; + +import static com.mongodb.assertions.Assertions.fail; + +/** + * The purpose of this interface is to ensure that all iterable API interfaces that share methods + * have the signatures of those methods the same, and to help a maintainer to see which methods are shared. + * See {@code com.mongodb.client.internal.InternalCommonIterableTest}. + * This is a synchronous counterpart to {@code com.mongodb.reactivestreams.client.internal.InternalCommonBatchCursorPublisher}. + *

+ * This class is not part of the public API and may be removed or changed at any time. + */ +public interface InternalCommonIterable extends MongoIterable { + default MongoIterable timeoutMode(TimeoutMode timeoutMode) { + throw fail(); + } + + default void toCollection() { + fail(); + } + + default MongoIterable filter(@Nullable Bson filter) { + throw fail(); + } + + default MongoIterable limit(int limit) { + throw fail(); + } + + default MongoIterable skip(int skip) { + throw fail(); + } + + default MongoIterable maxTime(long maxTime, TimeUnit timeUnit) { + throw fail(); + } + + default MongoIterable maxAwaitTime(long maxAwaitTime, TimeUnit timeUnit) { + throw fail(); + } + + default MongoIterable collation(@Nullable Collation collation) { + throw fail(); + } + + default MongoIterable sort(@Nullable Bson sort) { + throw fail(); + } + + default MongoIterable noCursorTimeout(boolean noCursorTimeout) { + throw fail(); + } + + default MongoIterable comment(@Nullable String comment) { + throw fail(); + } + + default MongoIterable comment(@Nullable BsonValue comment) { + throw fail(); + } + + default MongoIterable hint(@Nullable Bson hint) { + throw fail(); + } + + default MongoIterable hintString(@Nullable String hint) { + throw fail(); + } + + default MongoIterable let(@Nullable Bson variables) { + throw fail(); + } + + default MongoIterable allowDiskUse(@Nullable Boolean allowDiskUse) { + throw fail(); + } + + default Document explain() { + throw fail(); + } + + default Document explain(ExplainVerbosity verbosity) { + throw fail(); + } + + default E explain(Class explainResultClass) { + throw fail(); + } + + default E explain(Class explainResultClass, ExplainVerbosity verbosity) { + throw fail(); + } + + default MongoIterable bypassDocumentValidation(@Nullable Boolean bypassDocumentValidation) { + throw fail(); + } +} diff --git a/driver-sync/src/main/com/mongodb/client/internal/ListCollectionNamesIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ListCollectionNamesIterableImpl.java index aabdcd8e7a7..33e7f57debe 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ListCollectionNamesIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ListCollectionNamesIterableImpl.java @@ -32,7 +32,7 @@ import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; -final class ListCollectionNamesIterableImpl implements ListCollectionNamesIterable { +final class ListCollectionNamesIterableImpl implements InternalCommonIterable, ListCollectionNamesIterable { private final ListCollectionsIterableImpl wrapped; private final MongoIterable wrappedWithMapping; diff --git a/driver-sync/src/main/com/mongodb/client/internal/ListCollectionsIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ListCollectionsIterableImpl.java index 8e9a7b9e04d..d162ec2a714 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ListCollectionsIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ListCollectionsIterableImpl.java @@ -37,7 +37,8 @@ import static com.mongodb.assertions.Assertions.notNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; -class ListCollectionsIterableImpl extends MongoIterableImpl implements ListCollectionsIterable { +class ListCollectionsIterableImpl extends MongoIterableImpl + implements InternalCommonIterable, ListCollectionsIterable { private final Operations operations; private final String databaseName; private final Class resultClass; diff --git a/driver-sync/src/main/com/mongodb/client/internal/ListDatabasesIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ListDatabasesIterableImpl.java index 8b57e02ed0a..54d9128d3cb 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ListDatabasesIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ListDatabasesIterableImpl.java @@ -39,7 +39,8 @@ /** *

This class is not part of the public API and may be removed or changed at any time

*/ -public class ListDatabasesIterableImpl extends MongoIterableImpl implements ListDatabasesIterable { +public class ListDatabasesIterableImpl extends MongoIterableImpl + implements InternalCommonIterable, ListDatabasesIterable { private final Operations operations; private final Class resultClass; diff --git a/driver-sync/src/main/com/mongodb/client/internal/ListIndexesIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ListIndexesIterableImpl.java index ae69b1c9fe6..03a57f6fc5a 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ListIndexesIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ListIndexesIterableImpl.java @@ -36,7 +36,8 @@ import static com.mongodb.assertions.Assertions.notNull; import static java.util.concurrent.TimeUnit.MILLISECONDS; -class ListIndexesIterableImpl extends MongoIterableImpl implements ListIndexesIterable { +class ListIndexesIterableImpl extends MongoIterableImpl + implements InternalCommonIterable, ListIndexesIterable { private final Operations operations; private final Class resultClass; private long maxTimeMS; diff --git a/driver-sync/src/main/com/mongodb/client/internal/ListSearchIndexesIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ListSearchIndexesIterableImpl.java index 13fd7e71ba8..dbfbb1d54de 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ListSearchIndexesIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ListSearchIndexesIterableImpl.java @@ -38,7 +38,8 @@ import static com.mongodb.assertions.Assertions.notNull; -final class ListSearchIndexesIterableImpl extends MongoIterableImpl implements ListSearchIndexesIterable { +final class ListSearchIndexesIterableImpl extends MongoIterableImpl + implements InternalCommonIterable, ListSearchIndexesIterable { private final Operations operations; private final Class resultClass; @Nullable diff --git a/driver-sync/src/main/com/mongodb/client/internal/MapReduceIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MapReduceIterableImpl.java index 66a712b0054..8b3ed7b69c1 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MapReduceIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MapReduceIterableImpl.java @@ -47,7 +47,8 @@ import static com.mongodb.assertions.Assertions.notNull; @SuppressWarnings("deprecation") -class MapReduceIterableImpl extends MongoIterableImpl implements com.mongodb.client.MapReduceIterable { +class MapReduceIterableImpl extends MongoIterableImpl + implements InternalCommonIterable, com.mongodb.client.MapReduceIterable { private final Operations operations; private final MongoNamespace namespace; private final Class resultClass; diff --git a/driver-sync/src/test/unit/com/mongodb/client/ListCollectionNamesIterableTest.java b/driver-sync/src/test/unit/com/mongodb/client/ListCollectionNamesIterableTest.java index 309fdd1c466..fd423f1565e 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/ListCollectionNamesIterableTest.java +++ b/driver-sync/src/test/unit/com/mongodb/client/ListCollectionNamesIterableTest.java @@ -18,6 +18,7 @@ import org.junit.jupiter.api.Test; +import java.lang.reflect.Method; import java.util.Set; import java.util.TreeSet; @@ -64,10 +65,14 @@ public static void assertDeclaredMethodsMatch( private static Set declaredMethodSignatures(final Class klass) { return stream(klass.getDeclaredMethods()) - .map(method -> stream(method.getParameterTypes()) - .map(Class::getTypeName) - .collect(joining(", ", method.getName() + "(", ")"))) + .map(ListCollectionNamesIterableTest::signature) // `TreeSet` results in the alphabetic order of signatures in `toString`, improving assertion messages .collect(toCollection(TreeSet::new)); } + + public static String signature(final Method method) { + return stream(method.getParameterTypes()) + .map(Class::getTypeName) + .collect(joining(", ", method.getName() + "(", ")")); + } } diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/InternalCommonIterableTest.java b/driver-sync/src/test/unit/com/mongodb/client/internal/InternalCommonIterableTest.java new file mode 100644 index 00000000000..33e3690a755 --- /dev/null +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/InternalCommonIterableTest.java @@ -0,0 +1,206 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed 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 com.mongodb.client.internal; + +import com.mongodb.client.AggregateIterable; +import com.mongodb.client.ChangeStreamIterable; +import com.mongodb.client.DistinctIterable; +import com.mongodb.client.FindIterable; +import com.mongodb.client.ListCollectionNamesIterable; +import com.mongodb.client.ListCollectionNamesIterableTest; +import com.mongodb.client.ListCollectionsIterable; +import com.mongodb.client.ListDatabasesIterable; +import com.mongodb.client.ListIndexesIterable; +import com.mongodb.client.ListSearchIndexesIterable; +import com.mongodb.client.MongoIterable; +import com.mongodb.client.gridfs.GridFSFindIterable; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.lang.reflect.Modifier; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Predicate; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +import static java.lang.String.format; +import static java.nio.file.Files.isDirectory; +import static java.util.Arrays.asList; +import static java.util.Arrays.stream; +import static java.util.Comparator.comparing; +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toCollection; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public final class InternalCommonIterableTest { + /** + * The relevant iterable API interfaces. They are all subinterfaces of {@link MongoIterable}. + */ + @SuppressWarnings("deprecation") + public static final Set> API_INTERFACES = Stream.of( + AggregateIterable.class, + ChangeStreamIterable.class, + DistinctIterable.class, + FindIterable.class, + ListCollectionsIterable.class, + ListCollectionNamesIterable.class, + ListDatabasesIterable.class, + ListIndexesIterable.class, + ListSearchIndexesIterable.class, + com.mongodb.client.MapReduceIterable.class, + GridFSFindIterable.class). + collect(toCollection(() -> new TreeSet<>(comparing(Class::getName)))); + public static final Predicate> IS_PUBLIC_API = klass -> Modifier.isPublic(klass.getModifiers()) + && !asList(klass.getPackage().getName().split("\\.")).contains("internal"); + private static final ClassLoader CLASS_LOADER = MongoIterable.class.getClassLoader(); + private static Path codeSourcePath; + + @BeforeAll + static void beforeAll() throws Exception { + codeSourcePath = Paths.get(MongoIterable.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + } + + /** + * The relevant iterable API interfaces must be listed explicitly in {@link #API_INTERFACES}. + *

+ * An interface is relevant if all the following is true: + *

    + *
  1. + * it is {@code public};
  2. + *
  3. + * it is not in an internal package;
  4. + *
  5. + * it is subinterface of {@link MongoIterable}, but not {@link MongoIterable} itself.
  6. + *
+ */ + @Test + void relevantApiInterfacesAreListedExplicitly() { + assertEquals(API_INTERFACES, findClasses(codeSourcePath, IS_PUBLIC_API + .and(klass -> klass.isInterface()) + .and(klass -> MongoIterable.class.isAssignableFrom(klass)) + .and(klass -> !klass.equals(MongoIterable.class))), + "Either the explicit set of relevant interfaces or the code detecting them must be updated"); + } + + /** + * Each iterable API interface implementation must implement {@link InternalCommonIterable}. + */ + @Test + void eachApiInterfaceImplMustImplementInternalCommonIterable() { + assertEachApiInterfaceImplMustImplementInternalCommonInterface(codeSourcePath, API_INTERFACES, InternalCommonIterable.class); + } + + public static void assertEachApiInterfaceImplMustImplementInternalCommonInterface( + final Path codeSourceDirectory, final Set> apiInterfaces, final Class internalCommonInterface) { + Predicate> isImplClass = klass -> !klass.isInterface() + && apiInterfaces.stream().anyMatch(apiInterface -> apiInterface.isAssignableFrom(klass)); + Set> implClasses = findClasses(codeSourceDirectory, isImplClass); + apiInterfaces.forEach(apiInterface -> assertTrue( + implClasses.stream().anyMatch(implClass -> apiInterface.isAssignableFrom(implClass)), + () -> format("No implementing classes were found for %s", apiInterface))); + implClasses.forEach(implClass -> + assertTrue(internalCommonInterface.isAssignableFrom(implClass), () -> + format("%s implementing an API interface must implement %s", implClass, internalCommonInterface))); + } + + /** + * Each {@link InternalCommonIterable} method must be in at least two iterable API interfaces. + */ + @Test + void eachInternalCommonIterableMethodMustBeInAtLeastTwoApiInterfaces() { + assertEachInternalCommonInterfaceMethodMustBeInAtLeastTwoApiInterfaces(API_INTERFACES, InternalCommonIterable.class); + } + + public static void assertEachInternalCommonInterfaceMethodMustBeInAtLeastTwoApiInterfaces( + final Set> apiInterfaces, final Class internalCommonInterface) { + methodSignatures(internalCommonInterface).forEach(method -> { + Set> apiInterfacesWithMethod = apiInterfaces.stream() + .filter(apiInterface -> methodSignatures(apiInterface).contains(method)) + .collect(toCollection(() -> new TreeSet<>(comparing(Class::getName)))); + assertTrue(apiInterfacesWithMethod.size() >= 2, () -> + format("Method %s is in %d API interfaces %s, remove the method from %s", + method, apiInterfacesWithMethod.size(), apiInterfacesWithMethod, internalCommonInterface)); + }); + } + + /** + * Each iterable API interface method shared with another iterable API interface must be in {@link InternalCommonIterable}. + */ + @Test + void eachApiInterfaceMethodSharedWithAnotherApiInterfaceMustBeInInternalCommonIterable() { + assertEachApiInterfaceMethodSharedWithAnotherApiInterfaceMustBeInInternalCommonInterface(API_INTERFACES, + InternalCommonIterable.class); + } + + public static void assertEachApiInterfaceMethodSharedWithAnotherApiInterfaceMustBeInInternalCommonInterface( + final Set> apiInterfaces, final Class internalCommonInterface) { + Set expectedMethods = methodSignatures(internalCommonInterface); + apiInterfaces.forEach(apiInterface -> { + methodSignatures(apiInterface).forEach(method -> { + Set> apiInterfacesWithMethod = apiInterfaces.stream() + .filter(maybeSameApiInterface -> methodSignatures(maybeSameApiInterface).contains(method)) + .collect(toCollection(() -> new TreeSet<>(comparing(Class::getName)))); + if (apiInterfacesWithMethod.size() >= 2) { + assertTrue(expectedMethods.contains(method), () -> + format("Method %s is in multiple API interfaces %s, add the method to %s", + method, apiInterfacesWithMethod, internalCommonInterface)); + } + }); + }); + } + + public static Set> findClasses(final Path codeSourceDirectory, final Predicate> filter) { + com.mongodb.assertions.Assertions.assertTrue(isDirectory(codeSourceDirectory), format("%s is not a directory", codeSourceDirectory)); + try (Stream paths = Files.walk(codeSourceDirectory)) { + return paths.filter(path -> path.getFileName().toString().endsWith(".class")) + .filter(pathOfClass -> + !pathOfClass.getFileName().equals(Paths.get("package-info.class")) + && !pathOfClass.getFileName().equals(Paths.get("module-info.class"))) + .map(pathOfClass -> codeSourceDirectory.relativize(pathOfClass)) + .map(relativePathOfClass -> { + String dottedPath = StreamSupport.stream(relativePathOfClass.spliterator(), false) + .map(Path::toString) + .collect(joining(".")); + return dottedPath.substring(0, dottedPath.length() - ".class".length()); + }) + .map(classBinaryName -> { + try { + return Class.forName(classBinaryName, false, CLASS_LOADER); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } + }) + .filter(filter) + .collect(toCollection(() -> new TreeSet<>(comparing(Class::getName)))); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public static Set methodSignatures(final Class klass) { + return stream(klass.getMethods()) + .map(ListCollectionNamesIterableTest::signature) + // `TreeSet` results in the alphabetic order of signatures in `toString`, improving assertion messages + .collect(toCollection(TreeSet::new)); + } +} diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoDatabaseSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoDatabaseSpecification.groovy index 4e8ac62d8cb..6004a640fdf 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoDatabaseSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoDatabaseSpecification.groovy @@ -268,7 +268,8 @@ class MongoDatabaseSpecification extends Specification { BsonDocument, codecRegistry, primary(), executor, false, null, TIMEOUT_SETTINGS)) when: - def listCollectionNamesIterable = execute(listCollectionNamesMethod, session) + ListCollectionNamesIterableImpl listCollectionNamesIterable = + (ListCollectionNamesIterableImpl) execute(listCollectionNamesMethod, session) then: // `listCollectionNamesIterable` is an instance of a `ListCollectionNamesIterableImpl`, so have to get the wrapped iterable from it From ce5f53773c59e59c9bcce3ce658cd6335dcfe532 Mon Sep 17 00:00:00 2001 From: Valentin Kovalenko Date: Tue, 10 Nov 2026 08:44:08 -0600 Subject: [PATCH 05/11] JAVA-6258 Add `commandOption` aggregate and change stream iterable API method JAVA-6258 --- .../org/bson/codecs/kotlinx/KotlinSerializerCodecTest.kt | 1 - config/detekt/detekt.yml | 1 + .../coroutine/syncadapter/SyncAggregateIterable.kt | 4 ++++ .../coroutine/syncadapter/SyncChangeStreamIterable.kt | 4 ++++ .../com/mongodb/kotlin/client/coroutine/AggregateFlow.kt | 2 ++ .../mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt | 5 +++++ .../mongodb/kotlin/client/coroutine/AggregateFlowTest.kt | 8 ++++++++ .../kotlin/client/coroutine/ChangeStreamFlowTest.kt | 8 ++++++++ .../com/mongodb/kotlin/client/model/AggregatesTest.kt | 1 - .../kotlin/client/syncadapter/SyncAggregateIterable.kt | 4 ++++ .../client/syncadapter/SyncChangeStreamIterable.kt | 4 ++++ .../com/mongodb/kotlin/client/AggregateIterable.kt | 4 ++++ .../com/mongodb/kotlin/client/ChangeStreamIterable.kt | 4 ++++ .../com/mongodb/kotlin/client/AggregateIterableTest.kt | 8 ++++++++ .../mongodb/kotlin/client/ChangeStreamIterableTest.kt | 8 ++++++++ .../reactivestreams/client/AggregatePublisher.java | 2 ++ .../reactivestreams/client/ChangeStreamPublisher.java | 2 ++ .../client/internal/AggregatePublisherImpl.java | 6 ++++++ .../client/internal/BatchCursorPublisher.java | 5 +++++ .../client/internal/ChangeStreamPublisherImpl.java | 6 ++++++ .../internal/InternalCommonBatchCursorPublisher.java | 4 ++++ .../client/syncadapter/SyncAggregateIterable.java | 6 ++++++ .../client/syncadapter/SyncChangeStreamIterable.java | 6 ++++++ .../scala/syncadapter/SyncAggregateIterable.scala | 5 +++++ .../scala/syncadapter/SyncChangeStreamIterable.scala | 5 +++++ .../scala/org/mongodb/scala/AggregateObservable.scala | 5 +++++ .../scala/org/mongodb/scala/ChangeStreamObservable.scala | 5 +++++ .../org/mongodb/scala/AggregateObservableSpec.scala | 8 ++++++++ .../org/mongodb/scala/ChangeStreamObservableSpec.scala | 9 ++++++++- .../src/main/com/mongodb/client/AggregateIterable.java | 2 ++ .../main/com/mongodb/client/ChangeStreamIterable.java | 2 ++ .../mongodb/client/internal/AggregateIterableImpl.java | 6 ++++++ .../client/internal/ChangeStreamIterableImpl.java | 6 ++++++ .../mongodb/client/internal/InternalCommonIterable.java | 4 ++++ .../com/mongodb/client/internal/MongoIterableImpl.java | 5 +++++ 35 files changed, 162 insertions(+), 3 deletions(-) diff --git a/bson-kotlinx/src/test/kotlin/org/bson/codecs/kotlinx/KotlinSerializerCodecTest.kt b/bson-kotlinx/src/test/kotlin/org/bson/codecs/kotlinx/KotlinSerializerCodecTest.kt index c4c3246891d..b8998e8b0bc 100644 --- a/bson-kotlinx/src/test/kotlin/org/bson/codecs/kotlinx/KotlinSerializerCodecTest.kt +++ b/bson-kotlinx/src/test/kotlin/org/bson/codecs/kotlinx/KotlinSerializerCodecTest.kt @@ -1186,7 +1186,6 @@ class KotlinSerializerCodecTest { } @Test - @Suppress("LongMethod") fun testDataClassWithJsonElementBsonSupport() { val dataClassWithAllSupportedJsonTypes = DataClassWithJsonElement( diff --git a/config/detekt/detekt.yml b/config/detekt/detekt.yml index 4ac460b0738..e0b95bedbda 100644 --- a/config/detekt/detekt.yml +++ b/config/detekt/detekt.yml @@ -120,6 +120,7 @@ complexity: LongMethod: active: true threshold: 60 + excludes: ['**/test/**'] LongParameterList: active: true functionThreshold: 6 diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt index 439a0ccbb29..d5272b6ef9b 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt @@ -74,4 +74,8 @@ data class SyncAggregateIterable(val wrapped: AggregateFlow) : override fun explain(explainResultClass: Class, verbosity: ExplainVerbosity): E = runBlocking { wrapped.explain(explainResultClass, verbosity) } + + override fun commandOption(name: String, value: Any): SyncAggregateIterable = apply { + wrapped.commandOption(name, value) + } } diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncChangeStreamIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncChangeStreamIterable.kt index 3f5269cd10d..b2892f642ef 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncChangeStreamIterable.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncChangeStreamIterable.kt @@ -60,4 +60,8 @@ data class SyncChangeStreamIterable(val wrapped: ChangeStreamFlow) : override fun startAtOperationTime(startAtOperationTime: BsonTimestamp): SyncChangeStreamIterable = apply { wrapped.startAtOperationTime(startAtOperationTime) } + + override fun commandOption(name: String, value: Any): SyncChangeStreamIterable = apply { + wrapped.commandOption(name, value) + } } diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt index a1debfd812f..6775745d4ac 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt @@ -216,6 +216,8 @@ public class AggregateFlow(private val wrapped: AggregatePublisher) public suspend inline fun explain(verbosity: ExplainVerbosity? = null): R = explain(R::class.java, verbosity) + public fun commandOption(name: String, value: Any): AggregateFlow = apply { wrapped.commandOption(name, value) } + /** * Requests [AggregateFlow] to start streaming data according to the specified aggregation pipeline. * - If the aggregation pipeline ends with an `$out` or `$merge` stage, then finds all documents in the affected diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt index 55bfeb82060..9fe091713e5 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt @@ -173,6 +173,11 @@ public class ChangeStreamFlow(private val wrapped: ChangeStreamPublishe public fun showExpandedEvents(showExpandedEvents: Boolean): ChangeStreamFlow = apply { wrapped.showExpandedEvents(showExpandedEvents) } + + public fun commandOption(name: String, value: Any): ChangeStreamFlow = apply { + wrapped.commandOption(name, value) + } + public override suspend fun collect(collector: FlowCollector>): Unit = wrapped.asFlow().collect(collector) } diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlowTest.kt index ab4b9694986..ca88c358bf9 100644 --- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlowTest.kt +++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlowTest.kt @@ -59,6 +59,10 @@ class AggregateFlowTest { val hint = Document("h", 1) val hintString = "hintString" val verbosity = ExplainVerbosity.QUERY_PLANNER + val stringCommandOptionName = "stringCommandOptionName" + val stringCommandOptionValue = "stringCommandOptionValue" + val intCommandOptionName = "intCommandOptionName" + val intCommandOptionValue = 1 flow.allowDiskUse(true) flow.batchSize(batchSize) @@ -74,6 +78,8 @@ class AggregateFlowTest { flow.maxTime(1) flow.maxTime(1, TimeUnit.SECONDS) flow.timeoutMode(TimeoutMode.ITERATION) + flow.commandOption(stringCommandOptionName, stringCommandOptionValue) + flow.commandOption(intCommandOptionName, intCommandOptionValue) verify(wrapped).allowDiskUse(true) verify(wrapped).batchSize(batchSize) @@ -89,6 +95,8 @@ class AggregateFlowTest { verify(wrapped).maxTime(1, TimeUnit.SECONDS) verify(wrapped).let(bson) verify(wrapped).timeoutMode(TimeoutMode.ITERATION) + verify(wrapped).commandOption(stringCommandOptionName, stringCommandOptionValue) + verify(wrapped).commandOption(intCommandOptionName, intCommandOptionValue) whenever(wrapped.explain(Document::class.java)).doReturn(Mono.fromCallable { Document() }) whenever(wrapped.explain(Document::class.java, verbosity)).doReturn(Mono.fromCallable { Document() }) diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlowTest.kt index 47030468588..6a4a980a29c 100644 --- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlowTest.kt +++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlowTest.kt @@ -56,6 +56,10 @@ class ChangeStreamFlowTest { val comment = "comment" val operationTime = BsonTimestamp(1) val resumeToken = BsonDocument() + val stringCommandOptionName = "stringCommandOptionName" + val stringCommandOptionValue = "stringCommandOptionValue" + val intCommandOptionName = "intCommandOptionName" + val intCommandOptionValue = 1 flow.batchSize(batchSize) flow.collation(collation) @@ -69,6 +73,8 @@ class ChangeStreamFlowTest { flow.showExpandedEvents(true) flow.startAfter(resumeToken) flow.startAtOperationTime(operationTime) + flow.commandOption(stringCommandOptionName, stringCommandOptionValue) + flow.commandOption(intCommandOptionName, intCommandOptionValue) verify(wrapped).batchSize(batchSize) verify(wrapped).collation(collation) @@ -82,6 +88,8 @@ class ChangeStreamFlowTest { verify(wrapped).showExpandedEvents(true) verify(wrapped).startAfter(resumeToken) verify(wrapped).startAtOperationTime(operationTime) + verify(wrapped).commandOption(stringCommandOptionName, stringCommandOptionValue) + verify(wrapped).commandOption(intCommandOptionName, intCommandOptionValue) whenever(wrapped.withDocumentClass(BsonDocument::class.java)).doReturn(mock()) runBlocking { flow.withDocumentClass() } diff --git a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/AggregatesTest.kt b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/AggregatesTest.kt index f0fd6d7a1a4..778f000ecf9 100644 --- a/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/AggregatesTest.kt +++ b/driver-kotlin-extensions/src/test/kotlin/com/mongodb/kotlin/client/model/AggregatesTest.kt @@ -233,7 +233,6 @@ class AggregatesTest { } @Test - @Suppress("LongMethod") fun accumulators() { assertEquals(com.mongodb.client.model.Accumulators.sum("age", 1), sum(Person::age, 1)) diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt index b563c67c368..6c7bb2a212e 100644 --- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt +++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt @@ -70,4 +70,8 @@ internal class SyncAggregateIterable(val wrapped: AggregateIterable) override fun explain(explainResultClass: Class, verbosity: ExplainVerbosity): E = wrapped.explain(explainResultClass, verbosity) + + override fun commandOption(name: String, value: Any): SyncAggregateIterable = apply { + wrapped.commandOption(name, value) + } } diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncChangeStreamIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncChangeStreamIterable.kt index 0d579e68006..8cb39b0bd79 100644 --- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncChangeStreamIterable.kt +++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncChangeStreamIterable.kt @@ -58,4 +58,8 @@ internal class SyncChangeStreamIterable(val wrapped: ChangeStreamIterab override fun startAtOperationTime(startAtOperationTime: BsonTimestamp): SyncChangeStreamIterable = apply { wrapped.startAtOperationTime(startAtOperationTime) } + + override fun commandOption(name: String, value: Any): SyncChangeStreamIterable = apply { + wrapped.commandOption(name, value) + } } diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt index 49130b82c60..c16788f415d 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt @@ -219,4 +219,8 @@ public class AggregateIterable(private val wrapped: JAggregateIterable< */ public inline fun explain(verbosity: ExplainVerbosity? = null): R = explain(R::class.java, verbosity) + + public fun commandOption(name: String, value: Any): AggregateIterable = apply { + wrapped.commandOption(name, value) + } } diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt index cf7cc35b0b0..20f48a4fe53 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt @@ -178,4 +178,8 @@ public class ChangeStreamIterable(private val wrapped: JChangeStreamIte public fun showExpandedEvents(showExpandedEvents: Boolean): ChangeStreamIterable = apply { wrapped.showExpandedEvents(showExpandedEvents) } + + public fun commandOption(name: String, value: Any): ChangeStreamIterable = apply { + wrapped.commandOption(name, value) + } } diff --git a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/AggregateIterableTest.kt b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/AggregateIterableTest.kt index 83ca9bce0ad..9adba2627ed 100644 --- a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/AggregateIterableTest.kt +++ b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/AggregateIterableTest.kt @@ -57,6 +57,10 @@ class AggregateIterableTest { val hint = Document("h", 1) val hintString = "hintString" val verbosity = ExplainVerbosity.QUERY_PLANNER + val stringCommandOptionName = "stringCommandOptionName" + val stringCommandOptionValue = "stringCommandOptionValue" + val intCommandOptionName = "intCommandOptionName" + val intCommandOptionValue = 1 whenever(wrapped.explain(Document::class.java)).doReturn(mock()) whenever(wrapped.explain(Document::class.java, verbosity)).doReturn(mock()) @@ -82,6 +86,8 @@ class AggregateIterableTest { iterable.maxTime(1) iterable.maxTime(1, TimeUnit.SECONDS) iterable.timeoutMode(TimeoutMode.ITERATION) + iterable.commandOption(stringCommandOptionName, stringCommandOptionValue) + iterable.commandOption(intCommandOptionName, intCommandOptionValue) verify(wrapped).allowDiskUse(true) verify(wrapped).batchSize(batchSize) @@ -100,6 +106,8 @@ class AggregateIterableTest { verify(wrapped).maxTime(1, TimeUnit.SECONDS) verify(wrapped).let(bson) verify(wrapped).timeoutMode(TimeoutMode.ITERATION) + verify(wrapped).commandOption(stringCommandOptionName, stringCommandOptionValue) + verify(wrapped).commandOption(intCommandOptionName, intCommandOptionValue) iterable.toCollection() verify(wrapped).toCollection() diff --git a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ChangeStreamIterableTest.kt b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ChangeStreamIterableTest.kt index 53d56485c21..d7781b3a02d 100644 --- a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ChangeStreamIterableTest.kt +++ b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ChangeStreamIterableTest.kt @@ -54,6 +54,10 @@ class ChangeStreamIterableTest { val comment = "comment" val operationTime = BsonTimestamp(1) val resumeToken = BsonDocument() + val stringCommandOptionName = "stringCommandOptionName" + val stringCommandOptionValue = "stringCommandOptionValue" + val intCommandOptionName = "intCommandOptionName" + val intCommandOptionValue = 1 whenever(wrapped.withDocumentClass(BsonDocument::class.java)).doReturn(mock()) whenever(wrapped.cursor()).doReturn(mock()) @@ -72,6 +76,8 @@ class ChangeStreamIterableTest { iterable.startAfter(resumeToken) iterable.startAtOperationTime(operationTime) iterable.withDocumentClass() + iterable.commandOption(stringCommandOptionName, stringCommandOptionValue) + iterable.commandOption(intCommandOptionName, intCommandOptionValue) verify(wrapped).batchSize(batchSize) verify(wrapped).collation(collation) @@ -87,6 +93,8 @@ class ChangeStreamIterableTest { verify(wrapped).startAfter(resumeToken) verify(wrapped).startAtOperationTime(operationTime) verify(wrapped).withDocumentClass(BsonDocument::class.java) + verify(wrapped).commandOption(stringCommandOptionName, stringCommandOptionValue) + verify(wrapped).commandOption(intCommandOptionName, intCommandOptionValue) verifyNoMoreInteractions(wrapped) } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java index 4f18fe272bc..b26bf0b9a5d 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java @@ -272,4 +272,6 @@ public interface AggregatePublisher extends Publisher { * @mongodb.server.release 3.6 */ Publisher explain(Class explainResultClass, ExplainVerbosity verbosity); + + AggregatePublisher commandOption(String name, Object value); } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java index 27dc7b58238..9ce0f554fa0 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java @@ -178,4 +178,6 @@ public interface ChangeStreamPublisher extends Publisher showExpandedEvents(boolean showExpandedEvents); + + ChangeStreamPublisher commandOption(String name, Object value); } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java index 703985fed42..e373f28235f 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java @@ -171,6 +171,12 @@ public Publisher explain(final Class explainResultClass, final Explain return publishExplain(explainResultClass, notNull("verbosity", verbosity)); } + @Override + public AggregatePublisher commandOption(final String name, final Object value) { + setOverridingCommandOption(notNull("name", name), notNull("value", value)); + return this; + } + private Publisher publishExplain(final Class explainResultClass, @Nullable final ExplainVerbosity verbosity) { notNull("explainDocumentClass", explainResultClass); return getMongoOperationPublisher().createReadOperationMono( diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java index 6a869838529..bfdb4e85211 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java @@ -37,6 +37,7 @@ import java.util.function.Supplier; import static com.mongodb.assertions.Assertions.assertNotNull; +import static com.mongodb.assertions.Assertions.fail; import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; @@ -130,6 +131,10 @@ public Publisher first() { }); } + Publisher setOverridingCommandOption(final String name, final Object value) { + throw fail("VAKOTODO"); + } + @Override public void subscribe(final Subscriber subscriber) { new BatchCursorFlux<>(this).subscribe(subscriber); diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java index e8fa3c84a2b..9b6f3871569 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java @@ -175,6 +175,12 @@ public ChangeStreamPublisherImpl startAfter(final BsonDocument startAfter) { return this; } + @Override + public ChangeStreamPublisher commandOption(final String name, final Object value) { + setOverridingCommandOption(notNull("name", name), notNull("value", value)); + return this; + } + @Override ReadOperationCursor> asReadOperation(final int initialBatchSize) { return createChangeStreamOperation(codec, initialBatchSize); diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisher.java index 76f78b38a74..cc7da2f9b31 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisher.java @@ -129,4 +129,8 @@ default Publisher explain(Class explainResultClass, ExplainVerbosity v default Publisher bypassDocumentValidation(@Nullable Boolean bypassDocumentValidation) { throw fail(); } + + default Publisher commandOption(String name, Object value) { + throw fail(); + } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncAggregateIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncAggregateIterable.java index 6b81b1f42af..e934f3c1130 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncAggregateIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncAggregateIterable.java @@ -137,4 +137,10 @@ public E explain(final Class explainResultClass) { public E explain(final Class explainResultClass, final ExplainVerbosity verbosity) { return requireNonNull(Mono.from(wrapped.explain(explainResultClass, verbosity)).contextWrite(CONTEXT).block(TIMEOUT_DURATION)); } + + @Override + public AggregateIterable commandOption(final String name, final Object value) { + wrapped.commandOption(name, value); + return this; + } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncChangeStreamIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncChangeStreamIterable.java index d078e176bc2..9e455d7d17e 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncChangeStreamIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncChangeStreamIterable.java @@ -165,4 +165,10 @@ public ChangeStreamIterable showExpandedEvents(final boolean showExpandedEven wrapped.showExpandedEvents(showExpandedEvents); return this; } + + @Override + public ChangeStreamIterable commandOption(final String name, final Object value) { + wrapped.commandOption(name, value); + return this; + } } diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala index 74f5a909811..9ef3e7ac6d4 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala @@ -107,4 +107,9 @@ case class SyncAggregateIterable[T](wrapped: AggregateObservable[T]) .explain[E](verbosity)(DefaultsTo.overrideDefault[E, org.mongodb.scala.Document], ClassTag(explainResultClass)) .toFuture() .get() + + override def commandOption(name: String, value: Object): AggregateIterable[T] = { + wrapped.commandOption(name, value) + this + } } diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncChangeStreamIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncChangeStreamIterable.scala index 087b558f72b..4342f3dd19d 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncChangeStreamIterable.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncChangeStreamIterable.scala @@ -100,4 +100,9 @@ case class SyncChangeStreamIterable[T](wrapped: ChangeStreamObservable[T]) wrapped.showExpandedEvents(showExpandedEvents) this } + + override def commandOption(name: String, value: Object): ChangeStreamIterable[T] = { + wrapped.commandOption(name, value) + this + } } diff --git a/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala index a363ee21662..f02648f3000 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala @@ -263,6 +263,11 @@ case class AggregateObservable[TResult](private val wrapped: AggregatePublisher[ )(implicit e: ExplainResult DefaultsTo Document, ct: ClassTag[ExplainResult]): SingleObservable[ExplainResult] = wrapped.explain[ExplainResult](ct, verbosity) + def commandOption(name: String, value: Any): AggregateObservable[TResult] = { + wrapped.commandOption(name, value) + this + } + /** * Requests [[AggregateObservable]] to start streaming data according to the specified aggregation pipeline. * diff --git a/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala index 61136ca4fad..9fd931365a0 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala @@ -205,5 +205,10 @@ case class ChangeStreamObservable[TResult](private val wrapped: ChangeStreamPubl */ def first(): SingleObservable[ChangeStreamDocument[TResult]] = wrapped.first() + def commandOption(name: String, value: Any): ChangeStreamObservable[TResult] = { + wrapped.commandOption(name, value) + this + } + override def subscribe(observer: Observer[_ >: ChangeStreamDocument[TResult]]): Unit = wrapped.subscribe(observer) } diff --git a/driver-scala/src/test/scala/org/mongodb/scala/AggregateObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/AggregateObservableSpec.scala index bd30396ac28..a3a2a1d52e6 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/AggregateObservableSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/AggregateObservableSpec.scala @@ -48,6 +48,10 @@ class AggregateObservableSpec extends BaseSpec with MockitoSugar { val batchSize = 10 val ct = classOf[Document] val verbosity = ExplainVerbosity.QUERY_PLANNER + val stringCommandOptionName = "stringCommandOptionName" + val stringCommandOptionValue = "stringCommandOptionValue" + val intCommandOptionName = "intCommandOptionName" + val intCommandOptionValue = 1 observable.allowDiskUse(true) observable.maxTime(duration) @@ -60,6 +64,8 @@ class AggregateObservableSpec extends BaseSpec with MockitoSugar { observable.explain[Document]() observable.explain[Document](verbosity) observable.timeoutMode(TimeoutMode.ITERATION) + observable.commandOption(stringCommandOptionName, stringCommandOptionValue) + observable.commandOption(intCommandOptionName, intCommandOptionValue) verify(wrapper).allowDiskUse(true) verify(wrapper).maxTime(duration.toMillis, TimeUnit.MILLISECONDS) @@ -72,6 +78,8 @@ class AggregateObservableSpec extends BaseSpec with MockitoSugar { verify(wrapper).explain(ct) verify(wrapper).explain(ct, verbosity) verify(wrapper).timeoutMode(TimeoutMode.ITERATION) + verify(wrapper).commandOption(stringCommandOptionName, stringCommandOptionValue) + verify(wrapper).commandOption(intCommandOptionName, intCommandOptionValue) observable.toCollection() verify(wrapper).toCollection diff --git a/driver-scala/src/test/scala/org/mongodb/scala/ChangeStreamObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/ChangeStreamObservableSpec.scala index bcc4bfea815..0691bfa7e08 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/ChangeStreamObservableSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/ChangeStreamObservableSpec.scala @@ -16,7 +16,6 @@ package org.mongodb.scala -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.ChangeStreamPublisher import org.mockito.Mockito.{ verify, verifyNoMoreInteractions } import org.mongodb.scala.bson.BsonTimestamp @@ -54,6 +53,10 @@ class ChangeStreamObservableSpec extends BaseSpec with MockitoSugar { val startAtTime = BsonTimestamp() val collation = Collation.builder().locale("en").build() val batchSize = 10 + val stringCommandOptionName = "stringCommandOptionName" + val stringCommandOptionValue = "stringCommandOptionValue" + val intCommandOptionName = "intCommandOptionName" + val intCommandOptionValue = 1 observable.batchSize(batchSize) observable.fullDocument(fullDocument) @@ -63,6 +66,8 @@ class ChangeStreamObservableSpec extends BaseSpec with MockitoSugar { observable.maxAwaitTime(duration) observable.collation(collation) observable.withDocumentClass(classOf[Int]) + observable.commandOption(stringCommandOptionName, stringCommandOptionValue) + observable.commandOption(intCommandOptionName, intCommandOptionValue) verify(wrapper).batchSize(batchSize) verify(wrapper).fullDocument(fullDocument) @@ -72,6 +77,8 @@ class ChangeStreamObservableSpec extends BaseSpec with MockitoSugar { verify(wrapper).maxAwaitTime(duration.toMillis, TimeUnit.MILLISECONDS) verify(wrapper).collation(collation) verify(wrapper).withDocumentClass(classOf[Int]) + verify(wrapper).commandOption(stringCommandOptionName, stringCommandOptionValue) + verify(wrapper).commandOption(intCommandOptionName, intCommandOptionValue) verifyNoMoreInteractions(wrapper) } diff --git a/driver-sync/src/main/com/mongodb/client/AggregateIterable.java b/driver-sync/src/main/com/mongodb/client/AggregateIterable.java index 032e1860244..874e1e14d31 100644 --- a/driver-sync/src/main/com/mongodb/client/AggregateIterable.java +++ b/driver-sync/src/main/com/mongodb/client/AggregateIterable.java @@ -279,4 +279,6 @@ public interface AggregateIterable extends MongoIterable { * @mongodb.server.release 3.6 */ E explain(Class explainResultClass, ExplainVerbosity verbosity); + + AggregateIterable commandOption(String name, Object value); } diff --git a/driver-sync/src/main/com/mongodb/client/ChangeStreamIterable.java b/driver-sync/src/main/com/mongodb/client/ChangeStreamIterable.java index 017ee9c2442..32e2806825a 100644 --- a/driver-sync/src/main/com/mongodb/client/ChangeStreamIterable.java +++ b/driver-sync/src/main/com/mongodb/client/ChangeStreamIterable.java @@ -178,4 +178,6 @@ public interface ChangeStreamIterable extends MongoIterable showExpandedEvents(boolean showExpandedEvents); + + ChangeStreamIterable commandOption(String name, Object value); } diff --git a/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java index f7077c59285..66f7e6b1b1f 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java @@ -200,6 +200,12 @@ public E explain(final Class explainResultClass, final ExplainVerbosity v return executeExplain(explainResultClass, notNull("verbosity", verbosity)); } + @Override + public AggregateIterable commandOption(final String name, final Object value) { + setOverridingCommandOption(notNull("name", name), notNull("value", value)); + return this; + } + private E executeExplain(final Class explainResultClass, @Nullable final ExplainVerbosity verbosity) { notNull("explainDocumentClass", explainResultClass); return getExecutor().execute( diff --git a/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java index 824104797e0..0a4483e8e21 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java @@ -196,6 +196,12 @@ public ChangeStreamIterable showExpandedEvents(final boolean showExpand return this; } + @Override + public ChangeStreamIterable commandOption(final String name, final Object value) { + setOverridingCommandOption(notNull("name", name), notNull("value", value)); + return this; + } + @Override public MongoCursor> iterator() { return cursor(); diff --git a/driver-sync/src/main/com/mongodb/client/internal/InternalCommonIterable.java b/driver-sync/src/main/com/mongodb/client/internal/InternalCommonIterable.java index f1279a1a4ca..ba9cd1eb40b 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/InternalCommonIterable.java +++ b/driver-sync/src/main/com/mongodb/client/internal/InternalCommonIterable.java @@ -121,4 +121,8 @@ default E explain(Class explainResultClass, ExplainVerbosity verbosity) { default MongoIterable bypassDocumentValidation(@Nullable Boolean bypassDocumentValidation) { throw fail(); } + + default MongoIterable commandOption(String name, Object value) { + throw fail(); + } } diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java index c5d90cd6b56..3463f6c1797 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java @@ -32,6 +32,7 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; +import static com.mongodb.assertions.Assertions.fail; import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; @@ -114,6 +115,10 @@ public MongoIterable timeoutMode(final TimeoutMode timeoutMode) { return this; } + MongoIterable setOverridingCommandOption(final String name, final Object value) { + throw fail("VAKOTODO"); + } + @Override public MongoCursor iterator() { return new MongoBatchCursorAdapter<>(execute()); From 4a50fe6d03bf3b26acaaa1a5eb5f6c0f0de4cab0 Mon Sep 17 00:00:00 2001 From: Valentin Kovalenko Date: Wed, 25 Nov 2026 17:42:28 -0600 Subject: [PATCH 06/11] JAVA-6258 Implement `commandOption` aggregate and change stream iterable API method Test changes: - It does not seem possible to test the changes via both AggregateIterableSpecification/ChangeStreamIterableSpecification and AggregatePublisherImplTest/ChangeStreamPublisherImplTest, so I added AggregateIterableIntegrationTest/AggregatePublisherIntegrationTest, ChangeStreamIterableIntegrationTest/ChangeStreamPublisherIntegrationTest - Moved ChangeStreamProseTest.batchSizeWorksForWithDocumentClass to ChangeStreamIterableIntegrationTest/ChangeStreamPublisherIntegrationTest.batchSizeWorksForWithDocumentClass JAVA-6258 --- .../operation/AggregateOperation.java | 24 +++ .../operation/AggregateOperationImpl.java | 9 +- .../AggregateToCollectionOperation.java | 10 +- .../operation/ChangeStreamOperation.java | 21 ++ .../internal/operation/Operations.java | 29 ++- .../AggregateOperationSpecification.groovy | 3 + ...eToCollectionOperationSpecification.groovy | 17 +- .../ChangeStreamOperationSpecification.groovy | 4 +- .../kotlin/client/coroutine/AggregateFlow.kt | 15 ++ .../client/coroutine/ChangeStreamFlow.kt | 15 ++ .../kotlin/client/AggregateIterable.kt | 15 ++ .../kotlin/client/ChangeStreamIterable.kt | 15 ++ .../client/AggregatePublisher.java | 22 +++ .../client/ChangeStreamPublisher.java | 23 +++ .../internal/AggregatePublisherImpl.java | 13 +- .../client/internal/BatchCursorPublisher.java | 23 ++- .../internal/ChangeStreamPublisherImpl.java | 10 +- .../AggregatePublisherIntegrationTest.java | 153 +++++++++++++++ .../client/ChangeStreamProseTest.java | 13 -- .../ChangeStreamPublisherIntegrationTest.java | 157 +++++++++++++++ .../mongodb/scala/AggregateObservable.scala | 16 ++ .../scala/ChangeStreamObservable.scala | 16 ++ .../com/mongodb/client/AggregateIterable.java | 22 +++ .../mongodb/client/ChangeStreamIterable.java | 23 +++ .../internal/AggregateIterableImpl.java | 16 +- .../internal/ChangeStreamIterableImpl.java | 10 +- .../client/internal/MongoIterableImpl.java | 20 +- .../AggregateIterableIntegrationTest.java | 166 ++++++++++++++++ .../ChangeStreamIterableIntegrationTest.java | 179 ++++++++++++++++++ .../mongodb/client/ChangeStreamProseTest.java | 61 ------ 30 files changed, 1017 insertions(+), 103 deletions(-) create mode 100644 driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/AggregatePublisherIntegrationTest.java create mode 100644 driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamPublisherIntegrationTest.java create mode 100644 driver-sync/src/test/functional/com/mongodb/client/AggregateIterableIntegrationTest.java create mode 100644 driver-sync/src/test/functional/com/mongodb/client/ChangeStreamIterableIntegrationTest.java diff --git a/driver-core/src/main/com/mongodb/internal/operation/AggregateOperation.java b/driver-core/src/main/com/mongodb/internal/operation/AggregateOperation.java index 07ce3ce62bb..8215824d264 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AggregateOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AggregateOperation.java @@ -19,7 +19,9 @@ import com.mongodb.ExplainVerbosity; import com.mongodb.MongoNamespace; import com.mongodb.client.cursor.TimeoutMode; +import com.mongodb.client.model.Aggregates; import com.mongodb.client.model.Collation; +import com.mongodb.client.model.MergeOptions; import com.mongodb.internal.async.AsyncBatchCursor; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.binding.AsyncReadBinding; @@ -30,12 +32,17 @@ import org.bson.BsonDocument; import org.bson.BsonValue; import org.bson.codecs.Decoder; +import org.bson.conversions.Bson; import java.util.List; +import java.util.Set; +import java.util.stream.Stream; import static com.mongodb.internal.connection.CommandHelper.applyMaxTimeMS; import static com.mongodb.internal.operation.ExplainHelper.asExplainCommand; import static com.mongodb.internal.operation.ServerVersionHelper.UNKNOWN_WIRE_VERSION; +import static java.util.Collections.unmodifiableSet; +import static java.util.stream.Collectors.toSet; /** * An operation that executes an aggregation query. @@ -43,6 +50,18 @@ *

This class is not part of the public API and may be removed or changed at any time

*/ public class AggregateOperation implements ReadOperationExplainable { + /** + * The names of the fields that must not be passed to {@link #overridingCommandOptions(BsonDocument)}. + * These fields are either unconditionally required, or have client logic associated with them. + * For example, the {@code collation} field is also passed to the {@code find} command when {@link Aggregates#out(Bson) $out} or + * {@link Aggregates#merge(MongoNamespace, MergeOptions) $merge} is used. + * + * @see ChangeStreamOperation#FORBIDDEN_COMMAND_OPTIONS + */ + // When changing this set, remember to update the documentation of the affected API. + public static final Set FORBIDDEN_COMMAND_OPTIONS = unmodifiableSet( + Stream.concat(ChangeStreamOperation.FORBIDDEN_COMMAND_OPTIONS.stream(), Stream.of("collation")).collect(toSet())); + private final AggregateOperationImpl wrapped; public AggregateOperation(final MongoNamespace namespace, final List pipeline, final Decoder decoder, @@ -137,6 +156,11 @@ public AggregateOperation timeoutMode(@Nullable final TimeoutMode timeoutMode return this; } + AggregateOperation overridingCommandOptions(final BsonDocument overridingCommandOptions) { + wrapped.overridingCommandOptions(overridingCommandOptions); + return this; + } + @Override public String getCommandName() { return wrapped.getCommandName(); diff --git a/driver-core/src/main/com/mongodb/internal/operation/AggregateOperationImpl.java b/driver-core/src/main/com/mongodb/internal/operation/AggregateOperationImpl.java index 0442571f41c..00a438e6b8a 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AggregateOperationImpl.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AggregateOperationImpl.java @@ -75,6 +75,7 @@ class AggregateOperationImpl implements ReadOperationCursor { private BsonDocument variables; private TimeoutMode timeoutMode; private CursorType cursorType; + private BsonDocument overridingCommandOptions; AggregateOperationImpl(final MongoNamespace namespace, final List pipeline, final Decoder decoder, final AggregationLevel aggregationLevel, @@ -95,6 +96,7 @@ class AggregateOperationImpl implements ReadOperationCursor { this.aggregateTarget = notNull("aggregateTarget", aggregateTarget); this.pipelineCreator = notNull("pipelineCreator", pipelineCreator); this.maxAdaptiveRetriesSetting = maxAdaptiveRetriesSetting; + overridingCommandOptions = new BsonDocument(); } List getPipeline() { @@ -187,6 +189,10 @@ AggregateOperationImpl hint(@Nullable final BsonValue hint) { return this; } + void overridingCommandOptions(final BsonDocument overridingCommandOptions) { + this.overridingCommandOptions = overridingCommandOptions; + } + @Override public String getCommandName() { return COMMAND_NAME; @@ -242,7 +248,8 @@ BsonDocument getCommand(final OperationContext operationContext, final int maxWi if (variables != null) { commandDocument.put("let", variables); } - + // `overridingCommandOptions` must be applied after other options + commandDocument.putAll(overridingCommandOptions); return commandDocument; } diff --git a/driver-core/src/main/com/mongodb/internal/operation/AggregateToCollectionOperation.java b/driver-core/src/main/com/mongodb/internal/operation/AggregateToCollectionOperation.java index 763c9d1a78f..536a812b1f4 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AggregateToCollectionOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AggregateToCollectionOperation.java @@ -75,6 +75,7 @@ public class AggregateToCollectionOperation implements ReadOperationSimple private BsonValue comment; private BsonValue hint; private BsonDocument variables; + private BsonDocument overridingCommandOptions; public AggregateToCollectionOperation(final MongoNamespace namespace, final List pipeline, final ReadConcern readConcern, final WriteConcern writeConcern) { @@ -96,7 +97,7 @@ public AggregateToCollectionOperation(final MongoNamespace namespace, final List this.aggregationLevel = notNull("aggregationLevel", aggregationLevel); this.retryWrites = retryWrites; this.maxAdaptiveRetriesSetting = maxAdaptiveRetriesSetting; - + overridingCommandOptions = new BsonDocument(); isTrueArgument("pipeline is not empty", !pipeline.isEmpty()); } @@ -167,6 +168,11 @@ public AggregateToCollectionOperation timeoutMode(@Nullable final TimeoutMode ti return this; } + AggregateToCollectionOperation overridingCommandOptions(final BsonDocument overridingCommandOptions) { + this.overridingCommandOptions = overridingCommandOptions; + return this; + } + @Override public String getCommandName() { return COMMAND_NAME; @@ -242,6 +248,8 @@ private CommandOperationHelper.CommandCreator getCommandCreator() { if (variables != null) { commandDocument.put("let", variables); } + // `overridingCommandOptions` must be applied after other options + commandDocument.putAll(overridingCommandOptions); return commandDocument; }; } diff --git a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamOperation.java b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamOperation.java index c94dccebf50..e97741c353c 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamOperation.java @@ -42,11 +42,15 @@ import org.bson.codecs.RawBsonDocumentCodec; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.client.cursor.TimeoutMode.CURSOR_LIFETIME; +import static java.util.Arrays.asList; +import static java.util.Collections.unmodifiableSet; /** * An operation that executes an {@code $changeStream} aggregation. @@ -54,6 +58,18 @@ *

This class is not part of the public API and may be removed or changed at any time

*/ public class ChangeStreamOperation implements ReadOperationCursor { + /** + * The names of the fields that must not be passed to {@link #overridingCommandOptions(BsonDocument)}. + * These fields are either unconditionally required, or have client logic associated with them. + * For example, the {@code comment} field is also passed to {@code getMore} commands. + * + * @see AggregateOperation#FORBIDDEN_COMMAND_OPTIONS + */ + // When changing this set, take into account that it affects `AggregateOperation.FORBIDDEN_COMMAND_OPTIONS`, + // and remember to update the documentation of the affected API. + public static final Set FORBIDDEN_COMMAND_OPTIONS = unmodifiableSet(new HashSet<>(asList( + "aggregate", "pipeline", "maxTimeMS", "cursor", "explain", "comment"))); + private static final RawBsonDocumentCodec RAW_BSON_DOCUMENT_CODEC = new RawBsonDocumentCodec(); private final AggregateOperationImpl wrapped; private final FullDocument fullDocument; @@ -164,6 +180,11 @@ public ChangeStreamOperation comment(final BsonValue comment) { return this; } + ChangeStreamOperation overridingCommandOptions(final BsonDocument overridingCommandOptions) { + wrapped.overridingCommandOptions(overridingCommandOptions); + return this; + } + public boolean getShowExpandedEvents() { return this.showExpandedEvents; } diff --git a/driver-core/src/main/com/mongodb/internal/operation/Operations.java b/driver-core/src/main/com/mongodb/internal/operation/Operations.java index 8e1e4ab61cb..fabe9d6fe40 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/Operations.java +++ b/driver-core/src/main/com/mongodb/internal/operation/Operations.java @@ -77,6 +77,7 @@ import org.bson.BsonString; import org.bson.BsonTimestamp; import org.bson.BsonValue; +import org.bson.Document; import org.bson.codecs.Codec; import org.bson.codecs.CollectibleCodec; import org.bson.codecs.Decoder; @@ -319,7 +320,8 @@ public ReadOperationCursor distinct(final String fieldName, @Nullable fin public ReadOperationExplainable aggregate(final List pipeline, final Class resultClass, @Nullable final TimeoutMode timeoutMode, @Nullable final Integer batchSize, final Collation collation, @Nullable final Bson hint, @Nullable final String hintString, - final BsonValue comment, final Bson variables, final Boolean allowDiskUse, final AggregationLevel aggregationLevel) { + final BsonValue comment, final Bson variables, final Boolean allowDiskUse, final AggregationLevel aggregationLevel, + final Document overridingCommandOptions) { return new AggregateOperation<>(assertNotNull(namespace), assertNotNull(toBsonDocumentList(pipeline)), codecRegistry.get(resultClass), aggregationLevel, maxAdaptiveRetriesSetting) @@ -330,12 +332,14 @@ public ReadOperationExplainable aggregate(final List pipe .hint(hint != null ? toBsonDocument(hint) : (hintString != null ? new BsonString(hintString) : null)) .comment(comment) .let(toBsonDocument(variables)) - .timeoutMode(timeoutMode); + .timeoutMode(timeoutMode) + .overridingCommandOptions(encodeOverridingCommandOptions(overridingCommandOptions)); } public ReadOperationSimple aggregateToCollection(final List pipeline, @Nullable final TimeoutMode timeoutMode, final Boolean allowDiskUse, final Boolean bypassDocumentValidation, final Collation collation, @Nullable final Bson hint, - @Nullable final String hintString, final BsonValue comment, final Bson variables, final AggregationLevel aggregationLevel) { + @Nullable final String hintString, final BsonValue comment, final Bson variables, final AggregationLevel aggregationLevel, + final Document overridingCommandOptions) { return new AggregateToCollectionOperation(assertNotNull(namespace), assertNotNull(toBsonDocumentList(pipeline)), readConcern, writeConcern, aggregationLevel, isRetryWrites(), maxAdaptiveRetriesSetting) @@ -345,7 +349,8 @@ public ReadOperationSimple aggregateToCollection(final List ReadOperationCursor changeStream(final FullDocument fullDocument, final FullDocumentBeforeChange fullDocumentBeforeChange, final List pipeline, final Decoder decoder, final ChangeStreamLevel changeStreamLevel, @Nullable final Integer batchSize, final Collation collation, final BsonValue comment, final BsonDocument resumeToken, - final BsonTimestamp startAtOperationTime, final BsonDocument startAfter, final boolean showExpandedEvents) { + final BsonTimestamp startAtOperationTime, final BsonDocument startAfter, final boolean showExpandedEvents, + final Document overridingCommandOptions) { return new ChangeStreamOperation<>( assertNotNull(namespace), fullDocument, @@ -817,7 +823,8 @@ public ReadOperationCursor changeStream(final FullDocument fullDocument, .startAtOperationTime(startAtOperationTime) .startAfter(startAfter) .showExpandedEvents(showExpandedEvents) - .retryReads(retryReads); + .retryReads(retryReads) + .overridingCommandOptions(encodeOverridingCommandOptions(overridingCommandOptions)); } public WriteOperation clientBulkWriteOperation( @@ -866,4 +873,14 @@ private SearchIndexRequest createSearchIndexRequest(final SearchIndexModel model return new SearchIndexRequest(definition, indexName, searchIndexType); } + + /** + * Encodes {@code overridingCommandOptions} in a way that does not require {@link #codecRegistry} to have a {@link Codec} + * for {@link Document}, if {@code overridingCommandOptions} is {@linkplain Document#isEmpty() empty}. + */ + private BsonDocument encodeOverridingCommandOptions(final Document overridingCommandOptions) { + return overridingCommandOptions.isEmpty() + ? new BsonDocument() + : overridingCommandOptions.toBsonDocument(BsonDocument.class, codecRegistry); + } } diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateOperationSpecification.groovy index 9e8d6a8277e..192e7dcbfb9 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateOperationSpecification.groovy @@ -146,12 +146,15 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification { .allowDiskUse(true) .batchSize(10) .collation(defaultCollation) + .overridingCommandOptions(new BsonDocument('let', new BsonDocument('overriding', new BsonInt32(2)))) + .let(new BsonDocument('overridden', new BsonInt32(1))) expectedCommand = new BsonDocument('aggregate', new BsonString(helper.namespace.getCollectionName())) .append('pipeline', new BsonArray(pipeline)) .append('allowDiskUse', new BsonBoolean(true)) .append('collation', defaultCollation.asDocument()) .append('cursor', new BsonDocument('batchSize', new BsonInt32(10))) + .append('let', new BsonDocument('overriding', new BsonInt32(2))) then: testOperation(operation, [3, 4, 0], expectedCommand, async, helper.cursorResult) diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateToCollectionOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateToCollectionOperationSpecification.groovy index a14c4323fdd..367563d484e 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateToCollectionOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateToCollectionOperationSpecification.groovy @@ -243,15 +243,26 @@ class AggregateToCollectionOperationSpecification extends OperationFunctionalSpe operation.hint(new BsonString('x_1')) expectedCommand.append('hint', new BsonString('x_1')) } + if (useOverridingCommandOptions) { + operation.overridingCommandOptions(new BsonDocument('let', new BsonDocument('overriding', new BsonInt32(2)))) + .let(new BsonDocument('overridden', new BsonInt32(1))) + expectedCommand.append('let', new BsonDocument('overriding', new BsonInt32(2))) + } then: testOperation(operation, serverVersion, expectedCommand, async, BsonDocument.parse('{ok: 1}'), true, false, ReadPreference.primary(), false) where: - serverVersion | includeBypassValidation | includeReadConcern | includeWriteConcern | includeCollation | async | useCursor | useHint - [3, 6, 0] | true | true | true | true | true | true | true - [3, 6, 0] | true | true | true | true | false | true | false + serverVersion << [[3, 6, 0], [3, 6, 0]] + includeBypassValidation << [true, true] + includeReadConcern << [true, true] + includeWriteConcern << [true, true] + includeCollation << [true, true] + async << [true, false] + useCursor << [true, true] + useHint << [true, false] + useOverridingCommandOptions << [true, true] } def 'should support collation'() { diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationSpecification.groovy index fc2431f03f3..91756655d15 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/ChangeStreamOperationSpecification.groovy @@ -21,6 +21,7 @@ import com.mongodb.MongoNamespace import com.mongodb.OperationFunctionalSpecification import com.mongodb.ReadConcern import com.mongodb.WriteConcern +import com.mongodb.client.model.Collation import com.mongodb.client.model.CreateCollectionOptions import com.mongodb.client.model.changestream.ChangeStreamDocument import com.mongodb.client.model.changestream.FullDocument @@ -114,7 +115,8 @@ class ChangeStreamOperationSpecification extends OperationFunctionalSpecificatio def operation = new ChangeStreamOperation(namespace, FullDocument.DEFAULT, FullDocumentBeforeChange.DEFAULT, pipeline, new DocumentCodec(), changeStreamLevel as ChangeStreamLevel, null) .batchSize(5) - .collation(defaultCollation) + .overridingCommandOptions(new BsonDocument('collation', defaultCollation.asDocument())) + .collation(Collation.builder().locale('overridden').build()) .startAtOperationTime(new BsonTimestamp()) def expectedCommand = new BsonDocument('aggregate', aggregate) diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt index 6775745d4ac..a81caba8fa0 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt @@ -29,6 +29,7 @@ import kotlinx.coroutines.reactive.awaitFirstOrNull import kotlinx.coroutines.reactive.awaitSingle import org.bson.BsonValue import org.bson.Document +import org.bson.codecs.configuration.CodecRegistry import org.bson.conversions.Bson /** @@ -216,6 +217,20 @@ public class AggregateFlow(private val wrapped: AggregatePublisher) public suspend inline fun explain(verbosity: ExplainVerbosity? = null): R = explain(R::class.java, verbosity) + /** + * Sets an optional field of the `aggregate` command in situations when there is no method that better satisfies + * your needs. The behavior of this method is undefined if it is used to set any of the following: + * - a field from the following set: [maxTimeMS][maxTime], `cursor`, [explain][explain], [comment][comment], + * [collation][collation]; + * - a field that is configurable via means other than [AggregateFlow] methods; + * - a field that is also set via a different [AggregateFlow] method. + * + * @param name The name of the optional command field. + * @param value The value of the field specified by `name`. It is encoded via the configured [CodecRegistry], which + * must have a codec for [Document] regardless of the type of `value`. + * @return `this`. + * @since 5.16 + */ public fun commandOption(name: String, value: Any): AggregateFlow = apply { wrapped.commandOption(name, value) } /** diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt index 9fe091713e5..d4e2226b4c3 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt @@ -27,6 +27,8 @@ import kotlinx.coroutines.reactive.asFlow import org.bson.BsonDocument import org.bson.BsonTimestamp import org.bson.BsonValue +import org.bson.Document +import org.bson.codecs.configuration.CodecRegistry /** * Flow implementation for change streams. @@ -174,6 +176,19 @@ public class ChangeStreamFlow(private val wrapped: ChangeStreamPublishe wrapped.showExpandedEvents(showExpandedEvents) } + /** + * Sets an optional field of the `aggregate` command in situations when there is no method that better satisfies + * your needs. The behavior of this method is undefined if it is used to set any of the following: + * - a field from the following set: `maxTimeMS`, `cursor`, `explain`, [comment][comment]; + * - a field that is configurable via means other than [ChangeStreamFlow] methods; + * - a field that is also set via a different [ChangeStreamFlow] method. + * + * @param name The name of the optional command field. + * @param value The value of the field specified by `name`. It is encoded via the configured [CodecRegistry], which + * must have a codec for [Document] regardless of the type of `value`. + * @return `this`. + * @since 5.16 + */ public fun commandOption(name: String, value: Any): ChangeStreamFlow = apply { wrapped.commandOption(name, value) } diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt index c16788f415d..baf4e2af7b8 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt @@ -24,6 +24,7 @@ import com.mongodb.client.model.Collation import java.util.concurrent.TimeUnit import org.bson.BsonValue import org.bson.Document +import org.bson.codecs.configuration.CodecRegistry import org.bson.conversions.Bson /** @@ -220,6 +221,20 @@ public class AggregateIterable(private val wrapped: JAggregateIterable< public inline fun explain(verbosity: ExplainVerbosity? = null): R = explain(R::class.java, verbosity) + /** + * Sets an optional field of the `aggregate` command in situations when there is no method that better satisfies + * your needs. The behavior of this method is undefined if it is used to set any of the following: + * - a field from the following set: [maxTimeMS][maxTime], `cursor`, [explain][explain], [comment][comment], + * [collation][collation]; + * - a field that is configurable via means other than [AggregateIterable] methods; + * - a field that is also set via a different [AggregateIterable] method. + * + * @param name The name of the optional command field. + * @param value The value of the field specified by `name`. It is encoded via the configured [CodecRegistry], which + * must have a codec for [Document] regardless of the type of `value`. + * @return `this`. + * @since 5.16 + */ public fun commandOption(name: String, value: Any): AggregateIterable = apply { wrapped.commandOption(name, value) } diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt index 20f48a4fe53..ddd9dac0e30 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt @@ -24,6 +24,8 @@ import java.util.concurrent.TimeUnit import org.bson.BsonDocument import org.bson.BsonTimestamp import org.bson.BsonValue +import org.bson.Document +import org.bson.codecs.configuration.CodecRegistry /** * Iterable like implementation for change streams. @@ -179,6 +181,19 @@ public class ChangeStreamIterable(private val wrapped: JChangeStreamIte wrapped.showExpandedEvents(showExpandedEvents) } + /** + * Sets an optional field of the `aggregate` command in situations when there is no method that better satisfies + * your needs. The behavior of this method is undefined if it is used to set any of the following: + * - a field from the following set: `maxTimeMS`, `cursor`, `explain`, [comment][comment]; + * - a field that is configurable via means other than [ChangeStreamIterable] methods; + * - a field that is also set via a different [ChangeStreamIterable] method. + * + * @param name The name of the optional command field. + * @param value The value of the field specified by `name`. It is encoded via the configured [CodecRegistry], which + * must have a codec for [Document] regardless of the type of `value`. + * @return `this`. + * @since 5.16 + */ public fun commandOption(name: String, value: Any): ChangeStreamIterable = apply { wrapped.commandOption(name, value) } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java index b26bf0b9a5d..288a9441751 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java @@ -27,6 +27,7 @@ import com.mongodb.lang.Nullable; import org.bson.BsonValue; import org.bson.Document; +import org.bson.codecs.configuration.CodecRegistry; import org.bson.conversions.Bson; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; @@ -273,5 +274,26 @@ public interface AggregatePublisher extends Publisher { */ Publisher explain(Class explainResultClass, ExplainVerbosity verbosity); + /** + * Sets an optional field of the {@code aggregate} command in situations when there is no method that better satisfies your needs. + * The behavior of this method is undefined if it is used to set any of the following: + *
    + *
  • + * a field from the following set: + * {@link #maxTime(long, TimeUnit) maxTimeMS}, {@code cursor}, {@link #explain(Class, ExplainVerbosity) explain}, + * {@link #comment(BsonValue) comment}, {@link #collation(Collation) collation};
  • + *
  • + * a field that is configurable via means other than {@link AggregatePublisher} methods;
  • + *
  • + * a field that is also set via a different {@link AggregatePublisher} method.
  • + *
+ * + * @param name The name of the optional command field. + * @param value The value of the field specified by {@code name}. + * It is encoded via the configured {@link CodecRegistry}, + * which must have a codec for {@link Document} regardless of the type of {@code value}. + * @return {@code this}. + * @since 5.16 + */ AggregatePublisher commandOption(String name, Object value); } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java index 9ce0f554fa0..8e48a7c2a03 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java @@ -25,6 +25,8 @@ import org.bson.BsonDocument; import org.bson.BsonTimestamp; import org.bson.BsonValue; +import org.bson.Document; +import org.bson.codecs.configuration.CodecRegistry; import org.reactivestreams.Publisher; import java.util.concurrent.TimeUnit; @@ -179,5 +181,26 @@ public interface ChangeStreamPublisher extends Publisher showExpandedEvents(boolean showExpandedEvents); + /** + * Sets an optional field of the {@code aggregate} command in situations when there is no method that better satisfies your needs. + * The behavior of this method is undefined if it is used to set any of the following: + *
    + *
  • + * a field from the following set: + * {@code maxTimeMS}, {@code cursor}, {@code explain}, + * {@link #comment(BsonValue) comment};
  • + *
  • + * a field that is configurable via means other than {@link ChangeStreamPublisher} methods;
  • + *
  • + * a field that is also set via a different {@link ChangeStreamPublisher} method.
  • + *
+ * + * @param name The name of the optional command field. + * @param value The value of the field specified by {@code name}. + * It is encoded via the configured {@link CodecRegistry}, + * which must have a codec for {@link Document} regardless of the type of {@code value}. + * @return {@code this}. + * @since 5.16 + */ ChangeStreamPublisher commandOption(String name, Object value); } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java index e373f28235f..9d62d4eebfd 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java @@ -41,7 +41,10 @@ import java.util.concurrent.TimeUnit; import java.util.function.Function; +import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; +import static com.mongodb.internal.operation.AggregateOperation.FORBIDDEN_COMMAND_OPTIONS; +import static java.lang.String.format; final class AggregatePublisherImpl extends BatchCursorPublisher implements InternalCommonBatchCursorPublisher, AggregatePublisher { @@ -173,7 +176,9 @@ public Publisher explain(final Class explainResultClass, final Explain @Override public AggregatePublisher commandOption(final String name, final Object value) { - setOverridingCommandOption(notNull("name", name), notNull("value", value)); + notNull("name", name); + isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTIONS.contains(name)); + overridingCommandOption(name, notNull("value", value)); return this; } @@ -211,12 +216,14 @@ Function, TimeoutSettings> getTimeoutSettings() { private ReadOperationExplainable asAggregateOperation(final int initialBatchSize) { return getOperations() .aggregate(pipeline, getDocumentClass(), getTimeoutMode(), - initialBatchSize, collation, hint, hintString, comment, variables, allowDiskUse, aggregationLevel); + initialBatchSize, collation, hint, hintString, comment, variables, allowDiskUse, aggregationLevel, + getOverridingCommandOptions()); } private ReadOperationSimple getAggregateToCollectionOperation() { return getOperations().aggregateToCollection(pipeline, getTimeoutMode(), allowDiskUse, bypassDocumentValidation, - collation, hint, hintString, comment, variables, aggregationLevel); + collation, hint, hintString, comment, variables, aggregationLevel, + getOverridingCommandOptions()); } @Nullable diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java index bfdb4e85211..7bdc48620d6 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java @@ -27,6 +27,7 @@ import com.mongodb.internal.operation.ReadOperationCursor; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.ClientSession; +import org.bson.Document; import org.bson.codecs.configuration.CodecRegistry; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; @@ -37,7 +38,6 @@ import java.util.function.Supplier; import static com.mongodb.assertions.Assertions.assertNotNull; -import static com.mongodb.assertions.Assertions.fail; import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; @@ -50,10 +50,12 @@ public abstract class BatchCursorPublisher implements Publisher { private Integer batchSize; @Nullable private TimeoutMode timeoutMode; + private final Document overridingCommandOptions; BatchCursorPublisher(@Nullable final ClientSession clientSession, final MongoOperationPublisher mongoOperationPublisher) { this.clientSession = clientSession; this.mongoOperationPublisher = notNull("mongoOperationPublisher", mongoOperationPublisher); + overridingCommandOptions = new Document(); } abstract ReadOperationCursor asReadOperation(int initialBatchSize); @@ -131,8 +133,23 @@ public Publisher first() { }); } - Publisher setOverridingCommandOption(final String name, final Object value) { - throw fail("VAKOTODO"); + /** + * @see InternalCommonBatchCursorPublisher#commandOption(String, Object) + * @see #getOverridingCommandOptions() + */ + Publisher overridingCommandOption(final String name, final Object value) { + overridingCommandOptions.put(name, value); + return this; + } + + /** + * @see #overridingCommandOption(String, Object) + */ + Document getOverridingCommandOptions() { + // An application may mutate `overridingCommandOptions` via the `overridingCommandOption` method after subscribing to a `Publisher`. + // Such a mutation must not conflict with `overridingCommandOptions` being read while publishing. + // That is why we must return a shallow copy of `overridingCommandOptions`. + return new Document(overridingCommandOptions); } @Override diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java index 9b6f3871569..c8aded0bb78 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java @@ -39,7 +39,10 @@ import java.util.concurrent.TimeUnit; import java.util.function.Function; +import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; +import static com.mongodb.internal.operation.ChangeStreamOperation.FORBIDDEN_COMMAND_OPTIONS; +import static java.lang.String.format; final class ChangeStreamPublisherImpl extends BatchCursorPublisher> @@ -177,7 +180,9 @@ public ChangeStreamPublisherImpl startAfter(final BsonDocument startAfter) { @Override public ChangeStreamPublisher commandOption(final String name, final Object value) { - setOverridingCommandOption(notNull("name", name), notNull("value", value)); + notNull("name", name); + isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTIONS.contains(name)); + overridingCommandOption(name, notNull("value", value)); return this; } @@ -194,6 +199,7 @@ Function, TimeoutSettings> getTimeoutSettings() { private ReadOperationCursor createChangeStreamOperation(final Codec codec, final int initialBatchSize) { return getOperations().changeStream(fullDocument, fullDocumentBeforeChange, pipeline, codec, changeStreamLevel, initialBatchSize, - collation, comment, resumeToken, startAtOperationTime, startAfter, showExpandedEvents); + collation, comment, resumeToken, startAtOperationTime, startAfter, showExpandedEvents, + getOverridingCommandOptions()); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/AggregatePublisherIntegrationTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/AggregatePublisherIntegrationTest.java new file mode 100644 index 00000000000..7955feb051b --- /dev/null +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/AggregatePublisherIntegrationTest.java @@ -0,0 +1,153 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed 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 com.mongodb.reactivestreams.client; + +import com.mongodb.MongoClientSettings; +import com.mongodb.client.MongoClient; +import com.mongodb.event.ConnectionCheckedOutEvent; +import com.mongodb.event.ConnectionPoolListener; +import com.mongodb.internal.connection.TestCommandListener; +import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient; +import org.bson.BsonDocument; +import org.bson.Document; +import org.bson.conversions.Bson; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.reactivestreams.Publisher; +import reactor.core.publisher.Mono; + +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.function.Function; + +import static com.mongodb.ClusterFixture.TIMEOUT_DURATION; +import static com.mongodb.client.model.Aggregates.merge; +import static com.mongodb.client.model.Aggregates.out; +import static com.mongodb.internal.thread.InterruptionUtil.interruptAndCreateMongoInterruptedException; +import static com.mongodb.reactivestreams.client.Fixture.getMongoClientSettingsBuilder; +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +final class AggregatePublisherIntegrationTest extends com.mongodb.client.AggregateIterableIntegrationTest { + @Override + protected MongoClient createClient(final MongoClientSettings settings) { + return new SyncMongoClient(settings); + } + + @ParameterizedTest + @EnumSource(PublisherExecutor.class) + void commandOptionIsSeparateForSeparateSubscriptions(final PublisherExecutor publisherExecutor) + throws Exception { + TestCommandListener commandListener = new TestCommandListener(); + CountDownLatch commandOptionChanged = new CountDownLatch(1); + try (com.mongodb.reactivestreams.client.MongoClient client = MongoClients.create(getMongoClientSettingsBuilder() + .addCommandListener(commandListener) + .applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(new ConnectionPoolListener() { + @Override + public void connectionCheckedOut(final ConnectionCheckedOutEvent event) { + try { + // block subscriptions from executing commands + com.mongodb.assertions.Assertions.assertTrue( + commandOptionChanged.await(TIMEOUT_DURATION.toMillis(), MILLISECONDS)); + } catch (InterruptedException e) { + throw interruptAndCreateMongoInterruptedException(null, e); + } + } + })) + .build())) { + AggregatePublisher publisher = client.getDatabase(NAMESPACE.getDatabaseName()) + .getCollection(NAMESPACE.getCollectionName()) + .aggregate(publisherExecutor.getPipeline()); + publisher.commandOption("allowDiskUse", true); + CompletableFuture firstSubscription = publisherExecutor.apply(publisher); + publisher.commandOption("allowDiskUse", false); + // unblock subscriptions from executing commands + commandOptionChanged.countDown(); + firstSubscription.get(TIMEOUT_DURATION.toMillis(), MILLISECONDS); + assertTrue(publisherExecutor.getCommand(commandListener).getBoolean("allowDiskUse").getValue()); + commandListener.reset(); + CompletableFuture secondSubscription = publisherExecutor.apply(publisher); + secondSubscription.get(TIMEOUT_DURATION.toMillis(), MILLISECONDS); + assertFalse(publisherExecutor.getCommand(commandListener).getBoolean("allowDiskUse").getValue()); + } + } + + private enum PublisherExecutor implements Function, CompletableFuture> { + FIRST, + SUBSCRIBE, + SUBSCRIBE_WITH_OUT, + SUBSCRIBE_WITH_MERGE, + TO_COLLECTION_WITH_OUT, + TO_COLLECTION_WITH_MERGE, + EXPLAIN; + + List getPipeline() { + switch (this) { + case SUBSCRIBE_WITH_OUT: + case TO_COLLECTION_WITH_OUT: { + return singletonList(out(NAMESPACE.getCollectionName())); + } + case SUBSCRIBE_WITH_MERGE: + case TO_COLLECTION_WITH_MERGE: { + return singletonList(merge(NAMESPACE.getCollectionName() + "Merged")); + } + default: { + return emptyList(); + } + } + } + + @Override + public CompletableFuture apply(final AggregatePublisher publisher) { + Publisher publisherVariant; + switch (this) { + case FIRST: { + publisherVariant = publisher.first(); + break; + } + case SUBSCRIBE: + case SUBSCRIBE_WITH_OUT: + case SUBSCRIBE_WITH_MERGE: { + publisherVariant = publisher; + break; + } + case TO_COLLECTION_WITH_OUT: + case TO_COLLECTION_WITH_MERGE: { + publisherVariant = publisher.toCollection(); + break; + } + case EXPLAIN: { + publisherVariant = publisher.explain(); + break; + } + default: { + throw com.mongodb.assertions.Assertions.fail(); + } + } + return Mono.from(publisherVariant).toFuture(); + } + + BsonDocument getCommand(final TestCommandListener commandListener) { + return this == PublisherExecutor.EXPLAIN + ? commandListener.getCommandStartedEvent("explain").getCommand().getDocument("explain") + : commandListener.getCommandStartedEvent("aggregate").getCommand(); + } + } +} diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java index bd3d5d3cc49..702c579609a 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamProseTest.java @@ -17,7 +17,6 @@ import com.mongodb.MongoClientSettings; import com.mongodb.client.MongoClient; -import com.mongodb.reactivestreams.client.internal.BatchCursorPublisher; import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -94,16 +93,4 @@ protected void test19SplitChangeStreamEvents() { @Override protected void testNameSpaceTypeAbsentChangeStreamEvents() { } - - /** - * Not a prose spec test. - *

- * {@link ChangeStreamPublisher#withDocumentClass(Class)} returns a new {@link BatchCursorPublisher}, - * which must handle batch size correctly. - */ - @Test - @Override - protected void batchSizeWorksForWithDocumentClass() { - super.batchSizeWorksForWithDocumentClass(); - } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamPublisherIntegrationTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamPublisherIntegrationTest.java new file mode 100644 index 00000000000..39e646acac8 --- /dev/null +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamPublisherIntegrationTest.java @@ -0,0 +1,157 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed 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 com.mongodb.reactivestreams.client; + +import com.mongodb.MongoClientSettings; +import com.mongodb.client.MongoClient; +import com.mongodb.event.CommandStartedEvent; +import com.mongodb.event.ConnectionCheckedOutEvent; +import com.mongodb.event.ConnectionPoolListener; +import com.mongodb.internal.connection.TestCommandListener; +import com.mongodb.reactivestreams.client.internal.BatchCursorPublisher; +import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient; +import org.bson.BsonDocument; +import org.bson.Document; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.reactivestreams.Publisher; +import reactor.core.Disposable; +import reactor.core.publisher.Mono; + +import java.util.concurrent.CountDownLatch; +import java.util.function.Consumer; +import java.util.function.Function; + +import static com.mongodb.ClusterFixture.TIMEOUT_DURATION; +import static com.mongodb.internal.thread.InterruptionUtil.interruptAndCreateMongoInterruptedException; +import static com.mongodb.reactivestreams.client.Fixture.getMongoClientSettingsBuilder; +import static com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient.disableWaitForBatchCursorCreation; +import static com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient.enableWaitForBatchCursorCreation; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +final class ChangeStreamPublisherIntegrationTest extends com.mongodb.client.ChangeStreamIterableIntegrationTest { + @BeforeEach + void beforeEach() { + enableWaitForBatchCursorCreation(); + } + + @AfterEach + void afterEach() { + disableWaitForBatchCursorCreation(); + } + + @Override + protected MongoClient createClient(final MongoClientSettings settings) { + return new SyncMongoClient(settings); + } + + /** + * {@link ChangeStreamPublisher#withDocumentClass(Class)} returns a new {@link BatchCursorPublisher}, + * which must handle batch size correctly. + */ + @Test + @Override + protected void batchSizeWorksForWithDocumentClass() { + super.batchSizeWorksForWithDocumentClass(); + } + + /** + * @see #batchSizeWorksForWithDocumentClass() + */ + @Test + @Override + protected void commandOptionWorksForWithDocumentClass() { + super.commandOptionWorksForWithDocumentClass(); + } + + @ParameterizedTest + @EnumSource(PublisherExecutor.class) + void commandOptionIsSeparateForSeparateSubscriptions(final PublisherExecutor publisherExecutor) + throws Exception { + TestCommandListener commandListener = new TestCommandListener(); + CountDownLatch commandOptionChanged = new CountDownLatch(1); + try (com.mongodb.reactivestreams.client.MongoClient client = MongoClients.create(getMongoClientSettingsBuilder() + .addCommandListener(commandListener) + .applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(new ConnectionPoolListener() { + @Override + public void connectionCheckedOut(final ConnectionCheckedOutEvent event) { + try { + // block subscriptions from executing commands + com.mongodb.assertions.Assertions.assertTrue( + commandOptionChanged.await(TIMEOUT_DURATION.toMillis(), MILLISECONDS)); + } catch (InterruptedException e) { + throw interruptAndCreateMongoInterruptedException(null, e); + } + } + })) + .build())) { + MongoDatabase database = client.getDatabase(NAMESPACE.getDatabaseName()); + database.drop(); + ChangeStreamPublisher publisher = database.getCollection(NAMESPACE.getCollectionName()).watch(); + publisher.commandOption("allowDiskUse", true); + Disposable firstSubscription = publisherExecutor.apply(publisher); + try { + publisher.commandOption("allowDiskUse", false); + // unblock subscriptions from executing commands + commandOptionChanged.countDown(); + assertCommand(commandListener, command -> assertTrue(command.getBoolean("allowDiskUse").getValue())); + } finally { + firstSubscription.dispose(); + } + commandListener.reset(); + Disposable secondSubscription = publisherExecutor.apply(publisher); + try { + assertCommand(commandListener, command -> assertFalse(command.getBoolean("allowDiskUse").getValue())); + } finally { + secondSubscription.dispose(); + } + } + } + + private static void assertCommand(final TestCommandListener commandListener, final Consumer asserter) throws Exception { + commandListener.waitForEvents(CommandStartedEvent.class, event -> event.getCommandName().equals("aggregate"), 1); + asserter.accept(commandListener.getCommandStartedEvent("aggregate").getCommand()); + } + + private enum PublisherExecutor implements Function, Disposable> { + FIRST, + SUBSCRIBE; + + @Override + public Disposable apply(final ChangeStreamPublisher publisher) { + Publisher publisherVariant; + switch (this) { + case FIRST: { + publisherVariant = publisher.first(); + break; + } + case SUBSCRIBE: { + publisherVariant = publisher; + break; + } + default: { + throw com.mongodb.assertions.Assertions.fail(); + } + } + return Mono.from(publisherVariant).subscribe(); + } + } +} diff --git a/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala index f02648f3000..979589e515a 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala @@ -263,6 +263,22 @@ case class AggregateObservable[TResult](private val wrapped: AggregatePublisher[ )(implicit e: ExplainResult DefaultsTo Document, ct: ClassTag[ExplainResult]): SingleObservable[ExplainResult] = wrapped.explain[ExplainResult](ct, verbosity) + /** + * Sets an optional field of the `aggregate` command in situations when there is no method that better satisfies your needs. + * The behavior of this method is undefined if it is used to set any of the following: + * - a field from the following set: + * [[maxTime maxTimeMS]], `cursor`, [[[explain[ExplainResult](verbosity:com\.mongodb\.ExplainVerbosity)* explain]]], + * [[comment(comment:org\.mongodb\.scala\.bson\.BsonValue)* comment]], [[collation collation]]; + * - a field that is configurable via means other than [[AggregateObservable]] methods; + * - a field that is also set via a different [[AggregateObservable]] method. + * + * @param name The name of the optional command field. + * @param value The value of the field specified by `name`. + * It is encoded via the configured `CodecRegistry`, + * which must have a codec for `org.bson.Document` regardless of the type of `value`. + * @return `this`. + * @since 5.16 + */ def commandOption(name: String, value: Any): AggregateObservable[TResult] = { wrapped.commandOption(name, value) this diff --git a/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala index 9fd931365a0..1e572d04dc2 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala @@ -205,6 +205,22 @@ case class ChangeStreamObservable[TResult](private val wrapped: ChangeStreamPubl */ def first(): SingleObservable[ChangeStreamDocument[TResult]] = wrapped.first() + /** + * Sets an optional field of the `aggregate` command in situations when there is no method that better satisfies your needs. + * The behavior of this method is undefined if it is used to set any of the following: + * - a field from the following set: + * `maxTimeMS`, `cursor`, `explain`, + * [[comment(comment:org\.mongodb\.scala\.bson\.BsonValue)* comment]]; + * - a field that is configurable via means other than [[ChangeStreamObservable]] methods; + * - a field that is also set via a different [[ChangeStreamObservable]] method. + * + * @param name The name of the optional command field. + * @param value The value of the field specified by `name`. + * It is encoded via the configured `CodecRegistry`, + * which must have a codec for `org.bson.Document` regardless of the type of `value`. + * @return `this`. + * @since 5.16 + */ def commandOption(name: String, value: Any): ChangeStreamObservable[TResult] = { wrapped.commandOption(name, value) this diff --git a/driver-sync/src/main/com/mongodb/client/AggregateIterable.java b/driver-sync/src/main/com/mongodb/client/AggregateIterable.java index 874e1e14d31..631a753e789 100644 --- a/driver-sync/src/main/com/mongodb/client/AggregateIterable.java +++ b/driver-sync/src/main/com/mongodb/client/AggregateIterable.java @@ -27,6 +27,7 @@ import com.mongodb.lang.Nullable; import org.bson.BsonValue; import org.bson.Document; +import org.bson.codecs.configuration.CodecRegistry; import org.bson.conversions.Bson; import java.util.concurrent.TimeUnit; @@ -280,5 +281,26 @@ public interface AggregateIterable extends MongoIterable { */ E explain(Class explainResultClass, ExplainVerbosity verbosity); + /** + * Sets an optional field of the {@code aggregate} command in situations when there is no method that better satisfies your needs. + * The behavior of this method is undefined if it is used to set any of the following: + *

    + *
  • + * a field from the following set: + * {@link #maxTime(long, TimeUnit) maxTimeMS}, {@code cursor}, {@link #explain(Class, ExplainVerbosity) explain}, + * {@link #comment(BsonValue) comment}, {@link #collation(Collation) collation};
  • + *
  • + * a field that is configurable via means other than {@link AggregateIterable} methods;
  • + *
  • + * a field that is also set via a different {@link AggregateIterable} method.
  • + *
+ * + * @param name The name of the optional command field. + * @param value The value of the field specified by {@code name}. + * It is encoded via the configured {@link CodecRegistry}, + * which must have a codec for {@link Document} regardless of the type of {@code value}. + * @return {@code this}. + * @since 5.16 + */ AggregateIterable commandOption(String name, Object value); } diff --git a/driver-sync/src/main/com/mongodb/client/ChangeStreamIterable.java b/driver-sync/src/main/com/mongodb/client/ChangeStreamIterable.java index 32e2806825a..2b75b5739b9 100644 --- a/driver-sync/src/main/com/mongodb/client/ChangeStreamIterable.java +++ b/driver-sync/src/main/com/mongodb/client/ChangeStreamIterable.java @@ -24,6 +24,8 @@ import org.bson.BsonDocument; import org.bson.BsonTimestamp; import org.bson.BsonValue; +import org.bson.Document; +import org.bson.codecs.configuration.CodecRegistry; import java.util.concurrent.TimeUnit; @@ -179,5 +181,26 @@ public interface ChangeStreamIterable extends MongoIterable showExpandedEvents(boolean showExpandedEvents); + /** + * Sets an optional field of the {@code aggregate} command in situations when there is no method that better satisfies your needs. + * The behavior of this method is undefined if it is used to set any of the following: + *
    + *
  • + * a field from the following set: + * {@code maxTimeMS}, {@code cursor}, {@code explain}, + * {@link #comment(BsonValue) comment};
  • + *
  • + * a field that is configurable via means other than {@link ChangeStreamIterable} methods;
  • + *
  • + * a field that is also set via a different {@link ChangeStreamIterable} method.
  • + *
+ * + * @param name The name of the optional command field. + * @param value The value of the field specified by {@code name}. + * It is encoded via the configured {@link CodecRegistry}, + * which must have a codec for {@link Document} regardless of the type of {@code value}. + * @return {@code this}. + * @since 5.16 + */ ChangeStreamIterable commandOption(String name, Object value); } diff --git a/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java index 66f7e6b1b1f..dda53c8a8fc 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java @@ -42,7 +42,10 @@ import java.util.List; import java.util.concurrent.TimeUnit; +import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; +import static com.mongodb.internal.operation.AggregateOperation.FORBIDDEN_COMMAND_OPTIONS; +import static java.lang.String.format; class AggregateIterableImpl extends MongoIterableImpl implements InternalCommonIterable, AggregateIterable { @@ -103,7 +106,8 @@ public void toCollection() { getExecutor().execute( operations.aggregateToCollection(pipeline, getTimeoutMode(), allowDiskUse, - bypassDocumentValidation, collation, hint, hintString, comment, variables, aggregationLevel), + bypassDocumentValidation, collation, hint, hintString, comment, variables, aggregationLevel, + getOverridingCommandOptions()), getReadPreference(), getReadConcern(), getClientSession()); } @@ -202,7 +206,9 @@ public E explain(final Class explainResultClass, final ExplainVerbosity v @Override public AggregateIterable commandOption(final String name, final Object value) { - setOverridingCommandOption(notNull("name", name), notNull("value", value)); + notNull("name", name); + isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTIONS.contains(name)); + overridingCommandOption(name, notNull("value", value)); return this; } @@ -220,7 +226,8 @@ public ReadOperationCursor asReadOperation() { validateTimeoutMode(); getExecutor().execute( operations.aggregateToCollection(pipeline, getTimeoutMode(), allowDiskUse, - bypassDocumentValidation, collation, hint, hintString, comment, variables, aggregationLevel), + bypassDocumentValidation, collation, hint, hintString, comment, variables, aggregationLevel, + getOverridingCommandOptions()), getReadPreference(), getReadConcern(), getClientSession()); FindOptions findOptions = new FindOptions().collation(collation); @@ -240,7 +247,8 @@ protected OperationExecutor getExecutor() { private ReadOperationExplainable asAggregateOperation() { return operations.aggregate(pipeline, resultClass, getTimeoutMode(), getBatchSize(), collation, hint, hintString, comment, - variables, allowDiskUse, aggregationLevel); + variables, allowDiskUse, aggregationLevel, + getOverridingCommandOptions()); } @Nullable diff --git a/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java index 0a4483e8e21..f02fa9b2397 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java @@ -48,7 +48,10 @@ import java.util.concurrent.TimeUnit; import static com.mongodb.assertions.Assertions.fail; +import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; +import static com.mongodb.internal.operation.ChangeStreamOperation.FORBIDDEN_COMMAND_OPTIONS; +import static java.lang.String.format; /** *

This class is not part of the public API and may be removed or changed at any time

@@ -198,7 +201,9 @@ public ChangeStreamIterable showExpandedEvents(final boolean showExpand @Override public ChangeStreamIterable commandOption(final String name, final Object value) { - setOverridingCommandOption(notNull("name", name), notNull("value", value)); + notNull("name", name); + isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTIONS.contains(name)); + overridingCommandOption(name, notNull("value", value)); return this; } @@ -235,7 +240,8 @@ protected OperationExecutor getExecutor() { private ReadOperationCursor createChangeStreamOperation(@Nullable final Integer batchSize) { return operations.changeStream(fullDocument, fullDocumentBeforeChange, pipeline, new RawBsonDocumentCodec(), changeStreamLevel, - batchSize, collation, comment, resumeToken, startAtOperationTime, startAfter, showExpandedEvents); + batchSize, collation, comment, resumeToken, startAtOperationTime, startAfter, showExpandedEvents, + getOverridingCommandOptions()); } /** diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java index 3463f6c1797..8bcb0c8c374 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java @@ -27,12 +27,12 @@ import com.mongodb.internal.operation.BatchCursor; import com.mongodb.internal.operation.ReadOperationCursor; import com.mongodb.lang.Nullable; +import org.bson.Document; import java.util.Collection; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; -import static com.mongodb.assertions.Assertions.fail; import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; @@ -51,6 +51,7 @@ public abstract class MongoIterableImpl implements MongoIterable asReadOperation(); @@ -115,8 +117,20 @@ public MongoIterable timeoutMode(final TimeoutMode timeoutMode) { return this; } - MongoIterable setOverridingCommandOption(final String name, final Object value) { - throw fail("VAKOTODO"); + /** + * @see InternalCommonIterable#commandOption(String, Object) + * @see #getOverridingCommandOptions() + */ + MongoIterable overridingCommandOption(final String name, final Object value) { + overridingCommandOptions.put(name, value); + return this; + } + + /** + * @see #overridingCommandOption(String, Object) + */ + Document getOverridingCommandOptions() { + return overridingCommandOptions; } @Override diff --git a/driver-sync/src/test/functional/com/mongodb/client/AggregateIterableIntegrationTest.java b/driver-sync/src/test/functional/com/mongodb/client/AggregateIterableIntegrationTest.java new file mode 100644 index 00000000000..b1b48ac4ac3 --- /dev/null +++ b/driver-sync/src/test/functional/com/mongodb/client/AggregateIterableIntegrationTest.java @@ -0,0 +1,166 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed 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 com.mongodb.client; + +import com.mongodb.MongoClientSettings; +import com.mongodb.MongoNamespace; +import com.mongodb.internal.connection.TestCommandListener; +import org.bson.BsonBoolean; +import org.bson.BsonDocument; +import org.bson.BsonInt32; +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.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +import static com.mongodb.ClusterFixture.serverVersionAtLeast; +import static com.mongodb.client.Fixture.getMongoClientSettingsBuilder; +import static com.mongodb.client.model.Aggregates.merge; +import static com.mongodb.client.model.Aggregates.out; +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +public class AggregateIterableIntegrationTest { + protected static final MongoNamespace NAMESPACE = new MongoNamespace(AggregateIterableIntegrationTest.class.getSimpleName(), "test"); + + private MongoClient client; + private MongoCollection collection; + private TestCommandListener commandListener; + + @BeforeEach + void beforeEach() { + commandListener = new TestCommandListener(); + client = createClient(getMongoClientSettingsBuilder() + .addCommandListener(commandListener) + .build()); + MongoDatabase database = client.getDatabase(NAMESPACE.getDatabaseName()); + database.drop(); + collection = database.getCollection(NAMESPACE.getCollectionName()); + } + + @AfterEach + void afterEach() { + if (client != null) { + client.close(); + } + } + + protected MongoClient createClient(final MongoClientSettings settings) { + return MongoClients.create(settings); + } + + @ParameterizedTest + @EnumSource(IterableExecutor.class) + void commandOption(final IterableExecutor iterableExecutor) { + // `let` requires MongoDB 5.0 + assumeTrue(serverVersionAtLeast(5, 0)); + assertCommand( + iterable -> iterable + .commandOption("allowDiskUse", true) + .commandOption("let", new Document("overriding", 2)) + .let(new Document("overridden", 1)), + iterableExecutor, + command -> { + assertEquals(BsonBoolean.TRUE, command.get("allowDiskUse")); + assertEquals(new BsonDocument("overriding", new BsonInt32(2)), command.getDocument("let")); + }); + } + + private void assertCommand( + final Consumer> iterableTuner, + final IterableExecutor iterableExecutor, + final Consumer asserter) { + AggregateIterable iterable = collection.aggregate(iterableExecutor.getPipeline()); + iterableTuner.accept(iterable); + iterableExecutor.accept(iterable); + asserter.accept(iterableExecutor.getCommand(commandListener)); + } + + private enum IterableExecutor implements Consumer> { + FIRST, + INTO, + CURSOR, + CURSOR_WITH_OUT, + CURSOR_WITH_MERGE, + TO_COLLECTION_WITH_OUT, + TO_COLLECTION_WITH_MERGE, + EXPLAIN; + + List getPipeline() { + switch (this) { + case CURSOR_WITH_OUT: + case TO_COLLECTION_WITH_OUT: { + return singletonList(out(NAMESPACE.getCollectionName())); + } + case CURSOR_WITH_MERGE: + case TO_COLLECTION_WITH_MERGE: { + return singletonList(merge(NAMESPACE.getCollectionName() + "Merged")); + } + default: { + return emptyList(); + } + } + } + + @Override + public void accept(final AggregateIterable iterable) { + switch (this) { + case FIRST: { + iterable.first(); + break; + } + case INTO: { + iterable.into(new ArrayList<>()); + break; + } + case CURSOR: + case CURSOR_WITH_OUT: + case CURSOR_WITH_MERGE: { + try (MongoCursor cursor = iterable.cursor()) { + cursor.hasNext(); + } + break; + } + case TO_COLLECTION_WITH_OUT: + case TO_COLLECTION_WITH_MERGE: { + iterable.toCollection(); + break; + } + case EXPLAIN: { + iterable.explain(); + break; + } + default: { + com.mongodb.assertions.Assertions.fail(); + } + } + } + + BsonDocument getCommand(final TestCommandListener commandListener) { + return this == IterableExecutor.EXPLAIN + ? commandListener.getCommandStartedEvent("explain").getCommand().getDocument("explain") + : commandListener.getCommandStartedEvent("aggregate").getCommand(); + } + } +} diff --git a/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamIterableIntegrationTest.java b/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamIterableIntegrationTest.java new file mode 100644 index 00000000000..6a1aa90abfd --- /dev/null +++ b/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamIterableIntegrationTest.java @@ -0,0 +1,179 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed 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 com.mongodb.client; + +import com.mongodb.MongoClientSettings; +import com.mongodb.MongoNamespace; +import com.mongodb.client.model.Collation; +import com.mongodb.client.model.changestream.OperationType; +import com.mongodb.event.CommandStartedEvent; +import com.mongodb.internal.connection.TestCommandListener; +import org.bson.BsonDocument; +import org.bson.BsonString; +import org.bson.BsonValue; +import org.bson.Document; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Stream; + +import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; +import static com.mongodb.client.Fixture.getMongoClientSettingsBuilder; +import static java.util.stream.Collectors.toList; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +public class ChangeStreamIterableIntegrationTest { + protected static final MongoNamespace NAMESPACE = new MongoNamespace(ChangeStreamIterableIntegrationTest.class.getSimpleName(), "test"); + + private MongoClient client; + private MongoCollection collection; + private TestCommandListener commandListener; + + @BeforeEach + void beforeEach() { + assumeTrue(isDiscoverableReplicaSet()); + commandListener = new TestCommandListener(); + client = createClient(getMongoClientSettingsBuilder() + .addCommandListener(commandListener) + .build()); + MongoDatabase database = client.getDatabase(NAMESPACE.getDatabaseName()); + database.drop(); + collection = database.getCollection(NAMESPACE.getCollectionName()); + } + + @AfterEach + void afterEach() { + if (client != null) { + client.close(); + } + } + + protected MongoClient createClient(final MongoClientSettings settings) { + return MongoClients.create(settings); + } + + /** + * {@link ChangeStreamIterable#withDocumentClass(Class)} returns a new {@link MongoIterable}, + * which must handle batch size correctly. + */ + @Test + protected void batchSizeWorksForWithDocumentClass() { + assertAll( + () -> assertBatchSizeWorksForWithDocumentClass(true, true), + () -> assertBatchSizeWorksForWithDocumentClass(true, false), + () -> assertBatchSizeWorksForWithDocumentClass(false, true), + () -> assertBatchSizeWorksForWithDocumentClass(false, false)); + } + + private void assertBatchSizeWorksForWithDocumentClass(final boolean chaining, final boolean batchSizeBeforeWithDocumentClass) { + commandListener.reset(); + int batchSize = 3; + int batchCount = 2; + ChangeStreamIterable iterable = collection.watch(); + MongoIterable configuredIterable; + if (chaining) { + if (batchSizeBeforeWithDocumentClass) { + configuredIterable = iterable.batchSize(batchSize).withDocumentClass(Document.class); + } else { + configuredIterable = iterable.withDocumentClass(Document.class).batchSize(batchSize); + } + } else { + if (batchSizeBeforeWithDocumentClass) { + iterable.batchSize(batchSize); + configuredIterable = iterable.withDocumentClass(Document.class); + } else { + configuredIterable = iterable.withDocumentClass(Document.class); + iterable.batchSize(batchSize); + } + } + try (MongoCursor cursor = configuredIterable.cursor()) { + List insertedDocuments = Stream.generate(Document::new).limit(batchSize * batchCount).collect(toList()); + collection.insertMany(insertedDocuments); + for (int i = 0; i < insertedDocuments.size(); i++) { + assertEquals(OperationType.INSERT.getValue(), cursor.next().get("operationType")); + } + commandListener.getCommandStartedEvents("getMore").stream() + .map(CommandStartedEvent::getCommand) + .forEach(command -> assertEquals(batchSize, command.getInt32("batchSize").intValue())); + } + } + + /** + * @see #batchSizeWorksForWithDocumentClass() + */ + @Test + protected void commandOptionWorksForWithDocumentClass() { + assertAll( + () -> commandOptionWorksForWithDocumentClass(true, true), + () -> commandOptionWorksForWithDocumentClass(false, true), + () -> commandOptionWorksForWithDocumentClass(false, false)); + } + + private void commandOptionWorksForWithDocumentClass(final boolean chaining, final boolean commandOptionBeforeWithDocumentClass) { + commandListener.reset(); + assertCommand( + iterable -> { + Document collation = new Document("locale", "en"); + MongoIterable configuredIterable; + if (chaining) { + if (commandOptionBeforeWithDocumentClass) { + configuredIterable = iterable.commandOption("collation", collation).withDocumentClass(Document.class); + } else { + throw com.mongodb.assertions.Assertions.fail("this variant is not expressible in code"); + } + } else { + if (commandOptionBeforeWithDocumentClass) { + iterable.commandOption("collation", collation); + configuredIterable = iterable.withDocumentClass(Document.class); + } else { + configuredIterable = iterable.withDocumentClass(Document.class); + iterable.commandOption("collation", collation); + } + } + return configuredIterable; + }, + command -> { + BsonValue actualCollation = command.get("collation"); + assertEquals(new BsonDocument("locale", new BsonString("en")), actualCollation); + }); + } + + @Test + void commandOption() { + assertCommand( + iterable -> iterable + .commandOption("collation", new BsonDocument("locale", new BsonString("en"))) + .collation(Collation.builder().locale("overridden").build()), + command -> { + assertEquals(new BsonDocument("locale", new BsonString("en")), command.getDocument("collation")); + }); + } + + private void assertCommand( + final Function, MongoIterable> iterableTuner, + final Consumer asserter) { + MongoIterable iterable = iterableTuner.apply(collection.watch()); + iterable.cursor().close(); + asserter.accept(commandListener.getCommandStartedEvent("aggregate").getCommand()); + } +} diff --git a/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamProseTest.java index fd9d11fd68f..fc764a6642b 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamProseTest.java @@ -29,10 +29,7 @@ import com.mongodb.client.model.CreateCollectionOptions; import com.mongodb.client.model.changestream.ChangeStreamDocument; import com.mongodb.client.model.changestream.FullDocumentBeforeChange; -import com.mongodb.client.model.changestream.OperationType; import com.mongodb.client.model.changestream.SplitEvent; -import com.mongodb.event.CommandStartedEvent; -import com.mongodb.internal.connection.TestCommandListener; import com.mongodb.internal.operation.AggregateResponseBatchCursor; import com.mongodb.internal.operation.ChangeStreamOperationProseTestSpecification; import org.bson.BsonArray; @@ -47,9 +44,7 @@ import java.lang.reflect.Field; import java.time.Instant; -import java.util.List; import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Stream; import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; import static com.mongodb.ClusterFixture.serverVersionAtLeast; @@ -60,10 +55,7 @@ import static com.mongodb.client.model.Updates.set; import static java.lang.Math.toIntExact; import static java.lang.String.format; -import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; -import static java.util.stream.Collectors.toList; -import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @@ -471,59 +463,6 @@ void shouldDoOneServerSelectionForResumeAttempt() throws Exception { } } - /** - * Not a prose spec test. - *

- * {@link ChangeStreamIterable#withDocumentClass(Class)} returns a new {@link MongoIterable}, - * which must handle batch size correctly. - */ - @Test - protected void batchSizeWorksForWithDocumentClass() { - assertAll( - () -> assertBatchSizeWorksForWithDocumentClass(true, true), - () -> assertBatchSizeWorksForWithDocumentClass(true, false), - () -> assertBatchSizeWorksForWithDocumentClass(false, true), - () -> assertBatchSizeWorksForWithDocumentClass(false, false)); - } - - private void assertBatchSizeWorksForWithDocumentClass(final boolean chaining, final boolean batchSizeBeforeWithDocumentClass) { - TestCommandListener commandListener = new TestCommandListener(singletonList("commandStartedEvent"), emptyList()); - try (MongoClient client = createClient(getMongoClientSettingsBuilder().addCommandListener(commandListener).build())) { - MongoCollection collection = client - .getDatabase(NAMESPACE.getDatabaseName()) - .getCollection(NAMESPACE.getCollectionName()); - int batchSize = 3; - int batchCount = 2; - ChangeStreamIterable changeStreamIterable = collection.watch(); - MongoIterable configuredChangeStreamIterable; - if (chaining) { - if (batchSizeBeforeWithDocumentClass) { - configuredChangeStreamIterable = changeStreamIterable.batchSize(batchSize).withDocumentClass(Document.class); - } else { - configuredChangeStreamIterable = changeStreamIterable.withDocumentClass(Document.class).batchSize(batchSize); - } - } else { - if (batchSizeBeforeWithDocumentClass) { - changeStreamIterable.batchSize(batchSize); - configuredChangeStreamIterable = changeStreamIterable.withDocumentClass(Document.class); - } else { - configuredChangeStreamIterable = changeStreamIterable.withDocumentClass(Document.class); - changeStreamIterable.batchSize(batchSize); - } - } - try (MongoCursor changeStreamCursor = configuredChangeStreamIterable.cursor()) { - List insertedDocuments = Stream.generate(Document::new).limit(batchSize * batchCount).collect(toList()); - collection.insertMany(insertedDocuments); - for (int i = 0; i < insertedDocuments.size(); i++) { - assertEquals(OperationType.INSERT.getValue(), changeStreamCursor.next().get("operationType")); - } - commandListener.getCommandStartedEvents("getMore").stream() - .map(CommandStartedEvent::getCommand) - .forEach(command -> assertEquals(batchSize, command.getInt32("batchSize").intValue())); - } - } - } - private boolean canRunTests() { return isDiscoverableReplicaSet(); } From a117fe0aae15f2b42483e43acb96dae14c4a6a32 Mon Sep 17 00:00:00 2001 From: Valentin Kovalenko Date: Tue, 1 Dec 2026 14:26:11 -0600 Subject: [PATCH 07/11] JAVA-6258 Improve the reactive API documentation JAVA-6258 --- .../reactivestreams/client/package-info.java | 32 ++++++++++++++----- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/package-info.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/package-info.java index 80d98a2346a..95984ab4550 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/package-info.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/package-info.java @@ -15,21 +15,37 @@ */ /** - * This packages contains classes for the reactive stream client implementation. + * This package contains classes for the reactive stream client implementation. *

- * All API {@link org.reactivestreams.Publisher}s are + * All API {@link Publisher}s are * cold, * meaning that nothing happens until they are subscribed to. - * So just creating a {@link org.reactivestreams.Publisher} won’t cause any network IO. - * It’s not until {@link org.reactivestreams.Publisher#subscribe(org.reactivestreams.Subscriber)} is called that the driver executes the - * operation. + * So just creating a {@link Publisher} won’t cause any network IO. + * It’s not until {@link Publisher#subscribe(Subscriber)} is called that the driver executes + * operations. *

- * All API {@link org.reactivestreams.Publisher}s are unicast. - * Each {@link org.reactivestreams.Subscription} to a {@link org.reactivestreams.Publisher} relates to a single MongoDB operation and its - * {@link org.reactivestreams.Subscriber} will receive its own specific set of results. + * All API {@link Publisher}s are + * unicast: + * each {@link Subscription} to a {@link Publisher} relates to a separate set of + * operations, as identified by {@link CommandEvent#getOperationId()} + * (not to be confused with commands, as identified by {@link CommandEvent#getRequestId()}), + * and its {@link Subscriber} receives its own specific set of results. + * Usually, a single {@link Subscription} causes execution of a single operation, but in some cases, like + * {@link GridFSBucket#uploadFromPublisher(ClientSession, BsonValue, String, Publisher, GridFSUploadOptions)}, + * it causes execution of multiple operations. */ @NonNullApi package com.mongodb.reactivestreams.client; import com.mongodb.lang.NonNullApi; +// the following imports are used only in the API documentation comment, which `UnusedImports` does not take into account +// CHECKSTYLE.OFF: UnusedImports +import com.mongodb.client.gridfs.model.GridFSUploadOptions; +import com.mongodb.event.CommandEvent; +import com.mongodb.reactivestreams.client.gridfs.GridFSBucket; +import org.bson.BsonValue; +import org.reactivestreams.Publisher; +import org.reactivestreams.Subscriber; +import org.reactivestreams.Subscription; +// CHECKSTYLE.ON: UnusedImports From a5fd442e18789f029aa67bae5e9a31d61308922d Mon Sep 17 00:00:00 2001 From: Valentin Kovalenko Date: Wed, 2 Dec 2026 13:08:45 -0600 Subject: [PATCH 08/11] Review: fixes 1 --- AGENTS.md | 2 +- .../org/bson/codecs/RawBsonDocumentCodec.java | 2 +- .../org/bson/vector/BinaryVectorTest.java | 2 +- config/spotbugs/exclude.xml | 16 +++ driver-core/build.gradle.kts | 2 +- .../client/internal/BatchCursorPublisher.java | 2 +- .../internal/ChangeStreamPublisherImpl.java | 34 ++++--- .../AggregatePublisherIntegrationTest.java | 7 +- .../ChangeStreamPublisherIntegrationTest.java | 26 ++--- .../syncadapter/SyncChangeStreamIterable.java | 9 +- .../internal/ChangeStreamIterableImpl.java | 39 ++++---- .../client/internal/MongoIterableImpl.java | 8 +- .../ChangeStreamIterableIntegrationTest.java | 98 +++++++++---------- 13 files changed, 133 insertions(+), 114 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ff610b7d140..5925d9d30db 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,7 +16,7 @@ The default branch is `main` (not `master`). Always use `main` when comparing, d - **Branch naming:** `JAVA-XXXX` matching the Jira ticket (e.g., `JAVA-6143`) - **Commits:** Keep commits logical and reviewable — each commit should be a coherent unit of change - **TODO comments:** Must reference a Jira ticket if the work belongs to a different ticket: - `// TODO JAVA-XXXX reasoning for the todo` + `// TODO-JAVA-XXXX reasoning for the todo` ## Core Rules diff --git a/bson/src/main/org/bson/codecs/RawBsonDocumentCodec.java b/bson/src/main/org/bson/codecs/RawBsonDocumentCodec.java index a0d5947429f..58aa13895ab 100644 --- a/bson/src/main/org/bson/codecs/RawBsonDocumentCodec.java +++ b/bson/src/main/org/bson/codecs/RawBsonDocumentCodec.java @@ -45,7 +45,7 @@ public void encode(final BsonWriter writer, final RawBsonDocument value, final E // abstract would be a breaking change, and adding it as a default method would force // BsonWriter to depend on BsonBinaryReader/ByteBufferBsonInput, violating the // interface's abstraction. - // TODO JAVA-6211 move pipe(byte[], int, int) to BsonWriter to remove this instanceof. + // TODO-JAVA-6211 move pipe(byte[], int, int) to BsonWriter to remove this instanceof. ((BsonBinaryWriter) writer).pipe(value.getBackingArray(), value.getByteOffset(), value.getByteLength()); } else { try (BsonBinaryReader reader = new BsonBinaryReader(new ByteBufferBsonInput(value.getByteBuffer()))) { diff --git a/bson/src/test/unit/org/bson/vector/BinaryVectorTest.java b/bson/src/test/unit/org/bson/vector/BinaryVectorTest.java index 73188358b67..acc996767bb 100644 --- a/bson/src/test/unit/org/bson/vector/BinaryVectorTest.java +++ b/bson/src/test/unit/org/bson/vector/BinaryVectorTest.java @@ -68,7 +68,7 @@ class BinaryVectorTest { "FLOAT32 with padding", // It is impossible to provide padding for INT8 in the API. "INT8 with padding", - // TODO JAVA-5848 in 6.0.0 "Padding specified with no vector data PACKED_BIT" will throw an error (currently logs a warning). + // TODO-JAVA-5848 in 6.0.0 "Padding specified with no vector data PACKED_BIT" will throw an error (currently logs a warning). "Padding specified with no vector data PACKED_BIT" ); diff --git a/config/spotbugs/exclude.xml b/config/spotbugs/exclude.xml index 3146df34546..0e113429561 100644 --- a/config/spotbugs/exclude.xml +++ b/config/spotbugs/exclude.xml @@ -327,4 +327,20 @@ + + + + + + + + + + + + + + diff --git a/driver-core/build.gradle.kts b/driver-core/build.gradle.kts index e320f85652e..a6c24abc31a 100644 --- a/driver-core/build.gradle.kts +++ b/driver-core/build.gradle.kts @@ -68,7 +68,7 @@ dependencies { tasks.processTestResources { from("${rootProject.projectDir}/testing/resources") - // TODO JAVA-6283: remove this and the resources-ghsa-556f-q76p-2vxq + // TODO-JAVA-6283: remove this and the resources-ghsa-556f-q76p-2vxq // directory once the specifications submodule includes the GridFS $eq // tests. These files are vendored from the specifications security fork. // Some of them replace files the submodule already provides, so this spec diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java index 7bdc48620d6..b651433d450 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java @@ -146,7 +146,7 @@ Publisher overridingCommandOption(final String name, final Object value) { * @see #overridingCommandOption(String, Object) */ Document getOverridingCommandOptions() { - // An application may mutate `overridingCommandOptions` via the `overridingCommandOption` method after subscribing to a `Publisher`. + // An application may mutate `overridingCommandOptions` after subscribing to a `Publisher`. // Such a mutation must not conflict with `overridingCommandOptions` being read while publishing. // That is why we must return a shallow copy of `overridingCommandOptions`. return new Document(overridingCommandOptions); diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java index c8aded0bb78..d331b227139 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java @@ -31,6 +31,7 @@ import org.bson.BsonString; import org.bson.BsonTimestamp; import org.bson.BsonValue; +import org.bson.Document; import org.bson.codecs.Codec; import org.bson.conversions.Bson; import org.reactivestreams.Publisher; @@ -138,25 +139,24 @@ public ChangeStreamPublisher collation(@Nullable final Collation collation) { @Override public Publisher withDocumentClass(final Class clazz) { return new BatchCursorPublisher(getClientSession(), getMongoOperationPublisher().withDocumentClass(clazz)) { + { + Integer batchSize = ChangeStreamPublisherImpl.this.getBatchSize(); + if (batchSize != null) { + this.batchSize(batchSize); + } + ChangeStreamPublisherImpl.this.getOverridingCommandOptions().forEach(this::overridingCommandOption); + } + @Override ReadOperationCursor asReadOperation(final int initialBatchSize) { - return createChangeStreamOperation(getMongoOperationPublisher().getCodecRegistry().get(clazz), initialBatchSize); + return createChangeStreamOperation( + getMongoOperationPublisher().getCodecRegistry().get(clazz), initialBatchSize, getOverridingCommandOptions()); } @Override Function, TimeoutSettings> getTimeoutSettings() { return (operations -> operations.createTimeoutSettings(0, maxAwaitTimeMS)); } - - @Nullable - @Override - public Integer getBatchSize() { - Integer batchSize = super.getBatchSize(); - if (batchSize == null) { - batchSize = ChangeStreamPublisherImpl.this.getBatchSize(); - } - return batchSize; - } }; } @@ -188,7 +188,7 @@ public ChangeStreamPublisher commandOption(final String name, final Object va @Override ReadOperationCursor> asReadOperation(final int initialBatchSize) { - return createChangeStreamOperation(codec, initialBatchSize); + return createChangeStreamOperation(codec, initialBatchSize, getOverridingCommandOptions()); } @@ -197,9 +197,15 @@ Function, TimeoutSettings> getTimeoutSettings() { return (operations -> operations.createTimeoutSettings(0, maxAwaitTimeMS)); } - private ReadOperationCursor createChangeStreamOperation(final Codec codec, final int initialBatchSize) { + /** + * @param overridingCommandOptions This parameter exists to allow both {@code this} {@link ChangeStreamPublisherImpl}, + * and the {@link BatchCursorPublisher} created and returned by {@link #withDocumentClass(Class)} + * to pass their own {@link #getOverridingCommandOptions()}. + */ + private ReadOperationCursor createChangeStreamOperation( + final Codec codec, final int initialBatchSize, final Document overridingCommandOptions) { return getOperations().changeStream(fullDocument, fullDocumentBeforeChange, pipeline, codec, changeStreamLevel, initialBatchSize, collation, comment, resumeToken, startAtOperationTime, startAfter, showExpandedEvents, - getOverridingCommandOptions()); + overridingCommandOptions); } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/AggregatePublisherIntegrationTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/AggregatePublisherIntegrationTest.java index 7955feb051b..66db9427881 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/AggregatePublisherIntegrationTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/AggregatePublisherIntegrationTest.java @@ -53,8 +53,7 @@ protected MongoClient createClient(final MongoClientSettings settings) { @ParameterizedTest @EnumSource(PublisherExecutor.class) - void commandOptionIsSeparateForSeparateSubscriptions(final PublisherExecutor publisherExecutor) - throws Exception { + void commandOptionIsSeparateForSeparateSubscriptions(final PublisherExecutor publisherExecutor) throws Exception { TestCommandListener commandListener = new TestCommandListener(); CountDownLatch commandOptionChanged = new CountDownLatch(1); try (com.mongodb.reactivestreams.client.MongoClient client = MongoClients.create(getMongoClientSettingsBuilder() @@ -63,7 +62,7 @@ void commandOptionIsSeparateForSeparateSubscriptions(final PublisherExecutor pub @Override public void connectionCheckedOut(final ConnectionCheckedOutEvent event) { try { - // block subscriptions from executing commands + // block executions com.mongodb.assertions.Assertions.assertTrue( commandOptionChanged.await(TIMEOUT_DURATION.toMillis(), MILLISECONDS)); } catch (InterruptedException e) { @@ -78,7 +77,7 @@ public void connectionCheckedOut(final ConnectionCheckedOutEvent event) { publisher.commandOption("allowDiskUse", true); CompletableFuture firstSubscription = publisherExecutor.apply(publisher); publisher.commandOption("allowDiskUse", false); - // unblock subscriptions from executing commands + // unblock executions commandOptionChanged.countDown(); firstSubscription.get(TIMEOUT_DURATION.toMillis(), MILLISECONDS); assertTrue(publisherExecutor.getCommand(commandListener).getBoolean("allowDiskUse").getValue()); diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamPublisherIntegrationTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamPublisherIntegrationTest.java index 39e646acac8..6aafc936862 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamPublisherIntegrationTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ChangeStreamPublisherIntegrationTest.java @@ -30,6 +30,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; import org.reactivestreams.Publisher; import reactor.core.Disposable; import reactor.core.publisher.Mono; @@ -66,15 +67,18 @@ protected MongoClient createClient(final MongoClientSettings settings) { /** * {@link ChangeStreamPublisher#withDocumentClass(Class)} returns a new {@link BatchCursorPublisher}, * which must handle batch size correctly. + * + * @param batchSizeBeforeWithDocumentClass Is never {@code false} because the corresponding reactive API usage is impossible. */ - @Test + @ParameterizedTest + @ValueSource(booleans = {true}) @Override - protected void batchSizeWorksForWithDocumentClass() { - super.batchSizeWorksForWithDocumentClass(); + protected void batchSizeWorksForWithDocumentClass(final boolean batchSizeBeforeWithDocumentClass) { + super.batchSizeWorksForWithDocumentClass(batchSizeBeforeWithDocumentClass); } /** - * @see #batchSizeWorksForWithDocumentClass() + * @see #batchSizeWorksForWithDocumentClass(boolean) */ @Test @Override @@ -84,8 +88,7 @@ protected void commandOptionWorksForWithDocumentClass() { @ParameterizedTest @EnumSource(PublisherExecutor.class) - void commandOptionIsSeparateForSeparateSubscriptions(final PublisherExecutor publisherExecutor) - throws Exception { + void commandOptionIsSeparateForSeparateSubscriptions(final PublisherExecutor publisherExecutor) throws Exception { TestCommandListener commandListener = new TestCommandListener(); CountDownLatch commandOptionChanged = new CountDownLatch(1); try (com.mongodb.reactivestreams.client.MongoClient client = MongoClients.create(getMongoClientSettingsBuilder() @@ -94,7 +97,7 @@ void commandOptionIsSeparateForSeparateSubscriptions(final PublisherExecutor pub @Override public void connectionCheckedOut(final ConnectionCheckedOutEvent event) { try { - // block subscriptions from executing commands + // block executions com.mongodb.assertions.Assertions.assertTrue( commandOptionChanged.await(TIMEOUT_DURATION.toMillis(), MILLISECONDS)); } catch (InterruptedException e) { @@ -104,29 +107,28 @@ public void connectionCheckedOut(final ConnectionCheckedOutEvent event) { })) .build())) { MongoDatabase database = client.getDatabase(NAMESPACE.getDatabaseName()); - database.drop(); ChangeStreamPublisher publisher = database.getCollection(NAMESPACE.getCollectionName()).watch(); publisher.commandOption("allowDiskUse", true); Disposable firstSubscription = publisherExecutor.apply(publisher); try { publisher.commandOption("allowDiskUse", false); - // unblock subscriptions from executing commands + // unblock executions commandOptionChanged.countDown(); - assertCommand(commandListener, command -> assertTrue(command.getBoolean("allowDiskUse").getValue())); + waitForCommandAndAssert(commandListener, command -> assertTrue(command.getBoolean("allowDiskUse").getValue())); } finally { firstSubscription.dispose(); } commandListener.reset(); Disposable secondSubscription = publisherExecutor.apply(publisher); try { - assertCommand(commandListener, command -> assertFalse(command.getBoolean("allowDiskUse").getValue())); + waitForCommandAndAssert(commandListener, command -> assertFalse(command.getBoolean("allowDiskUse").getValue())); } finally { secondSubscription.dispose(); } } } - private static void assertCommand(final TestCommandListener commandListener, final Consumer asserter) throws Exception { + private static void waitForCommandAndAssert(final TestCommandListener commandListener, final Consumer asserter) throws Exception { commandListener.waitForEvents(CommandStartedEvent.class, event -> event.getCommandName().equals("aggregate"), 1); asserter.accept(commandListener.getCommandStartedEvent("aggregate").getCommand()); } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncChangeStreamIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncChangeStreamIterable.java index 9e455d7d17e..4bc5e39406f 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncChangeStreamIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncChangeStreamIterable.java @@ -36,8 +36,6 @@ class SyncChangeStreamIterable extends SyncMongoIterable> implements ChangeStreamIterable { private final ChangeStreamPublisher wrapped; - @Nullable - private Integer batchSize; SyncChangeStreamIterable(final ChangeStreamPublisher wrapped) { super(wrapped); @@ -110,7 +108,6 @@ public ChangeStreamIterable resumeAfter(final BsonDocument resumeToken) { @Override public ChangeStreamIterable batchSize(final int batchSize) { wrapped.batchSize(batchSize); - this.batchSize = batchSize; super.batchSize(batchSize); return this; } @@ -129,11 +126,7 @@ public ChangeStreamIterable collation(@Nullable final Collation collation) { @Override public MongoIterable withDocumentClass(final Class clazz) { - SyncMongoIterable result = new SyncMongoIterable<>(wrapped.withDocumentClass(clazz)); - if (batchSize != null) { - result.batchSize(batchSize); - } - return result; + return new SyncMongoIterable<>(wrapped.withDocumentClass(clazz)); } @Override diff --git a/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java index f02fa9b2397..10a7b48565d 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java @@ -38,6 +38,7 @@ import org.bson.BsonString; import org.bson.BsonTimestamp; import org.bson.BsonValue; +import org.bson.Document; import org.bson.RawBsonDocument; import org.bson.codecs.Codec; import org.bson.codecs.RawBsonDocumentCodec; @@ -136,6 +137,14 @@ public ChangeStreamIterable collation(@Nullable final Collation collati public MongoIterable withDocumentClass(final Class clazz) { return new MongoIterableImpl(getClientSession(), getExecutor(), getReadConcern(), getReadPreference(), getRetryReads(), getTimeoutSettings()) { + { + Integer batchSize = ChangeStreamIterableImpl.this.getBatchSize(); + if (batchSize != null) { + this.batchSize(batchSize); + } + ChangeStreamIterableImpl.this.getOverridingCommandOptions().forEach(this::overridingCommandOption); + } + @Override public MongoCursor iterator() { return cursor(); @@ -143,7 +152,9 @@ public MongoCursor iterator() { @Override public MongoChangeStreamCursor cursor() { - return new MongoChangeStreamCursorImpl<>(execute(getBatchSize()), codecRegistry.get(clazz), initialResumeToken()); + return new MongoChangeStreamCursorImpl<>( + execute(getBatchSize(), getOverridingCommandOptions()), + codecRegistry.get(clazz), initialResumeToken()); } @Override @@ -155,16 +166,6 @@ public ReadOperationCursor asReadOperation() { protected OperationExecutor getExecutor() { return ChangeStreamIterableImpl.this.getExecutor(); } - - @Nullable - @Override - public Integer getBatchSize() { - Integer batchSize = super.getBatchSize(); - if (batchSize == null) { - batchSize = ChangeStreamIterableImpl.this.getBatchSize(); - } - return batchSize; - } }; } @@ -214,7 +215,7 @@ public MongoCursor> iterator() { @Override public MongoChangeStreamCursor> cursor() { - return new MongoChangeStreamCursorImpl<>(execute(getBatchSize()), codec, initialResumeToken()); + return new MongoChangeStreamCursorImpl<>(execute(getBatchSize(), getOverridingCommandOptions()), codec, initialResumeToken()); } @Nullable @@ -238,19 +239,23 @@ protected OperationExecutor getExecutor() { return getExecutor(operations.createTimeoutSettings(0, maxAwaitTimeMS)); } - private ReadOperationCursor createChangeStreamOperation(@Nullable final Integer batchSize) { + private ReadOperationCursor createChangeStreamOperation( + @Nullable final Integer batchSize, final Document overridingCommandOptions) { return operations.changeStream(fullDocument, fullDocumentBeforeChange, pipeline, new RawBsonDocumentCodec(), changeStreamLevel, batchSize, collation, comment, resumeToken, startAtOperationTime, startAfter, showExpandedEvents, - getOverridingCommandOptions()); + overridingCommandOptions); } /** * @param batchSize This parameter exists to allow both {@code this} {@link ChangeStreamIterableImpl}, - * and the {@link MongoIterable} created and returned by {@link withDocumentClass} + * and the {@link MongoIterable} created and returned by {@link #withDocumentClass(Class)} * to pass their own {@link #getBatchSize()}. + * @param overridingCommandOptions See {@code batchSize}. */ - private BatchCursor execute(@Nullable final Integer batchSize) { - return getExecutor().execute(createChangeStreamOperation(batchSize), getReadPreference(), getReadConcern(), getClientSession()); + private BatchCursor execute(@Nullable final Integer batchSize, final Document overridingCommandOptions) { + return getExecutor().execute( + createChangeStreamOperation(batchSize, overridingCommandOptions), + getReadPreference(), getReadConcern(), getClientSession()); } private BsonDocument initialResumeToken() { diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java index 8bcb0c8c374..e4f8a295fae 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java @@ -130,7 +130,13 @@ MongoIterable overridingCommandOption(final String name, final Object v * @see #overridingCommandOption(String, Object) */ Document getOverridingCommandOptions() { - return overridingCommandOptions; + // If a change stream is resumed, the `aggregate` command executed when resuming must be the same + // as the one used to create the original cursor. + // An application may mutate `overridingCommandOptions` after creating the original cursor. + // Such a mutation must not conflict with `overridingCommandOptions` being read when resuming. + // That is why we must return a shallow copy of `overridingCommandOptions` here, + // even if there are effectively other copies made down the execution. + return new Document(overridingCommandOptions); } @Override diff --git a/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamIterableIntegrationTest.java b/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamIterableIntegrationTest.java index 6a1aa90abfd..83060a59e41 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamIterableIntegrationTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/ChangeStreamIterableIntegrationTest.java @@ -19,6 +19,7 @@ import com.mongodb.MongoClientSettings; import com.mongodb.MongoNamespace; import com.mongodb.client.model.Collation; +import com.mongodb.client.model.changestream.ChangeStreamDocument; import com.mongodb.client.model.changestream.OperationType; import com.mongodb.event.CommandStartedEvent; import com.mongodb.internal.connection.TestCommandListener; @@ -29,6 +30,8 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.util.List; import java.util.function.Consumer; @@ -37,9 +40,11 @@ import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; import static com.mongodb.client.Fixture.getMongoClientSettingsBuilder; +import static com.mongodb.client.Fixture.getPrimary; import static java.util.stream.Collectors.toList; -import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assumptions.assumeTrue; public class ChangeStreamIterableIntegrationTest { @@ -76,36 +81,18 @@ protected MongoClient createClient(final MongoClientSettings settings) { * {@link ChangeStreamIterable#withDocumentClass(Class)} returns a new {@link MongoIterable}, * which must handle batch size correctly. */ - @Test - protected void batchSizeWorksForWithDocumentClass() { - assertAll( - () -> assertBatchSizeWorksForWithDocumentClass(true, true), - () -> assertBatchSizeWorksForWithDocumentClass(true, false), - () -> assertBatchSizeWorksForWithDocumentClass(false, true), - () -> assertBatchSizeWorksForWithDocumentClass(false, false)); - } - - private void assertBatchSizeWorksForWithDocumentClass(final boolean chaining, final boolean batchSizeBeforeWithDocumentClass) { - commandListener.reset(); + @ParameterizedTest + @ValueSource(booleans = {true, false}) + protected void batchSizeWorksForWithDocumentClass(final boolean batchSizeBeforeWithDocumentClass) { int batchSize = 3; int batchCount = 2; + int ignoredBatchSize = batchSize * 2; ChangeStreamIterable iterable = collection.watch(); - MongoIterable configuredIterable; - if (chaining) { - if (batchSizeBeforeWithDocumentClass) { - configuredIterable = iterable.batchSize(batchSize).withDocumentClass(Document.class); - } else { - configuredIterable = iterable.withDocumentClass(Document.class).batchSize(batchSize); - } - } else { - if (batchSizeBeforeWithDocumentClass) { - iterable.batchSize(batchSize); - configuredIterable = iterable.withDocumentClass(Document.class); - } else { - configuredIterable = iterable.withDocumentClass(Document.class); - iterable.batchSize(batchSize); - } - } + iterable.batchSize(ignoredBatchSize); + MongoIterable configuredIterable = batchSizeBeforeWithDocumentClass + ? iterable.batchSize(batchSize).withDocumentClass(Document.class) + : iterable.withDocumentClass(Document.class).batchSize(batchSize); + iterable.batchSize(ignoredBatchSize); try (MongoCursor cursor = configuredIterable.cursor()) { List insertedDocuments = Stream.generate(Document::new).limit(batchSize * batchCount).collect(toList()); collection.insertMany(insertedDocuments); @@ -119,37 +106,17 @@ private void assertBatchSizeWorksForWithDocumentClass(final boolean chaining, fi } /** - * @see #batchSizeWorksForWithDocumentClass() + * @see #batchSizeWorksForWithDocumentClass(boolean) */ @Test protected void commandOptionWorksForWithDocumentClass() { - assertAll( - () -> commandOptionWorksForWithDocumentClass(true, true), - () -> commandOptionWorksForWithDocumentClass(false, true), - () -> commandOptionWorksForWithDocumentClass(false, false)); - } - - private void commandOptionWorksForWithDocumentClass(final boolean chaining, final boolean commandOptionBeforeWithDocumentClass) { - commandListener.reset(); assertCommand( iterable -> { Document collation = new Document("locale", "en"); - MongoIterable configuredIterable; - if (chaining) { - if (commandOptionBeforeWithDocumentClass) { - configuredIterable = iterable.commandOption("collation", collation).withDocumentClass(Document.class); - } else { - throw com.mongodb.assertions.Assertions.fail("this variant is not expressible in code"); - } - } else { - if (commandOptionBeforeWithDocumentClass) { - iterable.commandOption("collation", collation); - configuredIterable = iterable.withDocumentClass(Document.class); - } else { - configuredIterable = iterable.withDocumentClass(Document.class); - iterable.commandOption("collation", collation); - } - } + Document ignoredCollation = new Document("locale", "ignored"); + iterable.commandOption("collation", ignoredCollation); + MongoIterable configuredIterable = iterable.commandOption("collation", collation).withDocumentClass(Document.class); + iterable.commandOption("collation", ignoredCollation); return configuredIterable; }, command -> { @@ -169,6 +136,31 @@ void commandOption() { }); } + @Test + void commandOptionsReusedWithoutModificationsWhenResuming() throws Exception { + BsonDocument causeChangeStreamResumeFailPoint = BsonDocument.parse("{" + + " configureFailPoint: 'failCommand'," + + " mode: { times: 1 }," + + " data: {" + + " failCommands: ['getMore']," + + " errorCode: 10107," + + " errorLabels: ['ResumableChangeStreamError']" + + " }" + + "}"); + ChangeStreamIterable iterable = collection.watch().commandOption("allowDiskUse", true); + try (FailPoint ignored = FailPoint.enable(causeChangeStreamResumeFailPoint, getPrimary()); + MongoChangeStreamCursor> cursor = iterable.cursor()) { + iterable.commandOption("allowDiskUse", false); + collection.insertOne(new Document()); + // change stream resumes here, another `aggregate` is executed + assertNotNull(cursor.next()); + } + List commands = commandListener.getCommandStartedEvents("aggregate").stream() + .map(CommandStartedEvent::getCommand).collect(toList()); + assertEquals(2, commands.size()); + commands.forEach(command -> assertTrue(command.getBoolean("allowDiskUse").getValue())); + } + private void assertCommand( final Function, MongoIterable> iterableTuner, final Consumer asserter) { From 88231197f74d406212d2b2865c72d130a7b71a5f Mon Sep 17 00:00:00 2001 From: Valentin Kovalenko Date: Fri, 4 Dec 2026 11:12:54 -0600 Subject: [PATCH 09/11] Replace 5.16 with 5.17 --- .../kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt | 2 +- .../com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt | 2 +- .../main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt | 2 +- .../kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt | 2 +- .../com/mongodb/reactivestreams/client/AggregatePublisher.java | 2 +- .../mongodb/reactivestreams/client/ChangeStreamPublisher.java | 2 +- .../src/main/scala/org/mongodb/scala/AggregateObservable.scala | 2 +- .../main/scala/org/mongodb/scala/ChangeStreamObservable.scala | 2 +- driver-sync/src/main/com/mongodb/client/AggregateIterable.java | 2 +- .../src/main/com/mongodb/client/ChangeStreamIterable.java | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt index a81caba8fa0..d69caa011a7 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt @@ -229,7 +229,7 @@ public class AggregateFlow(private val wrapped: AggregatePublisher) * @param value The value of the field specified by `name`. It is encoded via the configured [CodecRegistry], which * must have a codec for [Document] regardless of the type of `value`. * @return `this`. - * @since 5.16 + * @since 5.17 */ public fun commandOption(name: String, value: Any): AggregateFlow = apply { wrapped.commandOption(name, value) } diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt index d4e2226b4c3..3982f888d0a 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ChangeStreamFlow.kt @@ -187,7 +187,7 @@ public class ChangeStreamFlow(private val wrapped: ChangeStreamPublishe * @param value The value of the field specified by `name`. It is encoded via the configured [CodecRegistry], which * must have a codec for [Document] regardless of the type of `value`. * @return `this`. - * @since 5.16 + * @since 5.17 */ public fun commandOption(name: String, value: Any): ChangeStreamFlow = apply { wrapped.commandOption(name, value) diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt index baf4e2af7b8..2ef638c0360 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt @@ -233,7 +233,7 @@ public class AggregateIterable(private val wrapped: JAggregateIterable< * @param value The value of the field specified by `name`. It is encoded via the configured [CodecRegistry], which * must have a codec for [Document] regardless of the type of `value`. * @return `this`. - * @since 5.16 + * @since 5.17 */ public fun commandOption(name: String, value: Any): AggregateIterable = apply { wrapped.commandOption(name, value) diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt index ddd9dac0e30..b5540c7cf17 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ChangeStreamIterable.kt @@ -192,7 +192,7 @@ public class ChangeStreamIterable(private val wrapped: JChangeStreamIte * @param value The value of the field specified by `name`. It is encoded via the configured [CodecRegistry], which * must have a codec for [Document] regardless of the type of `value`. * @return `this`. - * @since 5.16 + * @since 5.17 */ public fun commandOption(name: String, value: Any): ChangeStreamIterable = apply { wrapped.commandOption(name, value) diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java index 288a9441751..de71389e878 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java @@ -293,7 +293,7 @@ public interface AggregatePublisher extends Publisher { * It is encoded via the configured {@link CodecRegistry}, * which must have a codec for {@link Document} regardless of the type of {@code value}. * @return {@code this}. - * @since 5.16 + * @since 5.17 */ AggregatePublisher commandOption(String name, Object value); } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java index 8e48a7c2a03..440449c6747 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ChangeStreamPublisher.java @@ -200,7 +200,7 @@ public interface ChangeStreamPublisher extends Publisher commandOption(String name, Object value); } diff --git a/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala index 979589e515a..ccdd6a5ab41 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala @@ -277,7 +277,7 @@ case class AggregateObservable[TResult](private val wrapped: AggregatePublisher[ * It is encoded via the configured `CodecRegistry`, * which must have a codec for `org.bson.Document` regardless of the type of `value`. * @return `this`. - * @since 5.16 + * @since 5.17 */ def commandOption(name: String, value: Any): AggregateObservable[TResult] = { wrapped.commandOption(name, value) diff --git a/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala index 1e572d04dc2..d5845babf58 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/ChangeStreamObservable.scala @@ -219,7 +219,7 @@ case class ChangeStreamObservable[TResult](private val wrapped: ChangeStreamPubl * It is encoded via the configured `CodecRegistry`, * which must have a codec for `org.bson.Document` regardless of the type of `value`. * @return `this`. - * @since 5.16 + * @since 5.17 */ def commandOption(name: String, value: Any): ChangeStreamObservable[TResult] = { wrapped.commandOption(name, value) diff --git a/driver-sync/src/main/com/mongodb/client/AggregateIterable.java b/driver-sync/src/main/com/mongodb/client/AggregateIterable.java index 631a753e789..49435d5175f 100644 --- a/driver-sync/src/main/com/mongodb/client/AggregateIterable.java +++ b/driver-sync/src/main/com/mongodb/client/AggregateIterable.java @@ -300,7 +300,7 @@ public interface AggregateIterable extends MongoIterable { * It is encoded via the configured {@link CodecRegistry}, * which must have a codec for {@link Document} regardless of the type of {@code value}. * @return {@code this}. - * @since 5.16 + * @since 5.17 */ AggregateIterable commandOption(String name, Object value); } diff --git a/driver-sync/src/main/com/mongodb/client/ChangeStreamIterable.java b/driver-sync/src/main/com/mongodb/client/ChangeStreamIterable.java index 2b75b5739b9..3481f40dc7e 100644 --- a/driver-sync/src/main/com/mongodb/client/ChangeStreamIterable.java +++ b/driver-sync/src/main/com/mongodb/client/ChangeStreamIterable.java @@ -200,7 +200,7 @@ public interface ChangeStreamIterable extends MongoIterable commandOption(String name, Object value); } From 2ced33dc203e85be0ea7e0deb9a3fe5b34523cae Mon Sep 17 00:00:00 2001 From: Valentin Kovalenko Date: Fri, 4 Dec 2026 12:55:24 -0600 Subject: [PATCH 10/11] Review: fixes 2, tests --- .../mongodb/client/AggregateIterableIntegrationTest.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/driver-sync/src/test/functional/com/mongodb/client/AggregateIterableIntegrationTest.java b/driver-sync/src/test/functional/com/mongodb/client/AggregateIterableIntegrationTest.java index b1b48ac4ac3..c925d5c418f 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/AggregateIterableIntegrationTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/AggregateIterableIntegrationTest.java @@ -43,6 +43,7 @@ public class AggregateIterableIntegrationTest { protected static final MongoNamespace NAMESPACE = new MongoNamespace(AggregateIterableIntegrationTest.class.getSimpleName(), "test"); + protected static final String COLLECTION_NAME_FOR_OUT_MERGE = NAMESPACE.getCollectionName() + "OutMerge"; private MongoClient client; private MongoCollection collection; @@ -56,6 +57,8 @@ void beforeEach() { .build()); MongoDatabase database = client.getDatabase(NAMESPACE.getDatabaseName()); database.drop(); + database.createCollection(NAMESPACE.getCollectionName()); + database.createCollection(COLLECTION_NAME_FOR_OUT_MERGE); collection = database.getCollection(NAMESPACE.getCollectionName()); } @@ -111,11 +114,11 @@ List getPipeline() { switch (this) { case CURSOR_WITH_OUT: case TO_COLLECTION_WITH_OUT: { - return singletonList(out(NAMESPACE.getCollectionName())); + return singletonList(out(COLLECTION_NAME_FOR_OUT_MERGE)); } case CURSOR_WITH_MERGE: case TO_COLLECTION_WITH_MERGE: { - return singletonList(merge(NAMESPACE.getCollectionName() + "Merged")); + return singletonList(merge(COLLECTION_NAME_FOR_OUT_MERGE)); } default: { return emptyList(); From fce0a10cba1f43ab8e174a911c9ff7fd9bf65372 Mon Sep 17 00:00:00 2001 From: Valentin Kovalenko Date: Fri, 4 Dec 2026 20:16:32 -0600 Subject: [PATCH 11/11] Review: fixes 3 --- .../operation/AggregateOperation.java | 21 +++++++--------- .../operation/ChangeStreamOperation.java | 17 ++++++------- .../internal/AggregatePublisherImpl.java | 4 +-- .../internal/ChangeStreamPublisherImpl.java | 4 +-- ...nternalCommonBatchCursorPublisherTest.java | 15 +++++------ .../internal/AggregateIterableImpl.java | 4 +-- .../internal/ChangeStreamIterableImpl.java | 4 +-- .../ListCollectionNamesIterableTest.java | 21 ++++++++++++---- .../internal/InternalCommonIterableTest.java | 25 +++++++++++++------ 9 files changed, 67 insertions(+), 48 deletions(-) diff --git a/driver-core/src/main/com/mongodb/internal/operation/AggregateOperation.java b/driver-core/src/main/com/mongodb/internal/operation/AggregateOperation.java index 8215824d264..9277453f623 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AggregateOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AggregateOperation.java @@ -35,14 +35,11 @@ import org.bson.conversions.Bson; import java.util.List; -import java.util.Set; -import java.util.stream.Stream; +import java.util.function.Predicate; import static com.mongodb.internal.connection.CommandHelper.applyMaxTimeMS; import static com.mongodb.internal.operation.ExplainHelper.asExplainCommand; import static com.mongodb.internal.operation.ServerVersionHelper.UNKNOWN_WIRE_VERSION; -import static java.util.Collections.unmodifiableSet; -import static java.util.stream.Collectors.toSet; /** * An operation that executes an aggregation query. @@ -51,16 +48,16 @@ */ public class AggregateOperation implements ReadOperationExplainable { /** - * The names of the fields that must not be passed to {@link #overridingCommandOptions(BsonDocument)}. - * These fields are either unconditionally required, or have client logic associated with them. - * For example, the {@code collation} field is also passed to the {@code find} command when {@link Aggregates#out(Bson) $out} or - * {@link Aggregates#merge(MongoNamespace, MergeOptions) $merge} is used. + * {@linkplain Predicate#test(Object) Tests} if a field name is forbidden in {@link #overridingCommandOptions(BsonDocument)}. + * A forbidden field is either unconditionally required, or has client logic associated with it. + * For example, there is client logic that passes the {@code collation} field also to the {@code find} command + * when {@link Aggregates#out(Bson) $out} or {@link Aggregates#merge(MongoNamespace, MergeOptions) $merge} is used. * - * @see ChangeStreamOperation#FORBIDDEN_COMMAND_OPTIONS + * @see ChangeStreamOperation#FORBIDDEN_COMMAND_OPTION_NAME */ - // When changing this set, remember to update the documentation of the affected API. - public static final Set FORBIDDEN_COMMAND_OPTIONS = unmodifiableSet( - Stream.concat(ChangeStreamOperation.FORBIDDEN_COMMAND_OPTIONS.stream(), Stream.of("collation")).collect(toSet())); + // When changing this predicate, remember to update the documentation of the affected API. + public static final Predicate FORBIDDEN_COMMAND_OPTION_NAME = ChangeStreamOperation.FORBIDDEN_COMMAND_OPTION_NAME + .or(name -> name.equals("collation")); private final AggregateOperationImpl wrapped; diff --git a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamOperation.java b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamOperation.java index e97741c353c..0e7fb8e73a8 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamOperation.java @@ -44,13 +44,12 @@ import java.util.ArrayList; import java.util.HashSet; import java.util.List; -import java.util.Set; +import java.util.function.Predicate; import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.client.cursor.TimeoutMode.CURSOR_LIFETIME; import static java.util.Arrays.asList; -import static java.util.Collections.unmodifiableSet; /** * An operation that executes an {@code $changeStream} aggregation. @@ -59,16 +58,16 @@ */ public class ChangeStreamOperation implements ReadOperationCursor { /** - * The names of the fields that must not be passed to {@link #overridingCommandOptions(BsonDocument)}. - * These fields are either unconditionally required, or have client logic associated with them. - * For example, the {@code comment} field is also passed to {@code getMore} commands. + * {@linkplain Predicate#test(Object) Tests} if a field name is forbidden in {@link #overridingCommandOptions(BsonDocument)}. + * A forbidden field is either unconditionally required, or has client logic associated with it. + * For example, there is client logic that passes the {@code comment} field also to the {@code getMore} commands. * - * @see AggregateOperation#FORBIDDEN_COMMAND_OPTIONS + * @see AggregateOperation#FORBIDDEN_COMMAND_OPTION_NAME */ - // When changing this set, take into account that it affects `AggregateOperation.FORBIDDEN_COMMAND_OPTIONS`, + // When changing this predicate, take into account that it affects `AggregateOperation.FORBIDDEN_COMMAND_OPTION_NAME`, // and remember to update the documentation of the affected API. - public static final Set FORBIDDEN_COMMAND_OPTIONS = unmodifiableSet(new HashSet<>(asList( - "aggregate", "pipeline", "maxTimeMS", "cursor", "explain", "comment"))); + public static final Predicate FORBIDDEN_COMMAND_OPTION_NAME = new HashSet<>(asList( + "aggregate", "pipeline", "maxTimeMS", "cursor", "explain", "comment"))::contains; private static final RawBsonDocumentCodec RAW_BSON_DOCUMENT_CODEC = new RawBsonDocumentCodec(); private final AggregateOperationImpl wrapped; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java index 9d62d4eebfd..30fca259d79 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java @@ -43,7 +43,7 @@ import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.internal.operation.AggregateOperation.FORBIDDEN_COMMAND_OPTIONS; +import static com.mongodb.internal.operation.AggregateOperation.FORBIDDEN_COMMAND_OPTION_NAME; import static java.lang.String.format; final class AggregatePublisherImpl extends BatchCursorPublisher @@ -177,7 +177,7 @@ public Publisher explain(final Class explainResultClass, final Explain @Override public AggregatePublisher commandOption(final String name, final Object value) { notNull("name", name); - isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTIONS.contains(name)); + isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTION_NAME.test(name)); overridingCommandOption(name, notNull("value", value)); return this; } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java index d331b227139..7d7adc30e49 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ChangeStreamPublisherImpl.java @@ -42,7 +42,7 @@ import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.internal.operation.ChangeStreamOperation.FORBIDDEN_COMMAND_OPTIONS; +import static com.mongodb.internal.operation.ChangeStreamOperation.FORBIDDEN_COMMAND_OPTION_NAME; import static java.lang.String.format; @@ -181,7 +181,7 @@ public ChangeStreamPublisherImpl startAfter(final BsonDocument startAfter) { @Override public ChangeStreamPublisher commandOption(final String name, final Object value) { notNull("name", name); - isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTIONS.contains(name)); + isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTION_NAME.test(name)); overridingCommandOption(name, notNull("value", value)); return this; } diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisherTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisherTest.java index cc9fd7275cc..65b6dcd5c59 100644 --- a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisherTest.java +++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/InternalCommonBatchCursorPublisherTest.java @@ -32,6 +32,7 @@ import org.junit.jupiter.api.Test; import org.reactivestreams.Publisher; +import java.lang.reflect.Method; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Set; @@ -43,7 +44,7 @@ import static com.mongodb.client.internal.InternalCommonIterableTest.assertEachApiInterfaceMethodSharedWithAnotherApiInterfaceMustBeInInternalCommonInterface; import static com.mongodb.client.internal.InternalCommonIterableTest.assertEachInternalCommonInterfaceMethodMustBeInAtLeastTwoApiInterfaces; import static com.mongodb.client.internal.InternalCommonIterableTest.findClasses; -import static com.mongodb.client.internal.InternalCommonIterableTest.methodSignatures; +import static com.mongodb.client.internal.InternalCommonIterableTest.methodErasedSignatures; import static java.util.Arrays.stream; import static java.util.Comparator.comparing; import static java.util.stream.Collectors.toCollection; @@ -86,22 +87,22 @@ static void beforeAll() throws Exception { *

  • * it is subinterface of {@link Publisher}, but not {@link Publisher} itself;
  • *
  • - * it has a {@code public} method with the signature of a {@code public} method in {@link BatchCursorPublisher}, - * excluding the {@link Publisher} and {@link Object} methods.
  • + * it has a {@code public} method with the {@linkplain ListCollectionNamesIterableTest#erasedSignature(Method) erased signature} + * of a {@code public} method in {@link BatchCursorPublisher}, excluding the {@link Publisher} and {@link Object} methods. * */ @Test void relevantApiInterfacesAreListedExplicitly() { - Set publisherMethodSignatures = methodSignatures(Publisher.class); - Set objectMethodSignatures = methodSignatures(Object.class); + Set publisherMethodSignatures = methodErasedSignatures(Publisher.class); + Set objectMethodSignatures = methodErasedSignatures(Object.class); Set cursorPublisherMarkingMethods = stream(BatchCursorPublisher.class.getMethods()) - .map(ListCollectionNamesIterableTest::signature) + .map(ListCollectionNamesIterableTest::erasedSignature) .filter(signature -> !publisherMethodSignatures.contains(signature) && !objectMethodSignatures.contains(signature)) .collect(toCollection(TreeSet::new)); assertEquals(API_INTERFACES, findClasses(codeSourcePath, IS_PUBLIC_API .and(klass -> klass.isInterface()) .and(klass -> Publisher.class.isAssignableFrom(klass)) - .and(klass -> methodSignatures(klass).stream().anyMatch(cursorPublisherMarkingMethods::contains))), + .and(klass -> methodErasedSignatures(klass).stream().anyMatch(cursorPublisherMarkingMethods::contains))), "Either the explicit set of relevant interfaces or the code detecting them must be updated"); } diff --git a/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java index dda53c8a8fc..36332ccdf0d 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java @@ -44,7 +44,7 @@ import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.internal.operation.AggregateOperation.FORBIDDEN_COMMAND_OPTIONS; +import static com.mongodb.internal.operation.AggregateOperation.FORBIDDEN_COMMAND_OPTION_NAME; import static java.lang.String.format; class AggregateIterableImpl extends MongoIterableImpl @@ -207,7 +207,7 @@ public E explain(final Class explainResultClass, final ExplainVerbosity v @Override public AggregateIterable commandOption(final String name, final Object value) { notNull("name", name); - isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTIONS.contains(name)); + isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTION_NAME.test(name)); overridingCommandOption(name, notNull("value", value)); return this; } diff --git a/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java index 10a7b48565d..145e715daae 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ChangeStreamIterableImpl.java @@ -51,7 +51,7 @@ import static com.mongodb.assertions.Assertions.fail; import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.internal.operation.ChangeStreamOperation.FORBIDDEN_COMMAND_OPTIONS; +import static com.mongodb.internal.operation.ChangeStreamOperation.FORBIDDEN_COMMAND_OPTION_NAME; import static java.lang.String.format; /** @@ -203,7 +203,7 @@ public ChangeStreamIterable showExpandedEvents(final boolean showExpand @Override public ChangeStreamIterable commandOption(final String name, final Object value) { notNull("name", name); - isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTIONS.contains(name)); + isTrueArgument(format("name must not be '%s'", name), !FORBIDDEN_COMMAND_OPTION_NAME.test(name)); overridingCommandOption(name, notNull("value", value)); return this; } diff --git a/driver-sync/src/test/unit/com/mongodb/client/ListCollectionNamesIterableTest.java b/driver-sync/src/test/unit/com/mongodb/client/ListCollectionNamesIterableTest.java index fd423f1565e..00234735b22 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/ListCollectionNamesIterableTest.java +++ b/driver-sync/src/test/unit/com/mongodb/client/ListCollectionNamesIterableTest.java @@ -44,12 +44,17 @@ void declaredMethodsMatchListCollectionsIterable() { ListCollectionNamesIterable.class); } + /** + * Compares {@linkplain #erasedSignature(Method) erased signatures}, + * which means it misses discrepancies in the return type, type parameters of the method, + * and type arguments of the formal parameter types. + */ public static void assertDeclaredMethodsMatch( final Class expectedClass, final Set expectedExtraMethods, final Set expectedMissingMethods, final Class actualClass) { - Set expected = declaredMethodSignatures(expectedClass); + Set expected = declaredMethodErasedSignatures(expectedClass); for (String expectedExtraMethod : expectedExtraMethods) { assertFalse(expected.contains(expectedExtraMethod), () -> format("%s declares %s, remove it from expected extra methods", expectedClass, expectedExtraMethod)); @@ -60,17 +65,23 @@ public static void assertDeclaredMethodsMatch( } expected.addAll(expectedExtraMethods); expected.removeAll(expectedMissingMethods); - assertEquals(expected, declaredMethodSignatures(actualClass)); + assertEquals(expected, declaredMethodErasedSignatures(actualClass)); } - private static Set declaredMethodSignatures(final Class klass) { + private static Set declaredMethodErasedSignatures(final Class klass) { return stream(klass.getDeclaredMethods()) - .map(ListCollectionNamesIterableTest::signature) + .map(ListCollectionNamesIterableTest::erasedSignature) // `TreeSet` results in the alphabetic order of signatures in `toString`, improving assertion messages .collect(toCollection(TreeSet::new)); } - public static String signature(final Method method) { + /** + * Returns a {@link String} representation of the + * erasure of the + * signature + * of the {@code method}. Note that a signature does not include the return type. + */ + public static String erasedSignature(final Method method) { return stream(method.getParameterTypes()) .map(Class::getTypeName) .collect(joining(", ", method.getName() + "(", ")")); diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/InternalCommonIterableTest.java b/driver-sync/src/test/unit/com/mongodb/client/internal/InternalCommonIterableTest.java index 33e3690a755..df9705f27ff 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/InternalCommonIterableTest.java +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/InternalCommonIterableTest.java @@ -32,6 +32,7 @@ import org.junit.jupiter.api.Test; import java.io.IOException; +import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.file.Files; import java.nio.file.Path; @@ -131,11 +132,16 @@ void eachInternalCommonIterableMethodMustBeInAtLeastTwoApiInterfaces() { assertEachInternalCommonInterfaceMethodMustBeInAtLeastTwoApiInterfaces(API_INTERFACES, InternalCommonIterable.class); } + /** + * Compares {@linkplain ListCollectionNamesIterableTest#erasedSignature(Method) erased signatures}, + * which means it misses discrepancies in the return type, type parameters of the method, + * and type arguments of the formal parameter types. + */ public static void assertEachInternalCommonInterfaceMethodMustBeInAtLeastTwoApiInterfaces( final Set> apiInterfaces, final Class internalCommonInterface) { - methodSignatures(internalCommonInterface).forEach(method -> { + methodErasedSignatures(internalCommonInterface).forEach(method -> { Set> apiInterfacesWithMethod = apiInterfaces.stream() - .filter(apiInterface -> methodSignatures(apiInterface).contains(method)) + .filter(apiInterface -> methodErasedSignatures(apiInterface).contains(method)) .collect(toCollection(() -> new TreeSet<>(comparing(Class::getName)))); assertTrue(apiInterfacesWithMethod.size() >= 2, () -> format("Method %s is in %d API interfaces %s, remove the method from %s", @@ -152,13 +158,18 @@ void eachApiInterfaceMethodSharedWithAnotherApiInterfaceMustBeInInternalCommonIt InternalCommonIterable.class); } + /** + * Compares {@linkplain ListCollectionNamesIterableTest#erasedSignature(Method) erased signatures}, + * which means it misses discrepancies in the return type, type parameters of the method, + * and type arguments of the formal parameter types. + */ public static void assertEachApiInterfaceMethodSharedWithAnotherApiInterfaceMustBeInInternalCommonInterface( final Set> apiInterfaces, final Class internalCommonInterface) { - Set expectedMethods = methodSignatures(internalCommonInterface); + Set expectedMethods = methodErasedSignatures(internalCommonInterface); apiInterfaces.forEach(apiInterface -> { - methodSignatures(apiInterface).forEach(method -> { + methodErasedSignatures(apiInterface).forEach(method -> { Set> apiInterfacesWithMethod = apiInterfaces.stream() - .filter(maybeSameApiInterface -> methodSignatures(maybeSameApiInterface).contains(method)) + .filter(maybeSameApiInterface -> methodErasedSignatures(maybeSameApiInterface).contains(method)) .collect(toCollection(() -> new TreeSet<>(comparing(Class::getName)))); if (apiInterfacesWithMethod.size() >= 2) { assertTrue(expectedMethods.contains(method), () -> @@ -197,9 +208,9 @@ public static Set> findClasses(final Path codeSourceDirectory, final Pr } } - public static Set methodSignatures(final Class klass) { + public static Set methodErasedSignatures(final Class klass) { return stream(klass.getMethods()) - .map(ListCollectionNamesIterableTest::signature) + .map(ListCollectionNamesIterableTest::erasedSignature) // `TreeSet` results in the alphabetic order of signatures in `toString`, improving assertion messages .collect(toCollection(TreeSet::new)); }