Search in sources :

Example 1 with ReadConcern

use of com.mongodb.ReadConcern in project mongo-java-driver by mongodb.

the class ClientSessionImpl method commitTransaction.

@Override
public void commitTransaction() {
    if (transactionState == TransactionState.ABORTED) {
        throw new IllegalStateException("Cannot call commitTransaction after calling abortTransaction");
    }
    if (transactionState == TransactionState.NONE) {
        throw new IllegalStateException("There is no transaction started");
    }
    try {
        if (messageSentInCurrentTransaction) {
            ReadConcern readConcern = transactionOptions.getReadConcern();
            if (readConcern == null) {
                throw new MongoInternalException("Invariant violated.  Transaction options read concern can not be null");
            }
            commitInProgress = true;
            delegate.getOperationExecutor().execute(new CommitTransactionOperation(transactionOptions.getWriteConcern(), transactionState == TransactionState.COMMITTED).recoveryToken(getRecoveryToken()).maxCommitTime(transactionOptions.getMaxCommitTime(MILLISECONDS), MILLISECONDS), readConcern, this);
        }
    } catch (MongoException e) {
        clearTransactionContextOnError(e);
        throw e;
    } finally {
        transactionState = TransactionState.COMMITTED;
        commitInProgress = false;
    }
}
Also used : CommitTransactionOperation(com.mongodb.internal.operation.CommitTransactionOperation) MongoException(com.mongodb.MongoException) ReadConcern(com.mongodb.ReadConcern) MongoInternalException(com.mongodb.MongoInternalException)

Example 2 with ReadConcern

use of com.mongodb.ReadConcern in project mongo-java-driver by mongodb.

the class ClientSessionImpl method abortTransaction.

@Override
public void abortTransaction() {
    if (transactionState == TransactionState.ABORTED) {
        throw new IllegalStateException("Cannot call abortTransaction twice");
    }
    if (transactionState == TransactionState.COMMITTED) {
        throw new IllegalStateException("Cannot call abortTransaction after calling commitTransaction");
    }
    if (transactionState == TransactionState.NONE) {
        throw new IllegalStateException("There is no transaction started");
    }
    try {
        if (messageSentInCurrentTransaction) {
            ReadConcern readConcern = transactionOptions.getReadConcern();
            if (readConcern == null) {
                throw new MongoInternalException("Invariant violated.  Transaction options read concern can not be null");
            }
            delegate.getOperationExecutor().execute(new AbortTransactionOperation(transactionOptions.getWriteConcern()).recoveryToken(getRecoveryToken()), readConcern, this);
        }
    } catch (Exception e) {
    // ignore exceptions from abort
    } finally {
        clearTransactionContext();
        cleanupTransaction(TransactionState.ABORTED);
    }
}
Also used : ReadConcern(com.mongodb.ReadConcern) AbortTransactionOperation(com.mongodb.internal.operation.AbortTransactionOperation) MongoInternalException(com.mongodb.MongoInternalException) MongoClientException(com.mongodb.MongoClientException) MongoException(com.mongodb.MongoException) MongoExecutionTimeoutException(com.mongodb.MongoExecutionTimeoutException) MongoInternalException(com.mongodb.MongoInternalException)

Example 3 with ReadConcern

use of com.mongodb.ReadConcern in project mongo-java-driver by mongodb.

the class JsonPoweredCrudTestHelper method getCollection.

private MongoCollection<BsonDocument> getCollection(final BsonDocument collectionOptions) {
    MongoCollection<BsonDocument> retVal = baseCollection;
    if (collectionOptions.containsKey("readPreference")) {
        retVal = retVal.withReadPreference(getReadPreference(collectionOptions));
    }
    if (collectionOptions.containsKey("writeConcern")) {
        WriteConcern writeConcern = getWriteConcern(collectionOptions);
        retVal = retVal.withWriteConcern(writeConcern);
    }
    if (collectionOptions.containsKey("readConcern")) {
        ReadConcern readConcern = getReadConcern(collectionOptions);
        retVal = retVal.withReadConcern(readConcern);
    }
    return retVal;
}
Also used : BsonDocument(org.bson.BsonDocument) WriteConcern(com.mongodb.WriteConcern) ReadConcern(com.mongodb.ReadConcern)

Example 4 with ReadConcern

use of com.mongodb.ReadConcern in project mongo-java-driver by mongodb.

