Search in sources :

Example 6 with ClientSession

use of com.mongodb.reactivestreams.client.ClientSession in project spring-data-mongodb by spring-projects.

the class ReactiveClientSessionTests method shouldApplyClientSession.

// DATAMONGO-1880
@Test
public void shouldApplyClientSession() {
    ClientSession session = Mono.from(client.startSession(ClientSessionOptions.builder().causallyConsistent(true).build())).block();
    assertThat(session.getOperationTime()).isNull();
    // 
    template.withSession(() -> session).execute(// 
    action -> action.findAll(Document.class, COLLECTION_NAME)).as(// 
    StepVerifier::create).expectNextCount(1).verifyComplete();
    assertThat(session.getOperationTime()).isNotNull();
    assertThat(session.getServerSession().isClosed()).isFalse();
    session.close();
}
Also used : Document(org.bson.Document) BeforeEach(org.junit.jupiter.api.BeforeEach) StepVerifier(reactor.test.StepVerifier) MongoTestUtils(org.springframework.data.mongodb.test.util.MongoTestUtils) Mono(reactor.core.publisher.Mono) ClientSession(com.mongodb.reactivestreams.client.ClientSession) Supplier(java.util.function.Supplier) Client(org.springframework.data.mongodb.test.util.Client) Criteria(org.springframework.data.mongodb.core.query.Criteria) Query(org.springframework.data.mongodb.core.query.Query) MongoClient(com.mongodb.reactivestreams.client.MongoClient) Test(org.junit.jupiter.api.Test) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) ClientSessionOptions(com.mongodb.ClientSessionOptions) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Assertions(org.assertj.core.api.Assertions) EnableIfMongoServerVersion(org.springframework.data.mongodb.test.util.EnableIfMongoServerVersion) MongoClientExtension(org.springframework.data.mongodb.test.util.MongoClientExtension) EnableIfReplicaSetAvailable(org.springframework.data.mongodb.test.util.EnableIfReplicaSetAvailable) ClientSession(com.mongodb.reactivestreams.client.ClientSession) StepVerifier(reactor.test.StepVerifier) Test(org.junit.jupiter.api.Test)

Example 7 with ClientSession

use of com.mongodb.reactivestreams.client.ClientSession in project spring-data-mongodb by spring-projects.

the class ReactiveMongoTemplateTransactionTests method reactiveTransactionWithExplicitTransactionStart.

// DATAMONGO-1970
@Test
public void reactiveTransactionWithExplicitTransactionStart() {
    Publisher<ClientSession> sessionPublisher = client.startSession(ClientSessionOptions.builder().causallyConsistent(true).build());
    ClientSession clientSession = Mono.from(sessionPublisher).block();
    template.withSession(Mono.just(clientSession)).execute(action -> ReactiveMongoContext.getSession().flatMap(session -> {
        session.startTransaction();
        return action.remove(ID_QUERY, Document.class, COLLECTION_NAME);
    })).as(StepVerifier::create).expectNextCount(1).verifyComplete();
    // 
    template.exists(ID_QUERY, COLLECTION_NAME).as(// 
    StepVerifier::create).expectNext(// 
    true).verifyComplete();
    assertThat(clientSession.hasActiveTransaction()).isTrue();
    StepVerifier.create(clientSession.commitTransaction()).verifyComplete();
    // 
    template.exists(ID_QUERY, COLLECTION_NAME).as(// 
    StepVerifier::create).expectNext(// 
    false).verifyComplete();
}
Also used : Document(org.bson.Document) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) StepVerifier(reactor.test.StepVerifier) MongoTestUtils(org.springframework.data.mongodb.test.util.MongoTestUtils) Publisher(org.reactivestreams.Publisher) Mono(reactor.core.publisher.Mono) ClientSession(com.mongodb.reactivestreams.client.ClientSession) Collectors(java.util.stream.Collectors) Client(org.springframework.data.mongodb.test.util.Client) Criteria(org.springframework.data.mongodb.core.query.Criteria) Query(org.springframework.data.mongodb.core.query.Query) MongoClient(com.mongodb.reactivestreams.client.MongoClient) Test(org.junit.jupiter.api.Test) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) ClientSessionOptions(com.mongodb.ClientSessionOptions) Assertions(org.assertj.core.api.Assertions) Sort(org.springframework.data.domain.Sort) EnableIfMongoServerVersion(org.springframework.data.mongodb.test.util.EnableIfMongoServerVersion) MongoClientExtension(org.springframework.data.mongodb.test.util.MongoClientExtension) EnableIfReplicaSetAvailable(org.springframework.data.mongodb.test.util.EnableIfReplicaSetAvailable) ClientSession(com.mongodb.reactivestreams.client.ClientSession) StepVerifier(reactor.test.StepVerifier) Test(org.junit.jupiter.api.Test)

