Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -123,18 +125,42 @@ public TimeoutMode getTimeoutMode() {
}

public Publisher<T> 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<BatchCursor<T>> cursor = new AtomicReference<>();
sink.onCancel(() -> {
cancelled.set(true);
BatchCursor<T> 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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<Document> 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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;

Expand Down Expand Up @@ -99,6 +103,7 @@ public void testBatchCursorFirst() {
.expectNext(documents.get(0))
.expectComplete()
.verify();
Mockito.verify(batchCursor).close();
}

@Test
Expand All @@ -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<MonoSink<AsyncBatchCursor<Document>>> cursorSink = new AtomicReference<>();
Mockito.doAnswer(invocation -> Mono.<AsyncBatchCursor<Document>>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())
Expand Down Expand Up @@ -163,11 +199,8 @@ List<List<Document>> createBatches(final List<Document> expected, final int batc
return new ArrayList<>(expected.stream().collect(groupingBy(it -> counter.getAndIncrement() / batchSize)).values());
}

BatchCursorPublisher<Document> createVerifiableBatchCursor(final List<Document> expected, final int batchSize,
final boolean errorCreatingCursor, final boolean errorOnEmpty) {

BatchCursorPublisher<Document> publisher = new BatchCursorPublisher<Document>(
null, OPERATION_PUBLISHER) {
BatchCursorPublisher<Document> createBatchCursorPublisher() {
return new BatchCursorPublisher<Document>(null, OPERATION_PUBLISHER) {
@Override
ReadOperationCursor<Document> asReadOperation(final int initialBatchSize) {
return readOperation;
Expand All @@ -178,6 +211,12 @@ Function<Operations<?>, TimeoutSettings> getTimeoutSettings() {
return (Operations::getTimeoutSettings);
}
};
}

BatchCursorPublisher<Document> createVerifiableBatchCursor(final List<Document> expected, final int batchSize,
final boolean errorCreatingCursor, final boolean errorOnEmpty) {

BatchCursorPublisher<Document> publisher = createBatchCursorPublisher();

OperationExecutor executor = OPERATION_EXECUTOR;

Expand Down