the class AbstractUnifiedTest method setUp.

@Before
public void setUp() {
    assumeFalse(skipTest);
    assumeTrue("Skipping test: " + definition.getString("skipReason", new BsonString("")).getValue(), !definition.containsKey("skipReason"));
    assumeFalse("Skipping test of count", filename.equals("count.json"));
    collectionHelper = new CollectionHelper<Document>(new DocumentCodec(), new MongoNamespace(databaseName, collectionName));
    collectionHelper.killAllSessions();
    if (!isDataLakeTest()) {
        collectionHelper.create(collectionName, new CreateCollectionOptions(), WriteConcern.MAJORITY);
    }
    if (!data.isEmpty()) {
        List<BsonDocument> documents = new ArrayList<BsonDocument>();
        for (BsonValue document : data) {
            documents.add(document.asDocument());
        }
        collectionHelper.insertDocuments(documents, WriteConcern.MAJORITY);
    }
    if (definition.containsKey("failPoint")) {
        collectionHelper.runAdminCommand(definition.getDocument("failPoint"));
    }
    final BsonDocument clientOptions = definition.getDocument("clientOptions", new BsonDocument());
    connectionString = getConnectionString();
    useMultipleMongoses = definition.getBoolean("useMultipleMongoses", BsonBoolean.FALSE).getValue();
    if (useMultipleMongoses) {
        assumeTrue(isSharded());
        connectionString = getMultiMongosConnectionString();
        assumeTrue("The system property org.mongodb.test.transaction.uri is not set.", connectionString != null);
    }
    MongoClientSettings.Builder builder = getMongoClientSettingsBuilder().applyConnectionString(connectionString).addCommandListener(commandListener).applyToClusterSettings(clusterSettingsBuilder -> {
        if (clientOptions.containsKey("serverSelectionTimeoutMS")) {
            clusterSettingsBuilder.serverSelectionTimeout(clientOptions.getNumber("serverSelectionTimeoutMS").longValue(), MILLISECONDS);
        }
        if (clientOptions.containsKey("directConnection")) {
            setDirectConnection(clusterSettingsBuilder);
        }
    }).applyToSocketSettings(new Block<SocketSettings.Builder>() {

        @Override
        public void apply(final SocketSettings.Builder builder) {
            builder.readTimeout(clientOptions.getInt32("socketTimeoutMS", new BsonInt32(toIntExact(SECONDS.toMillis(5)))).getValue(), MILLISECONDS);
            if (clientOptions.containsKey("connectTimeoutMS")) {
                builder.connectTimeout(clientOptions.getNumber("connectTimeoutMS").intValue(), MILLISECONDS);
            }
        }
    }).writeConcern(getWriteConcern(clientOptions)).readConcern(getReadConcern(clientOptions)).readPreference(getReadPreference(clientOptions)).retryWrites(clientOptions.getBoolean("retryWrites", BsonBoolean.FALSE).getValue()).retryReads(false).applyToConnectionPoolSettings(poolSettingsBuilder -> {
        poolSettingsBuilder.addConnectionPoolListener(connectionPoolListener);
        if (clientOptions.containsKey("minPoolSize")) {
            poolSettingsBuilder.minSize(clientOptions.getInt32("minPoolSize").getValue());
        }
    }).applyToServerSettings(new Block<ServerSettings.Builder>() {

        @Override
        public void apply(final ServerSettings.Builder builder) {
            builder.heartbeatFrequency(50, MILLISECONDS);
            builder.minHeartbeatFrequency(MIN_HEARTBEAT_FREQUENCY_MS, MILLISECONDS);
            builder.addServerListener(serverListener);
        }
    });
    if (clientOptions.containsKey("heartbeatFrequencyMS")) {
        builder.applyToServerSettings(new Block<ServerSettings.Builder>() {

            @Override
            public void apply(final ServerSettings.Builder builder) {
                builder.heartbeatFrequency(clientOptions.getInt32("heartbeatFrequencyMS").intValue(), MILLISECONDS);
            }
        });
    }
    if (clientOptions.containsKey("appname")) {
        builder.applicationName(clientOptions.getString("appname").getValue());
    }
    if (clientOptions.containsKey("w")) {
        if (clientOptions.isString("w")) {
            builder.writeConcern(new WriteConcern(clientOptions.getString("w").getValue()));
        } else if (clientOptions.isNumber("w")) {
            builder.writeConcern(new WriteConcern(clientOptions.getNumber("w").intValue()));
        }
    }
    StreamFactoryFactory streamFactoryFactory = getStreamFactoryFactory();
    if (streamFactoryFactory != null) {
        builder.streamFactoryFactory(streamFactoryFactory);
    }
    mongoClient = createMongoClient(builder.build());
    database = mongoClient.getDatabase(databaseName);
    if (useMultipleMongoses) {
        // non-transactional distinct operation to avoid StaleDbVersion error
        runDistinctOnEachNode();
    }
    helper = new JsonPoweredCrudTestHelper(description, database, database.getCollection(collectionName, BsonDocument.class), null, mongoClient);
    sessionsMap = new HashMap<>();
    lsidMap = new HashMap<>();
    if (createSessions && serverVersionAtLeast(3, 6)) {
        ClientSession sessionZero = createSession("session0");
        ClientSession sessionOne = createSession("session1");
        sessionsMap.put("session0", sessionZero);
        sessionsMap.put("session1", sessionOne);
        lsidMap.put("session0", sessionZero.getServerSession().getIdentifier());
        lsidMap.put("session1", sessionOne.getServerSession().getIdentifier());
    }
}
Also used : Document(org.bson.Document) ServerDescription(com.mongodb.connection.ServerDescription) ClusterFixture.getConnectionString(com.mongodb.ClusterFixture.getConnectionString) BsonValue(org.bson.BsonValue) Collections.singletonList(java.util.Collections.singletonList) MongoWriteConcernException(com.mongodb.MongoWriteConcernException) StreamFactoryFactory(com.mongodb.connection.StreamFactoryFactory) Future(java.util.concurrent.Future) ClusterFixture.isSharded(com.mongodb.ClusterFixture.isSharded) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) SocketSettings(com.mongodb.connection.SocketSettings) BsonArray(org.bson.BsonArray) After(org.junit.After) Map(java.util.Map) ServerType(com.mongodb.connection.ServerType) ClusterFixture.getMultiMongosConnectionString(com.mongodb.ClusterFixture.getMultiMongosConnectionString) Assert.fail(org.junit.Assert.fail) ReadConcern(com.mongodb.ReadConcern) Parameterized(org.junit.runners.Parameterized) CommandMonitoringTestHelper.assertEventsEquality(com.mongodb.client.CommandMonitoringTestHelper.assertEventsEquality) CommandEvent(com.mongodb.event.CommandEvent) CollectionHelper(com.mongodb.client.test.CollectionHelper) MongoException(com.mongodb.MongoException) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) List(java.util.List) Block(com.mongodb.Block) Assert.assertFalse(org.junit.Assert.assertFalse) TestConnectionPoolListener(com.mongodb.internal.connection.TestConnectionPoolListener) Assume.assumeTrue(org.junit.Assume.assumeTrue) MongoClientSettings(com.mongodb.MongoClientSettings) ReadPreference(com.mongodb.ReadPreference) CommandMonitoringTestHelper.getExpectedEvents(com.mongodb.client.CommandMonitoringTestHelper.getExpectedEvents) BsonBoolean(org.bson.BsonBoolean) Assume.assumeFalse(org.junit.Assume.assumeFalse) MongoCommandException(com.mongodb.MongoCommandException) ClusterSettings(com.mongodb.connection.ClusterSettings) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) BsonString(org.bson.BsonString) ServerSettings(com.mongodb.connection.ServerSettings) BsonDocument(org.bson.BsonDocument) ArrayList(java.util.ArrayList) TransactionOptions(com.mongodb.TransactionOptions) TestCommandListener(com.mongodb.internal.connection.TestCommandListener) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) DocumentCodec(org.bson.codecs.DocumentCodec) Fixture.getMongoClient(com.mongodb.client.Fixture.getMongoClient) Math.toIntExact(java.lang.Math.toIntExact) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) ServerAddress(com.mongodb.ServerAddress) ClusterFixture.setDirectConnection(com.mongodb.ClusterFixture.setDirectConnection) MongoNamespace(com.mongodb.MongoNamespace) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec) ClusterFixture.isDataLakeTest(com.mongodb.ClusterFixture.isDataLakeTest) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) TimeUnit(java.util.concurrent.TimeUnit) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) ConnectionString(com.mongodb.ConnectionString) Assert.assertNull(org.junit.Assert.assertNull) ClientSessionOptions(com.mongodb.ClientSessionOptions) ReadConcernLevel(com.mongodb.ReadConcernLevel) ClusterFixture.serverVersionAtLeast(com.mongodb.ClusterFixture.serverVersionAtLeast) Nullable(com.mongodb.lang.Nullable) BsonInt32(org.bson.BsonInt32) WriteConcern(com.mongodb.WriteConcern) CommandStartedEvent(com.mongodb.event.CommandStartedEvent) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Assert.assertEquals(org.junit.Assert.assertEquals) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) DocumentCodec(org.bson.codecs.DocumentCodec) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec) ArrayList(java.util.ArrayList) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) SocketSettings(com.mongodb.connection.SocketSettings) BsonInt32(org.bson.BsonInt32) ServerSettings(com.mongodb.connection.ServerSettings) MongoClientSettings(com.mongodb.MongoClientSettings) MongoNamespace(com.mongodb.MongoNamespace) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) WriteConcern(com.mongodb.WriteConcern) CreateCollectionOptions(com.mongodb.client.model.CreateCollectionOptions) Block(com.mongodb.Block) StreamFactoryFactory(com.mongodb.connection.StreamFactoryFactory) BsonValue(org.bson.BsonValue) Before(org.junit.Before)