Example 8 with ClientSession

use of com.mongodb.reactivestreams.client.ClientSession in project spring-data-mongodb by spring-projects.

the class ReactiveSessionBoundMongoTemplateUnitTests method setUp.

@Before
public void setUp() {
    when(client.getDatabase(anyString())).thenReturn(database);
    when(codecRegistry.get(any(Class.class))).thenReturn(new BsonValueCodec());
    when(database.getCodecRegistry()).thenReturn(codecRegistry);
    when(database.getCollection(anyString())).thenReturn(collection);
    when(database.getCollection(anyString(), any())).thenReturn(collection);
    when(database.listCollectionNames(any(ClientSession.class))).thenReturn(findPublisher);
    when(database.createCollection(any(ClientSession.class), any(), any())).thenReturn(resultPublisher);
    when(database.runCommand(any(ClientSession.class), any(), any(Class.class))).thenReturn(resultPublisher);
    when(collection.find(any(ClientSession.class))).thenReturn(findPublisher);
    when(collection.find(any(ClientSession.class), any(Document.class))).thenReturn(findPublisher);
    when(collection.find(any(ClientSession.class), any(Class.class))).thenReturn(findPublisher);
    when(collection.find(any(ClientSession.class), any(), any())).thenReturn(findPublisher);
    when(collection.deleteMany(any(ClientSession.class), any(), any())).thenReturn(resultPublisher);
    when(collection.insertOne(any(ClientSession.class), any(Document.class))).thenReturn(resultPublisher);
    when(collection.aggregate(any(ClientSession.class), anyList(), any(Class.class))).thenReturn(aggregatePublisher);
    when(collection.countDocuments(any(ClientSession.class), any(), any(CountOptions.class))).thenReturn(resultPublisher);
    when(collection.drop(any(ClientSession.class))).thenReturn(resultPublisher);
    when(collection.findOneAndUpdate(any(ClientSession.class), any(), any(Bson.class), any())).thenReturn(resultPublisher);
    when(collection.distinct(any(ClientSession.class), any(), any(Bson.class), any())).thenReturn(distinctPublisher);
    when(collection.updateOne(any(ClientSession.class), any(), any(Bson.class), any(UpdateOptions.class))).thenReturn(resultPublisher);
    when(collection.updateMany(any(ClientSession.class), any(), any(Bson.class), any(UpdateOptions.class))).thenReturn(resultPublisher);
    when(collection.dropIndex(any(ClientSession.class), anyString())).thenReturn(resultPublisher);
    when(collection.mapReduce(any(ClientSession.class), any(), any(), any())).thenReturn(mapReducePublisher);
    when(findPublisher.projection(any())).thenReturn(findPublisher);
    when(findPublisher.limit(anyInt())).thenReturn(findPublisher);
    when(findPublisher.collation(any())).thenReturn(findPublisher);
    when(findPublisher.first()).thenReturn(resultPublisher);
    when(aggregatePublisher.allowDiskUse(anyBoolean())).thenReturn(aggregatePublisher);
    factory = new SimpleReactiveMongoDatabaseFactory(client, "foo");
    this.mappingContext = new MongoMappingContext();
    this.converter = new MappingMongoConverter(NoOpDbRefResolver.INSTANCE, mappingContext);
    this.template = new ReactiveSessionBoundMongoTemplate(clientSession, new ReactiveMongoTemplate(factory, converter));
}
Also used : BsonValueCodec(org.bson.codecs.BsonValueCodec) ClientSession(com.mongodb.reactivestreams.client.ClientSession) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) CountOptions(com.mongodb.client.model.CountOptions) MappingMongoConverter(org.springframework.data.mongodb.core.convert.MappingMongoConverter) Document(org.bson.Document) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) UpdateOptions(com.mongodb.client.model.UpdateOptions) ReactiveSessionBoundMongoTemplate(org.springframework.data.mongodb.core.ReactiveMongoTemplate.ReactiveSessionBoundMongoTemplate) Bson(org.bson.conversions.Bson) Before(org.junit.Before)

