diff --git a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java index 4146d06c22e..6ac8541e51c 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java +++ b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java @@ -94,7 +94,8 @@ import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.stream.Collectors.toList; -abstract class BaseCluster implements Cluster { +@VisibleForTesting(otherwise = PRIVATE) +public abstract class BaseCluster implements Cluster { private static final Logger LOGGER = Loggers.getLogger("cluster"); private static final StructuredLogger STRUCTURED_LOGGER = new StructuredLogger("cluster"); @@ -112,10 +113,11 @@ abstract class BaseCluster implements Cluster { private volatile boolean isClosed; private volatile ClusterDescription description; - BaseCluster(final ClusterId clusterId, - final ClusterSettings settings, - final ClusterableServerFactory serverFactory, - final ClientMetadata clientMetadata) { + @VisibleForTesting(otherwise = PRIVATE) + protected BaseCluster(final ClusterId clusterId, + final ClusterSettings settings, + final ClusterableServerFactory serverFactory, + final ClientMetadata clientMetadata) { this.clusterId = notNull("clusterId", clusterId); this.settings = notNull("settings", settings); this.serverFactory = notNull("serverFactory", serverFactory); @@ -361,8 +363,7 @@ private static ServerSelector getCompleteServerSelector( final ClusterSettings settings) { List selectors = Stream.of( getRaceConditionPreFilteringSelector(serversSnapshot), - serverSelector, - serverDeprioritization.getServerSelector(), + serverDeprioritization.applyDeprioritization(serverSelector), settings.getServerSelector(), // may be null new LatencyMinimizingServerSelector(settings.getLocalThreshold(MILLISECONDS), MILLISECONDS), AtMostTwoRandomServerSelector.instance(), diff --git a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java index f23d5e5226b..1cd69187c41 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -22,7 +22,6 @@ import com.mongodb.ServerAddress; import com.mongodb.ServerApi; import com.mongodb.connection.ClusterDescription; -import com.mongodb.connection.ClusterType; import com.mongodb.connection.ServerDescription; import com.mongodb.internal.IgnorableRequestContext; import com.mongodb.internal.TimeoutContext; @@ -40,6 +39,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; +import static com.mongodb.internal.VisibleForTesting.AccessModifier.PACKAGE; +import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; import static java.util.stream.Collectors.toList; /** @@ -113,6 +114,13 @@ public OperationContext withOperationName(final String operationName) { operationName, tracingSpan); } + // TODO-JAVA-6058: This method enables overriding the ServerDeprioritization state. + // It is a temporary solution to handle cases where deprioritization state persists across operations. + public OperationContext withServerDeprioritization(final ServerDeprioritization serverDeprioritization) { + return new OperationContext(id, requestContext, sessionContext, timeoutContext, serverDeprioritization, tracingManager, serverApi, + operationName, tracingSpan); + } + public long getId() { return id; } @@ -228,24 +236,26 @@ public static final class ServerDeprioritization { @Nullable private ServerAddress candidate; private final Set deprioritized; - private final DeprioritizingSelector selector; - private ServerDeprioritization() { + @VisibleForTesting(otherwise = PRIVATE) + public ServerDeprioritization() { candidate = null; deprioritized = new HashSet<>(); - selector = new DeprioritizingSelector(); } /** - * The returned {@link ServerSelector} tries to {@linkplain ServerSelector#select(ClusterDescription) select} - * only the {@link ServerDescription}s that do not have deprioritized {@link ServerAddress}es. - * If no such {@link ServerDescription} can be selected, then it selects {@link ClusterDescription#getServerDescriptions()}. + * The returned {@link ServerSelector} wraps the provided selector and attempts server selection in two passes: + *
    + *
  1. First pass: calls the wrapped selector with only non-deprioritized {@link ServerDescription}s
  2. + *
  3. Second pass: if the first pass returns no servers, calls the wrapped selector again with all servers (including deprioritized ones)
  4. + *
*/ - ServerSelector getServerSelector() { - return selector; + ServerSelector applyDeprioritization(final ServerSelector wrappedSelector) { + return new DeprioritizingSelector(wrappedSelector); } - void updateCandidate(final ServerAddress serverAddress) { + @VisibleForTesting(otherwise = PACKAGE) + public void updateCandidate(final ServerAddress serverAddress) { candidate = serverAddress; } @@ -263,24 +273,35 @@ public void onAttemptFailure(final Throwable failure) { * which indeed may be used concurrently. {@link DeprioritizingSelector} does not need to be thread-safe. */ private final class DeprioritizingSelector implements ServerSelector { - private DeprioritizingSelector() { + private final ServerSelector wrappedSelector; + + private DeprioritizingSelector(final ServerSelector wrappedSelector) { + this.wrappedSelector = wrappedSelector; } @Override public List select(final ClusterDescription clusterDescription) { List serverDescriptions = clusterDescription.getServerDescriptions(); - if (!isEnabled(clusterDescription.getType())) { - return serverDescriptions; + + if (serverDescriptions.size() == 1 || deprioritized.isEmpty()) { + return wrappedSelector.select(clusterDescription); } + List nonDeprioritizedServerDescriptions = serverDescriptions .stream() .filter(serverDescription -> !deprioritized.contains(serverDescription.getAddress())) .collect(toList()); - return nonDeprioritizedServerDescriptions.isEmpty() ? serverDescriptions : nonDeprioritizedServerDescriptions; - } - private boolean isEnabled(final ClusterType clusterType) { - return clusterType == ClusterType.SHARDED; + if (nonDeprioritizedServerDescriptions.isEmpty()) { + return wrappedSelector.select(clusterDescription); + } + + List selected = wrappedSelector.select( + new ClusterDescription(clusterDescription.getConnectionMode(), clusterDescription.getType(), + nonDeprioritizedServerDescriptions, + clusterDescription.getClusterSettings(), + clusterDescription.getServerSettings())); + return selected.isEmpty() ? wrappedSelector.select(clusterDescription) : selected; } } } diff --git a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursor.java b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursor.java index cf9f1dcf6c4..d2c643699fa 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursor.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursor.java @@ -85,7 +85,11 @@ final class ChangeStreamBatchCursor implements AggregateResponseBatchCursor("admin", new BsonDocument("buildInfo", new BsonInt32(1)), new BsonDocumentCodec()) - .execute(new ClusterBinding(getCluster(), ReadPreference.nearest()), OPERATION_CONTEXT)); + .execute(new ClusterBinding(getCluster(), ReadPreference.nearest()), getOperationContext())); } return serverVersion; } - public static final OperationContext OPERATION_CONTEXT = new OperationContext( - IgnorableRequestContext.INSTANCE, - new ReadConcernAwareNoOpSessionContext(ReadConcern.DEFAULT), - new TimeoutContext(TIMEOUT_SETTINGS), - getServerApi()); + public static OperationContext getOperationContext() { + return new OperationContext( + IgnorableRequestContext.INSTANCE, + new ReadConcernAwareNoOpSessionContext(ReadConcern.DEFAULT), + new TimeoutContext(TIMEOUT_SETTINGS), + getServerApi()); + } public static final InternalOperationContextFactory OPERATION_CONTEXT_FACTORY = new InternalOperationContextFactory(TIMEOUT_SETTINGS, getServerApi()); @@ -255,7 +257,7 @@ public static boolean hasEncryptionTestsEnabled() { public static Document getServerStatus() { return new CommandReadOperation<>("admin", new BsonDocument("serverStatus", new BsonInt32(1)), new DocumentCodec()) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } public static boolean supportsFsync() { @@ -270,7 +272,7 @@ static class ShutdownHook extends Thread { public void run() { if (cluster != null) { try { - new DropDatabaseOperation(getDefaultDatabaseName(), WriteConcern.ACKNOWLEDGED).execute(getBinding(), OPERATION_CONTEXT); + new DropDatabaseOperation(getDefaultDatabaseName(), WriteConcern.ACKNOWLEDGED).execute(getBinding(), getOperationContext()); } catch (MongoCommandException e) { // if we do not have permission to drop the database, assume it is cleaned up in some other way if (!e.getMessage().contains("Command dropDatabase requires authentication")) { @@ -322,7 +324,7 @@ public static synchronized ConnectionString getConnectionString() { try { BsonDocument helloResult = new CommandReadOperation<>("admin", new BsonDocument(LEGACY_HELLO, new BsonInt32(1)), new BsonDocumentCodec()) - .execute(new ClusterBinding(cluster, ReadPreference.nearest()), OPERATION_CONTEXT); + .execute(new ClusterBinding(cluster, ReadPreference.nearest()), getOperationContext()); if (helloResult.containsKey("setName")) { connectionString = new ConnectionString(DEFAULT_URI + "/?replicaSet=" + helloResult.getString("setName").getValue()); @@ -382,11 +384,11 @@ public static ReadWriteBinding getBinding(final OperationContext operationContex } public static ReadWriteBinding getBinding(final ReadPreference readPreference) { - return getBinding(getCluster(), readPreference, OPERATION_CONTEXT); + return getBinding(getCluster(), readPreference, getOperationContext()); } public static OperationContext createNewOperationContext(final TimeoutSettings timeoutSettings) { - return OPERATION_CONTEXT.withTimeoutContext(new TimeoutContext(timeoutSettings)); + return getOperationContext().withTimeoutContext(new TimeoutContext(timeoutSettings)); } private static ReadWriteBinding getBinding(final Cluster cluster, @@ -403,7 +405,7 @@ private static ReadWriteBinding getBinding(final Cluster cluster, } public static SingleConnectionBinding getSingleConnectionBinding() { - return new SingleConnectionBinding(getCluster(), ReadPreference.primary(), OPERATION_CONTEXT); + return new SingleConnectionBinding(getCluster(), ReadPreference.primary(), getOperationContext()); } public static AsyncSingleConnectionBinding getAsyncSingleConnectionBinding() { @@ -411,7 +413,7 @@ public static AsyncSingleConnectionBinding getAsyncSingleConnectionBinding() { } public static AsyncSingleConnectionBinding getAsyncSingleConnectionBinding(final Cluster cluster) { - return new AsyncSingleConnectionBinding(cluster, ReadPreference.primary(), OPERATION_CONTEXT); + return new AsyncSingleConnectionBinding(cluster, ReadPreference.primary(), getOperationContext()); } public static AsyncReadWriteBinding getAsyncBinding(final Cluster cluster) { @@ -419,7 +421,7 @@ public static AsyncReadWriteBinding getAsyncBinding(final Cluster cluster) { } public static AsyncReadWriteBinding getAsyncBinding() { - return getAsyncBinding(getAsyncCluster(), ReadPreference.primary(), OPERATION_CONTEXT); + return getAsyncBinding(getAsyncCluster(), ReadPreference.primary(), getOperationContext()); } public static AsyncReadWriteBinding getAsyncBinding(final TimeoutSettings timeoutSettings) { @@ -431,7 +433,7 @@ public static AsyncReadWriteBinding getAsyncBinding(final OperationContext opera } public static AsyncReadWriteBinding getAsyncBinding(final ReadPreference readPreference) { - return getAsyncBinding(getAsyncCluster(), readPreference, OPERATION_CONTEXT); + return getAsyncBinding(getAsyncCluster(), readPreference, getOperationContext()); } public static AsyncReadWriteBinding getAsyncBinding( @@ -605,7 +607,7 @@ public static BsonDocument getServerParameters() { if (serverParameters == null) { serverParameters = new CommandReadOperation<>("admin", new BsonDocument("getParameter", new BsonString("*")), new BsonDocumentCodec()) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } return serverParameters; } @@ -673,7 +675,7 @@ public static void configureFailPoint(final BsonDocument failPointDocument) { if (!isSharded()) { try { new CommandReadOperation<>("admin", failPointDocument, new BsonDocumentCodec()) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } catch (MongoCommandException e) { if (e.getErrorCode() == COMMAND_NOT_FOUND_ERROR_CODE) { failsPointsSupported = false; @@ -689,7 +691,7 @@ public static void disableFailPoint(final String failPoint) { .append("mode", new BsonString("off")); try { new CommandReadOperation<>("admin", failPointDocument, new BsonDocumentCodec()) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } catch (MongoCommandException e) { // ignore } @@ -703,7 +705,7 @@ public static T executeSync(final WriteOperation op) { @SuppressWarnings("overloads") public static T executeSync(final WriteOperation op, final ReadWriteBinding binding) { - return op.execute(binding, applySessionContext(OPERATION_CONTEXT, binding.getReadPreference())); + return op.execute(binding, applySessionContext(getOperationContext(), binding.getReadPreference())); } @SuppressWarnings("overloads") @@ -713,7 +715,7 @@ public static T executeSync(final ReadOperation op) { @SuppressWarnings("overloads") public static T executeSync(final ReadOperation op, final ReadWriteBinding binding) { - return op.execute(binding, OPERATION_CONTEXT); + return op.execute(binding, getOperationContext()); } @SuppressWarnings("overloads") @@ -729,7 +731,7 @@ public static T executeAsync(final WriteOperation op) throws Throwable { @SuppressWarnings("overloads") public static T executeAsync(final WriteOperation op, final AsyncReadWriteBinding binding) throws Throwable { FutureResultCallback futureResultCallback = new FutureResultCallback<>(); - op.executeAsync(binding, applySessionContext(OPERATION_CONTEXT, binding.getReadPreference()), futureResultCallback); + op.executeAsync(binding, applySessionContext(getOperationContext(), binding.getReadPreference()), futureResultCallback); return futureResultCallback.get(TIMEOUT, SECONDS); } @@ -741,7 +743,7 @@ public static T executeAsync(final ReadOperation op) throws Throwable @SuppressWarnings("overloads") public static T executeAsync(final ReadOperation op, final AsyncReadBinding binding) throws Throwable { FutureResultCallback futureResultCallback = new FutureResultCallback<>(); - op.executeAsync(binding, OPERATION_CONTEXT, futureResultCallback); + op.executeAsync(binding, getOperationContext(), futureResultCallback); return futureResultCallback.get(TIMEOUT, SECONDS); } @@ -811,19 +813,19 @@ public static List collectCursorResults(final BatchCursor batchCursor) public static AsyncConnectionSource getWriteConnectionSource(final AsyncReadWriteBinding binding) throws Throwable { FutureResultCallback futureResultCallback = new FutureResultCallback<>(); - binding.getWriteConnectionSource(OPERATION_CONTEXT, futureResultCallback); + binding.getWriteConnectionSource(getOperationContext(), futureResultCallback); return futureResultCallback.get(TIMEOUT, SECONDS); } public static AsyncConnectionSource getReadConnectionSource(final AsyncReadWriteBinding binding) throws Throwable { FutureResultCallback futureResultCallback = new FutureResultCallback<>(); - binding.getReadConnectionSource(OPERATION_CONTEXT, futureResultCallback); + binding.getReadConnectionSource(getOperationContext(), futureResultCallback); return futureResultCallback.get(TIMEOUT, SECONDS); } public static AsyncConnection getConnection(final AsyncConnectionSource source) throws Throwable { FutureResultCallback futureResultCallback = new FutureResultCallback<>(); - source.getConnection(OPERATION_CONTEXT, futureResultCallback); + source.getConnection(getOperationContext(), futureResultCallback); return futureResultCallback.get(TIMEOUT, SECONDS); } @@ -867,6 +869,6 @@ private static OperationContext applySessionContext(final OperationContext opera } public static OperationContext getOperationContext(final ReadPreference readPreference) { - return applySessionContext(OPERATION_CONTEXT, readPreference); + return applySessionContext(getOperationContext(), readPreference); } } diff --git a/driver-core/src/test/functional/com/mongodb/OperationFunctionalSpecification.groovy b/driver-core/src/test/functional/com/mongodb/OperationFunctionalSpecification.groovy index 6648edc50c7..d670fffe1a3 100644 --- a/driver-core/src/test/functional/com/mongodb/OperationFunctionalSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/OperationFunctionalSpecification.groovy @@ -61,7 +61,7 @@ import spock.lang.Specification import java.util.concurrent.TimeUnit -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.TIMEOUT import static com.mongodb.ClusterFixture.checkReferenceCountReachesTarget import static com.mongodb.ClusterFixture.executeAsync @@ -108,7 +108,7 @@ class OperationFunctionalSpecification extends Specification { void acknowledgeWrite(final SingleConnectionBinding binding) { new MixedBulkWriteOperation(getNamespace(), [new InsertRequest(new BsonDocument())], true, - ACKNOWLEDGED, false).execute(binding, OPERATION_CONTEXT) + ACKNOWLEDGED, false).execute(binding, getOperationContext()) binding.release() } @@ -279,7 +279,7 @@ class OperationFunctionalSpecification extends Specification { BsonDocument expectedCommand=null, Boolean checkSecondaryOk=false, ReadPreference readPreference=ReadPreference.primary(), Boolean retryable = false, ServerType serverType = ServerType.STANDALONE, Boolean activeTransaction = false) { - def operationContext = OPERATION_CONTEXT + def operationContext = getOperationContext() .withSessionContext(Stub(SessionContext) { hasActiveTransaction() >> activeTransaction getReadConcern() >> readConcern @@ -353,7 +353,7 @@ class OperationFunctionalSpecification extends Specification { Boolean checkCommand = true, BsonDocument expectedCommand = null, Boolean checkSecondaryOk = false, ReadPreference readPreference = ReadPreference.primary(), Boolean retryable = false, ServerType serverType = ServerType.STANDALONE, Boolean activeTransaction = false) { - def operationContext = OPERATION_CONTEXT + def operationContext = getOperationContext() .withSessionContext(Stub(SessionContext) { hasActiveTransaction() >> activeTransaction getReadConcern() >> readConcern @@ -447,7 +447,7 @@ class OperationFunctionalSpecification extends Specification { } } - def operationContext = OPERATION_CONTEXT.withSessionContext( + def operationContext = getOperationContext().withSessionContext( Stub(SessionContext) { hasSession() >> true hasActiveTransaction() >> false @@ -488,7 +488,7 @@ class OperationFunctionalSpecification extends Specification { } } - def operationContext = OPERATION_CONTEXT.withSessionContext( + def operationContext = getOperationContext().withSessionContext( Stub(SessionContext) { hasSession() >> true hasActiveTransaction() >> false diff --git a/driver-core/src/test/functional/com/mongodb/client/test/CollectionHelper.java b/driver-core/src/test/functional/com/mongodb/client/test/CollectionHelper.java index 935c2979fc4..f6bc4c3efe2 100644 --- a/driver-core/src/test/functional/com/mongodb/client/test/CollectionHelper.java +++ b/driver-core/src/test/functional/com/mongodb/client/test/CollectionHelper.java @@ -72,7 +72,7 @@ import java.util.Optional; import java.util.stream.Collectors; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.executeAsync; import static com.mongodb.ClusterFixture.getBinding; import static java.lang.String.format; @@ -93,7 +93,7 @@ public CollectionHelper(final Codec codec, final MongoNamespace namespace) { public T hello() { return new CommandReadOperation<>("admin", BsonDocument.parse("{isMaster: 1}"), codec) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } public static void drop(final MongoNamespace namespace) { @@ -106,7 +106,7 @@ public static void drop(final MongoNamespace namespace, final WriteConcern write boolean success = false; while (!success) { try { - new DropCollectionOperation(namespace, writeConcern).execute(getBinding(), OPERATION_CONTEXT); + new DropCollectionOperation(namespace, writeConcern).execute(getBinding(), getOperationContext()); success = true; } catch (MongoWriteConcernException e) { LOGGER.info("Retrying drop collection after a write concern error: " + e); @@ -131,7 +131,7 @@ public static void dropDatabase(final String name, final WriteConcern writeConce return; } try { - new DropDatabaseOperation(name, writeConcern).execute(getBinding(), OPERATION_CONTEXT); + new DropDatabaseOperation(name, writeConcern).execute(getBinding(), getOperationContext()); } catch (MongoCommandException e) { if (!e.getErrorMessage().contains("ns not found")) { throw e; @@ -141,7 +141,7 @@ public static void dropDatabase(final String name, final WriteConcern writeConce public static BsonDocument getCurrentClusterTime() { return new CommandReadOperation("admin", new BsonDocument("ping", new BsonInt32(1)), new BsonDocumentCodec()) - .execute(getBinding(), OPERATION_CONTEXT).getDocument("$clusterTime", null); + .execute(getBinding(), getOperationContext()).getDocument("$clusterTime", null); } public MongoNamespace getNamespace() { @@ -235,7 +235,7 @@ public void create(final String collectionName, final CreateCollectionOptions op boolean success = false; while (!success) { try { - operation.execute(getBinding(), OPERATION_CONTEXT); + operation.execute(getBinding(), getOperationContext()); success = true; } catch (MongoCommandException e) { if ("Interrupted".equals(e.getErrorCodeName())) { @@ -254,7 +254,7 @@ public void killCursor(final MongoNamespace namespace, final ServerCursor server .append("cursors", new BsonArray(singletonList(new BsonInt64(serverCursor.getId())))); try { new CommandReadOperation<>(namespace.getDatabaseName(), command, new BsonDocumentCodec()) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } catch (Exception e) { // Ignore any exceptions killing old cursors } @@ -286,7 +286,7 @@ public void insertDocuments(final List documents, final WriteConce for (BsonDocument document : documents) { insertRequests.add(new InsertRequest(document)); } - new MixedBulkWriteOperation(namespace, insertRequests, true, writeConcern, false).execute(binding, OPERATION_CONTEXT); + new MixedBulkWriteOperation(namespace, insertRequests, true, writeConcern, false).execute(binding, getOperationContext()); } public void insertDocuments(final Document... documents) { @@ -329,7 +329,7 @@ public List find() { public Optional listSearchIndex(final String indexName) { ListSearchIndexesOperation listSearchIndexesOperation = new ListSearchIndexesOperation<>(namespace, codec, indexName, null, null, null, null, true); - BatchCursor cursor = listSearchIndexesOperation.execute(getBinding(), OPERATION_CONTEXT); + BatchCursor cursor = listSearchIndexesOperation.execute(getBinding(), getOperationContext()); List results = new ArrayList<>(); while (cursor.hasNext()) { @@ -342,13 +342,13 @@ public Optional listSearchIndex(final String indexName) { public void createSearchIndex(final SearchIndexRequest searchIndexModel) { CreateSearchIndexesOperation searchIndexesOperation = new CreateSearchIndexesOperation(namespace, singletonList(searchIndexModel)); - searchIndexesOperation.execute(getBinding(), OPERATION_CONTEXT); + searchIndexesOperation.execute(getBinding(), getOperationContext()); } public List find(final Codec codec) { BatchCursor cursor = new FindOperation<>(namespace, codec) .sort(new BsonDocument("_id", new BsonInt32(1))) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); List results = new ArrayList<>(); while (cursor.hasNext()) { results.addAll(cursor.next()); @@ -367,7 +367,7 @@ public void updateOne(final Bson filter, final Bson update, final boolean isUpse WriteRequest.Type.UPDATE) .upsert(isUpsert)), true, WriteConcern.ACKNOWLEDGED, false) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } public void replaceOne(final Bson filter, final Bson update, final boolean isUpsert) { @@ -377,7 +377,7 @@ public void replaceOne(final Bson filter, final Bson update, final boolean isUps WriteRequest.Type.REPLACE) .upsert(isUpsert)), true, WriteConcern.ACKNOWLEDGED, false) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } public void deleteOne(final Bson filter) { @@ -392,7 +392,7 @@ private void delete(final Bson filter, final boolean multi) { new MixedBulkWriteOperation(namespace, singletonList(new DeleteRequest(filter.toBsonDocument(Document.class, registry)).multi(multi)), true, WriteConcern.ACKNOWLEDGED, false) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } public List find(final Bson filter) { @@ -417,7 +417,7 @@ private List aggregate(final List pipeline, final Decoder decode bsonDocumentPipeline.add(cur.toBsonDocument(Document.class, registry)); } BatchCursor cursor = new AggregateOperation<>(namespace, bsonDocumentPipeline, decoder, level) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); List results = new ArrayList<>(); while (cursor.hasNext()) { results.addAll(cursor.next()); @@ -452,7 +452,7 @@ public List find(final BsonDocument filter, final BsonDocument sort, fina public List find(final BsonDocument filter, final BsonDocument sort, final BsonDocument projection, final Decoder decoder) { BatchCursor cursor = new FindOperation<>(namespace, decoder).filter(filter).sort(sort) - .projection(projection).execute(getBinding(), OPERATION_CONTEXT); + .projection(projection).execute(getBinding(), getOperationContext()); List results = new ArrayList<>(); while (cursor.hasNext()) { results.addAll(cursor.next()); @@ -465,7 +465,7 @@ public long count() { } public long count(final ReadBinding binding) { - return new CountDocumentsOperation(namespace).execute(binding, OPERATION_CONTEXT); + return new CountDocumentsOperation(namespace).execute(binding, getOperationContext()); } public long count(final AsyncReadWriteBinding binding) throws Throwable { @@ -474,7 +474,7 @@ public long count(final AsyncReadWriteBinding binding) throws Throwable { public long count(final Bson filter) { return new CountDocumentsOperation(namespace) - .filter(toBsonDocument(filter)).execute(getBinding(), OPERATION_CONTEXT); + .filter(toBsonDocument(filter)).execute(getBinding(), getOperationContext()); } public BsonDocument wrap(final Document document) { @@ -487,36 +487,36 @@ public BsonDocument toBsonDocument(final Bson document) { public void createIndex(final BsonDocument key) { new CreateIndexesOperation(namespace, singletonList(new IndexRequest(key)), WriteConcern.ACKNOWLEDGED) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } public void createIndex(final Document key) { new CreateIndexesOperation(namespace, singletonList(new IndexRequest(wrap(key))), WriteConcern.ACKNOWLEDGED) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } public void createUniqueIndex(final Document key) { new CreateIndexesOperation(namespace, singletonList(new IndexRequest(wrap(key)).unique(true)), WriteConcern.ACKNOWLEDGED) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } public void createIndex(final Document key, final String defaultLanguage) { new CreateIndexesOperation(namespace, singletonList(new IndexRequest(wrap(key)).defaultLanguage(defaultLanguage)), WriteConcern.ACKNOWLEDGED).execute( - getBinding(), OPERATION_CONTEXT); + getBinding(), getOperationContext()); } public void createIndex(final Bson key) { new CreateIndexesOperation(namespace, singletonList(new IndexRequest(key.toBsonDocument(Document.class, registry))), WriteConcern.ACKNOWLEDGED).execute( - getBinding(), OPERATION_CONTEXT); + getBinding(), getOperationContext()); } public List listIndexes(){ List indexes = new ArrayList<>(); BatchCursor cursor = new ListIndexesOperation<>(namespace, new BsonDocumentCodec()) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); while (cursor.hasNext()) { indexes.addAll(cursor.next()); } @@ -526,7 +526,7 @@ public List listIndexes(){ public static void killAllSessions() { try { new CommandReadOperation<>("admin", - new BsonDocument("killAllSessions", new BsonArray()), new BsonDocumentCodec()).execute(getBinding(), OPERATION_CONTEXT); + new BsonDocument("killAllSessions", new BsonArray()), new BsonDocumentCodec()).execute(getBinding(), getOperationContext()); } catch (MongoCommandException e) { // ignore exception caused by killing the implicit session that the killAllSessions command itself is running in } @@ -537,7 +537,7 @@ public void renameCollection(final MongoNamespace newNamespace) { new CommandReadOperation<>("admin", new BsonDocument("renameCollection", new BsonString(getNamespace().getFullName())) .append("to", new BsonString(newNamespace.getFullName())), new BsonDocumentCodec()).execute( - getBinding(), OPERATION_CONTEXT); + getBinding(), getOperationContext()); } catch (MongoCommandException e) { // do nothing } @@ -549,11 +549,11 @@ public void runAdminCommand(final String command) { public void runAdminCommand(final BsonDocument command) { new CommandReadOperation<>("admin", command, new BsonDocumentCodec()) - .execute(getBinding(), OPERATION_CONTEXT); + .execute(getBinding(), getOperationContext()); } public void runAdminCommand(final BsonDocument command, final ReadPreference readPreference) { new CommandReadOperation<>("admin", command, new BsonDocumentCodec()) - .execute(getBinding(readPreference), OPERATION_CONTEXT); + .execute(getBinding(readPreference), getOperationContext()); } } diff --git a/driver-core/src/test/functional/com/mongodb/connection/ConnectionSpecification.groovy b/driver-core/src/test/functional/com/mongodb/connection/ConnectionSpecification.groovy index 5658ec5ea43..e4407fc392e 100644 --- a/driver-core/src/test/functional/com/mongodb/connection/ConnectionSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/connection/ConnectionSpecification.groovy @@ -23,7 +23,7 @@ import org.bson.BsonInt32 import org.bson.codecs.BsonDocumentCodec import static com.mongodb.ClusterFixture.LEGACY_HELLO -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.getBinding import static com.mongodb.connection.ConnectionDescription.getDefaultMaxMessageSize import static com.mongodb.connection.ConnectionDescription.getDefaultMaxWriteBatchSize @@ -32,8 +32,8 @@ class ConnectionSpecification extends OperationFunctionalSpecification { def 'should have id'() { when: - def source = getBinding().getReadConnectionSource(OPERATION_CONTEXT) - def connection = source.getConnection(OPERATION_CONTEXT) + def source = getBinding().getReadConnectionSource(getOperationContext()) + def connection = source.getConnection(getOperationContext()) then: connection.getDescription().getConnectionId() != null @@ -50,8 +50,8 @@ class ConnectionSpecification extends OperationFunctionalSpecification { new BsonInt32(getDefaultMaxMessageSize())).intValue() def expectedMaxBatchCount = commandResult.getNumber('maxWriteBatchSize', new BsonInt32(getDefaultMaxWriteBatchSize())).intValue() - def source = getBinding().getReadConnectionSource(OPERATION_CONTEXT) - def connection = source.getConnection(OPERATION_CONTEXT) + def source = getBinding().getReadConnectionSource(getOperationContext()) + def connection = source.getConnection(getOperationContext()) then: connection.description.serverAddress == source.getServerDescription().getAddress() @@ -66,6 +66,6 @@ class ConnectionSpecification extends OperationFunctionalSpecification { } private static BsonDocument getHelloResult() { new CommandReadOperation('admin', new BsonDocument(LEGACY_HELLO, new BsonInt32(1)), - new BsonDocumentCodec()).execute(getBinding(), OPERATION_CONTEXT) + new BsonDocumentCodec()).execute(getBinding(), getOperationContext()) } } diff --git a/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy b/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy index e582e0fc398..70130e0f14c 100644 --- a/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/connection/netty/NettyStreamSpecification.groovy @@ -18,7 +18,7 @@ import com.mongodb.spock.Slow import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.getSslSettings class NettyStreamSpecification extends Specification { @@ -43,7 +43,7 @@ class NettyStreamSpecification extends Specification { def stream = factory.create(new ServerAddress()) when: - stream.open(OPERATION_CONTEXT) + stream.open(getOperationContext()) then: !stream.isClosed() @@ -69,7 +69,7 @@ class NettyStreamSpecification extends Specification { def stream = factory.create(new ServerAddress()) when: - stream.open(OPERATION_CONTEXT) + stream.open(getOperationContext()) then: thrown(MongoSocketOpenException) @@ -96,7 +96,7 @@ class NettyStreamSpecification extends Specification { def callback = new CallbackErrorHolder() when: - stream.openAsync(OPERATION_CONTEXT, callback) + stream.openAsync(getOperationContext(), callback) then: callback.getError().is(exception) diff --git a/driver-core/src/test/functional/com/mongodb/internal/binding/AsyncSessionBindingSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/binding/AsyncSessionBindingSpecification.groovy index 173cd9f0935..7517fbc2d1c 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/binding/AsyncSessionBindingSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/binding/AsyncSessionBindingSpecification.groovy @@ -16,17 +16,17 @@ package com.mongodb.internal.binding +import com.mongodb.ClusterFixture import com.mongodb.internal.async.SingleResultCallback import spock.lang.Specification -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT - class AsyncSessionBindingSpecification extends Specification { def 'should wrap the passed in async binding'() { given: def wrapped = Mock(AsyncReadWriteBinding) def binding = new AsyncSessionBinding(wrapped) + def operationContext = ClusterFixture.getOperationContext() when: binding.getCount() @@ -52,17 +52,18 @@ class AsyncSessionBindingSpecification extends Specification { then: 1 * wrapped.release() + when: - binding.getReadConnectionSource(OPERATION_CONTEXT, Stub(SingleResultCallback)) + binding.getReadConnectionSource(operationContext, Stub(SingleResultCallback)) then: - 1 * wrapped.getReadConnectionSource(OPERATION_CONTEXT, _) + 1 * wrapped.getReadConnectionSource(operationContext, _) when: - binding.getWriteConnectionSource(OPERATION_CONTEXT, Stub(SingleResultCallback)) + binding.getWriteConnectionSource(operationContext, Stub(SingleResultCallback)) then: - 1 * wrapped.getWriteConnectionSource(OPERATION_CONTEXT, _) + 1 * wrapped.getWriteConnectionSource(operationContext, _) } } diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy index 85f23350984..76d503583bb 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncSocketChannelStreamSpecification.groovy @@ -13,7 +13,7 @@ import com.mongodb.spock.Slow import java.util.concurrent.CountDownLatch -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.getSslSettings import static java.util.concurrent.TimeUnit.MILLISECONDS @@ -40,7 +40,7 @@ class AsyncSocketChannelStreamSpecification extends Specification { def stream = factory.create(new ServerAddress('host1')) when: - stream.open(OPERATION_CONTEXT) + stream.open(getOperationContext()) then: !stream.isClosed() @@ -66,7 +66,7 @@ class AsyncSocketChannelStreamSpecification extends Specification { def stream = factory.create(new ServerAddress()) when: - stream.open(OPERATION_CONTEXT) + stream.open(getOperationContext()) then: thrown(MongoSocketOpenException) @@ -90,7 +90,7 @@ class AsyncSocketChannelStreamSpecification extends Specification { def callback = new CallbackErrorHolder() when: - stream.openAsync(OPERATION_CONTEXT, callback) + stream.openAsync(getOperationContext(), callback) then: callback.getError().is(exception) diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy index 3589362b8ac..ba5fb45d5e9 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/AsyncStreamTimeoutsSpecification.groovy @@ -30,7 +30,7 @@ import com.mongodb.spock.Slow import java.util.concurrent.TimeUnit -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.getCredentialWithCache import static com.mongodb.ClusterFixture.getServerApi import static com.mongodb.ClusterFixture.getSslSettings @@ -49,7 +49,7 @@ class AsyncStreamTimeoutsSpecification extends OperationFunctionalSpecification .create(new ServerId(new ClusterId(), new ServerAddress(new InetSocketAddress('192.168.255.255', 27017)))) when: - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) then: thrown(MongoSocketOpenException) @@ -63,7 +63,7 @@ class AsyncStreamTimeoutsSpecification extends OperationFunctionalSpecification new ServerAddress(new InetSocketAddress('192.168.255.255', 27017)))) when: - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) then: thrown(MongoSocketOpenException) diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/AwsAuthenticationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/AwsAuthenticationSpecification.groovy index 8dd53bc1c03..b4496811dcc 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/AwsAuthenticationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/AwsAuthenticationSpecification.groovy @@ -19,7 +19,7 @@ import spock.lang.Specification import java.util.function.Supplier import static com.mongodb.AuthenticationMechanism.MONGODB_AWS -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.getClusterConnectionMode import static com.mongodb.ClusterFixture.getConnectionString import static com.mongodb.ClusterFixture.getCredential @@ -52,7 +52,7 @@ class AwsAuthenticationSpecification extends Specification { when: openConnection(connection, async) executeCommand(getConnectionString().getDatabase(), new BsonDocument('count', new BsonString('test')), - getClusterConnectionMode(), null, connection, OPERATION_CONTEXT) + getClusterConnectionMode(), null, connection, getOperationContext()) then: thrown(MongoCommandException) @@ -71,7 +71,7 @@ class AwsAuthenticationSpecification extends Specification { when: openConnection(connection, async) executeCommand(getConnectionString().getDatabase(), new BsonDocument('count', new BsonString('test')), - getClusterConnectionMode(), null, connection, OPERATION_CONTEXT) + getClusterConnectionMode(), null, connection, getOperationContext()) then: true @@ -101,7 +101,7 @@ class AwsAuthenticationSpecification extends Specification { when: openConnection(connection, async) executeCommand(getConnectionString().getDatabase(), new BsonDocument('count', new BsonString('test')), - getClusterConnectionMode(), null, connection, OPERATION_CONTEXT) + getClusterConnectionMode(), null, connection, getOperationContext()) then: true @@ -160,10 +160,10 @@ class AwsAuthenticationSpecification extends Specification { private static void openConnection(final InternalConnection connection, final boolean async) { if (async) { FutureResultCallback futureResultCallback = new FutureResultCallback() - connection.openAsync(OPERATION_CONTEXT, futureResultCallback) + connection.openAsync(getOperationContext(), futureResultCallback) futureResultCallback.get(ClusterFixture.TIMEOUT, SECONDS) } else { - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) } } } diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/CommandHelperSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/CommandHelperSpecification.groovy index 2d7dc04d758..a8f3c0b9989 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/CommandHelperSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/CommandHelperSpecification.groovy @@ -31,7 +31,7 @@ import java.util.concurrent.CountDownLatch import static com.mongodb.ClusterFixture.CLIENT_METADATA import static com.mongodb.ClusterFixture.LEGACY_HELLO -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.getClusterConnectionMode import static com.mongodb.ClusterFixture.getCredentialWithCache import static com.mongodb.ClusterFixture.getPrimary @@ -48,7 +48,7 @@ class CommandHelperSpecification extends Specification { new NettyStreamFactory(SocketSettings.builder().build(), getSslSettings()), getCredentialWithCache(), CLIENT_METADATA, [], LoggerSettings.builder().build(), null, getServerApi()) .create(new ServerId(new ClusterId(), getPrimary())) - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) } def cleanup() { @@ -61,7 +61,7 @@ class CommandHelperSpecification extends Specification { Throwable receivedException = null def latch1 = new CountDownLatch(1) executeCommandAsync('admin', new BsonDocument(LEGACY_HELLO, new BsonInt32(1)), getClusterConnectionMode(), - getServerApi(), connection, OPERATION_CONTEXT) + getServerApi(), connection, getOperationContext()) { document, exception -> receivedDocument = document; receivedException = exception; latch1.countDown() } latch1.await() @@ -73,7 +73,7 @@ class CommandHelperSpecification extends Specification { when: def latch2 = new CountDownLatch(1) executeCommandAsync('admin', new BsonDocument('non-existent-command', new BsonInt32(1)), getClusterConnectionMode(), - getServerApi(), connection, OPERATION_CONTEXT) + getServerApi(), connection, getOperationContext()) { document, exception -> receivedDocument = document; receivedException = exception; latch2.countDown() } latch2.await() diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/DefaultConnectionPoolTest.java b/driver-core/src/test/functional/com/mongodb/internal/connection/DefaultConnectionPoolTest.java index fc5926b3bad..026ac22557b 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/DefaultConnectionPoolTest.java +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/DefaultConnectionPoolTest.java @@ -60,7 +60,7 @@ import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Stream; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.OPERATION_CONTEXT_FACTORY; import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS; import static com.mongodb.ClusterFixture.createOperationContext; @@ -173,7 +173,7 @@ public void shouldThrowOnPoolClosed() { String expectedExceptionMessage = "The server at 127.0.0.1:27017 is no longer available"; MongoServerUnavailableException exception; - exception = assertThrows(MongoServerUnavailableException.class, () -> provider.get(OPERATION_CONTEXT)); + exception = assertThrows(MongoServerUnavailableException.class, () -> provider.get(getOperationContext())); assertEquals(expectedExceptionMessage, exception.getMessage()); SupplyingCallback supplyingCallback = new SupplyingCallback<>(); provider.getAsync(createOperationContext(TIMEOUT_SETTINGS.withMaxWaitTimeMS(50)), supplyingCallback); @@ -194,10 +194,10 @@ public void shouldExpireConnectionAfterMaxLifeTime() throws InterruptedException provider.ready(); // when - provider.get(OPERATION_CONTEXT).close(); + provider.get(getOperationContext()).close(); sleep(100); provider.doMaintenance(); - provider.get(OPERATION_CONTEXT); + provider.get(getOperationContext()); // then assertTrue(connectionFactory.getNumCreatedConnections() >= 2); // should really be two, but it's racy @@ -215,7 +215,7 @@ public void shouldExpireConnectionAfterLifeTimeOnClose() throws InterruptedExcep provider.ready(); // when - InternalConnection connection = provider.get(OPERATION_CONTEXT); + InternalConnection connection = provider.get(getOperationContext()); sleep(50); connection.close(); @@ -236,10 +236,10 @@ public void shouldExpireConnectionAfterMaxIdleTime() throws InterruptedException provider.ready(); // when - provider.get(OPERATION_CONTEXT).close(); + provider.get(getOperationContext()).close(); sleep(100); provider.doMaintenance(); - provider.get(OPERATION_CONTEXT); + provider.get(getOperationContext()); // then assertTrue(connectionFactory.getNumCreatedConnections() >= 2); // should really be two, but it's racy @@ -258,10 +258,10 @@ public void shouldCloseConnectionAfterExpiration() throws InterruptedException { provider.ready(); // when - provider.get(OPERATION_CONTEXT).close(); + provider.get(getOperationContext()).close(); sleep(50); provider.doMaintenance(); - provider.get(OPERATION_CONTEXT); + provider.get(getOperationContext()); // then assertTrue(connectionFactory.getCreatedConnections().get(0).isClosed()); @@ -280,10 +280,10 @@ public void shouldCreateNewConnectionAfterExpiration() throws InterruptedExcepti provider.ready(); // when - provider.get(OPERATION_CONTEXT).close(); + provider.get(getOperationContext()).close(); sleep(50); provider.doMaintenance(); - InternalConnection secondConnection = provider.get(OPERATION_CONTEXT); + InternalConnection secondConnection = provider.get(getOperationContext()); // then assertNotNull(secondConnection); @@ -302,7 +302,7 @@ public void shouldPruneAfterMaintenanceTaskRuns() throws InterruptedException { .build(), mockSdamProvider(), OPERATION_CONTEXT_FACTORY); provider.ready(); - provider.get(OPERATION_CONTEXT).close(); + provider.get(getOperationContext()).close(); // when @@ -322,7 +322,7 @@ void infiniteMaxSize() { List connections = new ArrayList<>(); try { for (int i = 0; i < 2 * defaultMaxSize; i++) { - connections.add(provider.get(OPERATION_CONTEXT)); + connections.add(provider.get(getOperationContext())); } } finally { connections.forEach(connection -> { diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticationSpecification.groovy index cc3e0401bb5..e514a3fd0d3 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticationSpecification.groovy @@ -36,7 +36,7 @@ import javax.security.auth.Subject import javax.security.auth.login.LoginContext import static com.mongodb.AuthenticationMechanism.GSSAPI -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.getClusterConnectionMode import static com.mongodb.ClusterFixture.getConnectionString import static com.mongodb.ClusterFixture.getCredential @@ -58,7 +58,7 @@ class GSSAPIAuthenticationSpecification extends Specification { when: openConnection(connection, async) executeCommand(getConnectionString().getDatabase(), new BsonDocument('count', new BsonString('test')), - getClusterConnectionMode(), null, connection, OPERATION_CONTEXT) + getClusterConnectionMode(), null, connection, getOperationContext()) then: thrown(MongoCommandException) @@ -77,7 +77,7 @@ class GSSAPIAuthenticationSpecification extends Specification { when: openConnection(connection, async) executeCommand(getConnectionString().getDatabase(), new BsonDocument('count', new BsonString('test')), - getClusterConnectionMode(), null, connection, OPERATION_CONTEXT) + getClusterConnectionMode(), null, connection, getOperationContext()) then: true @@ -99,7 +99,7 @@ class GSSAPIAuthenticationSpecification extends Specification { when: openConnection(connection, async) executeCommand(getConnectionString().getDatabase(), new BsonDocument('count', new BsonString('test')), - getClusterConnectionMode(), null, connection, OPERATION_CONTEXT) + getClusterConnectionMode(), null, connection, getOperationContext()) then: thrown(MongoSecurityException) @@ -131,7 +131,7 @@ class GSSAPIAuthenticationSpecification extends Specification { def connection = createConnection(async, getMongoCredential(subject)) openConnection(connection, async) executeCommand(getConnectionString().getDatabase(), new BsonDocument('count', new BsonString('test')), - getClusterConnectionMode(), null, connection, OPERATION_CONTEXT) + getClusterConnectionMode(), null, connection, getOperationContext()) then: true @@ -175,7 +175,7 @@ class GSSAPIAuthenticationSpecification extends Specification { def connection = createConnection(async, getMongoCredential(saslClientProperties)) openConnection(connection, async) executeCommand(getConnectionString().getDatabase(), new BsonDocument('count', new BsonString('test')), - getClusterConnectionMode(), null, connection, OPERATION_CONTEXT) + getClusterConnectionMode(), null, connection, getOperationContext()) then: true @@ -219,10 +219,10 @@ class GSSAPIAuthenticationSpecification extends Specification { private static void openConnection(final InternalConnection connection, final boolean async) { if (async) { FutureResultCallback futureResultCallback = new FutureResultCallback() - connection.openAsync(OPERATION_CONTEXT, futureResultCallback) + connection.openAsync(getOperationContext(), futureResultCallback) futureResultCallback.get(ClusterFixture.TIMEOUT, SECONDS) } else { - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) } } } diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy index 223698d561c..2b5dcb112d5 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/GSSAPIAuthenticatorSpecification.groovy @@ -30,7 +30,7 @@ import spock.lang.Specification import javax.security.auth.login.LoginContext import static com.mongodb.AuthenticationMechanism.GSSAPI -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.getLoginContextName import static com.mongodb.ClusterFixture.getPrimary import static com.mongodb.ClusterFixture.getServerApi @@ -57,7 +57,7 @@ class GSSAPIAuthenticatorSpecification extends Specification { .create(new ServerId(new ClusterId(), getPrimary())) when: - internalConnection.open(OPERATION_CONTEXT) + internalConnection.open(getOperationContext()) then: 1 * subjectProvider.getSubject() >> subject diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticationSpecification.groovy index e8c2a408220..dd44aea3abd 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticationSpecification.groovy @@ -32,7 +32,7 @@ import spock.lang.IgnoreIf import spock.lang.Specification import static com.mongodb.AuthenticationMechanism.PLAIN -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.getClusterConnectionMode import static com.mongodb.ClusterFixture.getConnectionString import static com.mongodb.ClusterFixture.getCredential @@ -52,7 +52,7 @@ class PlainAuthenticationSpecification extends Specification { when: openConnection(connection, async) executeCommand(getConnectionString().getDatabase(), new BsonDocument('count', new BsonString('test')), - getClusterConnectionMode(), null, connection, OPERATION_CONTEXT) + getClusterConnectionMode(), null, connection, getOperationContext()) then: thrown(MongoCommandException) @@ -71,7 +71,7 @@ class PlainAuthenticationSpecification extends Specification { when: openConnection(connection, async) executeCommand(getConnectionString().getDatabase(), new BsonDocument('count', new BsonString('test')), - getClusterConnectionMode(), null, connection, OPERATION_CONTEXT) + getClusterConnectionMode(), null, connection, getOperationContext()) then: true @@ -90,7 +90,7 @@ class PlainAuthenticationSpecification extends Specification { when: openConnection(connection, async) executeCommand(getConnectionString().getDatabase(), new BsonDocument('count', new BsonString('test')), - getClusterConnectionMode(), null, connection, OPERATION_CONTEXT) + getClusterConnectionMode(), null, connection, getOperationContext()) then: thrown(MongoSecurityException) @@ -123,10 +123,10 @@ class PlainAuthenticationSpecification extends Specification { private static void openConnection(final InternalConnection connection, final boolean async) { if (async) { FutureResultCallback futureResultCallback = new FutureResultCallback() - connection.openAsync(OPERATION_CONTEXT, futureResultCallback) + connection.openAsync(getOperationContext(), futureResultCallback) futureResultCallback.get(ClusterFixture.TIMEOUT, SECONDS) } else { - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) } } } diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticatorTest.java b/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticatorTest.java index b95b9c96894..93836fc895b 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticatorTest.java +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/PlainAuthenticatorTest.java @@ -33,7 +33,7 @@ import java.util.Collections; import static com.mongodb.ClusterFixture.CLIENT_METADATA; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.getClusterConnectionMode; import static com.mongodb.ClusterFixture.getServerApi; import static com.mongodb.ClusterFixture.getSslSettings; @@ -69,14 +69,14 @@ public void tearDown() { public void testSuccessfulAuthentication() { PlainAuthenticator authenticator = new PlainAuthenticator(getCredentialWithCache(userName, source, password.toCharArray()), getClusterConnectionMode(), getServerApi()); - authenticator.authenticate(internalConnection, connectionDescription, OPERATION_CONTEXT); + authenticator.authenticate(internalConnection, connectionDescription, getOperationContext()); } @Test(expected = MongoSecurityException.class) public void testUnsuccessfulAuthentication() { PlainAuthenticator authenticator = new PlainAuthenticator(getCredentialWithCache(userName, source, "wrong".toCharArray()), getClusterConnectionMode(), getServerApi()); - authenticator.authenticate(internalConnection, connectionDescription, OPERATION_CONTEXT); + authenticator.authenticate(internalConnection, connectionDescription, getOperationContext()); } private static MongoCredentialWithCache getCredentialWithCache(final String userName, final String source, final char[] password) { diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/ScramSha256AuthenticationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/ScramSha256AuthenticationSpecification.groovy index 36aac9b6908..917f5f82404 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/ScramSha256AuthenticationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/ScramSha256AuthenticationSpecification.groovy @@ -33,7 +33,7 @@ import org.bson.codecs.DocumentCodec import spock.lang.IgnoreIf import spock.lang.Specification -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.createAsyncCluster import static com.mongodb.ClusterFixture.createCluster import static com.mongodb.ClusterFixture.getBinding @@ -105,7 +105,7 @@ class ScramSha256AuthenticationSpecification extends Specification { when: new CommandReadOperation('admin', new BsonDocumentWrapper(new Document('dbstats', 1), new DocumentCodec()), new DocumentCodec()) - .execute(new ClusterBinding(cluster, ReadPreference.primary()), OPERATION_CONTEXT) + .execute(new ClusterBinding(cluster, ReadPreference.primary()), getOperationContext()) then: noExceptionThrown() @@ -128,7 +128,7 @@ class ScramSha256AuthenticationSpecification extends Specification { def binding = new AsyncClusterBinding(cluster, ReadPreference.primary()) new CommandReadOperation('admin', new BsonDocumentWrapper(new Document('dbstats', 1), new DocumentCodec()), new DocumentCodec()) - .executeAsync(binding, OPERATION_CONTEXT, callback) + .executeAsync(binding, getOperationContext(), callback) callback.get() then: @@ -148,7 +148,7 @@ class ScramSha256AuthenticationSpecification extends Specification { when: new CommandReadOperation('admin', new BsonDocumentWrapper(new Document('dbstats', 1), new DocumentCodec()), new DocumentCodec()) - .execute(new ClusterBinding(cluster, ReadPreference.primary()), OPERATION_CONTEXT) + .execute(new ClusterBinding(cluster, ReadPreference.primary()), getOperationContext()) then: thrown(MongoSecurityException) @@ -168,7 +168,7 @@ class ScramSha256AuthenticationSpecification extends Specification { when: new CommandReadOperation('admin', new BsonDocumentWrapper(new Document('dbstats', 1), new DocumentCodec()), new DocumentCodec()) - .executeAsync(new AsyncClusterBinding(cluster, ReadPreference.primary()), OPERATION_CONTEXT, + .executeAsync(new AsyncClusterBinding(cluster, ReadPreference.primary()), getOperationContext(), callback) callback.get() @@ -189,7 +189,7 @@ class ScramSha256AuthenticationSpecification extends Specification { when: new CommandReadOperation('admin', new BsonDocumentWrapper(new Document('dbstats', 1), new DocumentCodec()), new DocumentCodec()) - .execute(new ClusterBinding(cluster, ReadPreference.primary()), OPERATION_CONTEXT) + .execute(new ClusterBinding(cluster, ReadPreference.primary()), getOperationContext()) then: noExceptionThrown() @@ -209,7 +209,7 @@ class ScramSha256AuthenticationSpecification extends Specification { when: new CommandReadOperation('admin', new BsonDocumentWrapper(new Document('dbstats', 1), new DocumentCodec()), new DocumentCodec()) - .executeAsync(new AsyncClusterBinding(cluster, ReadPreference.primary()), OPERATION_CONTEXT, + .executeAsync(new AsyncClusterBinding(cluster, ReadPreference.primary()), getOperationContext(), callback) callback.get() diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/ServerHelper.java b/driver-core/src/test/functional/com/mongodb/internal/connection/ServerHelper.java index 0295e8c1f9f..bc5fffaf9e4 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/ServerHelper.java +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/ServerHelper.java @@ -23,7 +23,7 @@ import com.mongodb.internal.binding.AsyncConnectionSource; import com.mongodb.internal.selector.ServerAddressSelector; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.getAsyncCluster; import static com.mongodb.ClusterFixture.getCluster; import static com.mongodb.assertions.Assertions.fail; @@ -54,7 +54,7 @@ public static void waitForLastRelease(final Cluster cluster) { public static void waitForLastRelease(final ServerAddress address, final Cluster cluster) { ConcurrentPool pool = connectionPool( - cluster.selectServer(new ServerAddressSelector(address), OPERATION_CONTEXT).getServer()); + cluster.selectServer(new ServerAddressSelector(address), getOperationContext()).getServer()); long startTime = System.currentTimeMillis(); while (pool.getInUseCount() > 0) { try { @@ -70,7 +70,7 @@ public static void waitForLastRelease(final ServerAddress address, final Cluster } private static ConcurrentPool getConnectionPool(final ServerAddress address, final Cluster cluster) { - return connectionPool(cluster.selectServer(new ServerAddressSelector(address), OPERATION_CONTEXT).getServer()); + return connectionPool(cluster.selectServer(new ServerAddressSelector(address), getOperationContext()).getServer()); } private static void checkPool(final ServerAddress address, final Cluster cluster) { diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/SingleServerClusterTest.java b/driver-core/src/test/functional/com/mongodb/internal/connection/SingleServerClusterTest.java index 62fa6c27032..703647bb645 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/SingleServerClusterTest.java +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/SingleServerClusterTest.java @@ -37,7 +37,7 @@ import java.util.Collections; import static com.mongodb.ClusterFixture.CLIENT_METADATA; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.OPERATION_CONTEXT_FACTORY; import static com.mongodb.ClusterFixture.getCredential; import static com.mongodb.ClusterFixture.getDefaultDatabaseName; @@ -93,7 +93,7 @@ public void shouldGetServerWithOkDescription() { setUpCluster(getPrimary()); // when - ServerTuple serverTuple = cluster.selectServer(clusterDescription -> getPrimaries(clusterDescription), OPERATION_CONTEXT); + ServerTuple serverTuple = cluster.selectServer(clusterDescription -> getPrimaries(clusterDescription), getOperationContext()); // then assertTrue(serverTuple.getServerDescription().isOk()); @@ -102,7 +102,7 @@ public void shouldGetServerWithOkDescription() { @Test public void shouldSuccessfullyQueryASecondaryWithPrimaryReadPreference() { // given - OperationContext operationContext = OPERATION_CONTEXT; + OperationContext operationContext = getOperationContext(); ServerAddress secondary = getSecondary(); setUpCluster(secondary); String collectionName = getClass().getName(); diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/SocketStreamHelperSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/SocketStreamHelperSpecification.groovy index 68a82fcbf74..2368d3bbff8 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/SocketStreamHelperSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/SocketStreamHelperSpecification.groovy @@ -33,7 +33,7 @@ import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory import java.lang.reflect.Method -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS import static com.mongodb.ClusterFixture.createOperationContext import static com.mongodb.ClusterFixture.getPrimary @@ -87,7 +87,7 @@ class SocketStreamHelperSpecification extends Specification { when: SocketStreamHelper.initialize( - OPERATION_CONTEXT.withTimeoutContext(new TimeoutContext( + getOperationContext().withTimeoutContext(new TimeoutContext( new TimeoutSettings( 1, 100, @@ -110,7 +110,8 @@ class SocketStreamHelperSpecification extends Specification { Socket socket = SocketFactory.default.createSocket() when: - SocketStreamHelper.initialize(OPERATION_CONTEXT, socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), + SocketStreamHelper.initialize(getOperationContext(), socket, getSocketAddresses(getPrimary(), + new DefaultInetAddressResolver()).get(0), SocketSettings.builder().build(), SslSettings.builder().build()) then: @@ -126,7 +127,8 @@ class SocketStreamHelperSpecification extends Specification { SSLSocket socket = SSLSocketFactory.default.createSocket() when: - SocketStreamHelper.initialize(OPERATION_CONTEXT, socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), + SocketStreamHelper.initialize(getOperationContext(), socket, getSocketAddresses(getPrimary(), + new DefaultInetAddressResolver()).get(0), SocketSettings.builder().build(), sslSettings) then: @@ -147,7 +149,8 @@ class SocketStreamHelperSpecification extends Specification { SSLSocket socket = SSLSocketFactory.default.createSocket() when: - SocketStreamHelper.initialize(OPERATION_CONTEXT, socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), + SocketStreamHelper.initialize(getOperationContext(), socket, getSocketAddresses(getPrimary(), + new DefaultInetAddressResolver()).get(0), SocketSettings.builder().build(), sslSettings) then: @@ -166,7 +169,8 @@ class SocketStreamHelperSpecification extends Specification { Socket socket = SocketFactory.default.createSocket() when: - SocketStreamHelper.initialize(OPERATION_CONTEXT, socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), + SocketStreamHelper.initialize(getOperationContext(), socket, getSocketAddresses(getPrimary(), + new DefaultInetAddressResolver()).get(0), SocketSettings.builder().build(), SslSettings.builder().enabled(true).build()) then: diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy index 0283ce44f7b..8f3038085ef 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/StreamSocketAddressSpecification.groovy @@ -13,7 +13,7 @@ import com.mongodb.spock.Slow import javax.net.SocketFactory import java.util.concurrent.TimeUnit -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.getSslSettings class StreamSocketAddressSpecification extends Specification { @@ -44,7 +44,7 @@ class StreamSocketAddressSpecification extends Specification { def socketStream = new SocketStream(serverAddress, null, socketSettings, sslSettings, socketFactory, bufferProvider) when: - socketStream.open(OPERATION_CONTEXT) + socketStream.open(getOperationContext()) then: !socket0.isConnected() @@ -83,7 +83,7 @@ class StreamSocketAddressSpecification extends Specification { def socketStream = new SocketStream(serverAddress, inetAddressResolver, socketSettings, sslSettings, socketFactory, bufferProvider) when: - socketStream.open(OPERATION_CONTEXT) + socketStream.open(getOperationContext()) then: thrown(MongoSocketOpenException) diff --git a/driver-core/src/test/functional/com/mongodb/internal/connection/TlsChannelStreamFunctionalTest.java b/driver-core/src/test/functional/com/mongodb/internal/connection/TlsChannelStreamFunctionalTest.java index 3af1eaa33e1..0c41af7cb8f 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/connection/TlsChannelStreamFunctionalTest.java +++ b/driver-core/src/test/functional/com/mongodb/internal/connection/TlsChannelStreamFunctionalTest.java @@ -184,11 +184,11 @@ void shouldNotCallBeginHandshakeMoreThenOnceDuringTlsSessionEstablishment() thro .build()); Stream stream = streamFactory.create(getPrimaryServerDescription().getAddress()); - stream.open(ClusterFixture.OPERATION_CONTEXT); + stream.open(ClusterFixture.getOperationContext()); ByteBuf wrap = new ByteBufNIO(ByteBuffer.wrap(new byte[]{1, 3, 4})); //when - stream.write(Collections.singletonList(wrap), ClusterFixture.OPERATION_CONTEXT); + stream.write(Collections.singletonList(wrap), ClusterFixture.getOperationContext()); //then SECONDS.sleep(5); 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 aa7506d6516..89da1e2c990 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 @@ -52,7 +52,6 @@ import org.bson.codecs.BsonDocumentCodec import org.bson.codecs.DocumentCodec import spock.lang.IgnoreIf -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT import static com.mongodb.ClusterFixture.collectCursorResults import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.ClusterFixture.getAsyncCluster @@ -381,7 +380,7 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification { def 'should add read concern to command'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) def binding = Stub(ReadBinding) def source = Stub(ConnectionSource) def connection = Mock(Connection) @@ -423,7 +422,7 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification { def 'should add read concern to command asynchronously'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) def binding = Stub(AsyncReadBinding) def source = Stub(AsyncConnectionSource) def connection = Mock(AsyncConnection) diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/AsyncCommandBatchCursorFunctionalTest.java b/driver-core/src/test/functional/com/mongodb/internal/operation/AsyncCommandBatchCursorFunctionalTest.java index 58e3e47ba74..b6f54e7d39c 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/AsyncCommandBatchCursorFunctionalTest.java +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/AsyncCommandBatchCursorFunctionalTest.java @@ -55,7 +55,7 @@ import java.util.stream.IntStream; import java.util.stream.Stream; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.checkReferenceCountReachesTarget; import static com.mongodb.ClusterFixture.getAsyncBinding; import static com.mongodb.ClusterFixture.getConnection; @@ -111,7 +111,7 @@ void cleanup() { void shouldExhaustCursorAsyncWithMultipleBatches() { // given BsonDocument commandResult = executeFindCommand(0, 3); // Fetch in batches of size 3 - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new AsyncCommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); // when @@ -133,7 +133,7 @@ void shouldExhaustCursorAsyncWithMultipleBatches() { void shouldExhaustCursorAsyncWithClosedCursor() { // given BsonDocument commandResult = executeFindCommand(0, 3); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new AsyncCommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); cursor.close(); @@ -156,7 +156,7 @@ void shouldExhaustCursorAsyncWithEmptyCursor() { getCollectionHelper().deleteMany(Filters.empty()); BsonDocument commandResult = executeFindCommand(0, 3); // No documents to fetch - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new AsyncCommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); // when @@ -175,7 +175,7 @@ void theServerCursorShouldNotBeNull() { BsonDocument commandResult = executeFindCommand(2); AsyncCommandCursor coreCursor = new AsyncCommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), coreCursor); assertNotNull(coreCursor.getServerCursor()); @@ -187,7 +187,7 @@ void shouldGetExceptionsForOperationsOnTheCursorAfterClosing() { BsonDocument commandResult = executeFindCommand(5); AsyncCommandCursor coreCursor = new AsyncCommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), coreCursor); cursor.close(); @@ -202,7 +202,7 @@ void shouldGetExceptionsForOperationsOnTheCursorAfterClosing() { @DisplayName("should throw an Exception when going off the end") void shouldThrowAnExceptionWhenGoingOffTheEnd() { BsonDocument commandResult = executeFindCommand(2, 1); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new AsyncCommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); cursorNext(); @@ -216,7 +216,7 @@ void shouldThrowAnExceptionWhenGoingOffTheEnd() { @DisplayName("test normal exhaustion") void testNormalExhaustion() { BsonDocument commandResult = executeFindCommand(); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new AsyncCommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(10, cursorFlatten().size()); @@ -227,7 +227,7 @@ void testNormalExhaustion() { @DisplayName("test limit exhaustion") void testLimitExhaustion(final int limit, final int batchSize, final int expectedTotal) { BsonDocument commandResult = executeFindCommand(limit, batchSize); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new AsyncCommandCursor<>(commandResult, batchSize, DOCUMENT_DECODER, null, connectionSource, connection)); @@ -246,7 +246,7 @@ void shouldBlockWaitingForNextBatchOnATailableCursor(final boolean awaitData, fi BsonDocument commandResult = executeFindCommand(new BsonDocument("ts", new BsonDocument("$gte", new BsonTimestamp(5, 0))), 0, 2, true, awaitData); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, maxTimeMS, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, maxTimeMS, getOperationContext(), new AsyncCommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertFalse(cursor.isClosed()); @@ -269,7 +269,7 @@ void testTailableInterrupt() throws InterruptedException { BsonDocument commandResult = executeFindCommand(new BsonDocument("ts", new BsonDocument("$gte", new BsonTimestamp(5, 0))), 0, 2, true, true); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new AsyncCommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); CountDownLatch latch = new CountDownLatch(1); @@ -304,7 +304,7 @@ void shouldKillCursorIfLimitIsReachedOnInitialQuery() { BsonDocument commandResult = executeFindCommand(5, 10); AsyncCommandCursor coreCursor = new AsyncCommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), coreCursor); assertNotNull(cursorNext()); @@ -319,7 +319,7 @@ void shouldKillCursorIfLimitIsReachedOnGetMore() { BsonDocument commandResult = executeFindCommand(5, 3); AsyncCommandCursor coreCursor = new AsyncCommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), coreCursor); ServerCursor serverCursor = coreCursor.getServerCursor(); @@ -341,7 +341,7 @@ void shouldReleaseConnectionSourceIfLimitIsReachedOnInitialQuery() { BsonDocument commandResult = executeFindCommand(5, 10); AsyncCommandCursor coreCursor = new AsyncCommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), coreCursor); assertDoesNotThrow(() -> checkReferenceCountReachesTarget(connectionSource, 1)); @@ -354,7 +354,7 @@ void shouldReleaseConnectionSourceIfLimitIsReachedOnInitialQuery() { void shouldReleaseConnectionSourceIfLimitIsReachedOnGetMore() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 3); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new AsyncCommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); assertNotNull(cursorNext()); @@ -367,7 +367,7 @@ void shouldReleaseConnectionSourceIfLimitIsReachedOnGetMore() { @DisplayName("test limit with get more") void testLimitWithGetMore() { BsonDocument commandResult = executeFindCommand(5, 2); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new AsyncCommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertNotNull(cursorNext()); @@ -390,7 +390,7 @@ void testLimitWithLargeDocuments() { ); BsonDocument commandResult = executeFindCommand(300, 0); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new AsyncCommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(300, cursorFlatten().size()); @@ -400,7 +400,7 @@ void testLimitWithLargeDocuments() { @DisplayName("should respect batch size") void shouldRespectBatchSize() { BsonDocument commandResult = executeFindCommand(2); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new AsyncCommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(2, cursor.getBatchSize()); @@ -419,7 +419,7 @@ void shouldThrowCursorNotFoundException() throws Throwable { BsonDocument commandResult = executeFindCommand(2); AsyncCommandCursor coreCursor = new AsyncCommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), coreCursor); ServerCursor serverCursor = coreCursor.getServerCursor(); @@ -428,7 +428,7 @@ void shouldThrowCursorNotFoundException() throws Throwable { this.block(cb -> localConnection.commandAsync(getNamespace().getDatabaseName(), new BsonDocument("killCursors", new BsonString(getNamespace().getCollectionName())) .append("cursors", new BsonArray(singletonList(new BsonInt64(serverCursor.getId())))), - NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), new BsonDocumentCodec(), OPERATION_CONTEXT, cb)); + NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), new BsonDocumentCodec(), getOperationContext(), cb)); localConnection.release(); cursorNext(); @@ -494,7 +494,7 @@ private BsonDocument executeFindCommand(final BsonDocument filter, final int lim BsonDocument results = block(cb -> connection.commandAsync(getDatabaseName(), findCommand, NoOpFieldNameValidator.INSTANCE, readPreference, CommandResultDocumentCodec.create(DOCUMENT_DECODER, FIRST_BATCH), - OPERATION_CONTEXT, cb)); + getOperationContext(), cb)); assertNotNull(results); return results; 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 19285eda077..fe70b7f3688 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 @@ -53,7 +53,7 @@ import org.bson.codecs.DocumentCodec import org.bson.codecs.ValueCodecProvider import spock.lang.IgnoreIf -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.getAsyncCluster import static com.mongodb.ClusterFixture.getCluster import static com.mongodb.ClusterFixture.isStandalone @@ -635,7 +635,7 @@ class ChangeStreamOperationSpecification extends OperationFunctionalSpecificatio def 'should set the startAtOperationTime on the sync cursor'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext( + def operationContext = getOperationContext().withSessionContext( Stub(SessionContext) { getReadConcern() >> ReadConcern.DEFAULT getOperationTime() >> new BsonTimestamp() @@ -690,7 +690,7 @@ class ChangeStreamOperationSpecification extends OperationFunctionalSpecificatio def 'should set the startAtOperationTime on the async cursor'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext( + def operationContext = getOperationContext().withSessionContext( Stub(SessionContext) { getReadConcern() >> ReadConcern.DEFAULT getOperationTime() >> new BsonTimestamp() diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/CommandBatchCursorFunctionalTest.java b/driver-core/src/test/functional/com/mongodb/internal/operation/CommandBatchCursorFunctionalTest.java index 407b03f5246..5fc6518d7af 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/CommandBatchCursorFunctionalTest.java +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/CommandBatchCursorFunctionalTest.java @@ -55,7 +55,7 @@ import java.util.stream.IntStream; import java.util.stream.Stream; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.checkReferenceCountReachesTarget; import static com.mongodb.ClusterFixture.getBinding; import static com.mongodb.ClusterFixture.getReferenceCountAfterTimeout; @@ -87,8 +87,8 @@ void setup() { .collect(Collectors.toList()); getCollectionHelper().insertDocuments(documents); - connectionSource = getBinding().getWriteConnectionSource(ClusterFixture.OPERATION_CONTEXT); - connection = connectionSource.getConnection(ClusterFixture.OPERATION_CONTEXT); + connectionSource = getBinding().getWriteConnectionSource(ClusterFixture.getOperationContext()); + connection = connectionSource.getConnection(ClusterFixture.getOperationContext()); } @AfterEach @@ -109,7 +109,7 @@ void cleanup() { void shouldExhaustCursorWithMultipleBatches() { // given BsonDocument commandResult = executeFindCommand(0, 3); // Fetch in batches of size 3 - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); // when @@ -127,7 +127,7 @@ void shouldExhaustCursorWithMultipleBatches() { void shouldExhaustCursorWithClosedCursor() { // given BsonDocument commandResult = executeFindCommand(0, 3); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); cursor.close(); @@ -143,7 +143,7 @@ void shouldExhaustCursorWithEmptyCursor() { getCollectionHelper().deleteMany(Filters.empty()); BsonDocument commandResult = executeFindCommand(0, 3); // No documents to fetch - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); // when @@ -157,7 +157,7 @@ void shouldExhaustCursorWithEmptyCursor() { @DisplayName("server cursor should not be null") void theServerCursorShouldNotBeNull() { BsonDocument commandResult = executeFindCommand(2); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertNotNull(cursor.getServerCursor()); @@ -167,7 +167,7 @@ void theServerCursorShouldNotBeNull() { @DisplayName("test server address should not be null") void theServerAddressShouldNotNull() { BsonDocument commandResult = executeFindCommand(); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertNotNull(cursor.getServerAddress()); @@ -177,7 +177,7 @@ void theServerAddressShouldNotNull() { @DisplayName("should get Exceptions for operations on the cursor after closing") void shouldGetExceptionsForOperationsOnTheCursorAfterClosing() { BsonDocument commandResult = executeFindCommand(); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); cursor.close(); @@ -192,7 +192,7 @@ void shouldGetExceptionsForOperationsOnTheCursorAfterClosing() { @DisplayName("should throw an Exception when going off the end") void shouldThrowAnExceptionWhenGoingOffTheEnd() { BsonDocument commandResult = executeFindCommand(1); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); cursor.next(); @@ -204,7 +204,7 @@ void shouldThrowAnExceptionWhenGoingOffTheEnd() { @DisplayName("test cursor remove") void testCursorRemove() { BsonDocument commandResult = executeFindCommand(); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertThrows(UnsupportedOperationException.class, () -> cursor.remove()); @@ -214,7 +214,7 @@ void testCursorRemove() { @DisplayName("test normal exhaustion") void testNormalExhaustion() { BsonDocument commandResult = executeFindCommand(); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(10, cursorFlatten().size()); @@ -225,7 +225,7 @@ void testNormalExhaustion() { @DisplayName("test limit exhaustion") void testLimitExhaustion(final int limit, final int batchSize, final int expectedTotal) { BsonDocument commandResult = executeFindCommand(limit, batchSize); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(expectedTotal, cursorFlatten().size()); @@ -244,7 +244,7 @@ void shouldBlockWaitingForNextBatchOnATailableCursor(final boolean awaitData, fi BsonDocument commandResult = executeFindCommand(new BsonDocument("ts", new BsonDocument("$gte", new BsonTimestamp(5, 0))), 0, 2, true, awaitData); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, maxTimeMS, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, maxTimeMS, getOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertTrue(cursor.hasNext()); @@ -267,7 +267,7 @@ void testTryNextWithTailable() { BsonDocument commandResult = executeFindCommand(new BsonDocument("ts", new BsonDocument("$gte", new BsonTimestamp(5, 0))), 0, 2, true, true); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); List nextBatch = cursor.tryNext(); @@ -293,7 +293,7 @@ void hasNextShouldThrowWhenCursorIsClosedInAnotherThread() throws InterruptedExc BsonDocument commandResult = executeFindCommand(new BsonDocument("ts", new BsonDocument("$gte", new BsonTimestamp(5, 0))), 0, 2, true, true); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertTrue(cursor.hasNext()); @@ -320,7 +320,7 @@ void testMaxTimeMS() { long maxTimeMS = 500; BsonDocument commandResult = executeFindCommand(new BsonDocument("ts", new BsonDocument("$gte", new BsonTimestamp(5, 0))), 0, 2, true, true); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, maxTimeMS, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, maxTimeMS, getOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); List nextBatch = cursor.tryNext(); @@ -344,7 +344,7 @@ void testTailableInterrupt() throws InterruptedException { BsonDocument commandResult = executeFindCommand(new BsonDocument("ts", new BsonDocument("$gte", new BsonTimestamp(5, 0))), 0, 2, true, true); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); CountDownLatch latch = new CountDownLatch(1); @@ -377,7 +377,7 @@ void testTailableInterrupt() throws InterruptedException { void shouldKillCursorIfLimitIsReachedOnInitialQuery() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 10); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertNotNull(cursor.next()); @@ -390,7 +390,7 @@ void shouldKillCursorIfLimitIsReachedOnInitialQuery() { void shouldKillCursorIfLimitIsReachedOnGetMore() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 3); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); ServerCursor serverCursor = cursor.getServerCursor(); @@ -409,7 +409,7 @@ void shouldKillCursorIfLimitIsReachedOnGetMore() { void shouldReleaseConnectionSourceIfLimitIsReachedOnInitialQuery() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 10); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertNull(cursor.getServerCursor()); @@ -422,7 +422,7 @@ void shouldReleaseConnectionSourceIfLimitIsReachedOnInitialQuery() { void shouldReleaseConnectionSourceIfLimitIsReachedOnGetMore() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 3); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); assertNotNull(cursor.next()); @@ -435,7 +435,7 @@ void shouldReleaseConnectionSourceIfLimitIsReachedOnGetMore() { @DisplayName("test limit with get more") void testLimitWithGetMore() { BsonDocument commandResult = executeFindCommand(5, 2); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertNotNull(cursor.next()); @@ -456,7 +456,7 @@ void testLimitWithLargeDocuments() { ); BsonDocument commandResult = executeFindCommand(300, 0); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(300, cursorFlatten().size()); @@ -466,7 +466,7 @@ void testLimitWithLargeDocuments() { @DisplayName("should respect batch size") void shouldRespectBatchSize() { BsonDocument commandResult = executeFindCommand(2); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(2, cursor.getBatchSize()); @@ -483,16 +483,16 @@ void shouldRespectBatchSize() { @DisplayName("should throw cursor not found exception") void shouldThrowCursorNotFoundException() { BsonDocument commandResult = executeFindCommand(2); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); ServerCursor serverCursor = cursor.getServerCursor(); assertNotNull(serverCursor); - Connection localConnection = connectionSource.getConnection(OPERATION_CONTEXT); + Connection localConnection = connectionSource.getConnection(getOperationContext()); localConnection.command(getNamespace().getDatabaseName(), new BsonDocument("killCursors", new BsonString(getNamespace().getCollectionName())) .append("cursors", new BsonArray(singletonList(new BsonInt64(serverCursor.getId())))), - NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), new BsonDocumentCodec(), OPERATION_CONTEXT); + NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), new BsonDocumentCodec(), getOperationContext()); localConnection.release(); cursor.next(); @@ -506,7 +506,7 @@ void shouldThrowCursorNotFoundException() { @DisplayName("should report available documents") void shouldReportAvailableDocuments() { BsonDocument commandResult = executeFindCommand(3); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, OPERATION_CONTEXT, + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(3, cursor.available()); @@ -584,7 +584,7 @@ private BsonDocument executeFindCommand(final BsonDocument filter, final int lim BsonDocument results = connection.command(getDatabaseName(), findCommand, NoOpFieldNameValidator.INSTANCE, readPreference, CommandResultDocumentCodec.create(DOCUMENT_DECODER, FIRST_BATCH), - OPERATION_CONTEXT); + getOperationContext()); assertNotNull(results); return results; diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/CountDocumentsOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/CountDocumentsOperationSpecification.groovy index 1e538b1af11..438632014c6 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/CountDocumentsOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/CountDocumentsOperationSpecification.groovy @@ -46,7 +46,7 @@ import org.bson.BsonTimestamp import org.bson.Document import org.bson.codecs.DocumentCodec -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.connection.ServerType.STANDALONE import static com.mongodb.internal.operation.OperationReadConcernHelper.appendReadConcernToCommand @@ -259,7 +259,7 @@ class CountDocumentsOperationSpecification extends OperationFunctionalSpecificat def 'should add read concern to command'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) def binding = Stub(ReadBinding) def source = Stub(ConnectionSource) def connection = Mock(Connection) @@ -297,7 +297,7 @@ class CountDocumentsOperationSpecification extends OperationFunctionalSpecificat def 'should add read concern to command asynchronously'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) def binding = Stub(AsyncReadBinding) def source = Stub(AsyncConnectionSource) def connection = Mock(AsyncConnection) diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/DistinctOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/DistinctOperationSpecification.groovy index f73c301d422..16c8fcb281e 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/DistinctOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/DistinctOperationSpecification.groovy @@ -51,7 +51,7 @@ import org.bson.codecs.StringCodec import org.bson.codecs.ValueCodecProvider import org.bson.types.ObjectId -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.connection.ServerType.STANDALONE import static com.mongodb.internal.operation.OperationReadConcernHelper.appendReadConcernToCommand @@ -227,7 +227,7 @@ class DistinctOperationSpecification extends OperationFunctionalSpecification { def 'should add read concern to command'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) def binding = Stub(ReadBinding) def source = Stub(ConnectionSource) def connection = Mock(Connection) @@ -266,7 +266,7 @@ class DistinctOperationSpecification extends OperationFunctionalSpecification { def 'should add read concern to command asynchronously'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) def binding = Stub(AsyncReadBinding) def source = Stub(AsyncConnectionSource) def connection = Mock(AsyncConnection) diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/FindOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/FindOperationSpecification.groovy index 5eb707201d5..e49128b0481 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/FindOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/FindOperationSpecification.groovy @@ -54,7 +54,6 @@ import org.bson.codecs.BsonDocumentCodec import org.bson.codecs.DocumentCodec import spock.lang.IgnoreIf -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.ClusterFixture.executeSync import static com.mongodb.ClusterFixture.getAsyncCluster @@ -482,7 +481,7 @@ class FindOperationSpecification extends OperationFunctionalSpecification { def 'should add read concern to command'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) def binding = Stub(ReadBinding) def source = Stub(ConnectionSource) def connection = Mock(Connection) @@ -522,7 +521,7 @@ class FindOperationSpecification extends OperationFunctionalSpecification { def 'should add read concern to command asynchronously'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) def binding = Stub(AsyncReadBinding) def source = Stub(AsyncConnectionSource) def connection = Mock(AsyncConnection) @@ -562,7 +561,7 @@ class FindOperationSpecification extends OperationFunctionalSpecification { def 'should add allowDiskUse to command if the server version >= 3.2'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) def binding = Stub(ReadBinding) def source = Stub(ConnectionSource) def connection = Mock(Connection) @@ -602,7 +601,7 @@ class FindOperationSpecification extends OperationFunctionalSpecification { def 'should add allowDiskUse to command if the server version >= 3.2 asynchronously'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) def binding = Stub(AsyncReadBinding) def source = Stub(AsyncConnectionSource) def connection = Mock(AsyncConnection) @@ -646,7 +645,7 @@ class FindOperationSpecification extends OperationFunctionalSpecification { def (cursorType, long maxAwaitTimeMS, long maxTimeMSForCursor) = cursorDetails def timeoutSettings = ClusterFixture.TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT.withMaxAwaitTimeMS(maxAwaitTimeMS) def timeoutContext = new TimeoutContext(timeoutSettings) - def operationContext = OPERATION_CONTEXT.withTimeoutContext(timeoutContext) + def operationContext = getOperationContext().withTimeoutContext(timeoutContext) collectionHelper.create(getCollectionName(), new CreateCollectionOptions().capped(true).sizeInBytes(1000)) def operation = new FindOperation(namespace, new BsonDocumentCodec()) diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/ListCollectionsOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/ListCollectionsOperationSpecification.groovy index ad55b706ba2..b30983a81c5 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/ListCollectionsOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/ListCollectionsOperationSpecification.groovy @@ -16,6 +16,7 @@ package com.mongodb.internal.operation +import com.mongodb.ClusterFixture import com.mongodb.MongoNamespace import com.mongodb.OperationFunctionalSpecification import com.mongodb.ReadPreference @@ -43,7 +44,6 @@ import org.bson.Document import org.bson.codecs.Decoder import org.bson.codecs.DocumentCodec -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.ClusterFixture.getBinding import static com.mongodb.ClusterFixture.getOperationContext @@ -398,6 +398,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def 'should use the readPreference to set secondaryOk'() { given: + def operationContext = ClusterFixture.getOperationContext() def connection = Mock(Connection) def connectionSource = Stub(ConnectionSource) { getConnection(_) >> connection @@ -410,12 +411,12 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def operation = new ListCollectionsOperation(helper.dbName, helper.decoder) when: '3.6.0' - operation.execute(readBinding, OPERATION_CONTEXT) + operation.execute(readBinding, operationContext) then: _ * connection.getDescription() >> helper.threeSixConnectionDescription 1 * connection.command(_, _, _, readPreference, _, _) >> { - assertEquals(((OperationContext) it[5]).getId(), OPERATION_CONTEXT.getId()) + assertEquals(((OperationContext) it[5]).getId(), operationContext.getId()) helper.commandResult } 1 * connection.release() @@ -426,6 +427,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def 'should use the readPreference to set secondaryOk in async'() { given: + def operationContext = ClusterFixture.getOperationContext() def connection = Mock(AsyncConnection) def connectionSource = Stub(AsyncConnectionSource) { getConnection(_, _) >> { it[1].onResult(connection, null) } @@ -436,14 +438,13 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica getReadPreference() >> readPreference } def operation = new ListCollectionsOperation(helper.dbName, helper.decoder) - when: '3.6.0' - operation.executeAsync(readBinding, OPERATION_CONTEXT, Stub(SingleResultCallback)) + operation.executeAsync(readBinding, operationContext, Stub(SingleResultCallback)) then: _ * connection.getDescription() >> helper.threeSixConnectionDescription 1 * connection.commandAsync(helper.dbName, _, _, readPreference, _, _, *_) >> { - assertEquals(((OperationContext) it[5]).getId(), OPERATION_CONTEXT.getId()) + assertEquals(((OperationContext) it[5]).getId(), operationContext.getId()) it.last().onResult(helper.commandResult, null) } where: diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/ListDatabasesOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/ListDatabasesOperationSpecification.groovy index 55504d0babc..bbdce7425a8 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/ListDatabasesOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/ListDatabasesOperationSpecification.groovy @@ -33,7 +33,7 @@ import org.bson.Document import org.bson.codecs.Decoder import org.bson.codecs.DocumentCodec -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext class ListDatabasesOperationSpecification extends OperationFunctionalSpecification { def codec = new DocumentCodec() @@ -82,7 +82,7 @@ class ListDatabasesOperationSpecification extends OperationFunctionalSpecificati def operation = new ListDatabasesOperation(helper.decoder) when: - operation.execute(readBinding, OPERATION_CONTEXT) + operation.execute(readBinding, getOperationContext()) then: _ * connection.getDescription() >> helper.connectionDescription @@ -107,7 +107,7 @@ class ListDatabasesOperationSpecification extends OperationFunctionalSpecificati def operation = new ListDatabasesOperation(helper.decoder) when: - operation.executeAsync(readBinding, OPERATION_CONTEXT, Stub(SingleResultCallback)) + operation.executeAsync(readBinding, getOperationContext(), Stub(SingleResultCallback)) then: _ * connection.getDescription() >> helper.connectionDescription diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/ListIndexesOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/ListIndexesOperationSpecification.groovy index c11d67bcf22..81766ae81d4 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/ListIndexesOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/ListIndexesOperationSpecification.groovy @@ -16,7 +16,7 @@ package com.mongodb.internal.operation - +import com.mongodb.ClusterFixture import com.mongodb.MongoNamespace import com.mongodb.OperationFunctionalSpecification import com.mongodb.ReadPreference @@ -44,7 +44,6 @@ import org.bson.codecs.Decoder import org.bson.codecs.DocumentCodec import org.junit.jupiter.api.Assertions -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.ClusterFixture.getBinding import static com.mongodb.ClusterFixture.getOperationContext @@ -226,6 +225,7 @@ class ListIndexesOperationSpecification extends OperationFunctionalSpecification def 'should use the readPreference to set secondaryOk'() { given: def connection = Mock(Connection) + def operationContext = ClusterFixture.getOperationContext() def connectionSource = Stub(ConnectionSource) { getConnection(_) >> connection getReadPreference() >> readPreference @@ -237,12 +237,12 @@ class ListIndexesOperationSpecification extends OperationFunctionalSpecification def operation = new ListIndexesOperation(helper.namespace, helper.decoder) when: '3.6.0' - operation.execute(readBinding, OPERATION_CONTEXT) + operation.execute(readBinding, operationContext) then: _ * connection.getDescription() >> helper.threeSixConnectionDescription 1 * connection.command(_, _, _, readPreference, _, _) >> { - Assertions.assertEquals(((OperationContext) it[5]).getId(), OPERATION_CONTEXT.getId()) + Assertions.assertEquals(((OperationContext) it[5]).getId(), operationContext.getId()) helper.commandResult } 1 * connection.release() @@ -265,7 +265,7 @@ class ListIndexesOperationSpecification extends OperationFunctionalSpecification def operation = new ListIndexesOperation(helper.namespace, helper.decoder) when: '3.6.0' - operation.executeAsync(readBinding, OPERATION_CONTEXT, Stub(SingleResultCallback)) + operation.executeAsync(readBinding, getOperationContext(), Stub(SingleResultCallback)) then: _ * connection.getDescription() >> helper.threeSixConnectionDescription diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/MapReduceWithInlineResultsOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/MapReduceWithInlineResultsOperationSpecification.groovy index 8efd4e00f6c..5215fa78c37 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/MapReduceWithInlineResultsOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/MapReduceWithInlineResultsOperationSpecification.groovy @@ -46,7 +46,7 @@ import org.bson.Document import org.bson.codecs.BsonDocumentCodec import org.bson.codecs.DocumentCodec -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.connection.ServerType.STANDALONE import static com.mongodb.internal.operation.OperationReadConcernHelper.appendReadConcernToCommand @@ -217,7 +217,7 @@ class MapReduceWithInlineResultsOperationSpecification extends OperationFunction def 'should add read concern to command'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) def binding = Stub(ReadBinding) def source = Stub(ConnectionSource) def connection = Mock(Connection) @@ -264,7 +264,7 @@ class MapReduceWithInlineResultsOperationSpecification extends OperationFunction def 'should add read concern to command asynchronously'() { given: - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) def binding = Stub(AsyncReadBinding) def source = Stub(AsyncConnectionSource) def connection = Mock(AsyncConnection) diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/TestOperationHelper.java b/driver-core/src/test/functional/com/mongodb/internal/operation/TestOperationHelper.java index 824517e10db..0e18016a556 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/TestOperationHelper.java +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/TestOperationHelper.java @@ -31,7 +31,7 @@ import org.bson.BsonString; import org.bson.codecs.BsonDocumentCodec; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; final class TestOperationHelper { @@ -56,7 +56,7 @@ static void makeAdditionalGetMoreCall(final MongoNamespace namespace, final Serv connection.command(namespace.getDatabaseName(), new BsonDocument("getMore", new BsonInt64(serverCursor.getId())) .append("collection", new BsonString(namespace.getCollectionName())), - NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), new BsonDocumentCodec(), OPERATION_CONTEXT)); + NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), new BsonDocumentCodec(), getOperationContext())); } static void makeAdditionalGetMoreCall(final MongoNamespace namespace, final ServerCursor serverCursor, @@ -66,7 +66,7 @@ static void makeAdditionalGetMoreCall(final MongoNamespace namespace, final Serv connection.commandAsync(namespace.getDatabaseName(), new BsonDocument("getMore", new BsonInt64(serverCursor.getId())) .append("collection", new BsonString(namespace.getCollectionName())), - NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), new BsonDocumentCodec(), OPERATION_CONTEXT, callback); + NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), new BsonDocumentCodec(), getOperationContext(), callback); callback.get(); }); } diff --git a/driver-core/src/test/resources/specifications b/driver-core/src/test/resources/specifications index a8d34be0df2..06055234926 160000 --- a/driver-core/src/test/resources/specifications +++ b/driver-core/src/test/resources/specifications @@ -1 +1 @@ -Subproject commit a8d34be0df234365600a9269af5a463f581562fd +Subproject commit 06055234926dc7c7f16e7c6303fa988928b29482 diff --git a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java index 5ac15e92817..826da8ed466 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -16,17 +16,27 @@ package com.mongodb.connection; +import com.mongodb.ClusterFixture; import com.mongodb.MongoConfigurationException; +import com.mongodb.MongoTimeoutException; import com.mongodb.ReadPreference; import com.mongodb.ServerAddress; import com.mongodb.Tag; import com.mongodb.TagSet; -import com.mongodb.internal.selector.LatencyMinimizingServerSelector; +import com.mongodb.event.ServerDescriptionChangedEvent; +import com.mongodb.internal.TimeoutContext; +import com.mongodb.internal.connection.BaseCluster; +import com.mongodb.internal.connection.Cluster; +import com.mongodb.internal.connection.OperationContext; +import com.mongodb.internal.connection.Server; +import com.mongodb.internal.connection.ServerTuple; +import com.mongodb.internal.connection.TestClusterableServerFactory; +import com.mongodb.internal.mockito.MongoMockito; import com.mongodb.internal.selector.ReadPreferenceServerSelector; import com.mongodb.internal.selector.WritableServerSelector; +import com.mongodb.internal.time.Timeout; import com.mongodb.lang.NonNull; import com.mongodb.lang.Nullable; -import com.mongodb.selector.CompositeServerSelector; import com.mongodb.selector.ServerSelector; import org.bson.BsonArray; import org.bson.BsonBoolean; @@ -34,22 +44,33 @@ import org.bson.BsonInt64; import org.bson.BsonString; import org.bson.BsonValue; +import org.bson.json.JsonWriterSettings; import org.junit.Test; +import org.junit.jupiter.api.Assertions; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import util.JsonPoweredTestHelper; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Set; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; -import static java.util.Arrays.asList; -import static org.junit.Assert.assertEquals; +import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS; +import static com.mongodb.connection.ServerDescription.MIN_DRIVER_WIRE_VERSION; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.when; // See https://github.com/mongodb/specifications/tree/master/source/server-selection/tests @RunWith(Parameterized.class) @@ -59,6 +80,14 @@ public class ServerSelectionSelectionTest { private final ClusterDescription clusterDescription; private final long heartbeatFrequencyMS; private final boolean error; + private final List deprioritizedServerAddresses; + + private static final long SERVER_SELECTION_TIMEOUT_MS = 200; + private static final Set TOPOLOGY_DESCRIPTION_FIELDS = new HashSet<>(Arrays.asList("type", "servers")); + private static final Set SERVER_DESCRIPTION_FIELDS = new HashSet<>(Arrays.asList( + "address", "type", "tags", "avg_rtt_ms", "lastWrite", "lastUpdateTime", "maxWireVersion")); + private static final Set READ_PREFERENCE_FIELDS = new HashSet<>( + Arrays.asList("mode", "tag_sets", "maxStalenessSeconds")); public ServerSelectionSelectionTest(final String description, final BsonDocument definition) { this.description = description; @@ -67,18 +96,19 @@ public ServerSelectionSelectionTest(final String description, final BsonDocument this.error = definition.getBoolean("error", BsonBoolean.FALSE).getValue(); this.clusterDescription = buildClusterDescription(definition.getDocument("topology_description"), ServerSettings.builder().heartbeatFrequency(heartbeatFrequencyMS, TimeUnit.MILLISECONDS).build()); + this.deprioritizedServerAddresses = extractDeprioritizedServerAddresses(definition); } @Test public void shouldPassAllOutcomes() { // skip this test because the driver prohibits maxStaleness or tagSets with mode of primary at a much lower level assumeTrue(!description.endsWith("/max-staleness/tests/ReplicaSetWithPrimary/MaxStalenessWithModePrimary.json")); - ServerSelector serverSelector = null; - List suitableServers = buildServerDescriptions(definition.getArray("suitable_servers", new BsonArray())); - List selectedServers = null; - try { - serverSelector = getServerSelector(); - selectedServers = serverSelector.select(clusterDescription); + ServerTuple serverTuple; + ServerSelector serverSelector = getServerSelector(); + OperationContext operationContext = createOperationContext(); + Cluster.ServersSnapshot serversSnapshot = createServersSnapshot(clusterDescription); + try (BaseCluster cluster = createTestCluster(clusterDescription, serversSnapshot);) { + serverTuple = cluster.selectServer(serverSelector, operationContext); if (error) { fail("Should have thrown exception"); } @@ -87,21 +117,25 @@ public void shouldPassAllOutcomes() { fail("Should not have thrown exception: " + e); } return; + } catch (MongoTimeoutException mongoTimeoutException) { + List inLatencyWindowServers = buildServerDescriptions(definition.getArray("in_latency_window")); + assertTrue("Expected emtpy but was " + inLatencyWindowServers.size() + " " + definition.toJson( + JsonWriterSettings.builder() + .indent(true).build()), inLatencyWindowServers.isEmpty()); + return; } - assertServers(selectedServers, suitableServers); - - ServerSelector latencyBasedServerSelector = new CompositeServerSelector(asList(serverSelector, - new LatencyMinimizingServerSelector(15, TimeUnit.MILLISECONDS))); List inLatencyWindowServers = buildServerDescriptions(definition.getArray("in_latency_window")); - List latencyBasedSelectedServers = latencyBasedServerSelector.select(clusterDescription); - assertServers(latencyBasedSelectedServers, inLatencyWindowServers); + assertNotNull(serverTuple); + assertTrue(inLatencyWindowServers.stream().anyMatch(s -> s.getAddress().equals(serverTuple.getServerDescription().getAddress()))); } @Parameterized.Parameters(name = "{0}") public static Collection data() { List data = new ArrayList<>(); + //source/server-selection/tests/server_selection/ReplicaSetNoPrimary/read/DeprioritizedPrimary.json for (BsonDocument testDocument : JsonPoweredTestHelper.getSpecTestDocuments("server-selection/tests/server_selection")) { - data.add(new Object[]{testDocument.getString("resourcePath").getValue(), testDocument}); + String resourcePath = testDocument.getString("resourcePath").getValue(); + data.add(new Object[]{resourcePath, testDocument}); } for (BsonDocument testDocument : JsonPoweredTestHelper.getSpecTestDocuments("max-staleness/tests")) { data.add(new Object[]{testDocument.getString("resourcePath").getValue(), testDocument}); @@ -110,11 +144,12 @@ public static Collection data() { } public static ClusterDescription buildClusterDescription(final BsonDocument topologyDescription, - @Nullable final ServerSettings serverSettings) { + @Nullable final ServerSettings serverSettings) { + validateTestDescriptionFields(topologyDescription.keySet(), TOPOLOGY_DESCRIPTION_FIELDS); ClusterType clusterType = getClusterType(topologyDescription.getString("type").getValue()); ClusterConnectionMode connectionMode = getClusterConnectionMode(clusterType); List servers = buildServerDescriptions(topologyDescription.getArray("servers")); - return new ClusterDescription(connectionMode, clusterType, servers, null, + return new ClusterDescription(connectionMode, clusterType, servers, ClusterSettings.builder().build(), serverSettings == null ? ServerSettings.builder().build() : serverSettings); } @@ -151,6 +186,7 @@ private static List buildServerDescriptions(final BsonArray s } private static ServerDescription buildServerDescription(final BsonDocument serverDescription) { + validateTestDescriptionFields(serverDescription.keySet(), SERVER_DESCRIPTION_FIELDS); ServerDescription.Builder builder = ServerDescription.builder(); builder.address(new ServerAddress(serverDescription.getString("address").getValue())); ServerType serverType = getServerType(serverDescription.getString("type").getValue()); @@ -173,6 +209,8 @@ private static ServerDescription buildServerDescription(final BsonDocument serve } if (serverDescription.containsKey("maxWireVersion")) { builder.maxWireVersion(serverDescription.getNumber("maxWireVersion").intValue()); + } else { + builder.maxWireVersion(MIN_DRIVER_WIRE_VERSION); } return builder.build(); } @@ -227,6 +265,7 @@ private ServerSelector getServerSelector() { return new WritableServerSelector(); } else { BsonDocument readPreferenceDefinition = definition.getDocument("read_preference"); + validateTestDescriptionFields(readPreferenceDefinition.keySet(), READ_PREFERENCE_FIELDS); ReadPreference readPreference; if (readPreferenceDefinition.getString("mode").getValue().equals("Primary")) { readPreference = ReadPreference.valueOf("Primary"); @@ -242,8 +281,78 @@ private ServerSelector getServerSelector() { } } - private void assertServers(final List actual, final List expected) { - assertEquals(expected.size(), actual.size()); - assertTrue(actual.containsAll(expected)); + private static List extractDeprioritizedServerAddresses(final BsonDocument definition) { + if (!definition.containsKey("deprioritized_servers")) { + return Collections.emptyList(); + } + return definition.getArray("deprioritized_servers") + .stream() + .map(BsonValue::asDocument) + .map(ServerSelectionSelectionTest::buildServerDescription) + .map(ServerDescription::getAddress) + .collect(Collectors.toList()); + } + + private OperationContext createOperationContext() { + OperationContext operationContext = + OperationContext.simpleOperationContext( + new TimeoutContext(TIMEOUT_SETTINGS.withServerSelectionTimeoutMS(SERVER_SELECTION_TIMEOUT_MS))); + OperationContext.ServerDeprioritization serverDeprioritization = operationContext.getServerDeprioritization(); + for (ServerAddress address : deprioritizedServerAddresses) { + serverDeprioritization.updateCandidate(address); + serverDeprioritization.onAttemptFailure(new MongoConfigurationException("test")); + } + return operationContext; + } + + private static Cluster.ServersSnapshot createServersSnapshot( + final ClusterDescription clusterDescription) { + Map serverMap = new HashMap<>(); + for (ServerDescription desc : clusterDescription.getServerDescriptions()) { + serverMap.put(desc.getAddress(), MongoMockito.mock(Server.class, server -> { + // Operation count selector should select any server since they all have 0 operation count. + when(server.operationCount()).thenReturn(0); + })); + } + return serverMap::get; + } + + private BaseCluster createTestCluster(final ClusterDescription clusterDescription, final Cluster.ServersSnapshot serversSnapshot) { + return new TestCluster(clusterDescription, serversSnapshot); + } + + private static void validateTestDescriptionFields(final Set actualFields, final Set knownFields) { + Set unknownFields = new HashSet<>(actualFields); + unknownFields.removeAll(knownFields); + if (!unknownFields.isEmpty()) { + throw new UnsupportedOperationException("Unknown fields: " + unknownFields); + } + } + + private static class TestCluster extends BaseCluster { + private final ServersSnapshot serversSnapshot; + + TestCluster(final ClusterDescription clusterDescription, final ServersSnapshot serversSnapshot) { + super(new ClusterId(), clusterDescription.getClusterSettings(), new TestClusterableServerFactory(), + ClusterFixture.CLIENT_METADATA); + this.serversSnapshot = serversSnapshot; + updateDescription(clusterDescription); + } + + @Override + protected void connect() { + // NOOP: this method may be invoked in test cases where no server is expected to be selected. + } + + @Override + public ServersSnapshot getServersSnapshot(final Timeout serverSelectionTimeout, final TimeoutContext timeoutContext) { + return serversSnapshot; + } + + @Override + public void onChange(final ServerDescriptionChangedEvent event) { + // We do not expect this to be called during server selection. + Assertions.fail(); + } } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/binding/SingleServerBindingSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/binding/SingleServerBindingSpecification.groovy index d52fb593a70..19f25dc6baa 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/binding/SingleServerBindingSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/binding/SingleServerBindingSpecification.groovy @@ -26,7 +26,7 @@ import com.mongodb.internal.connection.Server import com.mongodb.internal.connection.ServerTuple import spock.lang.Specification -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext class SingleServerBindingSpecification extends Specification { @@ -68,7 +68,7 @@ class SingleServerBindingSpecification extends Specification { binding.count == 1 when: - def source = binding.getReadConnectionSource(OPERATION_CONTEXT) + def source = binding.getReadConnectionSource(getOperationContext()) then: source.count == 1 @@ -96,7 +96,7 @@ class SingleServerBindingSpecification extends Specification { binding.count == 1 when: - source = binding.getWriteConnectionSource(OPERATION_CONTEXT) + source = binding.getWriteConnectionSource(getOperationContext()) then: source.count == 1 diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java index 69a2c236048..b92628aa827 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractConnectionPoolTest.java @@ -77,7 +77,7 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.OPERATION_CONTEXT_FACTORY; import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS; import static com.mongodb.assertions.Assertions.assertFalse; @@ -542,7 +542,7 @@ private Event getNextEvent(final Iterator eventsIterator, final private static void executeAdminCommand(final BsonDocument command) { new CommandReadOperation<>("admin", command, new BsonDocumentCodec()) - .execute(ClusterFixture.getBinding(), OPERATION_CONTEXT); + .execute(ClusterFixture.getBinding(), getOperationContext()); } private void setFailPoint() { diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractServerDiscoveryAndMonitoringTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractServerDiscoveryAndMonitoringTest.java index e187e94da7b..3a233e7c6e7 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractServerDiscoveryAndMonitoringTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/AbstractServerDiscoveryAndMonitoringTest.java @@ -43,7 +43,7 @@ import java.util.concurrent.TimeUnit; import static com.mongodb.ClusterFixture.CLIENT_METADATA; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS; import static com.mongodb.connection.ServerConnectionState.CONNECTING; import static com.mongodb.internal.connection.DescriptionHelper.createServerDescription; @@ -82,7 +82,7 @@ protected void applyResponse(final BsonArray response) { } protected void applyApplicationError(final BsonDocument applicationError) { - Timeout serverSelectionTimeout = OPERATION_CONTEXT.getTimeoutContext().computeServerSelectionTimeout(); + Timeout serverSelectionTimeout = getOperationContext().getTimeoutContext().computeServerSelectionTimeout(); ServerAddress serverAddress = new ServerAddress(applicationError.getString("address").getValue()); TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS); int errorGeneration = applicationError.getNumber("generation", @@ -98,7 +98,7 @@ protected void applyApplicationError(final BsonDocument applicationError) { switch (type) { case "command": exception = getCommandFailureException(applicationError.getDocument("response"), serverAddress, - OPERATION_CONTEXT.getTimeoutContext()); + getOperationContext().getTimeoutContext()); break; case "network": exception = new MongoSocketReadException("Read error", serverAddress, new IOException()); diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterSpecification.groovy index 56c500c6183..6016ee1d1e2 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterSpecification.groovy @@ -42,7 +42,7 @@ import spock.lang.Specification import java.util.concurrent.CountDownLatch import static com.mongodb.ClusterFixture.CLIENT_METADATA -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS import static com.mongodb.ClusterFixture.createOperationContext import static com.mongodb.connection.ClusterConnectionMode.MULTIPLE @@ -135,7 +135,7 @@ class BaseClusterSpecification extends Specification { factory.sendNotification(thirdServer, REPLICA_SET_PRIMARY, allServers) expect: - cluster.selectServer(new ReadPreferenceServerSelector(ReadPreference.secondary()), OPERATION_CONTEXT) + cluster.selectServer(new ReadPreferenceServerSelector(ReadPreference.secondary()), getOperationContext()) .serverDescription.address == firstServer } @@ -171,7 +171,7 @@ class BaseClusterSpecification extends Specification { factory.sendNotification(thirdServer, 1, REPLICA_SET_PRIMARY, allServers) expect: - cluster.selectServer(new ReadPreferenceServerSelector(ReadPreference.nearest()), OPERATION_CONTEXT) + cluster.selectServer(new ReadPreferenceServerSelector(ReadPreference.nearest()), getOperationContext()) .serverDescription.address == firstServer } @@ -189,7 +189,7 @@ class BaseClusterSpecification extends Specification { factory.sendNotification(thirdServer, 1, REPLICA_SET_PRIMARY, allServers) expect: // firstServer is the only secondary within the latency threshold - cluster.selectServer(new ReadPreferenceServerSelector(ReadPreference.secondary()), OPERATION_CONTEXT) + cluster.selectServer(new ReadPreferenceServerSelector(ReadPreference.secondary()), getOperationContext()) .serverDescription.address == firstServer } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterTest.java index 1cba6d91c3c..60c7bd3d81d 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/BaseClusterTest.java @@ -48,7 +48,7 @@ void selectServerToleratesWhenThereIsNoServerForTheSelectedAddress() { new ServerAddressSelector(serverAddressA), clusterDescriptionAB, serversSnapshotB, - ClusterFixture.OPERATION_CONTEXT.getServerDeprioritization(), + ClusterFixture.getOperationContext().getServerDeprioritization(), ClusterSettings.builder().build())); } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolSpecification.groovy index b3e78d2dc54..32937fc863e 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultConnectionPoolSpecification.groovy @@ -41,7 +41,7 @@ import java.util.concurrent.CountDownLatch import java.util.regex.Matcher import java.util.regex.Pattern -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.OPERATION_CONTEXT_FACTORY import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS import static com.mongodb.ClusterFixture.createOperationContext @@ -78,7 +78,7 @@ class DefaultConnectionPoolSpecification extends Specification { pool.ready() expect: - pool.get(OPERATION_CONTEXT) != null + pool.get(getOperationContext()) != null } def 'should reuse released connection'() throws InterruptedException { @@ -86,10 +86,11 @@ class DefaultConnectionPoolSpecification extends Specification { pool = new DefaultConnectionPool(SERVER_ID, connectionFactory, builder().maxSize(1).build(), mockSdamProvider(), OPERATION_CONTEXT_FACTORY) pool.ready() + def operationContext = getOperationContext() when: - pool.get(OPERATION_CONTEXT).close() - pool.get(OPERATION_CONTEXT) + pool.get(operationContext).close() + pool.get(operationContext) then: 1 * connectionFactory.create(SERVER_ID, _) @@ -102,7 +103,7 @@ class DefaultConnectionPoolSpecification extends Specification { pool.ready() when: - pool.get(OPERATION_CONTEXT).close() + pool.get(getOperationContext()).close() then: !connectionFactory.getCreatedConnections().get(0).isClosed() @@ -220,7 +221,7 @@ class DefaultConnectionPoolSpecification extends Specification { when: pool.ready() - pool.get(OPERATION_CONTEXT) + pool.get(getOperationContext()) then: 1 * listener.connectionCreated { it.connectionId.serverId == SERVER_ID } @@ -239,6 +240,7 @@ class DefaultConnectionPoolSpecification extends Specification { connectionDescription.getConnectionId() >> id connection.getDescription() >> connectionDescription connection.opened() >> false + def operationContext = getOperationContext() when: 'connection pool is created' pool = new DefaultConnectionPool(SERVER_ID, connectionFactory, settings, mockSdamProvider(), OPERATION_CONTEXT_FACTORY) @@ -257,7 +259,7 @@ class DefaultConnectionPoolSpecification extends Specification { "Connection pool ready for ${SERVER_ADDRESS.getHost()}:${SERVER_ADDRESS.getPort()}" == poolReadyLogMessage when: 'connection is created' - pool.get(OPERATION_CONTEXT) + pool.get(operationContext) then: '"connection created" and "connection ready" log messages are emitted' def createdLogMessage = getMessage( "Connection created") def readyLogMessage = getMessage("Connection ready") @@ -267,7 +269,7 @@ class DefaultConnectionPoolSpecification extends Specification { ", driver-generated ID=${driverConnectionId}, established in=\\d+ ms" when: 'connection is released back into the pool on close' - pool.get(OPERATION_CONTEXT).close() + pool.get(operationContext).close() then: '"connection check out" and "connection checked in" log messages are emitted' def checkoutStartedMessage = getMessage("Connection checkout started") def connectionCheckedInMessage = getMessage("Connection checked in") @@ -302,7 +304,7 @@ class DefaultConnectionPoolSpecification extends Specification { "Connection pool closed for ${SERVER_ADDRESS.getHost()}:${SERVER_ADDRESS.getPort()}" == poolClosedLogMessage when: 'connection checked out on closed pool' - pool.get(OPERATION_CONTEXT) + pool.get(operationContext) then: thrown(MongoServerUnavailableException) def connectionCheckoutFailedInMessage = getMessage("Connection checkout failed") @@ -351,7 +353,7 @@ class DefaultConnectionPoolSpecification extends Specification { when: pool.ready() - pool.get(OPERATION_CONTEXT).close() + pool.get(getOperationContext()).close() //not cool - but we have no way of waiting for connection to become idle Thread.sleep(500) pool.close(); @@ -386,11 +388,12 @@ class DefaultConnectionPoolSpecification extends Specification { def 'should log connection checkout failed with Reason.CONNECTION_ERROR if fails to open a connection'() { given: + def operationContext = getOperationContext() def listener = Mock(ConnectionPoolListener) def connection = Mock(InternalConnection) connection.getDescription() >> new ConnectionDescription(SERVER_ID) connection.opened() >> false - connection.open(OPERATION_CONTEXT) >> { throw new UncheckedIOException('expected failure', new IOException()) } + connection.open(operationContext) >> { throw new UncheckedIOException('expected failure', new IOException()) } connectionFactory.create(SERVER_ID, _) >> connection pool = new DefaultConnectionPool(SERVER_ID, connectionFactory, builder().addConnectionPoolListener(listener).build(), mockSdamProvider(), OPERATION_CONTEXT_FACTORY) @@ -398,7 +401,7 @@ class DefaultConnectionPoolSpecification extends Specification { when: try { - pool.get(OPERATION_CONTEXT) + pool.get(operationContext) } catch (UncheckedIOException e) { if ('expected failure' != e.getMessage()) { throw e @@ -435,7 +438,7 @@ class DefaultConnectionPoolSpecification extends Specification { pool = new DefaultConnectionPool(SERVER_ID, connectionFactory, builder().maxSize(10) .addConnectionPoolListener(listener).build(), mockSdamProvider(), OPERATION_CONTEXT_FACTORY) pool.ready() - def connection = pool.get(OPERATION_CONTEXT) + def connection = pool.get(getOperationContext()) connection.close() when: @@ -463,15 +466,16 @@ class DefaultConnectionPoolSpecification extends Specification { def 'should fire connection pool events on check out and check in'() { given: + def operationContext = getOperationContext() def listener = Mock(ConnectionPoolListener) pool = new DefaultConnectionPool(SERVER_ID, connectionFactory, builder().maxSize(1) .addConnectionPoolListener(listener).build(), mockSdamProvider(), OPERATION_CONTEXT_FACTORY) pool.ready() - def connection = pool.get(OPERATION_CONTEXT) + def connection = pool.get(operationContext) connection.close() when: - connection = pool.get(OPERATION_CONTEXT) + connection = pool.get(operationContext) then: 1 * listener.connectionCheckedOut { it.connectionId.serverId == SERVER_ID } @@ -493,7 +497,7 @@ class DefaultConnectionPoolSpecification extends Specification { connection.close() when: - connection = pool.get(OPERATION_CONTEXT) + connection = pool.get(getOperationContext()) then: 1 * listener.connectionCheckedOut { it.connectionId.serverId == SERVER_ID } @@ -507,11 +511,12 @@ class DefaultConnectionPoolSpecification extends Specification { def 'should fire connection checkout failed with Reason.CONNECTION_ERROR if fails to open a connection'() { given: + def operationContext = getOperationContext() def listener = Mock(ConnectionPoolListener) def connection = Mock(InternalConnection) connection.getDescription() >> new ConnectionDescription(SERVER_ID) connection.opened() >> false - connection.open(OPERATION_CONTEXT) >> { throw new UncheckedIOException('expected failure', new IOException()) } + connection.open(operationContext) >> { throw new UncheckedIOException('expected failure', new IOException()) } connectionFactory.create(SERVER_ID, _) >> connection pool = new DefaultConnectionPool(SERVER_ID, connectionFactory, builder().addConnectionPoolListener(listener).build(), mockSdamProvider(), OPERATION_CONTEXT_FACTORY) @@ -519,7 +524,7 @@ class DefaultConnectionPoolSpecification extends Specification { when: try { - pool.get(OPERATION_CONTEXT) + pool.get(operationContext) } catch (UncheckedIOException e) { if ('expected failure' != e.getMessage()) { throw e @@ -564,7 +569,7 @@ class DefaultConnectionPoolSpecification extends Specification { when: try { - pool.get(OPERATION_CONTEXT) + pool.get(getOperationContext()) } catch (MongoConnectionPoolClearedException e) { caught = e } @@ -579,7 +584,7 @@ class DefaultConnectionPoolSpecification extends Specification { CompletableFuture caught = new CompletableFuture<>() when: - pool.getAsync(OPERATION_CONTEXT) { InternalConnection result, Throwable t -> + pool.getAsync(getOperationContext()) { InternalConnection result, Throwable t -> if (t != null) { caught.complete(t) } @@ -599,7 +604,7 @@ class DefaultConnectionPoolSpecification extends Specification { when: pool.invalidate(cause) try { - pool.get(OPERATION_CONTEXT) + pool.get(getOperationContext()) } catch (MongoConnectionPoolClearedException e) { caught = e } @@ -630,7 +635,7 @@ class DefaultConnectionPoolSpecification extends Specification { pool = new DefaultConnectionPool(SERVER_ID, connectionFactory, builder().maxSize(1) .addConnectionPoolListener(listener).build(), mockSdamProvider(), OPERATION_CONTEXT_FACTORY) pool.ready() - def connection = pool.get(OPERATION_CONTEXT) + def connection = pool.get(getOperationContext()) pool.close() when: @@ -674,7 +679,7 @@ class DefaultConnectionPoolSpecification extends Specification { pool.ready() when: - def connection = pool.get(OPERATION_CONTEXT) + def connection = pool.get(getOperationContext()) def connectionLatch = selectConnectionAsync(pool) connection.close() @@ -684,12 +689,13 @@ class DefaultConnectionPoolSpecification extends Specification { def 'when getting a connection asynchronously should send MongoTimeoutException to callback after timeout period'() { given: + def operationContext = getOperationContext() pool = new DefaultConnectionPool(SERVER_ID, connectionFactory, builder().maxSize(1).maxWaitTime(5, MILLISECONDS).build(), mockSdamProvider(), OPERATION_CONTEXT_FACTORY) pool.ready() - pool.get(OPERATION_CONTEXT) - def firstConnectionLatch = selectConnectionAsync(pool) - def secondConnectionLatch = selectConnectionAsync(pool) + pool.get(operationContext) + def firstConnectionLatch = selectConnectionAsync(pool, operationContext) + def secondConnectionLatch = selectConnectionAsync(pool, operationContext) when: firstConnectionLatch.get() @@ -721,9 +727,9 @@ class DefaultConnectionPoolSpecification extends Specification { selectConnectionAsync(pool).get() } - def selectConnectionAsync(DefaultConnectionPool pool) { + def selectConnectionAsync(DefaultConnectionPool pool, operationContext = getOperationContext()) { def serverLatch = new ConnectionLatch() - pool.getAsync(OPERATION_CONTEXT) { InternalConnection result, Throwable e -> + pool.getAsync(operationContext) { InternalConnection result, Throwable e -> serverLatch.connection = result serverLatch.throwable = e serverLatch.latch.countDown() diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultServerConnectionSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultServerConnectionSpecification.groovy index be6fbe06b83..72575b544c4 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultServerConnectionSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultServerConnectionSpecification.groovy @@ -16,7 +16,7 @@ package com.mongodb.internal.connection - +import com.mongodb.ClusterFixture import com.mongodb.ReadPreference import com.mongodb.connection.ClusterConnectionMode import com.mongodb.internal.async.SingleResultCallback @@ -27,7 +27,6 @@ import org.bson.BsonInt32 import org.bson.codecs.BsonDocumentCodec import spock.lang.Specification -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT import static com.mongodb.CustomMatchers.compare import static com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback import static com.mongodb.internal.connection.MessageHelper.LEGACY_HELLO_LOWER @@ -43,14 +42,16 @@ class DefaultServerConnectionSpecification extends Specification { def codec = new BsonDocumentCodec() def executor = Mock(ProtocolExecutor) def connection = new DefaultServerConnection(internalConnection, executor, ClusterConnectionMode.MULTIPLE) + def operationContext = ClusterFixture.getOperationContext() + when: - connection.commandAsync('test', command, validator, ReadPreference.primary(), codec, OPERATION_CONTEXT, callback) + connection.commandAsync('test', command, validator, ReadPreference.primary(), codec, operationContext, callback) then: 1 * executor.executeAsync({ compare(new CommandProtocolImpl('test', command, validator, ReadPreference.primary(), codec, true, - MessageSequences.EmptyMessageSequences.INSTANCE, ClusterConnectionMode.MULTIPLE, OPERATION_CONTEXT), it) - }, internalConnection, OPERATION_CONTEXT.getSessionContext(), callback) + MessageSequences.EmptyMessageSequences.INSTANCE, ClusterConnectionMode.MULTIPLE, operationContext), it) + }, internalConnection, operationContext.getSessionContext(), callback) } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultServerSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultServerSpecification.groovy index 3910da575f0..dfaa2545ee7 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultServerSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/DefaultServerSpecification.groovy @@ -54,7 +54,7 @@ import spock.lang.Specification import java.util.concurrent.CountDownLatch import static com.mongodb.ClusterFixture.CLIENT_METADATA -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.MongoCredential.createCredential import static com.mongodb.connection.ClusterConnectionMode.MULTIPLE import static com.mongodb.connection.ClusterConnectionMode.SINGLE @@ -74,7 +74,7 @@ class DefaultServerSpecification extends Specification { Mock(SdamServerDescriptionManager), Mock(ServerListener), Mock(CommandListener), new ClusterClock(), false) when: - def receivedConnection = server.getConnection(OPERATION_CONTEXT) + def receivedConnection = server.getConnection(getOperationContext()) then: receivedConnection @@ -100,7 +100,7 @@ class DefaultServerSpecification extends Specification { when: def callback = new SupplyingCallback() - server.getConnectionAsync(OPERATION_CONTEXT, callback) + server.getConnectionAsync(getOperationContext(), callback) then: callback.get() == connection @@ -117,7 +117,7 @@ class DefaultServerSpecification extends Specification { server.close() when: - server.getConnection(OPERATION_CONTEXT) + server.getConnection(getOperationContext()) then: def ex = thrown(MongoServerUnavailableException) @@ -127,7 +127,7 @@ class DefaultServerSpecification extends Specification { def latch = new CountDownLatch(1) def receivedConnection = null def receivedThrowable = null - server.getConnectionAsync(OPERATION_CONTEXT) { + server.getConnectionAsync(getOperationContext()) { result, throwable -> receivedConnection = result; receivedThrowable = throwable; latch.countDown() } @@ -210,7 +210,7 @@ class DefaultServerSpecification extends Specification { given: def connectionPool = Mock(ConnectionPool) def serverMonitor = Mock(ServerMonitor) - connectionPool.get(OPERATION_CONTEXT) >> { throw exceptionToThrow } + connectionPool.get(getOperationContext()) >> { throw exceptionToThrow } def server = defaultServer(connectionPool, serverMonitor) server.close() @@ -242,7 +242,7 @@ class DefaultServerSpecification extends Specification { def server = defaultServer(connectionPool, serverMonitor) when: - server.getConnection(OPERATION_CONTEXT) + server.getConnection(getOperationContext()) then: def e = thrown(MongoException) @@ -267,7 +267,7 @@ class DefaultServerSpecification extends Specification { def server = defaultServer(connectionPool, serverMonitor) when: - server.getConnection(OPERATION_CONTEXT) + server.getConnection(getOperationContext()) then: def e = thrown(MongoSecurityException) @@ -292,7 +292,7 @@ class DefaultServerSpecification extends Specification { def latch = new CountDownLatch(1) def receivedConnection = null def receivedThrowable = null - server.getConnectionAsync(OPERATION_CONTEXT) { + server.getConnectionAsync(getOperationContext()) { result, throwable -> receivedConnection = result; receivedThrowable = throwable; latch.countDown() } @@ -325,7 +325,7 @@ class DefaultServerSpecification extends Specification { def latch = new CountDownLatch(1) def receivedConnection = null def receivedThrowable = null - server.getConnectionAsync(OPERATION_CONTEXT) { + server.getConnectionAsync(getOperationContext()) { result, throwable -> receivedConnection = result; receivedThrowable = throwable; latch.countDown() } @@ -350,7 +350,7 @@ class DefaultServerSpecification extends Specification { clusterClock.advance(clusterClockClusterTime) def server = new DefaultServer(serverId, SINGLE, Mock(ConnectionPool), new TestConnectionFactory(), Mock(ServerMonitor), Mock(SdamServerDescriptionManager), Mock(ServerListener), Mock(CommandListener), clusterClock, false) - def testConnection = (TestConnection) server.getConnection(OPERATION_CONTEXT) + def testConnection = (TestConnection) server.getConnection(getOperationContext()) def sessionContext = new TestSessionContext(initialClusterTime) def response = BsonDocument.parse( '''{ @@ -361,7 +361,7 @@ class DefaultServerSpecification extends Specification { ''') def protocol = new TestCommandProtocol(response) testConnection.enqueueProtocol(protocol) - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) when: if (async) { diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy index 3cdabf31da3..93e98ef4336 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionSpecification.groovy @@ -58,7 +58,7 @@ import java.util.concurrent.CountDownLatch import java.util.concurrent.ExecutorService import java.util.concurrent.Executors -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT import static com.mongodb.ReadPreference.primary import static com.mongodb.connection.ClusterConnectionMode.MULTIPLE @@ -114,7 +114,7 @@ class InternalStreamConnectionSpecification extends Specification { def getOpenedConnection() { def connection = getConnection() - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) connection } @@ -132,7 +132,7 @@ class InternalStreamConnectionSpecification extends Specification { .lastUpdateTimeNanos(connection.getInitialServerDescription().getLastUpdateTime(NANOSECONDS)) .build() when: - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) then: connection.opened() @@ -159,7 +159,7 @@ class InternalStreamConnectionSpecification extends Specification { .build() when: - connection.openAsync(OPERATION_CONTEXT, futureResultCallback) + connection.openAsync(getOperationContext(), futureResultCallback) futureResultCallback.get() then: @@ -177,7 +177,7 @@ class InternalStreamConnectionSpecification extends Specification { failedInitializer) when: - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) then: thrown MongoInternalException @@ -195,7 +195,7 @@ class InternalStreamConnectionSpecification extends Specification { when: def futureResultCallback = new FutureResultCallback() - connection.openAsync(OPERATION_CONTEXT, futureResultCallback) + connection.openAsync(getOperationContext(), futureResultCallback) futureResultCallback.get() then: @@ -212,14 +212,14 @@ class InternalStreamConnectionSpecification extends Specification { def (buffers2, messageId2) = helper.hello() when: - connection.sendMessage(buffers1, messageId1, OPERATION_CONTEXT) + connection.sendMessage(buffers1, messageId1, getOperationContext()) then: connection.isClosed() thrown MongoSocketWriteException when: - connection.sendMessage(buffers2, messageId2, OPERATION_CONTEXT) + connection.sendMessage(buffers2, messageId2, getOperationContext()) then: thrown MongoSocketClosedException @@ -243,7 +243,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.sendMessageAsync(buffers1, messageId1, OPERATION_CONTEXT, sndCallbck1) + connection.sendMessageAsync(buffers1, messageId1, getOperationContext(), sndCallbck1) sndCallbck1.get(10, SECONDS) then: @@ -251,7 +251,7 @@ class InternalStreamConnectionSpecification extends Specification { connection.isClosed() when: - connection.sendMessageAsync(buffers2, messageId2, OPERATION_CONTEXT, sndCallbck2) + connection.sendMessageAsync(buffers2, messageId2, getOperationContext(), sndCallbck2) sndCallbck2.get(10, SECONDS) then: @@ -267,16 +267,16 @@ class InternalStreamConnectionSpecification extends Specification { def (buffers2, messageId2) = helper.hello() when: - connection.sendMessage(buffers1, messageId1, OPERATION_CONTEXT) - connection.sendMessage(buffers2, messageId2, OPERATION_CONTEXT) - connection.receiveMessage(messageId1, OPERATION_CONTEXT) + connection.sendMessage(buffers1, messageId1, getOperationContext()) + connection.sendMessage(buffers2, messageId2, getOperationContext()) + connection.receiveMessage(messageId1, getOperationContext()) then: connection.isClosed() thrown MongoSocketReadException when: - connection.receiveMessage(messageId2, OPERATION_CONTEXT) + connection.receiveMessage(messageId2, getOperationContext()) then: thrown MongoSocketClosedException @@ -289,7 +289,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.receiveMessage(1, OPERATION_CONTEXT) + connection.receiveMessage(1, getOperationContext()) then: thrown(MongoInternalException) @@ -306,7 +306,7 @@ class InternalStreamConnectionSpecification extends Specification { def callback = new FutureResultCallback() when: - connection.receiveMessageAsync(1, OPERATION_CONTEXT, callback) + connection.receiveMessageAsync(1, getOperationContext(), callback) callback.get() then: @@ -321,7 +321,7 @@ class InternalStreamConnectionSpecification extends Specification { Thread.currentThread().interrupt() when: - connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, OPERATION_CONTEXT) + connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, getOperationContext()) then: Thread.interrupted() @@ -335,7 +335,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, OPERATION_CONTEXT) + connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, getOperationContext()) then: !Thread.interrupted() @@ -350,7 +350,7 @@ class InternalStreamConnectionSpecification extends Specification { Thread.currentThread().interrupt() when: - connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, OPERATION_CONTEXT) + connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, getOperationContext()) then: Thread.interrupted() @@ -365,7 +365,7 @@ class InternalStreamConnectionSpecification extends Specification { Thread.currentThread().interrupt() when: - connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, OPERATION_CONTEXT) + connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, getOperationContext()) then: Thread.interrupted() @@ -379,7 +379,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, OPERATION_CONTEXT) + connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, getOperationContext()) then: thrown(MongoSocketWriteException) @@ -393,7 +393,7 @@ class InternalStreamConnectionSpecification extends Specification { Thread.currentThread().interrupt() when: - connection.receiveMessage(1, OPERATION_CONTEXT) + connection.receiveMessage(1, getOperationContext()) then: Thread.interrupted() @@ -407,7 +407,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.receiveMessage(1, OPERATION_CONTEXT) + connection.receiveMessage(1, getOperationContext()) then: !Thread.interrupted() @@ -422,7 +422,7 @@ class InternalStreamConnectionSpecification extends Specification { Thread.currentThread().interrupt() when: - connection.receiveMessage(1, OPERATION_CONTEXT) + connection.receiveMessage(1, getOperationContext()) then: Thread.interrupted() @@ -437,7 +437,7 @@ class InternalStreamConnectionSpecification extends Specification { Thread.currentThread().interrupt() when: - connection.receiveMessage(1, OPERATION_CONTEXT) + connection.receiveMessage(1, getOperationContext()) then: Thread.interrupted() @@ -451,7 +451,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.receiveMessage(1, OPERATION_CONTEXT) + connection.receiveMessage(1, getOperationContext()) then: thrown(MongoSocketReadException) @@ -464,7 +464,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.receiveMessage(1, OPERATION_CONTEXT.withTimeoutContext( + connection.receiveMessage(1, getOperationContext().withTimeoutContext( new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT))) then: @@ -482,7 +482,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.receiveMessage(1, OPERATION_CONTEXT.withTimeoutContext( + connection.receiveMessage(1, getOperationContext().withTimeoutContext( new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT))) then: @@ -502,7 +502,7 @@ class InternalStreamConnectionSpecification extends Specification { } def connection = getOpenedConnection() def callback = new FutureResultCallback() - def operationContext = OPERATION_CONTEXT.withTimeoutContext( + def operationContext = getOperationContext().withTimeoutContext( new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT)) when: connection.receiveMessageAsync(1, operationContext, callback) @@ -525,7 +525,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() def callback = new FutureResultCallback() - def operationContext = OPERATION_CONTEXT.withTimeoutContext( + def operationContext = getOperationContext().withTimeoutContext( new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT)) when: connection.receiveMessageAsync(1, operationContext, callback) @@ -563,10 +563,10 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.sendMessageAsync(buffers1, messageId1, OPERATION_CONTEXT, sndCallbck1) - connection.sendMessageAsync(buffers2, messageId2, OPERATION_CONTEXT, sndCallbck2) - connection.receiveMessageAsync(messageId1, OPERATION_CONTEXT, rcvdCallbck1) - connection.receiveMessageAsync(messageId2, OPERATION_CONTEXT, rcvdCallbck2) + connection.sendMessageAsync(buffers1, messageId1, getOperationContext(), sndCallbck1) + connection.sendMessageAsync(buffers2, messageId2, getOperationContext(), sndCallbck2) + connection.receiveMessageAsync(messageId1, getOperationContext(), rcvdCallbck1) + connection.receiveMessageAsync(messageId2, getOperationContext(), rcvdCallbck2) rcvdCallbck1.get(1, SECONDS) then: @@ -588,14 +588,14 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.receiveMessage(1, OPERATION_CONTEXT) + connection.receiveMessage(1, getOperationContext()) then: connection.isClosed() thrown MongoSocketReadException when: - connection.receiveMessage(1, OPERATION_CONTEXT) + connection.receiveMessage(1, getOperationContext()) then: thrown MongoSocketClosedException @@ -620,9 +620,9 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.sendMessageAsync(buffers1, messageId1, OPERATION_CONTEXT, sndCallbck1) - connection.sendMessageAsync(buffers2, messageId2, OPERATION_CONTEXT, sndCallbck2) - connection.receiveMessageAsync(messageId1, OPERATION_CONTEXT, rcvdCallbck1) + connection.sendMessageAsync(buffers1, messageId1, getOperationContext(), sndCallbck1) + connection.sendMessageAsync(buffers2, messageId2, getOperationContext(), sndCallbck2) + connection.receiveMessageAsync(messageId1, getOperationContext(), rcvdCallbck1) rcvdCallbck1.get(1, SECONDS) then: @@ -630,7 +630,7 @@ class InternalStreamConnectionSpecification extends Specification { connection.isClosed() when: - connection.receiveMessageAsync(messageId2, OPERATION_CONTEXT, rcvdCallbck2) + connection.receiveMessageAsync(messageId2, getOperationContext(), rcvdCallbck2) rcvdCallbck2.get(1, SECONDS) then: @@ -649,7 +649,7 @@ class InternalStreamConnectionSpecification extends Specification { stream.read(_, _) >> helper.reply(response) when: - connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), getOperationContext()) then: thrown(MongoCommandException) @@ -677,7 +677,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT, callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) callback.get() then: @@ -705,7 +705,7 @@ class InternalStreamConnectionSpecification extends Specification { def callbacks = [] (1..numberOfOperations).each { n -> def (buffers, messageId, sndCallbck, rcvdCallbck) = messages.pop() - connection.sendMessageAsync(buffers, messageId, OPERATION_CONTEXT, sndCallbck) + connection.sendMessageAsync(buffers, messageId, getOperationContext(), sndCallbck) callbacks.add(sndCallbck) } streamLatch.countDown() @@ -730,7 +730,7 @@ class InternalStreamConnectionSpecification extends Specification { stream.read(90, _) >> helper.defaultReply() when: - connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), getOperationContext()) then: commandListener.eventsWereDelivered([ @@ -753,7 +753,7 @@ class InternalStreamConnectionSpecification extends Specification { when: connection.sendAndReceive(commandMessage, { BsonReader reader, DecoderContext decoderContext -> throw new CodecConfigurationException('') - }, OPERATION_CONTEXT) + }, getOperationContext()) then: thrown(CodecConfigurationException) @@ -783,7 +783,7 @@ class InternalStreamConnectionSpecification extends Specification { 1 * advanceClusterTime(BsonDocument.parse(response).getDocument('$clusterTime')) getReadConcern() >> ReadConcern.DEFAULT } - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) when: connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), operationContext) @@ -819,7 +819,7 @@ class InternalStreamConnectionSpecification extends Specification { 1 * advanceClusterTime(BsonDocument.parse(response).getDocument('$clusterTime')) getReadConcern() >> ReadConcern.DEFAULT } - def operationContext = OPERATION_CONTEXT.withSessionContext(sessionContext) + def operationContext = getOperationContext().withSessionContext(sessionContext) when: connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), operationContext, callback) @@ -839,7 +839,7 @@ class InternalStreamConnectionSpecification extends Specification { stream.write(_, _) >> { throw new MongoSocketWriteException('Failed to write', serverAddress, new IOException()) } when: - connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), getOperationContext()) then: def e = thrown(MongoSocketWriteException) @@ -859,7 +859,7 @@ class InternalStreamConnectionSpecification extends Specification { stream.read(16, _) >> { throw new MongoSocketReadException('Failed to read', serverAddress) } when: - connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), getOperationContext()) then: def e = thrown(MongoSocketReadException) @@ -880,7 +880,7 @@ class InternalStreamConnectionSpecification extends Specification { stream.read(90, _) >> { throw new MongoSocketReadException('Failed to read', serverAddress) } when: - connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), getOperationContext()) then: def e = thrown(MongoSocketException) @@ -902,7 +902,7 @@ class InternalStreamConnectionSpecification extends Specification { stream.read(_, _) >> helper.reply(response) when: - connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), getOperationContext()) then: def e = thrown(MongoCommandException) @@ -923,7 +923,7 @@ class InternalStreamConnectionSpecification extends Specification { stream.read(90, _) >> helper.defaultReply() when: - connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), getOperationContext()) then: commandListener.eventsWereDelivered([ @@ -959,7 +959,7 @@ class InternalStreamConnectionSpecification extends Specification { stream.read(_, _) >> helper.reply('{ok : 0, errmsg : "failed"}') when: - connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), getOperationContext()) then: thrown(MongoCommandException) @@ -1005,7 +1005,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT, callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) callback.get() then: @@ -1038,7 +1038,7 @@ class InternalStreamConnectionSpecification extends Specification { when: connection.sendAndReceiveAsync(commandMessage, { BsonReader reader, DecoderContext decoderContext -> throw new CodecConfigurationException('') - }, OPERATION_CONTEXT, callback) + }, getOperationContext(), callback) callback.get() then: @@ -1065,7 +1065,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT, callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) callback.get() then: @@ -1093,7 +1093,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT, callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) callback.get() then: @@ -1124,7 +1124,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT, callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) callback.get() then: @@ -1156,7 +1156,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT, callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) callback.get() then: @@ -1187,7 +1187,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), OPERATION_CONTEXT, callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) callback.get() then: diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/JMXConnectionPoolListenerSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/JMXConnectionPoolListenerSpecification.groovy index 374687f7d01..9924edafd9b 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/JMXConnectionPoolListenerSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/JMXConnectionPoolListenerSpecification.groovy @@ -29,7 +29,7 @@ import spock.lang.Unroll import javax.management.ObjectName import java.lang.management.ManagementFactory -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.OPERATION_CONTEXT_FACTORY class JMXConnectionPoolListenerSpecification extends Specification { @@ -50,8 +50,8 @@ class JMXConnectionPoolListenerSpecification extends Specification { provider.ready() when: - provider.get(OPERATION_CONTEXT) - provider.get(OPERATION_CONTEXT).close() + provider.get(getOperationContext()) + provider.get(getOperationContext()).close() then: with(jmxListener.getMBean(SERVER_ID)) { diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/LoadBalancedClusterTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/LoadBalancedClusterTest.java index 7366a03b584..5528907f503 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/LoadBalancedClusterTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/LoadBalancedClusterTest.java @@ -52,7 +52,7 @@ import java.util.concurrent.atomic.AtomicReference; import static com.mongodb.ClusterFixture.CLIENT_METADATA; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS; import static com.mongodb.ClusterFixture.createOperationContext; import static java.util.concurrent.TimeUnit.MILLISECONDS; @@ -96,14 +96,14 @@ public void shouldSelectServerWhenThereIsNoSRVLookup() { mock(DnsSrvRecordMonitorFactory.class)); // when - ServerTuple serverTuple = cluster.selectServer(mock(ServerSelector.class), OPERATION_CONTEXT); + ServerTuple serverTuple = cluster.selectServer(mock(ServerSelector.class), getOperationContext()); // then assertServerTupleExpectations(serverAddress, expectedServer, serverTuple); // when FutureResultCallback callback = new FutureResultCallback<>(); - cluster.selectServerAsync(mock(ServerSelector.class), OPERATION_CONTEXT, callback); + cluster.selectServerAsync(mock(ServerSelector.class), getOperationContext(), callback); serverTuple = callback.get(); // then @@ -131,7 +131,7 @@ public void shouldSelectServerWhenThereIsSRVLookup() { cluster = new LoadBalancedCluster(new ClusterId(), clusterSettings, serverFactory, CLIENT_METADATA, dnsSrvRecordMonitorFactory); // when - ServerTuple serverTuple = cluster.selectServer(mock(ServerSelector.class), OPERATION_CONTEXT); + ServerTuple serverTuple = cluster.selectServer(mock(ServerSelector.class), getOperationContext()); // then assertServerTupleExpectations(resolvedServerAddress, expectedServer, serverTuple); @@ -159,7 +159,7 @@ public void shouldSelectServerAsynchronouslyWhenThereIsSRVLookup() { // when FutureResultCallback callback = new FutureResultCallback<>(); - cluster.selectServerAsync(mock(ServerSelector.class), OPERATION_CONTEXT, callback); + cluster.selectServerAsync(mock(ServerSelector.class), getOperationContext(), callback); ServerTuple serverTuple = callback.get(); // then @@ -185,7 +185,7 @@ public void shouldFailSelectServerWhenThereIsSRVMisconfiguration() { cluster = new LoadBalancedCluster(new ClusterId(), clusterSettings, serverFactory, CLIENT_METADATA, dnsSrvRecordMonitorFactory); MongoClientException exception = assertThrows(MongoClientException.class, () -> cluster.selectServer(mock(ServerSelector.class), - OPERATION_CONTEXT)); + getOperationContext())); assertEquals("In load balancing mode, the host must resolve to a single SRV record, but instead it resolved to multiple hosts", exception.getMessage()); } @@ -209,7 +209,7 @@ public void shouldFailSelectServerAsynchronouslyWhenThereIsSRVMisconfiguration() cluster = new LoadBalancedCluster(new ClusterId(), clusterSettings, serverFactory, CLIENT_METADATA, dnsSrvRecordMonitorFactory); FutureResultCallback callback = new FutureResultCallback<>(); - cluster.selectServerAsync(mock(ServerSelector.class), OPERATION_CONTEXT, callback); + cluster.selectServerAsync(mock(ServerSelector.class), getOperationContext(), callback); MongoClientException exception = assertThrows(MongoClientException.class, callback::get); assertEquals("In load balancing mode, the host must resolve to a single SRV record, but instead it resolved to multiple hosts", diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/LoggingCommandEventSenderSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/LoggingCommandEventSenderSpecification.groovy index e6f6afb02e0..d4ec64661ee 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/LoggingCommandEventSenderSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/LoggingCommandEventSenderSpecification.groovy @@ -39,7 +39,7 @@ import org.bson.BsonInt32 import org.bson.BsonString import spock.lang.Specification -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.connection.ClusterConnectionMode.MULTIPLE import static com.mongodb.connection.ClusterConnectionMode.SINGLE import static com.mongodb.internal.operation.ServerVersionHelper.LATEST_WIRE_VERSION @@ -63,7 +63,7 @@ class LoggingCommandEventSenderSpecification extends Specification { def logger = Stub(Logger) { isDebugEnabled() >> debugLoggingEnabled } - def operationContext = OPERATION_CONTEXT + def operationContext = getOperationContext() def sender = new LoggingCommandEventSender([] as Set, [] as Set, connectionDescription, commandListener, operationContext, message, message.getCommandDocument(bsonOutput), new StructuredLogger(logger), LoggerSettings.builder().build()) @@ -109,7 +109,7 @@ class LoggingCommandEventSenderSpecification extends Specification { def logger = Mock(Logger) { isDebugEnabled() >> true } - def operationContext = OPERATION_CONTEXT + def operationContext = getOperationContext() def sender = new LoggingCommandEventSender([] as Set, [] as Set, connectionDescription, commandListener, operationContext, message, message.getCommandDocument(bsonOutput), new StructuredLogger(logger), LoggerSettings.builder().build()) @@ -166,7 +166,7 @@ class LoggingCommandEventSenderSpecification extends Specification { def logger = Mock(Logger) { isDebugEnabled() >> true } - def operationContext = OPERATION_CONTEXT + def operationContext = getOperationContext() def sender = new LoggingCommandEventSender([] as Set, [] as Set, connectionDescription, null, operationContext, message, message.getCommandDocument(bsonOutput), new StructuredLogger(logger), LoggerSettings.builder().build()) @@ -200,7 +200,7 @@ class LoggingCommandEventSenderSpecification extends Specification { def logger = Mock(Logger) { isDebugEnabled() >> true } - def operationContext = OPERATION_CONTEXT + def operationContext = getOperationContext() def sender = new LoggingCommandEventSender(['createUser'] as Set, [] as Set, connectionDescription, null, operationContext, message, message.getCommandDocument(bsonOutput), new StructuredLogger(logger), LoggerSettings.builder().build()) diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/MultiServerClusterSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/MultiServerClusterSpecification.groovy index a3cf8104fd3..5c286372c25 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/MultiServerClusterSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/MultiServerClusterSpecification.groovy @@ -29,7 +29,7 @@ import org.bson.types.ObjectId import spock.lang.Specification import static com.mongodb.ClusterFixture.CLIENT_METADATA -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.connection.ClusterConnectionMode.MULTIPLE import static com.mongodb.connection.ClusterType.REPLICA_SET import static com.mongodb.connection.ClusterType.SHARDED @@ -96,8 +96,8 @@ class MultiServerClusterSpecification extends Specification { when: cluster.getServersSnapshot( - OPERATION_CONTEXT.getTimeoutContext().computeServerSelectionTimeout(), - OPERATION_CONTEXT.getTimeoutContext()) + getOperationContext().getTimeoutContext().computeServerSelectionTimeout(), + getOperationContext().getTimeoutContext()) then: thrown(IllegalStateException) @@ -386,7 +386,7 @@ class MultiServerClusterSpecification extends Specification { cluster.close() when: - cluster.selectServer(new WritableServerSelector(), OPERATION_CONTEXT) + cluster.selectServer(new WritableServerSelector(), getOperationContext()) then: thrown(IllegalStateException) diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/PlainAuthenticatorUnitTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/PlainAuthenticatorUnitTest.java index 12d8e9fa7c3..258a0fbde30 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/PlainAuthenticatorUnitTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/PlainAuthenticatorUnitTest.java @@ -30,7 +30,7 @@ import java.util.List; import java.util.concurrent.ExecutionException; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.getServerApi; import static com.mongodb.internal.connection.MessageHelper.getApiVersionField; import static com.mongodb.internal.connection.MessageHelper.getDbField; @@ -54,7 +54,7 @@ public void before() { public void testSuccessfulAuthentication() { enqueueSuccessfulReply(); - subject.authenticate(connection, connectionDescription, OPERATION_CONTEXT); + subject.authenticate(connection, connectionDescription, getOperationContext()); validateMessages(); } @@ -64,7 +64,7 @@ public void testSuccessfulAuthenticationAsync() throws ExecutionException, Inter enqueueSuccessfulReply(); FutureResultCallback futureCallback = new FutureResultCallback<>(); - subject.authenticateAsync(connection, connectionDescription, OPERATION_CONTEXT, futureCallback); + subject.authenticateAsync(connection, connectionDescription, getOperationContext(), futureCallback); futureCallback.get(); validateMessages(); diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDeprioritizationTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDeprioritizationTest.java index f1c8f69eb29..ee75b9c726e 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDeprioritizationTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDeprioritizationTest.java @@ -25,29 +25,40 @@ import com.mongodb.connection.ServerDescription; import com.mongodb.connection.ServerId; import com.mongodb.internal.connection.OperationContext.ServerDeprioritization; +import com.mongodb.selector.ServerSelector; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Named; 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.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import java.util.List; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import java.util.stream.Stream; import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS; import static com.mongodb.ClusterFixture.createOperationContext; import static java.util.Arrays.asList; +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; import static java.util.Collections.unmodifiableList; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.params.provider.EnumSource.Mode.EXCLUDE; +import static org.junit.jupiter.params.provider.Arguments.of; final class ServerDeprioritizationTest { private static final ServerDescription SERVER_A = serverDescription("a"); private static final ServerDescription SERVER_B = serverDescription("b"); private static final ServerDescription SERVER_C = serverDescription("c"); private static final List ALL_SERVERS = unmodifiableList(asList(SERVER_A, SERVER_B, SERVER_C)); - private static final ClusterDescription REPLICA_SET = clusterDescription(ClusterType.REPLICA_SET); - private static final ClusterDescription SHARDED_CLUSTER = clusterDescription(ClusterType.SHARDED); + private static final ClusterDescription REPLICA_SET_CLUSTER = multipleModeClusterDescription(ClusterType.REPLICA_SET); + private static final ClusterDescription SHARDED_CLUSTER = multipleModeClusterDescription(ClusterType.SHARDED); + private static final ClusterDescription LOAD_BALANCED_CLUSTER = singleModeClusterDescription(ClusterType.LOAD_BALANCED); + private static final ClusterDescription STANDALONE_CLUSTER = singleModeClusterDescription(ClusterType.STANDALONE); + private static final ClusterDescription UNKNOWN_CLUSTER = multipleModeClusterDescription(ClusterType.UNKNOWN); private ServerDeprioritization serverDeprioritization; @@ -56,40 +67,114 @@ void beforeEach() { serverDeprioritization = createOperationContext(TIMEOUT_SETTINGS).getServerDeprioritization(); } - @Test - void selectNoneDeprioritized() { + private static Stream selectNoneDeprioritized() { + return Stream.of( + of(Named.of(generateArgumentName(emptyList()), emptyList())), + of(Named.of(generateArgumentName(singletonList(SERVER_A)), singletonList(SERVER_A))), + of(Named.of(generateArgumentName(singletonList(SERVER_B)), singletonList(SERVER_B))), + of(Named.of(generateArgumentName(singletonList(SERVER_C)), singletonList(SERVER_C))), + of(Named.of(generateArgumentName(asList(SERVER_A, SERVER_B)), asList(SERVER_A, SERVER_B))), + of(Named.of(generateArgumentName(asList(SERVER_B, SERVER_A)), asList(SERVER_B, SERVER_A))), + of(Named.of(generateArgumentName(asList(SERVER_A, SERVER_C)), asList(SERVER_A, SERVER_C))), + of(Named.of(generateArgumentName(asList(SERVER_C, SERVER_A)), asList(SERVER_C, SERVER_A))), + of(Named.of(generateArgumentName(ALL_SERVERS), ALL_SERVERS)) + ); + } + @ParameterizedTest + @MethodSource + void selectNoneDeprioritized(final List selectorResult) { + ServerSelector wrappedSelector = createAssertingSelector(ALL_SERVERS, selectorResult); assertAll( - () -> assertEquals(ALL_SERVERS, serverDeprioritization.getServerSelector().select(SHARDED_CLUSTER)), - () -> assertEquals(ALL_SERVERS, serverDeprioritization.getServerSelector().select(REPLICA_SET)) + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(wrappedSelector).select(SHARDED_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(wrappedSelector).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(wrappedSelector).select(UNKNOWN_CLUSTER)) ); } @Test - void selectSomeDeprioritized() { + void selectNoneDeprioritizedSingleServerCluster() { + ServerSelector wrappedSelector = createAssertingSelector(singletonList(SERVER_A), singletonList(SERVER_A)); + ServerSelector emptyListWrappedSelector = createAssertingSelector(singletonList(SERVER_A), emptyList()); + assertAll( + () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(wrappedSelector).select(STANDALONE_CLUSTER)), + () -> assertEquals(emptyList(), serverDeprioritization.applyDeprioritization(emptyListWrappedSelector).select(STANDALONE_CLUSTER)), + () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(wrappedSelector).select(LOAD_BALANCED_CLUSTER)), + () -> assertEquals(emptyList(), serverDeprioritization.applyDeprioritization(emptyListWrappedSelector).select(LOAD_BALANCED_CLUSTER)) + ); + } + + private static Stream selectSomeDeprioritized() { + return Stream.of( + of(Named.of(generateArgumentName(singletonList(SERVER_A)), singletonList(SERVER_A))), + of(Named.of(generateArgumentName(singletonList(SERVER_C)), singletonList(SERVER_C))), + of(Named.of(generateArgumentName(asList(SERVER_A, SERVER_C)), asList(SERVER_A, SERVER_C))), + of(Named.of(generateArgumentName(asList(SERVER_C, SERVER_A)), asList(SERVER_C, SERVER_A))) + ); + } + + @ParameterizedTest + @MethodSource + void selectSomeDeprioritized(final List selectorResult) { deprioritize(SERVER_B); + List expectedWrappedSelectorFilteredInput = asList(SERVER_A, SERVER_C); + ServerSelector selector = createAssertingSelector(expectedWrappedSelectorFilteredInput, selectorResult); assertAll( - () -> assertEquals(asList(SERVER_A, SERVER_C), serverDeprioritization.getServerSelector().select(SHARDED_CLUSTER)), - () -> assertEquals(ALL_SERVERS, serverDeprioritization.getServerSelector().select(REPLICA_SET)) + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selector).select(SHARDED_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selector).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selector).select(UNKNOWN_CLUSTER)) ); } - @Test - void selectAllDeprioritized() { + @ParameterizedTest + @MethodSource("selectNoneDeprioritized") + void selectAllDeprioritized(final List selectorResult) { deprioritize(SERVER_A); deprioritize(SERVER_B); deprioritize(SERVER_C); + ServerSelector selector = createAssertingSelector(ALL_SERVERS, selectorResult); + assertAll( + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selector).select(SHARDED_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selector).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selector).select(UNKNOWN_CLUSTER)) + ); + } + + @Test + void selectAllDeprioritizedSingleServerCluster() { + deprioritize(SERVER_A); + ServerSelector selector = createAssertingSelector(singletonList(SERVER_A), singletonList(SERVER_A)); assertAll( - () -> assertEquals(ALL_SERVERS, serverDeprioritization.getServerSelector().select(SHARDED_CLUSTER)), - () -> assertEquals(ALL_SERVERS, serverDeprioritization.getServerSelector().select(REPLICA_SET)) + () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector).select(STANDALONE_CLUSTER)), + () -> assertEquals(singletonList(SERVER_A), + serverDeprioritization.applyDeprioritization(selector).select(LOAD_BALANCED_CLUSTER)) ); } @ParameterizedTest - @EnumSource(value = ClusterType.class, mode = EXCLUDE, names = {"SHARDED"}) - void serverSelectorSelectsAllIfNotShardedCluster(final ClusterType clusterType) { - serverDeprioritization.updateCandidate(SERVER_A.getAddress()); - serverDeprioritization.onAttemptFailure(new RuntimeException()); - assertEquals(ALL_SERVERS, serverDeprioritization.getServerSelector().select(clusterDescription(clusterType))); + @MethodSource("selectSomeDeprioritized") + void selectWithRetryWhenWrappedReturnsEmpty(final List selectorResult) { + deprioritize(SERVER_B); + Supplier selector = () -> new ServerSelector() { + private boolean firstCall = true; + + @Override + public List select(final ClusterDescription clusterDescription) { + List servers = clusterDescription.getServerDescriptions(); + if (firstCall) { + firstCall = false; + assertEquals(asList(SERVER_A, SERVER_C), servers); + return emptyList(); + } + assertEquals(ALL_SERVERS, servers); + return selectorResult; + } + }; + + assertAll( + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selector.get()).select(SHARDED_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selector.get()).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selector.get()).select(UNKNOWN_CLUSTER)) + ); } @Test @@ -97,7 +182,8 @@ void onAttemptFailureIgnoresIfPoolClearedException() { serverDeprioritization.updateCandidate(SERVER_A.getAddress()); serverDeprioritization.onAttemptFailure( new MongoConnectionPoolClearedException(new ServerId(new ClusterId(), new ServerAddress()), null)); - assertEquals(ALL_SERVERS, serverDeprioritization.getServerSelector().select(SHARDED_CLUSTER)); + ServerSelector selector = createAssertingSelector(ALL_SERVERS, singletonList(SERVER_A)); + assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector).select(SHARDED_CLUSTER)); } @Test @@ -112,6 +198,15 @@ private void deprioritize(final ServerDescription... serverDescriptions) { } } + private static ServerSelector createAssertingSelector( + final List expectedInput, + final List selectorResult) { + return clusterDescription -> { + assertEquals(expectedInput, clusterDescription.getServerDescriptions()); + return selectorResult; + }; + } + private static ServerDescription serverDescription(final String host) { return ServerDescription.builder() .state(ServerConnectionState.CONNECTED) @@ -120,7 +215,18 @@ private static ServerDescription serverDescription(final String host) { .build(); } - private static ClusterDescription clusterDescription(final ClusterType clusterType) { + private static ClusterDescription multipleModeClusterDescription(final ClusterType clusterType) { return new ClusterDescription(ClusterConnectionMode.MULTIPLE, clusterType, ALL_SERVERS); } + + private static ClusterDescription singleModeClusterDescription(final ClusterType clusterType) { + return new ClusterDescription(ClusterConnectionMode.SINGLE, clusterType, singletonList(SERVER_A)); + } + + private static String generateArgumentName(final List servers) { + return "[" + servers.stream() + .map(ServerDescription::getAddress) + .map(ServerAddress::getHost) + .collect(Collectors.joining(", ")) + "]"; + } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDiscoveryAndMonitoringTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDiscoveryAndMonitoringTest.java index dc81e5071e1..0ebd1d2b9b9 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDiscoveryAndMonitoringTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDiscoveryAndMonitoringTest.java @@ -32,7 +32,7 @@ import java.util.Collection; import java.util.stream.Collectors; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.getClusterDescription; import static com.mongodb.internal.connection.ClusterDescriptionHelper.getPrimaries; import static com.mongodb.internal.event.EventListenerHelper.NO_OP_CLUSTER_LISTENER; @@ -154,9 +154,9 @@ private void assertServer(final String serverName, final BsonDocument expectedSe if (expectedServerDescriptionDocument.isDocument("pool")) { int expectedGeneration = expectedServerDescriptionDocument.getDocument("pool").getNumber("generation").intValue(); - Timeout serverSelectionTimeout = OPERATION_CONTEXT.getTimeoutContext().computeServerSelectionTimeout(); + Timeout serverSelectionTimeout = getOperationContext().getTimeoutContext().computeServerSelectionTimeout(); DefaultServer server = (DefaultServer) getCluster() - .getServersSnapshot(serverSelectionTimeout, OPERATION_CONTEXT.getTimeoutContext()) + .getServersSnapshot(serverSelectionTimeout, getOperationContext().getTimeoutContext()) .getServer(new ServerAddress(serverName)); assertEquals(expectedGeneration, server.getConnectionPool().getGeneration()); } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/SingleServerClusterSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/SingleServerClusterSpecification.groovy index faa04a188f9..9fe84995d7a 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/SingleServerClusterSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/SingleServerClusterSpecification.groovy @@ -29,7 +29,7 @@ import com.mongodb.internal.selector.WritableServerSelector import spock.lang.Specification import static com.mongodb.ClusterFixture.CLIENT_METADATA -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.connection.ClusterConnectionMode.SINGLE import static com.mongodb.connection.ClusterType.REPLICA_SET import static com.mongodb.connection.ClusterType.UNKNOWN @@ -78,10 +78,10 @@ class SingleServerClusterSpecification extends Specification { sendNotification(firstServer, STANDALONE) then: - cluster.getServersSnapshot(OPERATION_CONTEXT + cluster.getServersSnapshot(getOperationContext() .getTimeoutContext() .computeServerSelectionTimeout(), - OPERATION_CONTEXT.getTimeoutContext()).getServer(firstServer) == factory.getServer(firstServer) + getOperationContext().getTimeoutContext()).getServer(firstServer) == factory.getServer(firstServer) cleanup: cluster?.close() @@ -95,8 +95,8 @@ class SingleServerClusterSpecification extends Specification { cluster.close() when: - cluster.getServersSnapshot(OPERATION_CONTEXT.getTimeoutContext().computeServerSelectionTimeout(), - OPERATION_CONTEXT.getTimeoutContext()) + cluster.getServersSnapshot(getOperationContext().getTimeoutContext().computeServerSelectionTimeout(), + getOperationContext().getTimeoutContext()) then: thrown(IllegalStateException) @@ -146,7 +146,7 @@ class SingleServerClusterSpecification extends Specification { sendNotification(firstServer, getBuilder(firstServer).minWireVersion(1000).maxWireVersion(1000).build()) when: - cluster.selectServer(new WritableServerSelector(), OPERATION_CONTEXT) + cluster.selectServer(new WritableServerSelector(), getOperationContext()) then: thrown(MongoIncompatibleDriverException) diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/UsageTrackingConnectionSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/UsageTrackingConnectionSpecification.groovy index 78d79fba8b2..0e84acb1943 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/UsageTrackingConnectionSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/UsageTrackingConnectionSpecification.groovy @@ -26,7 +26,7 @@ import org.bson.BsonInt32 import org.bson.codecs.BsonDocumentCodec import spock.lang.Specification -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ReadPreference.primary import static com.mongodb.connection.ClusterConnectionMode.SINGLE @@ -49,7 +49,7 @@ class UsageTrackingConnectionSpecification extends Specification { connection.openedAt == Long.MAX_VALUE when: - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) then: connection.openedAt <= System.currentTimeMillis() @@ -65,7 +65,7 @@ class UsageTrackingConnectionSpecification extends Specification { connection.openedAt == Long.MAX_VALUE when: - connection.openAsync(OPERATION_CONTEXT, futureResultCallback) + connection.openAsync(getOperationContext(), futureResultCallback) futureResultCallback.get() then: @@ -80,7 +80,7 @@ class UsageTrackingConnectionSpecification extends Specification { connection.lastUsedAt == Long.MAX_VALUE when: - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) then: connection.lastUsedAt <= System.currentTimeMillis() @@ -96,7 +96,7 @@ class UsageTrackingConnectionSpecification extends Specification { connection.lastUsedAt == Long.MAX_VALUE when: - connection.openAsync(OPERATION_CONTEXT, futureResultCallback) + connection.openAsync(getOperationContext(), futureResultCallback) futureResultCallback.get() then: @@ -106,11 +106,11 @@ class UsageTrackingConnectionSpecification extends Specification { def 'lastUsedAt should be set on sendMessage'() { given: def connection = createConnection() - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) def openedLastUsedAt = connection.lastUsedAt when: - connection.sendMessage([], 1, OPERATION_CONTEXT) + connection.sendMessage([], 1, getOperationContext()) then: connection.lastUsedAt >= openedLastUsedAt @@ -121,12 +121,12 @@ class UsageTrackingConnectionSpecification extends Specification { def 'lastUsedAt should be set on sendMessage asynchronously'() { given: def connection = createConnection() - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) def openedLastUsedAt = connection.lastUsedAt def futureResultCallback = new FutureResultCallback() when: - connection.sendMessageAsync([], 1, OPERATION_CONTEXT, futureResultCallback) + connection.sendMessageAsync([], 1, getOperationContext(), futureResultCallback) futureResultCallback.get() then: @@ -137,10 +137,10 @@ class UsageTrackingConnectionSpecification extends Specification { def 'lastUsedAt should be set on receiveMessage'() { given: def connection = createConnection() - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) def openedLastUsedAt = connection.lastUsedAt when: - connection.receiveMessage(1, OPERATION_CONTEXT) + connection.receiveMessage(1, getOperationContext()) then: connection.lastUsedAt >= openedLastUsedAt @@ -150,12 +150,12 @@ class UsageTrackingConnectionSpecification extends Specification { def 'lastUsedAt should be set on receiveMessage asynchronously'() { given: def connection = createConnection() - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) def openedLastUsedAt = connection.lastUsedAt def futureResultCallback = new FutureResultCallback() when: - connection.receiveMessageAsync(1, OPERATION_CONTEXT, futureResultCallback) + connection.receiveMessageAsync(1, getOperationContext(), futureResultCallback) futureResultCallback.get() then: @@ -166,13 +166,13 @@ class UsageTrackingConnectionSpecification extends Specification { def 'lastUsedAt should be set on sendAndReceive'() { given: def connection = createConnection() - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) def openedLastUsedAt = connection.lastUsedAt when: connection.sendAndReceive(new CommandMessage('test', new BsonDocument('ping', new BsonInt32(1)), NoOpFieldNameValidator.INSTANCE, primary(), - MessageSettings.builder().build(), SINGLE, null), new BsonDocumentCodec(), OPERATION_CONTEXT) + MessageSettings.builder().build(), SINGLE, null), new BsonDocumentCodec(), getOperationContext()) then: connection.lastUsedAt >= openedLastUsedAt @@ -182,7 +182,7 @@ class UsageTrackingConnectionSpecification extends Specification { def 'lastUsedAt should be set on sendAndReceive asynchronously'() { given: def connection = createConnection() - connection.open(OPERATION_CONTEXT) + connection.open(getOperationContext()) def openedLastUsedAt = connection.lastUsedAt def futureResultCallback = new FutureResultCallback() @@ -190,7 +190,7 @@ class UsageTrackingConnectionSpecification extends Specification { connection.sendAndReceiveAsync(new CommandMessage('test', new BsonDocument('ping', new BsonInt32(1)), NoOpFieldNameValidator.INSTANCE, primary(), MessageSettings.builder().build(), SINGLE, null), - new BsonDocumentCodec(), OPERATION_CONTEXT, futureResultCallback) + new BsonDocumentCodec(), getOperationContext(), futureResultCallback) futureResultCallback.get() then: diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/X509AuthenticatorNoUserNameTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/X509AuthenticatorNoUserNameTest.java index 5326c8c723d..9346e529e2e 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/X509AuthenticatorNoUserNameTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/X509AuthenticatorNoUserNameTest.java @@ -32,7 +32,7 @@ import java.util.List; import java.util.concurrent.ExecutionException; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.getServerApi; import static com.mongodb.connection.ClusterConnectionMode.MULTIPLE; import static com.mongodb.internal.connection.MessageHelper.buildSuccessfulReply; @@ -58,7 +58,7 @@ public void testSuccessfulAuthentication() { enqueueSuccessfulAuthenticationReply(); new X509Authenticator(getCredentialWithCache(), MULTIPLE, getServerApi()) - .authenticate(connection, connectionDescriptionThreeSix, OPERATION_CONTEXT); + .authenticate(connection, connectionDescriptionThreeSix, getOperationContext()); validateMessages(); } @@ -69,7 +69,7 @@ public void testSuccessfulAuthenticationAsync() throws ExecutionException, Inter FutureResultCallback futureCallback = new FutureResultCallback<>(); new X509Authenticator(getCredentialWithCache(), MULTIPLE, getServerApi()).authenticateAsync(connection, - connectionDescriptionThreeSix, OPERATION_CONTEXT, futureCallback); + connectionDescriptionThreeSix, getOperationContext(), futureCallback); futureCallback.get(); diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/X509AuthenticatorUnitTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/X509AuthenticatorUnitTest.java index a8b2d7b71d5..3d971461de3 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/X509AuthenticatorUnitTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/X509AuthenticatorUnitTest.java @@ -31,7 +31,7 @@ import java.util.List; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.getServerApi; import static com.mongodb.internal.connection.MessageHelper.buildSuccessfulReply; import static com.mongodb.internal.connection.MessageHelper.getApiVersionField; @@ -58,7 +58,7 @@ public void testFailedAuthentication() { enqueueFailedAuthenticationReply(); try { - subject.authenticate(connection, connectionDescription, OPERATION_CONTEXT); + subject.authenticate(connection, connectionDescription, getOperationContext()); fail(); } catch (MongoSecurityException e) { // all good @@ -70,7 +70,7 @@ public void testFailedAuthenticationAsync() { enqueueFailedAuthenticationReply(); FutureResultCallback futureCallback = new FutureResultCallback<>(); - subject.authenticateAsync(connection, connectionDescription, OPERATION_CONTEXT, futureCallback); + subject.authenticateAsync(connection, connectionDescription, getOperationContext(), futureCallback); try { futureCallback.get(); @@ -92,7 +92,7 @@ private void enqueueFailedAuthenticationReply() { public void testSuccessfulAuthentication() { enqueueSuccessfulAuthenticationReply(); - subject.authenticate(connection, connectionDescription, OPERATION_CONTEXT); + subject.authenticate(connection, connectionDescription, getOperationContext()); validateMessages(); } @@ -102,7 +102,7 @@ public void testSuccessfulAuthenticationAsync() { enqueueSuccessfulAuthenticationReply(); FutureResultCallback futureCallback = new FutureResultCallback<>(); - subject.authenticateAsync(connection, connectionDescription, OPERATION_CONTEXT, futureCallback); + subject.authenticateAsync(connection, connectionDescription, getOperationContext(), futureCallback); futureCallback.get(); @@ -117,7 +117,7 @@ public void testSpeculativeAuthentication() { + "user: \"CN=client,OU=kerneluser,O=10Gen,L=New York City,ST=New York,C=US\", " + "mechanism: \"MONGODB-X509\", db: \"$external\"}"); subject.setSpeculativeAuthenticateResponse(BsonDocument.parse(speculativeAuthenticateResponse)); - subject.authenticate(connection, connectionDescription, OPERATION_CONTEXT); + subject.authenticate(connection, connectionDescription, getOperationContext()); assertEquals(connection.getSent().size(), 0); assertEquals(expectedSpeculativeAuthenticateCommand, subject.createSpeculativeAuthenticateCommand(connection)); diff --git a/driver-core/src/test/unit/com/mongodb/internal/mockito/InsufficientStubbingDetectorDemoTest.java b/driver-core/src/test/unit/com/mongodb/internal/mockito/InsufficientStubbingDetectorDemoTest.java index 5d8bd8e61b1..aa3a2d70d50 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/mockito/InsufficientStubbingDetectorDemoTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/mockito/InsufficientStubbingDetectorDemoTest.java @@ -24,7 +24,7 @@ import org.mockito.Mockito; import org.mockito.internal.stubbing.answers.ThrowsException; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; @@ -40,33 +40,33 @@ void beforeEach() { @Test void mockObjectWithDefaultAnswer() { ReadBinding binding = Mockito.mock(ReadBinding.class); - assertThrows(NullPointerException.class, () -> operation.execute(binding, OPERATION_CONTEXT)); + assertThrows(NullPointerException.class, () -> operation.execute(binding, getOperationContext())); } @Test void mockObjectWithThrowsException() { ReadBinding binding = Mockito.mock(ReadBinding.class, new ThrowsException(new AssertionError("Insufficient stubbing for " + ReadBinding.class))); - assertThrows(AssertionError.class, () -> operation.execute(binding, OPERATION_CONTEXT)); + assertThrows(AssertionError.class, () -> operation.execute(binding, getOperationContext())); } @Test void mockObjectWithInsufficientStubbingDetector() { ReadBinding binding = MongoMockito.mock(ReadBinding.class); - assertThrows(AssertionError.class, () -> operation.execute(binding, OPERATION_CONTEXT)); + assertThrows(AssertionError.class, () -> operation.execute(binding, getOperationContext())); } @Test void stubbingWithThrowsException() { ReadBinding binding = Mockito.mock(ReadBinding.class, new ThrowsException(new AssertionError("Unfortunately, you cannot do stubbing"))); - assertThrows(AssertionError.class, () -> when(binding.getReadConnectionSource(OPERATION_CONTEXT)).thenReturn(null)); + assertThrows(AssertionError.class, () -> when(binding.getReadConnectionSource(getOperationContext())).thenReturn(null)); } @Test void stubbingWithInsufficientStubbingDetector() { MongoMockito.mock(ReadBinding.class, bindingMock -> - when(bindingMock.getReadConnectionSource(OPERATION_CONTEXT)).thenReturn(null) + when(bindingMock.getReadConnectionSource(getOperationContext())).thenReturn(null) ); } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/AsyncOperationHelperSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/operation/AsyncOperationHelperSpecification.groovy index d573822cab7..4e488a69bee 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/AsyncOperationHelperSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/AsyncOperationHelperSpecification.groovy @@ -36,7 +36,7 @@ import org.bson.codecs.BsonDocumentCodec import org.bson.codecs.Decoder import spock.lang.Specification -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ReadPreference.primary import static com.mongodb.internal.operation.AsyncOperationHelper.CommandReadTransformerAsync import static com.mongodb.internal.operation.AsyncOperationHelper.executeCommandAsync @@ -74,7 +74,7 @@ class AsyncOperationHelperSpecification extends Specification { _ * getDescription() >> connectionDescription } - def operationContext = OPERATION_CONTEXT.withSessionContext( + def operationContext = getOperationContext().withSessionContext( Stub(SessionContext) { hasSession() >> true hasActiveTransaction() >> false @@ -116,7 +116,7 @@ class AsyncOperationHelperSpecification extends Specification { def connectionDescription = Stub(ConnectionDescription) when: - executeCommandAsync(asyncWriteBinding, OPERATION_CONTEXT, dbName, command, connection, { t, conn -> t }, callback) + executeCommandAsync(asyncWriteBinding, getOperationContext(), dbName, command, connection, { t, conn -> t }, callback) then: _ * connection.getDescription() >> connectionDescription @@ -143,7 +143,7 @@ class AsyncOperationHelperSpecification extends Specification { def connectionDescription = Stub(ConnectionDescription) when: - executeRetryableReadAsync(asyncReadBinding, OPERATION_CONTEXT, dbName, commandCreator, decoder, function, false, callback) + executeRetryableReadAsync(asyncReadBinding, getOperationContext(), dbName, commandCreator, decoder, function, false, callback) then: _ * connection.getDescription() >> connectionDescription diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/ClientBulkWriteOperationTest.java b/driver-core/src/test/unit/com/mongodb/internal/operation/ClientBulkWriteOperationTest.java index 5de1992b69d..0a7083bb65a 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/ClientBulkWriteOperationTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/ClientBulkWriteOperationTest.java @@ -124,7 +124,7 @@ void shouldIgnoreSuccessfulCursorResultWhenVerboseResultIsFalse() { false, getDefaultCodecRegistry()); //when - ClientBulkWriteResult result = op.execute(binding, ClusterFixture.OPERATION_CONTEXT); + ClientBulkWriteResult result = op.execute(binding, ClusterFixture.getOperationContext()); //then assertEquals( @@ -176,7 +176,7 @@ void shouldUseDefaultNumberOfModifiedDocumentsWhenMissingInCursor() { false, getDefaultCodecRegistry()); //when - ClientBulkWriteResult result = op.execute(binding, ClusterFixture.OPERATION_CONTEXT); + ClientBulkWriteResult result = op.execute(binding, ClusterFixture.getOperationContext()); //then assertEquals(1, result.getInsertedCount()); diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/CommitTransactionOperationUnitSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/operation/CommitTransactionOperationUnitSpecification.groovy index 75ed9e6c5f3..ae86661fe2e 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/CommitTransactionOperationUnitSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/CommitTransactionOperationUnitSpecification.groovy @@ -27,7 +27,7 @@ import com.mongodb.internal.binding.WriteBinding import com.mongodb.internal.connection.OperationContext import com.mongodb.internal.session.SessionContext -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext class CommitTransactionOperationUnitSpecification extends OperationUnitSpecification { def 'should add UnknownTransactionCommitResult error label to MongoTimeoutException'() { @@ -42,7 +42,7 @@ class CommitTransactionOperationUnitSpecification extends OperationUnitSpecifica def operation = new CommitTransactionOperation(WriteConcern.ACKNOWLEDGED) when: - operation.execute(writeBinding, OPERATION_CONTEXT.withSessionContext(sessionContext)) + operation.execute(writeBinding, getOperationContext().withSessionContext(sessionContext)) then: def e = thrown(MongoTimeoutException) @@ -64,7 +64,7 @@ class CommitTransactionOperationUnitSpecification extends OperationUnitSpecifica def callback = new FutureResultCallback() when: - operation.executeAsync(writeBinding, OPERATION_CONTEXT.withSessionContext(sessionContext), callback) + operation.executeAsync(writeBinding, getOperationContext().withSessionContext(sessionContext), callback) callback.get() then: diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/CursorResourceManagerTest.java b/driver-core/src/test/unit/com/mongodb/internal/operation/CursorResourceManagerTest.java index 68b3bf7f606..9c7a9d3fcd7 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/CursorResourceManagerTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/CursorResourceManagerTest.java @@ -24,7 +24,7 @@ import com.mongodb.internal.mockito.MongoMockito; import org.junit.jupiter.api.Test; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.mockito.Mockito.when; @@ -50,12 +50,12 @@ void doClose(final OperationContext operationContext) { cursorResourceManager.tryStartOperation(); try { assertDoesNotThrow(() -> { - cursorResourceManager.close(OPERATION_CONTEXT); - cursorResourceManager.close(OPERATION_CONTEXT); + cursorResourceManager.close(getOperationContext()); + cursorResourceManager.close(getOperationContext()); cursorResourceManager.setServerCursor(null); }); } finally { - cursorResourceManager.endOperation(OPERATION_CONTEXT); + cursorResourceManager.endOperation(getOperationContext()); } } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/ListCollectionsOperationTest.java b/driver-core/src/test/unit/com/mongodb/internal/operation/ListCollectionsOperationTest.java index de1bfe405ed..ff09b40246a 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/ListCollectionsOperationTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/ListCollectionsOperationTest.java @@ -39,7 +39,7 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.internal.mockito.MongoMockito.mock; import static java.util.Collections.emptyList; @@ -99,7 +99,7 @@ void authorizedCollectionsIsFalseByDefault() { } private BsonDocument executeOperationAndCaptureCommand() { - operation.execute(mocks.readBinding(), OPERATION_CONTEXT); + operation.execute(mocks.readBinding(), getOperationContext()); ArgumentCaptor commandCaptor = forClass(BsonDocument.class); verify(mocks.connection()).command(any(), commandCaptor.capture(), any(), any(), any(), any()); return commandCaptor.getValue(); diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/OperationHelperSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/operation/OperationHelperSpecification.groovy index fd9786e8dbf..d71739b8f7c 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/OperationHelperSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/OperationHelperSpecification.groovy @@ -32,7 +32,7 @@ import org.bson.BsonArray import org.bson.BsonDocument import spock.lang.Specification -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.WriteConcern.ACKNOWLEDGED import static com.mongodb.WriteConcern.UNACKNOWLEDGED import static com.mongodb.connection.ServerConnectionState.CONNECTED @@ -108,8 +108,8 @@ class OperationHelperSpecification extends Specification { } expect: - canRetryRead(retryableServerDescription, OPERATION_CONTEXT.withSessionContext(noTransactionSessionContext)) - !canRetryRead(retryableServerDescription, OPERATION_CONTEXT.withSessionContext(activeTransactionSessionContext)) + canRetryRead(retryableServerDescription, getOperationContext().withSessionContext(noTransactionSessionContext)) + !canRetryRead(retryableServerDescription, getOperationContext().withSessionContext(activeTransactionSessionContext)) } diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/OperationUnitSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/operation/OperationUnitSpecification.groovy index ec5cb74156f..4df237b0710 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/OperationUnitSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/OperationUnitSpecification.groovy @@ -41,7 +41,7 @@ import spock.lang.Specification import java.util.concurrent.TimeUnit -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext class OperationUnitSpecification extends Specification { @@ -97,7 +97,7 @@ class OperationUnitSpecification extends Specification { def testSyncOperation(operation, List serverVersion, result, Boolean checkCommand=true, BsonDocument expectedCommand=null, Boolean checkSecondaryOk=false, ReadPreference readPreference=ReadPreference.primary()) { - def operationContext = OPERATION_CONTEXT + def operationContext = getOperationContext() .withSessionContext(Stub(SessionContext) { hasActiveTransaction() >> false getReadConcern() >> ReadConcern.DEFAULT @@ -151,7 +151,7 @@ class OperationUnitSpecification extends Specification { Boolean checkCommand=true, BsonDocument expectedCommand=null, Boolean checkSecondaryOk=false, ReadPreference readPreference=ReadPreference.primary()) { - def operationContext = OPERATION_CONTEXT + def operationContext = getOperationContext() .withSessionContext(Stub(SessionContext) { hasActiveTransaction() >> false getReadConcern() >> ReadConcern.DEFAULT diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/SyncOperationHelperSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/operation/SyncOperationHelperSpecification.groovy index bd9bd2f2578..41e60240ece 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/SyncOperationHelperSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/SyncOperationHelperSpecification.groovy @@ -34,7 +34,7 @@ import org.bson.codecs.BsonDocumentCodec import org.bson.codecs.Decoder import spock.lang.Specification -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ReadPreference.primary import static com.mongodb.internal.operation.OperationUnitSpecification.getMaxWireVersionForServerVersion import static com.mongodb.internal.operation.SyncOperationHelper.CommandReadTransformer @@ -61,7 +61,7 @@ class SyncOperationHelperSpecification extends Specification { def connectionDescription = Stub(ConnectionDescription) when: - executeCommand(writeBinding, OPERATION_CONTEXT, dbName, command, decoder, function) + executeCommand(writeBinding, getOperationContext(), dbName, command, decoder, function) then: _ * connection.getDescription() >> connectionDescription @@ -71,7 +71,7 @@ class SyncOperationHelperSpecification extends Specification { def 'should retry with retryable exception'() { given: - def operationContext = OPERATION_CONTEXT + def operationContext = getOperationContext() .withSessionContext(Stub(SessionContext) { hasSession() >> true hasActiveTransaction() >> false @@ -132,7 +132,7 @@ class SyncOperationHelperSpecification extends Specification { def connectionDescription = Stub(ConnectionDescription) when: - executeRetryableRead(readBinding, OPERATION_CONTEXT, dbName, commandCreator, decoder, function, false) + executeRetryableRead(readBinding, getOperationContext(), dbName, commandCreator, decoder, function, false) then: _ * connection.getDescription() >> connectionDescription diff --git a/driver-core/src/test/unit/com/mongodb/internal/session/BaseClientSessionImplTest.java b/driver-core/src/test/unit/com/mongodb/internal/session/BaseClientSessionImplTest.java index c7fc1d73e20..189fcc07ce0 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/session/BaseClientSessionImplTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/session/BaseClientSessionImplTest.java @@ -20,7 +20,7 @@ import com.mongodb.session.ClientSession; import org.junit.jupiter.api.Test; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.getCluster; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -28,7 +28,7 @@ class BaseClientSessionImplTest { @Test void shouldNotCheckoutServerSessionIfNeverRequested() { - ServerSessionPool serverSessionPool = new ServerSessionPool(getCluster(), OPERATION_CONTEXT); + ServerSessionPool serverSessionPool = new ServerSessionPool(getCluster(), getOperationContext()); ClientSession clientSession = new BaseClientSessionImpl(serverSessionPool, new Object(), ClientSessionOptions.builder().build()); assertEquals(0, serverSessionPool.getInUseCount()); @@ -40,7 +40,7 @@ void shouldNotCheckoutServerSessionIfNeverRequested() { @Test void shouldDelayServerSessionCheckoutUntilRequested() { - ServerSessionPool serverSessionPool = new ServerSessionPool(getCluster(), OPERATION_CONTEXT); + ServerSessionPool serverSessionPool = new ServerSessionPool(getCluster(), getOperationContext()); ClientSession clientSession = new BaseClientSessionImpl(serverSessionPool, new Object(), ClientSessionOptions.builder().build()); assertEquals(0, serverSessionPool.getInUseCount()); diff --git a/driver-core/src/test/unit/com/mongodb/internal/session/ServerSessionPoolSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/session/ServerSessionPoolSpecification.groovy index 19bfa994200..962b60bdffb 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/session/ServerSessionPoolSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/session/ServerSessionPoolSpecification.groovy @@ -32,7 +32,7 @@ import org.bson.BsonDocument import org.bson.codecs.BsonDocumentCodec import spock.lang.Specification -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS import static com.mongodb.ClusterFixture.getServerApi import static com.mongodb.ReadPreference.primaryPreferred @@ -120,7 +120,7 @@ class ServerSessionPoolSpecification extends Specification { millis() >>> [0, MINUTES.toMillis(29) + 1, ] } - def pool = new ServerSessionPool(cluster, OPERATION_CONTEXT, clock) + def pool = new ServerSessionPool(cluster, getOperationContext(), clock) def sessionOne = pool.get() when: @@ -146,7 +146,7 @@ class ServerSessionPoolSpecification extends Specification { def clock = Stub(ServerSessionPool.Clock) { millis() >>> [0, 0, 0] } - def pool = new ServerSessionPool(cluster, OPERATION_CONTEXT, clock) + def pool = new ServerSessionPool(cluster, getOperationContext(), clock) def session = pool.get() when: @@ -165,7 +165,7 @@ class ServerSessionPoolSpecification extends Specification { def clock = Stub(ServerSessionPool.Clock) { millis() >> 42 } - def pool = new ServerSessionPool(cluster, OPERATION_CONTEXT, clock) + def pool = new ServerSessionPool(cluster, getOperationContext(), clock) when: def session = pool.get() as ServerSessionPool.ServerSessionImpl @@ -187,7 +187,7 @@ class ServerSessionPoolSpecification extends Specification { def clock = Stub(ServerSessionPool.Clock) { millis() >> 42 } - def pool = new ServerSessionPool(cluster, OPERATION_CONTEXT, clock) + def pool = new ServerSessionPool(cluster, getOperationContext(), clock) when: def session = pool.get() as ServerSessionPool.ServerSessionImpl diff --git a/driver-legacy/src/test/functional/com/mongodb/DBTest.java b/driver-legacy/src/test/functional/com/mongodb/DBTest.java index cf44573a2b4..622900490ff 100644 --- a/driver-legacy/src/test/functional/com/mongodb/DBTest.java +++ b/driver-legacy/src/test/functional/com/mongodb/DBTest.java @@ -31,7 +31,7 @@ import java.util.Locale; import java.util.UUID; -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT; +import static com.mongodb.ClusterFixture.getOperationContext; import static com.mongodb.ClusterFixture.disableMaxTimeFailPoint; import static com.mongodb.ClusterFixture.enableMaxTimeFailPoint; import static com.mongodb.ClusterFixture.getBinding; @@ -345,7 +345,7 @@ public void shouldApplyUuidRepresentationToCommandEncodingAndDecoding() { BsonDocument getCollectionInfo(final String collectionName) { return new ListCollectionsOperation<>(getDefaultDatabaseName(), new BsonDocumentCodec()) - .filter(new BsonDocument("name", new BsonString(collectionName))).execute(getBinding(), OPERATION_CONTEXT).next().get(0); + .filter(new BsonDocument("name", new BsonString(collectionName))).execute(getBinding(), getOperationContext()).next().get(0); } private boolean isCapped(final DBCollection collection) { diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/ClientSessionBindingSpecification.groovy b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/ClientSessionBindingSpecification.groovy index cfe66a8031f..df996b6088e 100644 --- a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/ClientSessionBindingSpecification.groovy +++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/ClientSessionBindingSpecification.groovy @@ -16,6 +16,7 @@ package com.mongodb.reactivestreams.client.internal +import com.mongodb.ClusterFixture import com.mongodb.ReadPreference import com.mongodb.ServerAddress import com.mongodb.async.FutureResultCallback @@ -31,32 +32,34 @@ import com.mongodb.internal.connection.ServerTuple import com.mongodb.reactivestreams.client.ClientSession import spock.lang.Specification -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT +import static com.mongodb.ClusterFixture.getOperationContext class ClientSessionBindingSpecification extends Specification { def 'should return the session context from the connection source'() { given: def session = Stub(ClientSession) + def operationContext = ClusterFixture.getOperationContext() def wrappedBinding = Mock(AsyncClusterAwareReadWriteBinding); wrappedBinding.retain() >> wrappedBinding def binding = new ClientSessionBinding(session, false, wrappedBinding) when: def futureResultCallback = new FutureResultCallback() - binding.getReadConnectionSource(OPERATION_CONTEXT, futureResultCallback) + + binding.getReadConnectionSource(operationContext, futureResultCallback) then: - 1 * wrappedBinding.getReadConnectionSource(OPERATION_CONTEXT, _) >> { + 1 * wrappedBinding.getReadConnectionSource(operationContext, _) >> { it[1].onResult(Stub(AsyncConnectionSource), null) } when: futureResultCallback = new FutureResultCallback() - binding.getWriteConnectionSource(OPERATION_CONTEXT, futureResultCallback) + binding.getWriteConnectionSource(operationContext, futureResultCallback) then: - 1 * wrappedBinding.getWriteConnectionSource(OPERATION_CONTEXT, _) >> { + 1 * wrappedBinding.getWriteConnectionSource(operationContext, _) >> { it[1].onResult(Stub(AsyncConnectionSource), null) } } @@ -87,10 +90,10 @@ class ClientSessionBindingSpecification extends Specification { def wrappedBinding = createStubBinding() def binding = new ClientSessionBinding(session, true, wrappedBinding) def futureResultCallback = new FutureResultCallback() - binding.getReadConnectionSource(OPERATION_CONTEXT, futureResultCallback) + binding.getReadConnectionSource(getOperationContext(), futureResultCallback) def readConnectionSource = futureResultCallback.get() futureResultCallback = new FutureResultCallback() - binding.getWriteConnectionSource(OPERATION_CONTEXT, futureResultCallback) + binding.getWriteConnectionSource(getOperationContext(), futureResultCallback) def writeConnectionSource = futureResultCallback.get() when: diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/ClientSessionBindingSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/internal/ClientSessionBindingSpecification.groovy index e2e664f324d..02b81be8c7f 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/ClientSessionBindingSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/ClientSessionBindingSpecification.groovy @@ -16,7 +16,7 @@ package com.mongodb.client.internal - +import com.mongodb.ClusterFixture import com.mongodb.ReadPreference import com.mongodb.client.ClientSession import com.mongodb.internal.binding.ClusterBinding @@ -25,29 +25,28 @@ import com.mongodb.internal.binding.ReadWriteBinding import com.mongodb.internal.connection.Cluster import spock.lang.Specification -import static com.mongodb.ClusterFixture.OPERATION_CONTEXT - class ClientSessionBindingSpecification extends Specification { def 'should call underlying wrapped binding'() { given: def session = Stub(ClientSession) + def operationContext = ClusterFixture.getOperationContext() def wrappedBinding = Mock(ClusterBinding); def binding = new ClientSessionBinding(session, false, wrappedBinding) when: - binding.getReadConnectionSource(OPERATION_CONTEXT) + binding.getReadConnectionSource(operationContext) then: - 1 * wrappedBinding.getReadConnectionSource(OPERATION_CONTEXT) >> { + 1 * wrappedBinding.getReadConnectionSource(operationContext) >> { Stub(ConnectionSource) } when: - binding.getWriteConnectionSource(OPERATION_CONTEXT) + binding.getWriteConnectionSource(operationContext) then: - 1 * wrappedBinding.getWriteConnectionSource(OPERATION_CONTEXT) >> { + 1 * wrappedBinding.getWriteConnectionSource(operationContext) >> { Stub(ConnectionSource) } } @@ -77,8 +76,9 @@ class ClientSessionBindingSpecification extends Specification { def session = Mock(ClientSession) def wrappedBinding = createStubBinding() def binding = new ClientSessionBinding(session, true, wrappedBinding) - def readConnectionSource = binding.getReadConnectionSource(OPERATION_CONTEXT) - def writeConnectionSource = binding.getWriteConnectionSource(OPERATION_CONTEXT) + def operationContext = ClusterFixture.getOperationContext() + def readConnectionSource = binding.getReadConnectionSource(operationContext) + def writeConnectionSource = binding.getWriteConnectionSource(operationContext) when: binding.release() diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/CryptConnectionSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/internal/CryptConnectionSpecification.groovy index 8a38f966754..82749134253 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/CryptConnectionSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/CryptConnectionSpecification.groovy @@ -61,7 +61,7 @@ class CryptConnectionSpecification extends Specification { def cryptConnection = new CryptConnection(wrappedConnection, crypt) def codec = new DocumentCodec() def timeoutContext = Mock(TimeoutContext) - def operationContext = ClusterFixture.OPERATION_CONTEXT.withTimeoutContext(timeoutContext) + def operationContext = ClusterFixture.getOperationContext().withTimeoutContext(timeoutContext) def operationTimeout = Mock(Timeout) timeoutContext.getTimeout() >> operationTimeout @@ -127,7 +127,7 @@ class CryptConnectionSpecification extends Specification { def encryptedResponse = toRaw(new BsonDocument('ok', new BsonInt32(1))) def decryptedResponse = encryptedResponse def timeoutContext = Mock(TimeoutContext) - def operationContext = ClusterFixture.OPERATION_CONTEXT.withTimeoutContext(timeoutContext) + def operationContext = ClusterFixture.getOperationContext().withTimeoutContext(timeoutContext) def operationTimeout = Mock(Timeout) timeoutContext.getTimeout() >> operationTimeout @@ -183,7 +183,7 @@ class CryptConnectionSpecification extends Specification { def encryptedResponse = toRaw(new BsonDocument('ok', new BsonInt32(1))) def decryptedResponse = encryptedResponse def timeoutContext = Mock(TimeoutContext) - def operationContext = ClusterFixture.OPERATION_CONTEXT.withTimeoutContext(timeoutContext) + def operationContext = ClusterFixture.getOperationContext().withTimeoutContext(timeoutContext) def operationTimeout = Mock(Timeout) timeoutContext.getTimeout() >> operationTimeout