Example 5 with ReadConcern

use of com.mongodb.ReadConcern in project mongo-java-driver by mongodb.

the class ClientSessionPublisherImpl method commitTransaction.

@Override
public Publisher<Void> commitTransaction() {
    if (transactionState == TransactionState.ABORTED) {
        throw new IllegalStateException("Cannot call commitTransaction after calling abortTransaction");
    }
    if (transactionState == TransactionState.NONE) {
        throw new IllegalStateException("There is no transaction started");
    }
    if (!messageSentInCurrentTransaction) {
        cleanupTransaction(TransactionState.COMMITTED);
        return Mono.create(MonoSink::success);
    } else {
        ReadConcern readConcern = transactionOptions.getReadConcern();
        if (readConcern == null) {
            throw new MongoInternalException("Invariant violated. Transaction options read concern can not be null");
        }
        boolean alreadyCommitted = commitInProgress || transactionState == TransactionState.COMMITTED;
        commitInProgress = true;
        return executor.execute(new CommitTransactionOperation(transactionOptions.getWriteConcern(), alreadyCommitted).recoveryToken(getRecoveryToken()).maxCommitTime(transactionOptions.getMaxCommitTime(MILLISECONDS), MILLISECONDS), readConcern, this).doOnTerminate(() -> {
            commitInProgress = false;
            transactionState = TransactionState.COMMITTED;
        }).doOnError(MongoException.class, this::clearTransactionContextOnError);
    }
}
Also used : MonoSink(reactor.core.publisher.MonoSink) CommitTransactionOperation(com.mongodb.internal.operation.CommitTransactionOperation) ReadConcern(com.mongodb.ReadConcern) MongoInternalException(com.mongodb.MongoInternalException)