Example 9 with ClientSession

use of com.mongodb.reactivestreams.client.ClientSession in project mongo-java-driver by mongodb.

the class GridFSUploadPublisherImpl method createCheckAndCreateIndexesMono.

private Mono<Void> createCheckAndCreateIndexesMono() {
    MongoCollection<Document> collection = filesCollection.withDocumentClass(Document.class).withReadPreference(primary());
    FindPublisher<Document> findPublisher;
    if (clientSession != null) {
        findPublisher = collection.find(clientSession);
    } else {
        findPublisher = collection.find();
    }
    AtomicBoolean collectionExists = new AtomicBoolean(false);
    return Mono.create(sink -> Mono.from(findPublisher.projection(PROJECTION).first()).subscribe(d -> collectionExists.set(true), sink::error, () -> {
        if (collectionExists.get()) {
            sink.success();
        } else {
            checkAndCreateIndex(filesCollection.withReadPreference(primary()), FILES_INDEX).doOnError(sink::error).doOnSuccess(i -> {
                checkAndCreateIndex(chunksCollection.withReadPreference(primary()), CHUNKS_INDEX).doOnError(sink::error).doOnSuccess(sink::success).subscribe();
            }).subscribe();
        }
    }));
}
Also used : Document(org.bson.Document) ListIndexesPublisher(com.mongodb.reactivestreams.client.ListIndexesPublisher) Date(java.util.Date) MongoGridFSException(com.mongodb.MongoGridFSException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) Function(java.util.function.Function) ByteBuffer(java.nio.ByteBuffer) BsonValue(org.bson.BsonValue) GridFSUploadPublisher(com.mongodb.reactivestreams.client.gridfs.GridFSUploadPublisher) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Subscriber(org.reactivestreams.Subscriber) GridFSFile(com.mongodb.client.gridfs.model.GridFSFile) Binary(org.bson.types.Binary) InsertOneResult(com.mongodb.client.result.InsertOneResult) Publisher(org.reactivestreams.Publisher) Mono(reactor.core.publisher.Mono) ClientSession(com.mongodb.reactivestreams.client.ClientSession) Consumer(java.util.function.Consumer) Flux(reactor.core.publisher.Flux) AtomicLong(java.util.concurrent.atomic.AtomicLong) Assertions.notNull(com.mongodb.assertions.Assertions.notNull) FindPublisher(com.mongodb.reactivestreams.client.FindPublisher) DeleteResult(com.mongodb.client.result.DeleteResult) ObjectId(org.bson.types.ObjectId) ReadPreference.primary(com.mongodb.ReadPreference.primary) Nullable(com.mongodb.lang.Nullable) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Document(org.bson.Document)

Example 10 with ClientSession

use of com.mongodb.reactivestreams.client.ClientSession in project mongo-java-driver by mongodb.

the class OperationExecutorImpl method execute.

