From f028d77225df67fd9dd8499349cf58a800dc93ec Mon Sep 17 00:00:00 2001 From: suvvvv Date: Fri, 4 Dec 2026 15:39:23 +0530 Subject: [PATCH] JAVA-6379 Close the cursor of BatchCursorPublisher.first() on cancellation first() closed the cursor only when next() terminated. A cancellation while the cursor was being created dropped the cursor without closing it, and a cancellation during next() left it open. Get the cursor the way BatchCursorFlux does, and close it in both cases. --- .../client/internal/BatchCursorPublisher.java | 50 ++++++++++++++----- .../client/internal/BatchCursorFluxTest.java | 21 ++++++++ .../internal/BatchCursorPublisherTest.java | 49 ++++++++++++++++-- 3 files changed, 103 insertions(+), 17 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..c8b58e56dae 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 @@ -33,6 +33,8 @@ import reactor.core.publisher.Mono; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.function.Supplier; @@ -123,18 +125,42 @@ public TimeoutMode getTimeoutMode() { } public Publisher first() { - return batchCursor(this::asReadOperationFirst) - .flatMap(batchCursor -> { - batchCursor.setBatchSize(1); - return Mono.from(batchCursor.next()) - .doOnTerminate(batchCursor::close) - .flatMap(results -> { - if (results == null || results.isEmpty()) { - return Mono.empty(); - } - return Mono.fromCallable(() -> results.get(0)); - }); - }); + return Mono.create(sink -> { + AtomicBoolean cancelled = new AtomicBoolean(); + AtomicReference> cursor = new AtomicReference<>(); + sink.onCancel(() -> { + cancelled.set(true); + BatchCursor batchCursor = cursor.get(); + if (batchCursor != null) { + batchCursor.close(); + } + }); + // Not cancelled with the sink, so that a cursor created after a cancellation is still received and closed + batchCursor(this::asReadOperationFirst) + .contextWrite(sink.contextView()) + .subscribe(batchCursor -> { + cursor.set(batchCursor); + if (cancelled.get()) { + batchCursor.close(); + return; + } + batchCursor.setBatchSize(1); + Mono.from(batchCursor.next()) + .contextWrite(sink.contextView()) + .doOnTerminate(batchCursor::close) + .subscribe(results -> { + if (results == null || results.isEmpty()) { + sink.success(); + } else { + sink.success(results.get(0)); + } + }, sink::error, sink::success); + }, sink::error, () -> { + if (cursor.get() == null) { + sink.success(); + } + }); + }); } @Override diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/internal/BatchCursorFluxTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/internal/BatchCursorFluxTest.java index 3e581415537..2b419598fb5 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/internal/BatchCursorFluxTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/internal/BatchCursorFluxTest.java @@ -22,6 +22,7 @@ import com.mongodb.event.CommandEvent; import com.mongodb.event.CommandStartedEvent; import com.mongodb.internal.connection.TestCommandListener; +import com.mongodb.reactivestreams.client.ChangeStreamPublisher; import com.mongodb.reactivestreams.client.FindPublisher; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; @@ -40,6 +41,8 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.reactivestreams.Publisher; @@ -306,6 +309,24 @@ void changeStreamPublisherCompletesAfterDroppingCollection() { subscriber.assertNoErrors(); } + @ParameterizedTest(name = "first: {0}") + @ValueSource(booleans = {false, true}) + @DisplayName("Cancelling a subscription right away kills the cursor") + void cancellingSubscriptionKillsCursor(final boolean first) throws Exception { + assumeTrue(isReplicaSet()); + TestCommandListener listener = new TestCommandListener(); + try (MongoClient mongoClient = MongoClients.create(getMongoClientBuilderFromConnectionString().addCommandListener(listener).build())) { + ChangeStreamPublisher publisher = mongoClient.getDatabase(getDefaultDatabaseName()) + .getCollection(collection.getNamespace().getCollectionName()).watch(); + if (first) { + Mono.from(publisher.first()).subscribe().dispose(); + } else { + Flux.from(publisher).subscribe().dispose(); + } + listener.waitForEvents(CommandStartedEvent.class, event -> event.getCommandName().equals("killCursors"), 1); + } + } + @Test @DisplayName("Ensure BatchCursor does not drop an error") public void testBatchCursorDoesNotDropAnError() { diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/internal/BatchCursorPublisherTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/internal/BatchCursorPublisherTest.java index b8f88596691..3ce095ea713 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/internal/BatchCursorPublisherTest.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/internal/BatchCursorPublisherTest.java @@ -24,12 +24,15 @@ import com.mongodb.internal.operation.Operations; import com.mongodb.internal.operation.ReadOperationCursor; import org.bson.Document; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import reactor.core.Disposable; import reactor.core.publisher.Mono; +import reactor.core.publisher.MonoSink; import reactor.test.StepVerifier; import java.util.ArrayList; @@ -38,6 +41,7 @@ import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.IntStream; @@ -99,6 +103,7 @@ public void testBatchCursorFirst() { .expectNext(documents.get(0)) .expectComplete() .verify(); + Mockito.verify(batchCursor).close(); } @Test @@ -108,6 +113,37 @@ public void testBatchCursorFirstEmpty() { .verify(); } + @Test + @DisplayName("first() closes a cursor that is created after the subscription is cancelled") + public void testBatchCursorFirstClosesCursorCreatedAfterCancel() { + AtomicReference>> cursorSink = new AtomicReference<>(); + Mockito.doAnswer(invocation -> Mono.>create(cursorSink::set)) + .when(OPERATION_EXECUTOR) + .execute(eq(readOperation), eq(ReadPreference.primary()), eq(ReadConcern.DEFAULT), eq(null)); + + Disposable subscription = Mono.from(createBatchCursorPublisher().first()).subscribe(); + subscription.dispose(); + cursorSink.get().success(batchCursor); + + Mockito.verify(batchCursor).close(); + Mockito.verify(batchCursor, Mockito.never()).next(any(SingleResultCallback.class)); + } + + @Test + @DisplayName("first() closes the cursor when the subscription is cancelled while waiting for the first batch") + public void testBatchCursorFirstClosesCursorWhenCancelledDuringNext() { + Mockito.doAnswer(invocation -> Mono.fromCallable(() -> batchCursor)) + .when(OPERATION_EXECUTOR) + .execute(eq(readOperation), eq(ReadPreference.primary()), eq(ReadConcern.DEFAULT), eq(null)); + Mockito.doAnswer(invocation -> null).when(batchCursor).next(any(SingleResultCallback.class)); + + Disposable subscription = Mono.from(createBatchCursorPublisher().first()).subscribe(); + Mockito.verify(batchCursor, Mockito.never()).close(); + + subscription.dispose(); + Mockito.verify(batchCursor).close(); + } + @Test public void testBatchCursorError() { StepVerifier.create(createVerifiableBatchCursorError()) @@ -163,11 +199,8 @@ List> createBatches(final List expected, final int batc return new ArrayList<>(expected.stream().collect(groupingBy(it -> counter.getAndIncrement() / batchSize)).values()); } - BatchCursorPublisher createVerifiableBatchCursor(final List expected, final int batchSize, - final boolean errorCreatingCursor, final boolean errorOnEmpty) { - - BatchCursorPublisher publisher = new BatchCursorPublisher( - null, OPERATION_PUBLISHER) { + BatchCursorPublisher createBatchCursorPublisher() { + return new BatchCursorPublisher(null, OPERATION_PUBLISHER) { @Override ReadOperationCursor asReadOperation(final int initialBatchSize) { return readOperation; @@ -178,6 +211,12 @@ Function, TimeoutSettings> getTimeoutSettings() { return (Operations::getTimeoutSettings); } }; + } + + BatchCursorPublisher createVerifiableBatchCursor(final List expected, final int batchSize, + final boolean errorCreatingCursor, final boolean errorOnEmpty) { + + BatchCursorPublisher publisher = createBatchCursorPublisher(); OperationExecutor executor = OPERATION_EXECUTOR;