Aggregations

ReadConcern (com.mongodb.ReadConcern)11 WriteConcern (com.mongodb.WriteConcern)6 MongoException (com.mongodb.MongoException)5 MongoInternalException (com.mongodb.MongoInternalException)5 ReadPreference (com.mongodb.ReadPreference)4 ClientSessionOptions (com.mongodb.ClientSessionOptions)3 MongoClientException (com.mongodb.MongoClientException)3 MongoClientSettings (com.mongodb.MongoClientSettings)3 ReadConcernLevel (com.mongodb.ReadConcernLevel)3 TransactionOptions (com.mongodb.TransactionOptions)3 ClusterFixture.getMultiMongosConnectionString (com.mongodb.ClusterFixture.getMultiMongosConnectionString)2 ClusterFixture.isSharded (com.mongodb.ClusterFixture.isSharded)2 ConnectionString (com.mongodb.ConnectionString)2 TRANSIENT_TRANSACTION_ERROR_LABEL (com.mongodb.MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL)2 UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL (com.mongodb.MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)2 ServerAddress (com.mongodb.ServerAddress)2 Assertions.notNull (com.mongodb.assertions.Assertions.notNull)2 Fixture.getMongoClientSettingsBuilder (com.mongodb.client.Fixture.getMongoClientSettingsBuilder)2 MongoClient (com.mongodb.client.MongoClient)2 MongoCollection (com.mongodb.client.MongoCollection)2