@Override
public <T> Mono<T> execute(final AsyncReadOperation<T> operation, final ReadPreference readPreference, final ReadConcern readConcern, @Nullable final ClientSession session) {
    notNull("operation", operation);
    notNull("readPreference", readPreference);
    notNull("readConcern", readConcern);
    if (session != null) {
        session.notifyOperationInitiated(operation);
    }
    return Mono.from(subscriber -> clientSessionHelper.withClientSession(session, OperationExecutorImpl.this).map(clientSession -> getReadWriteBinding(getContext(subscriber), readPreference, readConcern, clientSession, session == null && clientSession != null)).switchIfEmpty(Mono.fromCallable(() -> getReadWriteBinding(getContext(subscriber), readPreference, readConcern, session, false))).flatMap(binding -> {
        if (session != null && session.hasActiveTransaction() && !binding.getReadPreference().equals(primary())) {
            binding.release();
            return Mono.error(new MongoClientException("Read preference in a transaction must be primary"));
        } else {
            return Mono.<T>create(sink -> operation.executeAsync(binding, (result, t) -> {
                try {
                    binding.release();
                } finally {
                    sinkToCallback(sink).onResult(result, t);
                }
            })).doOnError((t) -> {
                labelException(session, t);
                unpinServerAddressOnTransientTransactionError(session, t);
            });
        }
    }).subscribe(subscriber));
}
Also used : MongoInternalException(com.mongodb.MongoInternalException) ReadPreference(com.mongodb.ReadPreference) AsyncReadWriteBinding(com.mongodb.internal.binding.AsyncReadWriteBinding) MongoClientException(com.mongodb.MongoClientException) MongoSocketException(com.mongodb.MongoSocketException) MongoQueryException(com.mongodb.MongoQueryException) CryptBinding(com.mongodb.reactivestreams.client.internal.crypt.CryptBinding) TRANSIENT_TRANSACTION_ERROR_LABEL(com.mongodb.MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL) IgnorableRequestContext(com.mongodb.internal.IgnorableRequestContext) ReadConcern(com.mongodb.ReadConcern) Subscriber(org.reactivestreams.Subscriber) MongoException(com.mongodb.MongoException) AsyncWriteOperation(com.mongodb.internal.operation.AsyncWriteOperation) Mono(reactor.core.publisher.Mono) RequestContext(com.mongodb.RequestContext) ClientSessionBinding(com.mongodb.internal.async.client.ClientSessionBinding) ClientSession(com.mongodb.reactivestreams.client.ClientSession) ReactiveContextProvider(com.mongodb.reactivestreams.client.ReactiveContextProvider) MongoTimeoutException(com.mongodb.MongoTimeoutException) Crypt(com.mongodb.reactivestreams.client.internal.crypt.Crypt) Assertions.notNull(com.mongodb.assertions.Assertions.notNull) ContextProvider(com.mongodb.ContextProvider) AsyncReadOperation(com.mongodb.internal.operation.AsyncReadOperation) AsyncClusterBinding(com.mongodb.internal.binding.AsyncClusterBinding) UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL(com.mongodb.MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) ReadPreference.primary(com.mongodb.ReadPreference.primary) MongoOperationPublisher.sinkToCallback(com.mongodb.reactivestreams.client.internal.MongoOperationPublisher.sinkToCallback) Nullable(com.mongodb.lang.Nullable) AsyncClusterAwareReadWriteBinding(com.mongodb.internal.binding.AsyncClusterAwareReadWriteBinding) MongoClientException(com.mongodb.MongoClientException)

Aggregations

ClientSession (com.mongodb.reactivestreams.client.ClientSession)14 Document (org.bson.Document)11 Mono (reactor.core.publisher.Mono)10 Test (org.junit.jupiter.api.Test)9 ClientSessionOptions (com.mongodb.ClientSessionOptions)7 MongoClient (com.mongodb.reactivestreams.client.MongoClient)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 Assertions (org.assertj.core.api.Assertions)6 BeforeEach (org.junit.jupiter.api.BeforeEach)6 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)6 Criteria (org.springframework.data.mongodb.core.query.Criteria)6 Query (org.springframework.data.mongodb.core.query.Query)6 Client (org.springframework.data.mongodb.test.util.Client)6 EnableIfMongoServerVersion (org.springframework.data.mongodb.test.util.EnableIfMongoServerVersion)6 EnableIfReplicaSetAvailable (org.springframework.data.mongodb.test.util.EnableIfReplicaSetAvailable)6 MongoClientExtension (org.springframework.data.mongodb.test.util.MongoClientExtension)6 MongoTestUtils (org.springframework.data.mongodb.test.util.MongoTestUtils)6 StepVerifier (reactor.test.StepVerifier)6 Publisher (org.reactivestreams.Publisher)5 Assertions.notNull (com.mongodb.assertions.Assertions.notNull)4