From 282bf5774077b65f06a98bbcaf9b2532cfe86939 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Mon, 12 Jan 2026 13:05:30 -0800 Subject: [PATCH 01/43] Add support for server selection's deprioritized servers to all topologies. JAVA-6021 --- .../internal/connection/BaseCluster.java | 19 ++- .../internal/connection/OperationContext.java | 41 +++-- .../selector/CompositeServerSelector.java | 3 + driver-core/src/test/resources/specifications | 2 +- .../ServerSelectionSelectionTest.java | 147 +++++++++++++++--- .../ServerDeprioritizationTest.java | 135 +++++++++++++--- 6 files changed, 280 insertions(+), 67 deletions(-) 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..305cdc2428d 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java +++ b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java @@ -68,6 +68,7 @@ import static com.mongodb.connection.ServerDescription.MIN_DRIVER_WIRE_VERSION; import static com.mongodb.internal.Locks.withInterruptibleLock; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; +import static com.mongodb.internal.VisibleForTesting.AccessModifier.PROTECTED; import static com.mongodb.internal.connection.EventHelper.wouldDescriptionsGenerateEquivalentEvents; import static com.mongodb.internal.event.EventListenerHelper.singleClusterListener; import static com.mongodb.internal.logging.LogMessage.Component.SERVER_SELECTION; @@ -94,7 +95,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 +114,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); @@ -234,7 +237,8 @@ public boolean isClosed() { return isClosed; } - protected void updateDescription(final ClusterDescription newDescription) { + @VisibleForTesting(otherwise = PROTECTED) + public void updateDescription(final ClusterDescription newDescription) { withLock(() -> { if (LOGGER.isDebugEnabled()) { LOGGER.debug(format("Updating cluster description to %s", newDescription.getShortDescription())); @@ -361,8 +365,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..d4b2e8858f9 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; @@ -228,24 +227,23 @@ public static final class ServerDeprioritization { @Nullable private ServerAddress candidate; private final Set deprioritized; - private final DeprioritizingSelector selector; private 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 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 retries without filtering deprioritized servers. */ - ServerSelector getServerSelector() { - return selector; + ServerSelector applyDeprioritization(final ServerSelector wrappedSelector) { + return new DeprioritizingSelector(wrappedSelector); } - void updateCandidate(final ServerAddress serverAddress) { + public void updateCandidate(final ServerAddress serverAddress) { candidate = serverAddress; } @@ -263,24 +261,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/selector/CompositeServerSelector.java b/driver-core/src/main/com/mongodb/selector/CompositeServerSelector.java index 40feab69433..8318d819774 100644 --- a/driver-core/src/main/com/mongodb/selector/CompositeServerSelector.java +++ b/driver-core/src/main/com/mongodb/selector/CompositeServerSelector.java @@ -72,6 +72,9 @@ public List select(final ClusterDescription clusterDescriptio List choices = null; for (ServerSelector cur : serverSelectors) { choices = cur.select(curClusterDescription); + if (choices.isEmpty()) { + return choices; + } curClusterDescription = new ClusterDescription(clusterDescription.getConnectionMode(), clusterDescription.getType(), choices, clusterDescription.getClusterSettings(), clusterDescription.getServerSettings()); 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..52872c364bd 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,32 @@ import org.bson.BsonInt64; import org.bson.BsonString; import org.bson.BsonValue; +import org.bson.json.JsonWriterSettings; import org.junit.Test; 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 +79,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 +95,21 @@ 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; + ServerTuple serverTuple; + BaseCluster cluster = null; try { - serverSelector = getServerSelector(); - selectedServers = serverSelector.select(clusterDescription); + ServerSelector serverSelector = getServerSelector(); + OperationContext operationContext = createOperationContext(); + Cluster.ServersSnapshot serversSnapshot = createServersSnapshot(clusterDescription); + cluster = createTestCluster(clusterDescription, serversSnapshot); + serverTuple = cluster.selectServer(serverSelector, operationContext); if (error) { fail("Should have thrown exception"); } @@ -87,21 +118,29 @@ 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; + } finally { + if (cluster != null) { + cluster.close(); + } } - 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 +149,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 +191,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 +214,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 +270,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 +286,69 @@ 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) { + BaseCluster baseCluster = new BaseCluster( + new ClusterId(), + clusterDescription.getClusterSettings(), + new TestClusterableServerFactory(), + ClusterFixture.CLIENT_METADATA) { + @Override + protected void connect() { + } + + @Override + public ServersSnapshot getServersSnapshot(final Timeout serverSelectionTimeout, final TimeoutContext timeoutContext) { + return serversSnapshot; + } + + @Override + public void onChange(final ServerDescriptionChangedEvent event) { + } + }; + baseCluster.updateDescription(clusterDescription); + return baseCluster; + } + + 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); + } } } 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..09663421a9a 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,37 @@ 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.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.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; 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,20 +64,60 @@ void beforeEach() { serverDeprioritization = createOperationContext(TIMEOUT_SETTINGS).getServerDeprioritization(); } - @Test - void selectNoneDeprioritized() { + private static Stream selectNoneDeprioritized() { + return Stream.of( + Arguments.of(singletonList(SERVER_A)), + Arguments.of(singletonList(SERVER_C)), + Arguments.of(singletonList(SERVER_B)), + Arguments.of(asList(SERVER_A, SERVER_C)) + ); + } + + @ParameterizedTest + @MethodSource + void selectNoneDeprioritized(final List selectorResult) { + ServerSelector wrappedSelector = createAssertingSelector(ALL_SERVERS, selectorResult); + ServerSelector emptyListWrappedSelector = createAssertingSelector(ALL_SERVERS, emptyList()); 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(emptyList(), serverDeprioritization.applyDeprioritization(emptyListWrappedSelector).select(SHARDED_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(wrappedSelector).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(emptyList(), serverDeprioritization.applyDeprioritization(emptyListWrappedSelector).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(wrappedSelector).select(UNKNOWN_CLUSTER)), + () -> assertEquals(emptyList(), serverDeprioritization.applyDeprioritization(emptyListWrappedSelector).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( + Arguments.of(singletonList(SERVER_A)), + Arguments.of(singletonList(SERVER_C)), + Arguments.of(asList(SERVER_A, SERVER_C)) + ); + } + + @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)) ); } @@ -78,18 +126,49 @@ void selectAllDeprioritized() { deprioritize(SERVER_A); deprioritize(SERVER_B); deprioritize(SERVER_C); + ServerSelector selector = createAssertingSelector(ALL_SERVERS, 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(SHARDED_CLUSTER)), + () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector).select(UNKNOWN_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))); + @Test + void selectAllDeprioritizedSingleServerCluster() { + deprioritize(SERVER_A); + ServerSelector selector = createAssertingSelector(singletonList(SERVER_A), singletonList(SERVER_A)); + assertAll( + () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector).select(STANDALONE_CLUSTER)), + () -> assertEquals(singletonList(SERVER_A), + serverDeprioritization.applyDeprioritization(selector).select(LOAD_BALANCED_CLUSTER)) + ); + } + + @Test + void selectWithRetryWhenWrappedReturnsEmpty() { + deprioritize(SERVER_A); + 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_B, SERVER_C), servers); + return emptyList(); + } + assertEquals(ALL_SERVERS, servers); + return singletonList(SERVER_A); + } + }; + + assertAll( + () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector.get()).select(SHARDED_CLUSTER)), + () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector.get()).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector.get()).select(UNKNOWN_CLUSTER)) + ); } @Test @@ -97,7 +176,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 +192,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 +209,11 @@ 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)); + } } From cb8905c4053ad04a463dc4227ecb2869ac66f9f0 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 14 Jan 2026 23:32:10 -0800 Subject: [PATCH 02/43] Remove global OperationContext in tests as it has mutable state. --- .../internal/connection/OperationContext.java | 8 +- .../operation/ChangeStreamBatchCursor.java | 5 +- .../selector/CompositeServerSelector.java | 3 - .../com/mongodb/ClusterFixture.java | 54 ++++---- .../OperationFunctionalSpecification.groovy | 12 +- .../mongodb/client/test/CollectionHelper.java | 56 ++++---- .../connection/ConnectionSpecification.groovy | 12 +- .../netty/NettyStreamSpecification.groovy | 8 +- .../AsyncSessionBindingSpecification.groovy | 13 +- ...yncSocketChannelStreamSpecification.groovy | 8 +- .../AsyncStreamTimeoutsSpecification.groovy | 6 +- .../AwsAuthenticationSpecification.groovy | 12 +- .../CommandHelperSpecification.groovy | 8 +- .../connection/DefaultConnectionPoolTest.java | 26 ++-- .../GSSAPIAuthenticationSpecification.groovy | 16 +-- .../GSSAPIAuthenticatorSpecification.groovy | 4 +- .../PlainAuthenticationSpecification.groovy | 12 +- .../connection/PlainAuthenticatorTest.java | 6 +- ...amSha256AuthenticationSpecification.groovy | 14 +- .../internal/connection/ServerHelper.java | 6 +- .../connection/SingleServerClusterTest.java | 6 +- .../SocketStreamHelperSpecification.groovy | 16 ++- .../StreamSocketAddressSpecification.groovy | 6 +- .../TlsChannelStreamFunctionalTest.java | 4 +- .../AggregateOperationSpecification.groovy | 5 +- ...AsyncCommandBatchCursorFunctionalTest.java | 42 +++--- .../ChangeStreamOperationSpecification.groovy | 6 +- .../CommandBatchCursorFunctionalTest.java | 60 ++++----- ...ountDocumentsOperationSpecification.groovy | 6 +- .../DistinctOperationSpecification.groovy | 6 +- .../FindOperationSpecification.groovy | 11 +- ...stCollectionsOperationSpecification.groovy | 13 +- ...ListDatabasesOperationSpecification.groovy | 6 +- .../ListIndexesOperationSpecification.groovy | 10 +- ...InlineResultsOperationSpecification.groovy | 6 +- .../operation/TestOperationHelper.java | 6 +- .../SingleServerBindingSpecification.groovy | 6 +- .../AbstractConnectionPoolTest.java | 4 +- ...tractServerDiscoveryAndMonitoringTest.java | 6 +- .../BaseClusterSpecification.groovy | 8 +- .../internal/connection/BaseClusterTest.java | 2 +- .../DefaultConnectionPoolSpecification.groovy | 62 +++++---- ...efaultServerConnectionSpecification.groovy | 11 +- .../DefaultServerSpecification.groovy | 24 ++-- ...ternalStreamConnectionSpecification.groovy | 120 +++++++++--------- ...ConnectionPoolListenerSpecification.groovy | 6 +- .../connection/LoadBalancedClusterTest.java | 14 +- ...gingCommandEventSenderSpecification.groovy | 10 +- .../MultiServerClusterSpecification.groovy | 8 +- .../PlainAuthenticatorUnitTest.java | 6 +- .../ServerDiscoveryAndMonitoringTest.java | 6 +- .../SingleServerClusterSpecification.groovy | 12 +- ...sageTrackingConnectionSpecification.groovy | 34 ++--- .../X509AuthenticatorNoUserNameTest.java | 6 +- .../connection/X509AuthenticatorUnitTest.java | 12 +- .../InsufficientStubbingDetectorDemoTest.java | 12 +- .../AsyncOperationHelperSpecification.groovy | 8 +- .../ClientBulkWriteOperationTest.java | 4 +- ...ansactionOperationUnitSpecification.groovy | 6 +- .../operation/CursorResourceManagerTest.java | 8 +- .../ListCollectionsOperationTest.java | 4 +- .../OperationHelperSpecification.groovy | 6 +- .../OperationUnitSpecification.groovy | 6 +- .../SyncOperationHelperSpecification.groovy | 8 +- .../session/BaseClientSessionImplTest.java | 6 +- .../ServerSessionPoolSpecification.groovy | 10 +- .../test/functional/com/mongodb/DBTest.java | 4 +- .../ClientSessionBindingSpecification.groovy | 17 ++- .../ClientSessionBindingSpecification.groovy | 18 +-- .../CryptConnectionSpecification.groovy | 6 +- 70 files changed, 500 insertions(+), 478 deletions(-) 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 d4b2e8858f9..2f56f288ad6 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -112,6 +112,12 @@ public OperationContext withOperationName(final String operationName) { operationName, tracingSpan); } + //TODO-JAVA + public OperationContext withServerDeprioritization(final ServerDeprioritization serverDeprioritization) { + return new OperationContext(id, requestContext, sessionContext, timeoutContext, serverDeprioritization, tracingManager, serverApi, + operationName, tracingSpan); + } + public long getId() { return id; } @@ -228,7 +234,7 @@ public static final class ServerDeprioritization { private ServerAddress candidate; private final Set deprioritized; - private ServerDeprioritization() { + public ServerDeprioritization() { candidate = null; deprioritized = new HashSet<>(); } 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..3503711ec71 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,10 @@ final class ChangeStreamBatchCursor implements AggregateResponseBatchCursor select(final ClusterDescription clusterDescriptio List choices = null; for (ServerSelector cur : serverSelectors) { choices = cur.select(curClusterDescription); - if (choices.isEmpty()) { - return choices; - } curClusterDescription = new ClusterDescription(clusterDescription.getConnectionMode(), clusterDescription.getType(), choices, clusterDescription.getClusterSettings(), clusterDescription.getServerSettings()); diff --git a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java index 1a5bead6207..c0f219ee1ea 100644 --- a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java +++ b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java @@ -193,16 +193,18 @@ public static ServerVersion getServerVersion() { if (serverVersion == null) { serverVersion = getVersion(new CommandReadOperation<>("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/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/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 From 2a4cd70602e467078c8416ef57c3cee4e7f62070 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Sat, 17 Jan 2026 13:14:34 -0800 Subject: [PATCH 03/43] Add more test-cases. --- .../internal/connection/BaseCluster.java | 4 +- .../internal/connection/OperationContext.java | 16 +++-- .../operation/ChangeStreamBatchCursor.java | 3 +- .../ServerSelectionSelectionTest.java | 53 ++++++++------ .../ServerDeprioritizationTest.java | 69 +++++++++++-------- 5 files changed, 87 insertions(+), 58 deletions(-) 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 305cdc2428d..6ac8541e51c 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java +++ b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java @@ -68,7 +68,6 @@ import static com.mongodb.connection.ServerDescription.MIN_DRIVER_WIRE_VERSION; import static com.mongodb.internal.Locks.withInterruptibleLock; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; -import static com.mongodb.internal.VisibleForTesting.AccessModifier.PROTECTED; import static com.mongodb.internal.connection.EventHelper.wouldDescriptionsGenerateEquivalentEvents; import static com.mongodb.internal.event.EventListenerHelper.singleClusterListener; import static com.mongodb.internal.logging.LogMessage.Component.SERVER_SELECTION; @@ -237,8 +236,7 @@ public boolean isClosed() { return isClosed; } - @VisibleForTesting(otherwise = PROTECTED) - public void updateDescription(final ClusterDescription newDescription) { + protected void updateDescription(final ClusterDescription newDescription) { withLock(() -> { if (LOGGER.isDebugEnabled()) { LOGGER.debug(format("Updating cluster description to %s", newDescription.getShortDescription())); 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 2f56f288ad6..1cd69187c41 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -39,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; /** @@ -112,7 +114,8 @@ public OperationContext withOperationName(final String operationName) { operationName, tracingSpan); } - //TODO-JAVA + // 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); @@ -234,21 +237,24 @@ public static final class ServerDeprioritization { private ServerAddress candidate; private final Set deprioritized; + @VisibleForTesting(otherwise = PRIVATE) public ServerDeprioritization() { candidate = null; deprioritized = new HashSet<>(); } /** - * The returned {@link ServerSelector} wraps the provided selector and 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 retries without filtering deprioritized servers. + * 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 applyDeprioritization(final ServerSelector wrappedSelector) { return new DeprioritizingSelector(wrappedSelector); } + @VisibleForTesting(otherwise = PACKAGE) public void updateCandidate(final ServerAddress serverAddress) { candidate = serverAddress; } 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 3503711ec71..d2c643699fa 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursor.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursor.java @@ -87,7 +87,8 @@ final class ChangeStreamBatchCursor implements AggregateResponseBatchCursor extractDeprioritizedServerAddresses(final Bso private OperationContext createOperationContext() { OperationContext operationContext = - OperationContext.simpleOperationContext(new TimeoutContext(TIMEOUT_SETTINGS.withServerSelectionTimeoutMS(SERVER_SELECTION_TIMEOUT_MS))); + OperationContext.simpleOperationContext( + new TimeoutContext(TIMEOUT_SETTINGS.withServerSelectionTimeoutMS(SERVER_SELECTION_TIMEOUT_MS))); OperationContext.ServerDeprioritization serverDeprioritization = operationContext.getServerDeprioritization(); for (ServerAddress address : deprioritizedServerAddresses) { serverDeprioritization.updateCandidate(address); @@ -322,26 +324,7 @@ private static Cluster.ServersSnapshot createServersSnapshot( } private BaseCluster createTestCluster(final ClusterDescription clusterDescription, final Cluster.ServersSnapshot serversSnapshot) { - BaseCluster baseCluster = new BaseCluster( - new ClusterId(), - clusterDescription.getClusterSettings(), - new TestClusterableServerFactory(), - ClusterFixture.CLIENT_METADATA) { - @Override - protected void connect() { - } - - @Override - public ServersSnapshot getServersSnapshot(final Timeout serverSelectionTimeout, final TimeoutContext timeoutContext) { - return serversSnapshot; - } - - @Override - public void onChange(final ServerDescriptionChangedEvent event) { - } - }; - baseCluster.updateDescription(clusterDescription); - return baseCluster; + return new TestCluster(clusterDescription, serversSnapshot); } private static void validateTestDescriptionFields(final Set actualFields, final Set knownFields) { @@ -351,4 +334,32 @@ private static void validateTestDescriptionFields(final Set actualFields throw new UnsupportedOperationException("Unknown fields: " + unknownFields); } } + + private static class TestCluster extends BaseCluster { + private final ServersSnapshot serversSnapshot; + + public 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() { + // We do not expect this to be called during server selection. + Assertions.fail(); + } + + @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/connection/ServerDeprioritizationTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/ServerDeprioritizationTest.java index 09663421a9a..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 @@ -27,6 +27,7 @@ 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.Arguments; @@ -34,6 +35,7 @@ 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; @@ -45,6 +47,7 @@ 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.Arguments.of; final class ServerDeprioritizationTest { private static final ServerDescription SERVER_A = serverDescription("a"); @@ -66,25 +69,25 @@ void beforeEach() { private static Stream selectNoneDeprioritized() { return Stream.of( - Arguments.of(singletonList(SERVER_A)), - Arguments.of(singletonList(SERVER_C)), - Arguments.of(singletonList(SERVER_B)), - Arguments.of(asList(SERVER_A, SERVER_C)) + 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); - ServerSelector emptyListWrappedSelector = createAssertingSelector(ALL_SERVERS, emptyList()); assertAll( () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(wrappedSelector).select(SHARDED_CLUSTER)), - () -> assertEquals(emptyList(), serverDeprioritization.applyDeprioritization(emptyListWrappedSelector).select(SHARDED_CLUSTER)), () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(wrappedSelector).select(REPLICA_SET_CLUSTER)), - () -> assertEquals(emptyList(), serverDeprioritization.applyDeprioritization(emptyListWrappedSelector).select(REPLICA_SET_CLUSTER)), - () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(wrappedSelector).select(UNKNOWN_CLUSTER)), - () -> assertEquals(emptyList(), serverDeprioritization.applyDeprioritization(emptyListWrappedSelector).select(UNKNOWN_CLUSTER)) + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(wrappedSelector).select(UNKNOWN_CLUSTER)) ); } @@ -100,11 +103,12 @@ void selectNoneDeprioritizedSingleServerCluster() { ); } - private static Stream selectSomeDeprioritized() { + private static Stream selectSomeDeprioritized() { return Stream.of( - Arguments.of(singletonList(SERVER_A)), - Arguments.of(singletonList(SERVER_C)), - Arguments.of(asList(SERVER_A, SERVER_C)) + 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))) ); } @@ -121,16 +125,17 @@ void selectSomeDeprioritized(final List selectorResult) { ); } - @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, singletonList(SERVER_A)); + ServerSelector selector = createAssertingSelector(ALL_SERVERS, selectorResult); assertAll( - () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector).select(SHARDED_CLUSTER)), - () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector).select(REPLICA_SET_CLUSTER)), - () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector).select(UNKNOWN_CLUSTER)) + () -> 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)) ); } @@ -145,9 +150,10 @@ void selectAllDeprioritizedSingleServerCluster() { ); } - @Test - void selectWithRetryWhenWrappedReturnsEmpty() { - deprioritize(SERVER_A); + @ParameterizedTest + @MethodSource("selectSomeDeprioritized") + void selectWithRetryWhenWrappedReturnsEmpty(final List selectorResult) { + deprioritize(SERVER_B); Supplier selector = () -> new ServerSelector() { private boolean firstCall = true; @@ -156,18 +162,18 @@ public List select(final ClusterDescription clusterDescriptio List servers = clusterDescription.getServerDescriptions(); if (firstCall) { firstCall = false; - assertEquals(asList(SERVER_B, SERVER_C), servers); + assertEquals(asList(SERVER_A, SERVER_C), servers); return emptyList(); } assertEquals(ALL_SERVERS, servers); - return singletonList(SERVER_A); + return selectorResult; } }; assertAll( - () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector.get()).select(SHARDED_CLUSTER)), - () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector.get()).select(REPLICA_SET_CLUSTER)), - () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector.get()).select(UNKNOWN_CLUSTER)) + () -> 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)) ); } @@ -216,4 +222,11 @@ private static ClusterDescription multipleModeClusterDescription(final ClusterTy 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(", ")) + "]"; + } } From fa35dd9ab4260dabc0c76108da33d9988aac97f8 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Sat, 17 Jan 2026 13:18:41 -0800 Subject: [PATCH 04/43] Fix static checks. --- .../connection/ServerSelectionSelectionTest.java | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) 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 7c9c8d75b95..875b8f6fcc1 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -104,12 +104,10 @@ 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")); ServerTuple serverTuple; - BaseCluster cluster = null; - try { - ServerSelector serverSelector = getServerSelector(); - OperationContext operationContext = createOperationContext(); - Cluster.ServersSnapshot serversSnapshot = createServersSnapshot(clusterDescription); - cluster = createTestCluster(clusterDescription, serversSnapshot); + 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"); @@ -125,10 +123,6 @@ public void shouldPassAllOutcomes() { JsonWriterSettings.builder() .indent(true).build()), inLatencyWindowServers.isEmpty()); return; - } finally { - if (cluster != null) { - cluster.close(); - } } List inLatencyWindowServers = buildServerDescriptions(definition.getArray("in_latency_window")); assertNotNull(serverTuple); @@ -338,7 +332,7 @@ private static void validateTestDescriptionFields(final Set actualFields private static class TestCluster extends BaseCluster { private final ServersSnapshot serversSnapshot; - public TestCluster(final ClusterDescription clusterDescription, final ServersSnapshot serversSnapshot) { + TestCluster(final ClusterDescription clusterDescription, final ServersSnapshot serversSnapshot) { super(new ClusterId(), clusterDescription.getClusterSettings(), new TestClusterableServerFactory(), ClusterFixture.CLIENT_METADATA); this.serversSnapshot = serversSnapshot; From 7b613e4efc2361070fb775625d2717d52e4ad4f3 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Sat, 17 Jan 2026 20:02:45 -0800 Subject: [PATCH 05/43] Allow invoking connect. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) 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 875b8f6fcc1..826da8ed466 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -341,8 +341,7 @@ private static class TestCluster extends BaseCluster { @Override protected void connect() { - // We do not expect this to be called during server selection. - Assertions.fail(); + // NOOP: this method may be invoked in test cases where no server is expected to be selected. } @Override From f20b48277b7a390ab1fcb92b3a4ca1cff94923c7 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Mon, 9 Feb 2026 23:28:32 -0800 Subject: [PATCH 06/43] Bump specification commit. --- testing/resources/specifications | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/resources/specifications b/testing/resources/specifications index de684cf1ef9..bb9dddd8176 160000 --- a/testing/resources/specifications +++ b/testing/resources/specifications @@ -1 +1 @@ -Subproject commit de684cf1ef9feede71d358cbb7d253840f1a8647 +Subproject commit bb9dddd8176eddbb9424f9bebedfe8c6bbf28c3a From 09f24dd778acbb6347cbac36da71265998873770 Mon Sep 17 00:00:00 2001 From: Viacheslav Babanin Date: Wed, 4 Mar 2026 14:45:06 -0800 Subject: [PATCH 07/43] Update driver-core/src/main/com/mongodb/internal/connection/OperationContext.java Co-authored-by: Valentin Kovalenko --- .../com/mongodb/internal/connection/OperationContext.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) 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 1cd69187c41..d647d6ab0a0 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -244,10 +244,12 @@ public ServerDeprioritization() { } /** - * The returned {@link ServerSelector} wraps the provided selector and attempts server selection in two passes: + * The returned {@link ServerSelector} wraps the provided selector and attempts + * {@linkplain ServerSelector#select(ClusterDescription) 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. + *
  5. First pass: selects using the wrapped selector with only non-deprioritized {@link ServerDescription}s.
  6. + *
  7. Second pass: if the first pass selects no {@link ServerDescription}s, + * selects using the wrapped selector again with all {@link ServerDescription}s, including deprioritized ones.
  8. *
*/ ServerSelector applyDeprioritization(final ServerSelector wrappedSelector) { From 733ee91a338c4d15f2c333e1296966ae991cfc87 Mon Sep 17 00:00:00 2001 From: Viacheslav Babanin Date: Wed, 4 Mar 2026 18:31:22 -0800 Subject: [PATCH 08/43] Update driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java Co-authored-by: Valentin Kovalenko --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 826da8ed466..579e7dd5a96 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -126,7 +126,7 @@ public void shouldPassAllOutcomes() { } List inLatencyWindowServers = buildServerDescriptions(definition.getArray("in_latency_window")); assertNotNull(serverTuple); - assertTrue(inLatencyWindowServers.stream().anyMatch(s -> s.getAddress().equals(serverTuple.getServerDescription().getAddress()))); + assertTrue(inLatencyWindowServers.stream().anyMatch(s -> s.equals(serverTuple.getServerDescription()))); } @Parameterized.Parameters(name = "{0}") From f324ab9fb43fe8df58827900659a69172f82af87 Mon Sep 17 00:00:00 2001 From: Viacheslav Babanin Date: Wed, 4 Mar 2026 18:39:08 -0800 Subject: [PATCH 09/43] Update driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java Co-authored-by: Valentin Kovalenko --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 579e7dd5a96..e53e1559487 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -310,7 +310,7 @@ private static Cluster.ServersSnapshot createServersSnapshot( 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. + // `MinimumOperationCountServerSelector` should select any server since they all have 0 operation count. when(server.operationCount()).thenReturn(0); })); } From 103c4b014bec582489d9baaa2392c147452b7b88 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Tue, 3 Mar 2026 14:23:44 -0800 Subject: [PATCH 10/43] Use "create" prefix consistently. --- .../com/mongodb/ClusterFixture.java | 46 +++---- .../OperationFunctionalSpecification.groovy | 12 +- .../mongodb/client/test/CollectionHelper.java | 56 ++++---- .../connection/ConnectionSpecification.groovy | 12 +- .../netty/NettyStreamSpecification.groovy | 8 +- .../AsyncSessionBindingSpecification.groovy | 2 +- ...yncSocketChannelStreamSpecification.groovy | 8 +- .../AsyncStreamTimeoutsSpecification.groovy | 6 +- .../AwsAuthenticationSpecification.groovy | 12 +- .../CommandHelperSpecification.groovy | 8 +- .../connection/DefaultConnectionPoolTest.java | 26 ++-- .../GSSAPIAuthenticationSpecification.groovy | 16 +-- .../GSSAPIAuthenticatorSpecification.groovy | 4 +- .../PlainAuthenticationSpecification.groovy | 12 +- .../connection/PlainAuthenticatorTest.java | 6 +- ...amSha256AuthenticationSpecification.groovy | 18 +-- .../internal/connection/ServerHelper.java | 5 +- .../connection/SingleServerClusterTest.java | 6 +- .../SocketStreamHelperSpecification.groovy | 11 +- .../StreamSocketAddressSpecification.groovy | 6 +- .../TlsChannelStreamFunctionalTest.java | 4 +- .../AggregateOperationSpecification.groovy | 14 +- ...eToCollectionOperationSpecification.groovy | 4 +- ...AsyncCommandBatchCursorFunctionalTest.java | 42 +++--- .../ChangeStreamOperationSpecification.groovy | 6 +- .../CommandBatchCursorFunctionalTest.java | 59 +++++---- ...ountDocumentsOperationSpecification.groovy | 8 +- ...ateCollectionOperationSpecification.groovy | 10 +- ...CreateIndexesOperationSpecification.groovy | 2 +- .../CreateViewOperationSpecification.groovy | 1 - .../DistinctOperationSpecification.groovy | 6 +- ...ropCollectionOperationSpecification.groovy | 8 +- .../DropDatabaseOperationSpecification.groovy | 1 - .../DropIndexOperationSpecification.groovy | 2 +- .../FindOperationSpecification.groovy | 12 +- ...stCollectionsOperationSpecification.groovy | 5 +- ...ListDatabasesOperationSpecification.groovy | 6 +- .../ListIndexesOperationSpecification.groovy | 6 +- ...eToCollectionOperationSpecification.groovy | 2 +- ...InlineResultsOperationSpecification.groovy | 6 +- ...ameCollectionOperationSpecification.groovy | 1 - .../operation/TestOperationHelper.java | 7 +- .../SingleServerBindingSpecification.groovy | 6 +- .../AbstractConnectionPoolTest.java | 3 +- ...tractServerDiscoveryAndMonitoringTest.java | 6 +- .../BaseClusterSpecification.groovy | 7 +- .../internal/connection/BaseClusterTest.java | 2 +- .../DefaultConnectionPoolSpecification.groovy | 37 +++--- ...efaultServerConnectionSpecification.groovy | 2 +- .../DefaultServerSpecification.groovy | 24 ++-- ...ternalStreamConnectionSpecification.groovy | 120 +++++++++--------- ...ConnectionPoolListenerSpecification.groovy | 6 +- .../connection/LoadBalancedClusterTest.java | 14 +- ...gingCommandEventSenderSpecification.groovy | 10 +- .../MultiServerClusterSpecification.groovy | 8 +- .../PlainAuthenticatorUnitTest.java | 6 +- .../ServerDiscoveryAndMonitoringTest.java | 6 +- .../SingleServerClusterSpecification.groovy | 12 +- ...sageTrackingConnectionSpecification.groovy | 34 ++--- .../X509AuthenticatorNoUserNameTest.java | 6 +- .../connection/X509AuthenticatorUnitTest.java | 12 +- .../InsufficientStubbingDetectorDemoTest.java | 12 +- .../AsyncOperationHelperSpecification.groovy | 8 +- .../ClientBulkWriteOperationTest.java | 4 +- ...ansactionOperationUnitSpecification.groovy | 6 +- .../operation/CursorResourceManagerTest.java | 8 +- .../ListCollectionsOperationTest.java | 4 +- .../OperationHelperSpecification.groovy | 6 +- .../OperationUnitSpecification.groovy | 6 +- .../SyncOperationHelperSpecification.groovy | 8 +- .../session/BaseClientSessionImplTest.java | 6 +- .../ServerSessionPoolSpecification.groovy | 10 +- .../test/functional/com/mongodb/DBTest.java | 3 +- ...ixedBulkWriteOperationSpecification.groovy | 2 +- .../ClientSessionBindingSpecification.groovy | 8 +- .../ClientSessionBindingSpecification.groovy | 4 +- .../CryptConnectionSpecification.groovy | 6 +- 77 files changed, 451 insertions(+), 463 deletions(-) diff --git a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java index c0f219ee1ea..82d5ff6029f 100644 --- a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java +++ b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java @@ -193,12 +193,12 @@ public static ServerVersion getServerVersion() { if (serverVersion == null) { serverVersion = getVersion(new CommandReadOperation<>("admin", new BsonDocument("buildInfo", new BsonInt32(1)), new BsonDocumentCodec()) - .execute(new ClusterBinding(getCluster(), ReadPreference.nearest()), getOperationContext())); + .execute(new ClusterBinding(getCluster(), ReadPreference.nearest()), createOperationContext())); } return serverVersion; } - public static OperationContext getOperationContext() { + public static OperationContext createOperationContext() { return new OperationContext( IgnorableRequestContext.INSTANCE, new ReadConcernAwareNoOpSessionContext(ReadConcern.DEFAULT), @@ -257,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(), getOperationContext()); + .execute(getBinding(), createOperationContext()); } public static boolean supportsFsync() { @@ -272,7 +272,7 @@ static class ShutdownHook extends Thread { public void run() { if (cluster != null) { try { - new DropDatabaseOperation(getDefaultDatabaseName(), WriteConcern.ACKNOWLEDGED).execute(getBinding(), getOperationContext()); + new DropDatabaseOperation(getDefaultDatabaseName(), WriteConcern.ACKNOWLEDGED).execute(getBinding(), createOperationContext()); } 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")) { @@ -324,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()), getOperationContext()); + .execute(new ClusterBinding(cluster, ReadPreference.nearest()), createOperationContext()); if (helloResult.containsKey("setName")) { connectionString = new ConnectionString(DEFAULT_URI + "/?replicaSet=" + helloResult.getString("setName").getValue()); @@ -384,11 +384,11 @@ public static ReadWriteBinding getBinding(final OperationContext operationContex } public static ReadWriteBinding getBinding(final ReadPreference readPreference) { - return getBinding(getCluster(), readPreference, getOperationContext()); + return getBinding(getCluster(), readPreference, createOperationContext()); } public static OperationContext createNewOperationContext(final TimeoutSettings timeoutSettings) { - return getOperationContext().withTimeoutContext(new TimeoutContext(timeoutSettings)); + return createOperationContext().withTimeoutContext(new TimeoutContext(timeoutSettings)); } private static ReadWriteBinding getBinding(final Cluster cluster, @@ -405,7 +405,7 @@ private static ReadWriteBinding getBinding(final Cluster cluster, } public static SingleConnectionBinding getSingleConnectionBinding() { - return new SingleConnectionBinding(getCluster(), ReadPreference.primary(), getOperationContext()); + return new SingleConnectionBinding(getCluster(), ReadPreference.primary(), createOperationContext()); } public static AsyncSingleConnectionBinding getAsyncSingleConnectionBinding() { @@ -413,7 +413,7 @@ public static AsyncSingleConnectionBinding getAsyncSingleConnectionBinding() { } public static AsyncSingleConnectionBinding getAsyncSingleConnectionBinding(final Cluster cluster) { - return new AsyncSingleConnectionBinding(cluster, ReadPreference.primary(), getOperationContext()); + return new AsyncSingleConnectionBinding(cluster, ReadPreference.primary(), createOperationContext()); } public static AsyncReadWriteBinding getAsyncBinding(final Cluster cluster) { @@ -421,7 +421,7 @@ public static AsyncReadWriteBinding getAsyncBinding(final Cluster cluster) { } public static AsyncReadWriteBinding getAsyncBinding() { - return getAsyncBinding(getAsyncCluster(), ReadPreference.primary(), getOperationContext()); + return getAsyncBinding(getAsyncCluster(), ReadPreference.primary(), createOperationContext()); } public static AsyncReadWriteBinding getAsyncBinding(final TimeoutSettings timeoutSettings) { @@ -433,7 +433,7 @@ public static AsyncReadWriteBinding getAsyncBinding(final OperationContext opera } public static AsyncReadWriteBinding getAsyncBinding(final ReadPreference readPreference) { - return getAsyncBinding(getAsyncCluster(), readPreference, getOperationContext()); + return getAsyncBinding(getAsyncCluster(), readPreference, createOperationContext()); } public static AsyncReadWriteBinding getAsyncBinding( @@ -607,7 +607,7 @@ public static BsonDocument getServerParameters() { if (serverParameters == null) { serverParameters = new CommandReadOperation<>("admin", new BsonDocument("getParameter", new BsonString("*")), new BsonDocumentCodec()) - .execute(getBinding(), getOperationContext()); + .execute(getBinding(), createOperationContext()); } return serverParameters; } @@ -675,7 +675,7 @@ public static void configureFailPoint(final BsonDocument failPointDocument) { if (!isSharded()) { try { new CommandReadOperation<>("admin", failPointDocument, new BsonDocumentCodec()) - .execute(getBinding(), getOperationContext()); + .execute(getBinding(), createOperationContext()); } catch (MongoCommandException e) { if (e.getErrorCode() == COMMAND_NOT_FOUND_ERROR_CODE) { failsPointsSupported = false; @@ -691,7 +691,7 @@ public static void disableFailPoint(final String failPoint) { .append("mode", new BsonString("off")); try { new CommandReadOperation<>("admin", failPointDocument, new BsonDocumentCodec()) - .execute(getBinding(), getOperationContext()); + .execute(getBinding(), createOperationContext()); } catch (MongoCommandException e) { // ignore } @@ -705,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(getOperationContext(), binding.getReadPreference())); + return op.execute(binding, applySessionContext(createOperationContext(), binding.getReadPreference())); } @SuppressWarnings("overloads") @@ -715,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, getOperationContext()); + return op.execute(binding, createOperationContext()); } @SuppressWarnings("overloads") @@ -731,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(getOperationContext(), binding.getReadPreference()), futureResultCallback); + op.executeAsync(binding, applySessionContext(createOperationContext(), binding.getReadPreference()), futureResultCallback); return futureResultCallback.get(TIMEOUT, SECONDS); } @@ -743,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, getOperationContext(), futureResultCallback); + op.executeAsync(binding, createOperationContext(), futureResultCallback); return futureResultCallback.get(TIMEOUT, SECONDS); } @@ -813,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(getOperationContext(), futureResultCallback); + binding.getWriteConnectionSource(createOperationContext(), futureResultCallback); return futureResultCallback.get(TIMEOUT, SECONDS); } public static AsyncConnectionSource getReadConnectionSource(final AsyncReadWriteBinding binding) throws Throwable { FutureResultCallback futureResultCallback = new FutureResultCallback<>(); - binding.getReadConnectionSource(getOperationContext(), futureResultCallback); + binding.getReadConnectionSource(createOperationContext(), futureResultCallback); return futureResultCallback.get(TIMEOUT, SECONDS); } public static AsyncConnection getConnection(final AsyncConnectionSource source) throws Throwable { FutureResultCallback futureResultCallback = new FutureResultCallback<>(); - source.getConnection(getOperationContext(), futureResultCallback); + source.getConnection(createOperationContext(), futureResultCallback); return futureResultCallback.get(TIMEOUT, SECONDS); } @@ -868,7 +868,7 @@ private static OperationContext applySessionContext(final OperationContext opera return operationContext.withSessionContext(simpleSessionContext); } - public static OperationContext getOperationContext(final ReadPreference readPreference) { - return applySessionContext(getOperationContext(), readPreference); + public static OperationContext createOperationContext(final ReadPreference readPreference) { + return applySessionContext(createOperationContext(), readPreference); } } diff --git a/driver-core/src/test/functional/com/mongodb/OperationFunctionalSpecification.groovy b/driver-core/src/test/functional/com/mongodb/OperationFunctionalSpecification.groovy index d670fffe1a3..a0dd685d4b3 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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, getOperationContext()) + ACKNOWLEDGED, false).execute(binding, createOperationContext()) 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 = getOperationContext() + def operationContext = createOperationContext() .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 = getOperationContext() + def operationContext = createOperationContext() .withSessionContext(Stub(SessionContext) { hasActiveTransaction() >> activeTransaction getReadConcern() >> readConcern @@ -447,7 +447,7 @@ class OperationFunctionalSpecification extends Specification { } } - def operationContext = getOperationContext().withSessionContext( + def operationContext = createOperationContext().withSessionContext( Stub(SessionContext) { hasSession() >> true hasActiveTransaction() >> false @@ -488,7 +488,7 @@ class OperationFunctionalSpecification extends Specification { } } - def operationContext = getOperationContext().withSessionContext( + def operationContext = createOperationContext().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 f6bc4c3efe2..e6c28d9d5bc 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 @@ -16,6 +16,7 @@ package com.mongodb.client.test; +import com.mongodb.ClusterFixture; import com.mongodb.MongoClientSettings; import com.mongodb.MongoCommandException; import com.mongodb.MongoNamespace; @@ -72,7 +73,6 @@ import java.util.Optional; import java.util.stream.Collectors; -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(), getOperationContext()); + .execute(getBinding(), ClusterFixture.createOperationContext()); } 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(), getOperationContext()); + new DropCollectionOperation(namespace, writeConcern).execute(getBinding(), ClusterFixture.createOperationContext()); 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(), getOperationContext()); + new DropDatabaseOperation(name, writeConcern).execute(getBinding(), ClusterFixture.createOperationContext()); } 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(), getOperationContext()).getDocument("$clusterTime", null); + .execute(getBinding(), ClusterFixture.createOperationContext()).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(), getOperationContext()); + operation.execute(getBinding(), ClusterFixture.createOperationContext()); 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(), getOperationContext()); + .execute(getBinding(), ClusterFixture.createOperationContext()); } 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, getOperationContext()); + new MixedBulkWriteOperation(namespace, insertRequests, true, writeConcern, false).execute(binding, ClusterFixture.createOperationContext()); } 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(), getOperationContext()); + BatchCursor cursor = listSearchIndexesOperation.execute(getBinding(), ClusterFixture.createOperationContext()); 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(), getOperationContext()); + searchIndexesOperation.execute(getBinding(), ClusterFixture.createOperationContext()); } public List find(final Codec codec) { BatchCursor cursor = new FindOperation<>(namespace, codec) .sort(new BsonDocument("_id", new BsonInt32(1))) - .execute(getBinding(), getOperationContext()); + .execute(getBinding(), ClusterFixture.createOperationContext()); 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(), getOperationContext()); + .execute(getBinding(), ClusterFixture.createOperationContext()); } 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(), getOperationContext()); + .execute(getBinding(), ClusterFixture.createOperationContext()); } 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(), getOperationContext()); + .execute(getBinding(), ClusterFixture.createOperationContext()); } 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(), getOperationContext()); + .execute(getBinding(), ClusterFixture.createOperationContext()); 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(), getOperationContext()); + .projection(projection).execute(getBinding(), ClusterFixture.createOperationContext()); 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, getOperationContext()); + return new CountDocumentsOperation(namespace).execute(binding, ClusterFixture.createOperationContext()); } 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(), getOperationContext()); + .filter(toBsonDocument(filter)).execute(getBinding(), ClusterFixture.createOperationContext()); } 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(), getOperationContext()); + .execute(getBinding(), ClusterFixture.createOperationContext()); } public void createIndex(final Document key) { new CreateIndexesOperation(namespace, singletonList(new IndexRequest(wrap(key))), WriteConcern.ACKNOWLEDGED) - .execute(getBinding(), getOperationContext()); + .execute(getBinding(), ClusterFixture.createOperationContext()); } public void createUniqueIndex(final Document key) { new CreateIndexesOperation(namespace, singletonList(new IndexRequest(wrap(key)).unique(true)), WriteConcern.ACKNOWLEDGED) - .execute(getBinding(), getOperationContext()); + .execute(getBinding(), ClusterFixture.createOperationContext()); } public void createIndex(final Document key, final String defaultLanguage) { new CreateIndexesOperation(namespace, singletonList(new IndexRequest(wrap(key)).defaultLanguage(defaultLanguage)), WriteConcern.ACKNOWLEDGED).execute( - getBinding(), getOperationContext()); + getBinding(), ClusterFixture.createOperationContext()); } public void createIndex(final Bson key) { new CreateIndexesOperation(namespace, singletonList(new IndexRequest(key.toBsonDocument(Document.class, registry))), WriteConcern.ACKNOWLEDGED).execute( - getBinding(), getOperationContext()); + getBinding(), ClusterFixture.createOperationContext()); } public List listIndexes(){ List indexes = new ArrayList<>(); BatchCursor cursor = new ListIndexesOperation<>(namespace, new BsonDocumentCodec()) - .execute(getBinding(), getOperationContext()); + .execute(getBinding(), ClusterFixture.createOperationContext()); 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(), getOperationContext()); + new BsonDocument("killAllSessions", new BsonArray()), new BsonDocumentCodec()).execute(getBinding(), ClusterFixture.createOperationContext()); } 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(), getOperationContext()); + getBinding(), ClusterFixture.createOperationContext()); } 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(), getOperationContext()); + .execute(getBinding(), ClusterFixture.createOperationContext()); } public void runAdminCommand(final BsonDocument command, final ReadPreference readPreference) { new CommandReadOperation<>("admin", command, new BsonDocumentCodec()) - .execute(getBinding(readPreference), getOperationContext()); + .execute(getBinding(readPreference), ClusterFixture.createOperationContext()); } } 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 e4407fc392e..c73f37f8d5f 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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(getOperationContext()) - def connection = source.getConnection(getOperationContext()) + def source = getBinding().getReadConnectionSource(createOperationContext()) + def connection = source.getConnection(createOperationContext()) 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(getOperationContext()) - def connection = source.getConnection(getOperationContext()) + def source = getBinding().getReadConnectionSource(createOperationContext()) + def connection = source.getConnection(createOperationContext()) 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(), getOperationContext()) + new BsonDocumentCodec()).execute(getBinding(), createOperationContext()) } } 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 70130e0f14c..8747b8c75b9 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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(getOperationContext()) + stream.open(createOperationContext()) then: !stream.isClosed() @@ -69,7 +69,7 @@ class NettyStreamSpecification extends Specification { def stream = factory.create(new ServerAddress()) when: - stream.open(getOperationContext()) + stream.open(createOperationContext()) then: thrown(MongoSocketOpenException) @@ -96,7 +96,7 @@ class NettyStreamSpecification extends Specification { def callback = new CallbackErrorHolder() when: - stream.openAsync(getOperationContext(), callback) + stream.openAsync(createOperationContext(), 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 7517fbc2d1c..81ab2ead1e2 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 @@ -26,7 +26,7 @@ class AsyncSessionBindingSpecification extends Specification { given: def wrapped = Mock(AsyncReadWriteBinding) def binding = new AsyncSessionBinding(wrapped) - def operationContext = ClusterFixture.getOperationContext() + def operationContext = ClusterFixture.createOperationContext() when: binding.getCount() 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 76d503583bb..2660693eccf 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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(getOperationContext()) + stream.open(createOperationContext()) then: !stream.isClosed() @@ -66,7 +66,7 @@ class AsyncSocketChannelStreamSpecification extends Specification { def stream = factory.create(new ServerAddress()) when: - stream.open(getOperationContext()) + stream.open(createOperationContext()) then: thrown(MongoSocketOpenException) @@ -90,7 +90,7 @@ class AsyncSocketChannelStreamSpecification extends Specification { def callback = new CallbackErrorHolder() when: - stream.openAsync(getOperationContext(), callback) + stream.openAsync(createOperationContext(), 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 ba5fb45d5e9..fc4cd8be576 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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(getOperationContext()) + connection.open(createOperationContext()) then: thrown(MongoSocketOpenException) @@ -63,7 +63,7 @@ class AsyncStreamTimeoutsSpecification extends OperationFunctionalSpecification new ServerAddress(new InetSocketAddress('192.168.255.255', 27017)))) when: - connection.open(getOperationContext()) + connection.open(createOperationContext()) 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 b4496811dcc..501be77d6d9 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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, getOperationContext()) + getClusterConnectionMode(), null, connection, createOperationContext()) 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, getOperationContext()) + getClusterConnectionMode(), null, connection, createOperationContext()) 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, getOperationContext()) + getClusterConnectionMode(), null, connection, createOperationContext()) 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(getOperationContext(), futureResultCallback) + connection.openAsync(createOperationContext(), futureResultCallback) futureResultCallback.get(ClusterFixture.TIMEOUT, SECONDS) } else { - connection.open(getOperationContext()) + connection.open(createOperationContext()) } } } 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 69397d8db11..e67f5a10b91 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 @@ -32,7 +32,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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext import static com.mongodb.ClusterFixture.getClusterConnectionMode import static com.mongodb.ClusterFixture.getCredentialWithCache import static com.mongodb.ClusterFixture.getPrimary @@ -49,7 +49,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(getOperationContext()) + connection.open(createOperationContext()) } def cleanup() { @@ -64,7 +64,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, getOperationContext()) + getServerApi(), connection, createOperationContext()) { document, exception -> receivedDocument = document; receivedException = exception; latch1.countDown() } latch1.await() @@ -76,7 +76,7 @@ class CommandHelperSpecification extends Specification { when: def latch2 = new CountDownLatch(1) executeCommandAsync('admin', new BsonDocument('non-existent-command', new BsonInt32(1)), getClusterConnectionMode(), - getServerApi(), connection, getOperationContext()) + getServerApi(), connection, createOperationContext()) { 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 026ac22557b..e7ebcebb65a 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 @@ -16,6 +16,7 @@ package com.mongodb.internal.connection; +import com.mongodb.ClusterFixture; import com.mongodb.MongoConnectionPoolClearedException; import com.mongodb.MongoServerUnavailableException; import com.mongodb.ServerAddress; @@ -60,7 +61,6 @@ import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Stream; -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(getOperationContext())); + exception = assertThrows(MongoServerUnavailableException.class, () -> provider.get(ClusterFixture.createOperationContext())); 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(getOperationContext()).close(); + provider.get(ClusterFixture.createOperationContext()).close(); sleep(100); provider.doMaintenance(); - provider.get(getOperationContext()); + provider.get(ClusterFixture.createOperationContext()); // 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(getOperationContext()); + InternalConnection connection = provider.get(ClusterFixture.createOperationContext()); sleep(50); connection.close(); @@ -236,10 +236,10 @@ public void shouldExpireConnectionAfterMaxIdleTime() throws InterruptedException provider.ready(); // when - provider.get(getOperationContext()).close(); + provider.get(ClusterFixture.createOperationContext()).close(); sleep(100); provider.doMaintenance(); - provider.get(getOperationContext()); + provider.get(ClusterFixture.createOperationContext()); // 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(getOperationContext()).close(); + provider.get(ClusterFixture.createOperationContext()).close(); sleep(50); provider.doMaintenance(); - provider.get(getOperationContext()); + provider.get(ClusterFixture.createOperationContext()); // then assertTrue(connectionFactory.getCreatedConnections().get(0).isClosed()); @@ -280,10 +280,10 @@ public void shouldCreateNewConnectionAfterExpiration() throws InterruptedExcepti provider.ready(); // when - provider.get(getOperationContext()).close(); + provider.get(ClusterFixture.createOperationContext()).close(); sleep(50); provider.doMaintenance(); - InternalConnection secondConnection = provider.get(getOperationContext()); + InternalConnection secondConnection = provider.get(ClusterFixture.createOperationContext()); // then assertNotNull(secondConnection); @@ -302,7 +302,7 @@ public void shouldPruneAfterMaintenanceTaskRuns() throws InterruptedException { .build(), mockSdamProvider(), OPERATION_CONTEXT_FACTORY); provider.ready(); - provider.get(getOperationContext()).close(); + provider.get(ClusterFixture.createOperationContext()).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(getOperationContext())); + connections.add(provider.get(ClusterFixture.createOperationContext())); } } 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 e514a3fd0d3..fa649022aaa 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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, getOperationContext()) + getClusterConnectionMode(), null, connection, createOperationContext()) 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, getOperationContext()) + getClusterConnectionMode(), null, connection, createOperationContext()) 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, getOperationContext()) + getClusterConnectionMode(), null, connection, createOperationContext()) 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, getOperationContext()) + getClusterConnectionMode(), null, connection, createOperationContext()) 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, getOperationContext()) + getClusterConnectionMode(), null, connection, createOperationContext()) 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(getOperationContext(), futureResultCallback) + connection.openAsync(createOperationContext(), futureResultCallback) futureResultCallback.get(ClusterFixture.TIMEOUT, SECONDS) } else { - connection.open(getOperationContext()) + connection.open(createOperationContext()) } } } 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 2b5dcb112d5..f7fd3534960 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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(getOperationContext()) + internalConnection.open(createOperationContext()) 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 dd44aea3abd..b1078711f7d 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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, getOperationContext()) + getClusterConnectionMode(), null, connection, createOperationContext()) 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, getOperationContext()) + getClusterConnectionMode(), null, connection, createOperationContext()) 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, getOperationContext()) + getClusterConnectionMode(), null, connection, createOperationContext()) 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(getOperationContext(), futureResultCallback) + connection.openAsync(createOperationContext(), futureResultCallback) futureResultCallback.get(ClusterFixture.TIMEOUT, SECONDS) } else { - connection.open(getOperationContext()) + connection.open(createOperationContext()) } } } 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 93836fc895b..6fb9f48d078 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 @@ -16,6 +16,7 @@ package com.mongodb.internal.connection; +import com.mongodb.ClusterFixture; import com.mongodb.LoggerSettings; import com.mongodb.MongoCredential; import com.mongodb.MongoSecurityException; @@ -33,7 +34,6 @@ import java.util.Collections; import static com.mongodb.ClusterFixture.CLIENT_METADATA; -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, getOperationContext()); + authenticator.authenticate(internalConnection, connectionDescription, ClusterFixture.createOperationContext()); } @Test(expected = MongoSecurityException.class) public void testUnsuccessfulAuthentication() { PlainAuthenticator authenticator = new PlainAuthenticator(getCredentialWithCache(userName, source, "wrong".toCharArray()), getClusterConnectionMode(), getServerApi()); - authenticator.authenticate(internalConnection, connectionDescription, getOperationContext()); + authenticator.authenticate(internalConnection, connectionDescription, ClusterFixture.createOperationContext()); } 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 917f5f82404..b5baa3837f3 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext import static com.mongodb.ClusterFixture.createAsyncCluster import static com.mongodb.ClusterFixture.createCluster import static com.mongodb.ClusterFixture.getBinding @@ -88,12 +88,12 @@ class ScramSha256AuthenticationSpecification extends Specification { def binding = getBinding() new CommandReadOperation<>('admin', new BsonDocumentWrapper(createUserCommand, new DocumentCodec()), new DocumentCodec()) - .execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + .execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) } def dropUser(final String userName) { def binding = getBinding() - def operationContext = ClusterFixture.getOperationContext(binding.getReadPreference()) + def operationContext = ClusterFixture.createOperationContext(binding.getReadPreference()) new CommandReadOperation<>('admin', new BsonDocument('dropUser', new BsonString(userName)), new BsonDocumentCodec()).execute(binding, operationContext) } @@ -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()), getOperationContext()) + .execute(new ClusterBinding(cluster, ReadPreference.primary()), createOperationContext()) 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, getOperationContext(), callback) + .executeAsync(binding, createOperationContext(), 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()), getOperationContext()) + .execute(new ClusterBinding(cluster, ReadPreference.primary()), createOperationContext()) 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()), getOperationContext(), + .executeAsync(new AsyncClusterBinding(cluster, ReadPreference.primary()), createOperationContext(), 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()), getOperationContext()) + .execute(new ClusterBinding(cluster, ReadPreference.primary()), createOperationContext()) 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()), getOperationContext(), + .executeAsync(new AsyncClusterBinding(cluster, ReadPreference.primary()), createOperationContext(), 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 bc5fffaf9e4..8e9b2385ee5 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,6 @@ import com.mongodb.internal.binding.AsyncConnectionSource; import com.mongodb.internal.selector.ServerAddressSelector; -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 +53,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), getOperationContext()).getServer()); + cluster.selectServer(new ServerAddressSelector(address), ClusterFixture.createOperationContext()).getServer()); long startTime = System.currentTimeMillis(); while (pool.getInUseCount() > 0) { try { @@ -70,7 +69,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), getOperationContext()).getServer()); + return connectionPool(cluster.selectServer(new ServerAddressSelector(address), ClusterFixture.createOperationContext()).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 703647bb645..a624a27454c 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 @@ -16,6 +16,7 @@ package com.mongodb.internal.connection; +import com.mongodb.ClusterFixture; import com.mongodb.LoggerSettings; import com.mongodb.ReadPreference; import com.mongodb.ServerAddress; @@ -37,7 +38,6 @@ import java.util.Collections; import static com.mongodb.ClusterFixture.CLIENT_METADATA; -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), getOperationContext()); + ServerTuple serverTuple = cluster.selectServer(clusterDescription -> getPrimaries(clusterDescription), ClusterFixture.createOperationContext()); // then assertTrue(serverTuple.getServerDescription().isOk()); @@ -102,7 +102,7 @@ public void shouldGetServerWithOkDescription() { @Test public void shouldSuccessfullyQueryASecondaryWithPrimaryReadPreference() { // given - OperationContext operationContext = getOperationContext(); + OperationContext operationContext = ClusterFixture.createOperationContext(); 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 2368d3bbff8..ef0e7d09264 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,6 @@ import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory import java.lang.reflect.Method -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 +86,7 @@ class SocketStreamHelperSpecification extends Specification { when: SocketStreamHelper.initialize( - getOperationContext().withTimeoutContext(new TimeoutContext( + createOperationContext().withTimeoutContext(new TimeoutContext( new TimeoutSettings( 1, 100, @@ -110,7 +109,7 @@ class SocketStreamHelperSpecification extends Specification { Socket socket = SocketFactory.default.createSocket() when: - SocketStreamHelper.initialize(getOperationContext(), socket, getSocketAddresses(getPrimary(), + SocketStreamHelper.initialize(createOperationContext(), socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), SocketSettings.builder().build(), SslSettings.builder().build()) @@ -127,7 +126,7 @@ class SocketStreamHelperSpecification extends Specification { SSLSocket socket = SSLSocketFactory.default.createSocket() when: - SocketStreamHelper.initialize(getOperationContext(), socket, getSocketAddresses(getPrimary(), + SocketStreamHelper.initialize(createOperationContext(), socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), SocketSettings.builder().build(), sslSettings) @@ -149,7 +148,7 @@ class SocketStreamHelperSpecification extends Specification { SSLSocket socket = SSLSocketFactory.default.createSocket() when: - SocketStreamHelper.initialize(getOperationContext(), socket, getSocketAddresses(getPrimary(), + SocketStreamHelper.initialize(createOperationContext(), socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), SocketSettings.builder().build(), sslSettings) @@ -169,7 +168,7 @@ class SocketStreamHelperSpecification extends Specification { Socket socket = SocketFactory.default.createSocket() when: - SocketStreamHelper.initialize(getOperationContext(), socket, getSocketAddresses(getPrimary(), + SocketStreamHelper.initialize(createOperationContext(), socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), SocketSettings.builder().build(), SslSettings.builder().enabled(true).build()) 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 8f3038085ef..520dd3932de 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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(getOperationContext()) + socketStream.open(createOperationContext()) then: !socket0.isConnected() @@ -83,7 +83,7 @@ class StreamSocketAddressSpecification extends Specification { def socketStream = new SocketStream(serverAddress, inetAddressResolver, socketSettings, sslSettings, socketFactory, bufferProvider) when: - socketStream.open(getOperationContext()) + socketStream.open(createOperationContext()) 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 0c41af7cb8f..46e0cc6f964 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.getOperationContext()); + stream.open(ClusterFixture.createOperationContext()); ByteBuf wrap = new ByteBufNIO(ByteBuffer.wrap(new byte[]{1, 3, 4})); //when - stream.write(Collections.singletonList(wrap), ClusterFixture.getOperationContext()); + stream.write(Collections.singletonList(wrap), ClusterFixture.createOperationContext()); //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 89da1e2c990..7ddc5a83e97 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 @@ -56,7 +56,7 @@ import static com.mongodb.ClusterFixture.collectCursorResults import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.ClusterFixture.getAsyncCluster import static com.mongodb.ClusterFixture.getCluster -import static com.mongodb.ClusterFixture.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext import static com.mongodb.ClusterFixture.isSharded import static com.mongodb.ClusterFixture.isStandalone import static com.mongodb.ExplainVerbosity.QUERY_PLANNER @@ -231,7 +231,7 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification { def binding = ClusterFixture.getBinding(ClusterFixture.getCluster()) new CreateViewOperation(getDatabaseName(), viewName, getCollectionName(), [], WriteConcern.ACKNOWLEDGED) - .execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + .execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) when: AggregateOperation operation = new AggregateOperation(viewNamespace, [], new DocumentCodec()) @@ -245,7 +245,7 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification { cleanup: binding = ClusterFixture.getBinding(ClusterFixture.getCluster()) new DropCollectionOperation(viewNamespace, WriteConcern.ACKNOWLEDGED) - .execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + .execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) where: async << [true, false] @@ -272,7 +272,7 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification { .allowDiskUse(allowDiskUse) def binding = ClusterFixture.getBinding() - def cursor = operation.execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) then: cursor.next()*.getString('name') == ['Pete', 'Sam', 'Pete'] @@ -287,7 +287,7 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification { .batchSize(batchSize) def binding = ClusterFixture.getBinding() - def cursor = operation.execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) then: cursor.next()*.getString('name') == ['Pete', 'Sam', 'Pete'] @@ -380,7 +380,7 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification { def 'should add read concern to command'() { given: - def operationContext = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().withSessionContext(sessionContext) def binding = Stub(ReadBinding) def source = Stub(ConnectionSource) def connection = Mock(Connection) @@ -422,7 +422,7 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification { def 'should add read concern to command asynchronously'() { given: - def operationContext = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().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/AggregateToCollectionOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateToCollectionOperationSpecification.groovy index 6ebdcdc6b40..a14c4323fdd 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateToCollectionOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/AggregateToCollectionOperationSpecification.groovy @@ -278,7 +278,7 @@ class AggregateToCollectionOperationSpecification extends OperationFunctionalSpe def profileCollectionHelper = getCollectionHelper(new MongoNamespace(getDatabaseName(), 'system.profile')) def binding = getBinding() new CommandReadOperation<>(getDatabaseName(), new BsonDocument('profile', new BsonInt32(2)), - new BsonDocumentCodec()).execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + new BsonDocumentCodec()).execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) def expectedComment = 'this is a comment' AggregateToCollectionOperation operation = createOperation(getNamespace(), [Aggregates.out('outputCollection').toBsonDocument(BsonDocument, registry)], ACKNOWLEDGED) @@ -293,7 +293,7 @@ class AggregateToCollectionOperationSpecification extends OperationFunctionalSpe cleanup: new CommandReadOperation<>(getDatabaseName(), new BsonDocument('profile', new BsonInt32(0)), - new BsonDocumentCodec()).execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + new BsonDocumentCodec()).execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) profileCollectionHelper.drop() where: 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 b6f54e7d39c..103a18df32e 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 @@ -17,6 +17,7 @@ package com.mongodb.internal.operation; +import com.mongodb.ClusterFixture; import com.mongodb.MongoCursorNotFoundException; import com.mongodb.MongoQueryException; import com.mongodb.ReadPreference; @@ -55,7 +56,6 @@ import java.util.stream.IntStream; import java.util.stream.Stream; -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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, maxTimeMS, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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, getOperationContext(), + cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), 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(), getOperationContext(), cb)); + NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), new BsonDocumentCodec(), ClusterFixture.createOperationContext(), 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), - getOperationContext(), cb)); + ClusterFixture.createOperationContext(), 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 fe70b7f3688..f2374e92160 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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 = getOperationContext().withSessionContext( + def operationContext = createOperationContext().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 = getOperationContext().withSessionContext( + def operationContext = createOperationContext().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 5fc6518d7af..21e903abc34 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,6 @@ import java.util.stream.IntStream; import java.util.stream.Stream; -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 +86,8 @@ void setup() { .collect(Collectors.toList()); getCollectionHelper().insertDocuments(documents); - connectionSource = getBinding().getWriteConnectionSource(ClusterFixture.getOperationContext()); - connection = connectionSource.getConnection(ClusterFixture.getOperationContext()); + connectionSource = getBinding().getWriteConnectionSource(ClusterFixture.createOperationContext()); + connection = connectionSource.getConnection(ClusterFixture.createOperationContext()); } @AfterEach @@ -109,7 +108,7 @@ void cleanup() { void shouldExhaustCursorWithMultipleBatches() { // given BsonDocument commandResult = executeFindCommand(0, 3); // Fetch in batches of size 3 - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); // when @@ -127,7 +126,7 @@ void shouldExhaustCursorWithMultipleBatches() { void shouldExhaustCursorWithClosedCursor() { // given BsonDocument commandResult = executeFindCommand(0, 3); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); cursor.close(); @@ -143,7 +142,7 @@ void shouldExhaustCursorWithEmptyCursor() { getCollectionHelper().deleteMany(Filters.empty()); BsonDocument commandResult = executeFindCommand(0, 3); // No documents to fetch - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); // when @@ -157,7 +156,7 @@ void shouldExhaustCursorWithEmptyCursor() { @DisplayName("server cursor should not be null") void theServerCursorShouldNotBeNull() { BsonDocument commandResult = executeFindCommand(2); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertNotNull(cursor.getServerCursor()); @@ -167,7 +166,7 @@ void theServerCursorShouldNotBeNull() { @DisplayName("test server address should not be null") void theServerAddressShouldNotNull() { BsonDocument commandResult = executeFindCommand(); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertNotNull(cursor.getServerAddress()); @@ -177,7 +176,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, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); cursor.close(); @@ -192,7 +191,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, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); cursor.next(); @@ -204,7 +203,7 @@ void shouldThrowAnExceptionWhenGoingOffTheEnd() { @DisplayName("test cursor remove") void testCursorRemove() { BsonDocument commandResult = executeFindCommand(); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertThrows(UnsupportedOperationException.class, () -> cursor.remove()); @@ -214,7 +213,7 @@ void testCursorRemove() { @DisplayName("test normal exhaustion") void testNormalExhaustion() { BsonDocument commandResult = executeFindCommand(); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(10, cursorFlatten().size()); @@ -225,7 +224,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, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(expectedTotal, cursorFlatten().size()); @@ -244,7 +243,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, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, maxTimeMS, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertTrue(cursor.hasNext()); @@ -267,7 +266,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, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); List nextBatch = cursor.tryNext(); @@ -293,7 +292,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, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertTrue(cursor.hasNext()); @@ -320,7 +319,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, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, maxTimeMS, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); List nextBatch = cursor.tryNext(); @@ -344,7 +343,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, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); CountDownLatch latch = new CountDownLatch(1); @@ -377,7 +376,7 @@ void testTailableInterrupt() throws InterruptedException { void shouldKillCursorIfLimitIsReachedOnInitialQuery() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 10); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertNotNull(cursor.next()); @@ -390,7 +389,7 @@ void shouldKillCursorIfLimitIsReachedOnInitialQuery() { void shouldKillCursorIfLimitIsReachedOnGetMore() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 3); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); ServerCursor serverCursor = cursor.getServerCursor(); @@ -409,7 +408,7 @@ void shouldKillCursorIfLimitIsReachedOnGetMore() { void shouldReleaseConnectionSourceIfLimitIsReachedOnInitialQuery() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 10); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertNull(cursor.getServerCursor()); @@ -422,7 +421,7 @@ void shouldReleaseConnectionSourceIfLimitIsReachedOnInitialQuery() { void shouldReleaseConnectionSourceIfLimitIsReachedOnGetMore() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 3); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection)); assertNotNull(cursor.next()); @@ -435,7 +434,7 @@ void shouldReleaseConnectionSourceIfLimitIsReachedOnGetMore() { @DisplayName("test limit with get more") void testLimitWithGetMore() { BsonDocument commandResult = executeFindCommand(5, 2); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertNotNull(cursor.next()); @@ -456,7 +455,7 @@ void testLimitWithLargeDocuments() { ); BsonDocument commandResult = executeFindCommand(300, 0); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(300, cursorFlatten().size()); @@ -466,7 +465,7 @@ void testLimitWithLargeDocuments() { @DisplayName("should respect batch size") void shouldRespectBatchSize() { BsonDocument commandResult = executeFindCommand(2); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(2, cursor.getBatchSize()); @@ -483,16 +482,16 @@ void shouldRespectBatchSize() { @DisplayName("should throw cursor not found exception") void shouldThrowCursorNotFoundException() { BsonDocument commandResult = executeFindCommand(2); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); ServerCursor serverCursor = cursor.getServerCursor(); assertNotNull(serverCursor); - Connection localConnection = connectionSource.getConnection(getOperationContext()); + Connection localConnection = connectionSource.getConnection(ClusterFixture.createOperationContext()); 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(), getOperationContext()); + NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), new BsonDocumentCodec(), ClusterFixture.createOperationContext()); localConnection.release(); cursor.next(); @@ -506,7 +505,7 @@ void shouldThrowCursorNotFoundException() { @DisplayName("should report available documents") void shouldReportAvailableDocuments() { BsonDocument commandResult = executeFindCommand(3); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, getOperationContext(), + cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection)); assertEquals(3, cursor.available()); @@ -584,7 +583,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), - getOperationContext()); + ClusterFixture.createOperationContext()); 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 438632014c6..dc9746053c3 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.connection.ServerType.STANDALONE import static com.mongodb.internal.operation.OperationReadConcernHelper.appendReadConcernToCommand @@ -156,7 +156,7 @@ class CountDocumentsOperationSpecification extends OperationFunctionalSpecificat def binding = ClusterFixture.getBinding() new CreateIndexesOperation(getNamespace(), [new IndexRequest(indexDefinition).sparse(true)], null) - .execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + .execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) def operation = new CountDocumentsOperation(getNamespace()).hint(indexDefinition) when: @@ -259,7 +259,7 @@ class CountDocumentsOperationSpecification extends OperationFunctionalSpecificat def 'should add read concern to command'() { given: - def operationContext = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().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 = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().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/CreateCollectionOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/CreateCollectionOperationSpecification.groovy index 860ffb4a2bf..a0b80cc178a 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/CreateCollectionOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/CreateCollectionOperationSpecification.groovy @@ -113,7 +113,7 @@ class CreateCollectionOperationSpecification extends OperationFunctionalSpecific then: def binding = ClusterFixture.getBinding() new ListCollectionsOperation(getDatabaseName(), new BsonDocumentCodec()) - .execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + .execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) .next() .find { it -> it.getString('name').value == getCollectionName() } .getDocument('options').getDocument('storageEngine') == operation.storageEngineOptions @@ -134,7 +134,7 @@ class CreateCollectionOperationSpecification extends OperationFunctionalSpecific then: def binding = ClusterFixture.getBinding() new ListCollectionsOperation(getDatabaseName(), new BsonDocumentCodec()) - .execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + .execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) .next() .find { it -> it.getString('name').value == getCollectionName() } .getDocument('options').getDocument('storageEngine') == operation.storageEngineOptions @@ -255,7 +255,7 @@ class CreateCollectionOperationSpecification extends OperationFunctionalSpecific def binding = getBinding() new ListCollectionsOperation(databaseName, new BsonDocumentCodec()).filter(new BsonDocument('name', new BsonString(collectionName))).execute(binding, - ClusterFixture.getOperationContext(binding.getReadPreference())).tryNext()?.head() + ClusterFixture.createOperationContext(binding.getReadPreference())).tryNext()?.head() } def collectionNameExists(String collectionName) { @@ -268,13 +268,13 @@ class CreateCollectionOperationSpecification extends OperationFunctionalSpecific def binding = getBinding() return new CommandReadOperation<>(getDatabaseName(), new BsonDocument('collStats', new BsonString(getCollectionName())), - new BsonDocumentCodec()).execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + new BsonDocumentCodec()).execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) } def binding = ClusterFixture.getBinding() BatchCursor cursor = new AggregateOperation( getNamespace(), singletonList(new BsonDocument('$collStats', new BsonDocument('storageStats', new BsonDocument()))), - new BsonDocumentCodec()).execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + new BsonDocumentCodec()).execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) try { return cursor.next().first().getDocument('storageStats') } finally { diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/CreateIndexesOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/CreateIndexesOperationSpecification.groovy index fce0904b786..5365f19f1de 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/CreateIndexesOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/CreateIndexesOperationSpecification.groovy @@ -494,7 +494,7 @@ class CreateIndexesOperationSpecification extends OperationFunctionalSpecificati def binding = ClusterFixture.getBinding() def cursor = new ListIndexesOperation(getNamespace(), new DocumentCodec()) - .execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + .execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) while (cursor.hasNext()) { indexes.addAll(cursor.next()) } diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/CreateViewOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/CreateViewOperationSpecification.groovy index b8145de44b4..7877fd653a5 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/CreateViewOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/CreateViewOperationSpecification.groovy @@ -30,7 +30,6 @@ import org.bson.codecs.BsonDocumentCodec import spock.lang.IgnoreIf import static com.mongodb.ClusterFixture.getBinding -import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet class CreateViewOperationSpecification extends OperationFunctionalSpecification { 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 16c8fcb281e..66936080558 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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 = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().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 = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().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/DropCollectionOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/DropCollectionOperationSpecification.groovy index eb8f3efa573..703d0e14212 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/DropCollectionOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/DropCollectionOperationSpecification.groovy @@ -39,7 +39,7 @@ class DropCollectionOperationSpecification extends OperationFunctionalSpecificat when: def binding = getBinding() new DropCollectionOperation(getNamespace(), WriteConcern.ACKNOWLEDGED) - .execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + .execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) then: !collectionNameExists(getCollectionName()) @@ -64,7 +64,7 @@ class DropCollectionOperationSpecification extends OperationFunctionalSpecificat when: new DropCollectionOperation(namespace, WriteConcern.ACKNOWLEDGED) - .execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + .execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) then: !collectionNameExists('nonExistingCollection') @@ -91,7 +91,7 @@ class DropCollectionOperationSpecification extends OperationFunctionalSpecificat when: def binding = getBinding() - async ? executeAsync(operation) : operation.execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + async ? executeAsync(operation) : operation.execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) then: def ex = thrown(MongoWriteConcernException) @@ -104,7 +104,7 @@ class DropCollectionOperationSpecification extends OperationFunctionalSpecificat def collectionNameExists(String collectionName) { def cursor = new ListCollectionsOperation(databaseName, new DocumentCodec()) - .execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + .execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) if (!cursor.hasNext()) { return false } diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/DropDatabaseOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/DropDatabaseOperationSpecification.groovy index b56e2c1fe50..8cecd74e468 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/DropDatabaseOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/DropDatabaseOperationSpecification.groovy @@ -28,7 +28,6 @@ import spock.lang.IgnoreIf import static com.mongodb.ClusterFixture.configureFailPoint import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.ClusterFixture.getBinding -import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet import static com.mongodb.ClusterFixture.isSharded diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/DropIndexOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/DropIndexOperationSpecification.groovy index 7b1f5b2a392..0aff76df1cb 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/DropIndexOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/DropIndexOperationSpecification.groovy @@ -159,7 +159,7 @@ class DropIndexOperationSpecification extends OperationFunctionalSpecification { def indexes = [] def binding = getBinding() def cursor = new ListIndexesOperation(getNamespace(), new DocumentCodec()) - .execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + .execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) while (cursor.hasNext()) { indexes.addAll(cursor.next()) } 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 e49128b0481..1b8490632c3 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 @@ -59,7 +59,7 @@ import static com.mongodb.ClusterFixture.executeSync import static com.mongodb.ClusterFixture.getAsyncCluster import static com.mongodb.ClusterFixture.getBinding import static com.mongodb.ClusterFixture.getCluster -import static com.mongodb.ClusterFixture.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext import static com.mongodb.ClusterFixture.isSharded import static com.mongodb.ClusterFixture.serverVersionLessThan import static com.mongodb.CursorType.NonTailable @@ -481,7 +481,7 @@ class FindOperationSpecification extends OperationFunctionalSpecification { def 'should add read concern to command'() { given: - def operationContext = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().withSessionContext(sessionContext) def binding = Stub(ReadBinding) def source = Stub(ConnectionSource) def connection = Mock(Connection) @@ -521,7 +521,7 @@ class FindOperationSpecification extends OperationFunctionalSpecification { def 'should add read concern to command asynchronously'() { given: - def operationContext = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().withSessionContext(sessionContext) def binding = Stub(AsyncReadBinding) def source = Stub(AsyncConnectionSource) def connection = Mock(AsyncConnection) @@ -561,7 +561,7 @@ class FindOperationSpecification extends OperationFunctionalSpecification { def 'should add allowDiskUse to command if the server version >= 3.2'() { given: - def operationContext = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().withSessionContext(sessionContext) def binding = Stub(ReadBinding) def source = Stub(ConnectionSource) def connection = Mock(Connection) @@ -601,7 +601,7 @@ class FindOperationSpecification extends OperationFunctionalSpecification { def 'should add allowDiskUse to command if the server version >= 3.2 asynchronously'() { given: - def operationContext = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().withSessionContext(sessionContext) def binding = Stub(AsyncReadBinding) def source = Stub(AsyncConnectionSource) def connection = Mock(AsyncConnection) @@ -645,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 = getOperationContext().withTimeoutContext(timeoutContext) + def operationContext = createOperationContext().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 b30983a81c5..aa27242dd8c 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 @@ -46,7 +46,6 @@ import org.bson.codecs.DocumentCodec import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.ClusterFixture.getBinding -import static com.mongodb.ClusterFixture.getOperationContext import static org.junit.jupiter.api.Assertions.assertEquals class ListCollectionsOperationSpecification extends OperationFunctionalSpecification { @@ -398,7 +397,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def 'should use the readPreference to set secondaryOk'() { given: - def operationContext = ClusterFixture.getOperationContext() + def operationContext = ClusterFixture.createOperationContext() def connection = Mock(Connection) def connectionSource = Stub(ConnectionSource) { getConnection(_) >> connection @@ -427,7 +426,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def 'should use the readPreference to set secondaryOk in async'() { given: - def operationContext = ClusterFixture.getOperationContext() + def operationContext = ClusterFixture.createOperationContext() def connection = Mock(AsyncConnection) def connectionSource = Stub(AsyncConnectionSource) { getConnection(_, _) >> { it[1].onResult(connection, null) } 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 bbdce7425a8..a6ed542bde2 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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, getOperationContext()) + operation.execute(readBinding, createOperationContext()) then: _ * connection.getDescription() >> helper.connectionDescription @@ -107,7 +107,7 @@ class ListDatabasesOperationSpecification extends OperationFunctionalSpecificati def operation = new ListDatabasesOperation(helper.decoder) when: - operation.executeAsync(readBinding, getOperationContext(), Stub(SingleResultCallback)) + operation.executeAsync(readBinding, createOperationContext(), 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 81766ae81d4..e22fcd6d396 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 @@ -46,7 +46,7 @@ import org.junit.jupiter.api.Assertions import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.ClusterFixture.getBinding -import static com.mongodb.ClusterFixture.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext class ListIndexesOperationSpecification extends OperationFunctionalSpecification { @@ -225,7 +225,7 @@ class ListIndexesOperationSpecification extends OperationFunctionalSpecification def 'should use the readPreference to set secondaryOk'() { given: def connection = Mock(Connection) - def operationContext = ClusterFixture.getOperationContext() + def operationContext = ClusterFixture.createOperationContext() def connectionSource = Stub(ConnectionSource) { getConnection(_) >> connection getReadPreference() >> readPreference @@ -265,7 +265,7 @@ class ListIndexesOperationSpecification extends OperationFunctionalSpecification def operation = new ListIndexesOperation(helper.namespace, helper.decoder) when: '3.6.0' - operation.executeAsync(readBinding, getOperationContext(), Stub(SingleResultCallback)) + operation.executeAsync(readBinding, createOperationContext(), Stub(SingleResultCallback)) then: _ * connection.getDescription() >> helper.threeSixConnectionDescription diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/MapReduceToCollectionOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/MapReduceToCollectionOperationSpecification.groovy index 5d6be781d1f..31f8ed45715 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/MapReduceToCollectionOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/MapReduceToCollectionOperationSpecification.groovy @@ -64,7 +64,7 @@ class MapReduceToCollectionOperationSpecification extends OperationFunctionalSpe def cleanup() { def binding = getBinding() - def operationContext = ClusterFixture.getOperationContext(binding.getReadPreference()) + def operationContext = ClusterFixture.createOperationContext(binding.getReadPreference()) new DropCollectionOperation(mapReduceInputNamespace, WriteConcern.ACKNOWLEDGED) .execute(binding, operationContext) new DropCollectionOperation(mapReduceOutputNamespace, WriteConcern.ACKNOWLEDGED) 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 5215fa78c37..14ee33d7ec5 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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 = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().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 = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().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/RenameCollectionOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/RenameCollectionOperationSpecification.groovy index bc55bf5a134..e79f35b76ee 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/RenameCollectionOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/RenameCollectionOperationSpecification.groovy @@ -28,7 +28,6 @@ import spock.lang.IgnoreIf import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.ClusterFixture.getBinding -import static com.mongodb.ClusterFixture.getOperationContext import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet import static com.mongodb.ClusterFixture.isSharded 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 0e18016a556..2565521deb7 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 @@ -16,6 +16,7 @@ package com.mongodb.internal.operation; +import com.mongodb.ClusterFixture; import com.mongodb.MongoCommandException; import com.mongodb.MongoCursorNotFoundException; import com.mongodb.MongoNamespace; @@ -31,8 +32,6 @@ import org.bson.BsonString; import org.bson.codecs.BsonDocumentCodec; -import static com.mongodb.ClusterFixture.getOperationContext; - final class TestOperationHelper { static BsonDocument getKeyPattern(final BsonDocument explainPlan) { @@ -56,7 +55,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(), getOperationContext())); + NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), new BsonDocumentCodec(), ClusterFixture.createOperationContext())); } static void makeAdditionalGetMoreCall(final MongoNamespace namespace, final ServerCursor serverCursor, @@ -66,7 +65,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(), getOperationContext(), callback); + NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), new BsonDocumentCodec(), ClusterFixture.createOperationContext(), callback); callback.get(); }); } 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 19f25dc6baa..64bd904aaed 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext class SingleServerBindingSpecification extends Specification { @@ -68,7 +68,7 @@ class SingleServerBindingSpecification extends Specification { binding.count == 1 when: - def source = binding.getReadConnectionSource(getOperationContext()) + def source = binding.getReadConnectionSource(createOperationContext()) then: source.count == 1 @@ -96,7 +96,7 @@ class SingleServerBindingSpecification extends Specification { binding.count == 1 when: - source = binding.getWriteConnectionSource(getOperationContext()) + source = binding.getWriteConnectionSource(createOperationContext()) 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 b92628aa827..deaeacafb07 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,6 @@ import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; -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 +541,7 @@ private Event getNextEvent(final Iterator eventsIterator, final private static void executeAdminCommand(final BsonDocument command) { new CommandReadOperation<>("admin", command, new BsonDocumentCodec()) - .execute(ClusterFixture.getBinding(), getOperationContext()); + .execute(ClusterFixture.getBinding(), ClusterFixture.createOperationContext()); } 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 3a233e7c6e7..0769939fd2a 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 @@ -16,6 +16,7 @@ package com.mongodb.internal.connection; +import com.mongodb.ClusterFixture; import com.mongodb.ConnectionString; import com.mongodb.MongoSocketReadException; import com.mongodb.MongoSocketReadTimeoutException; @@ -43,7 +44,6 @@ import java.util.concurrent.TimeUnit; import static com.mongodb.ClusterFixture.CLIENT_METADATA; -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 = getOperationContext().getTimeoutContext().computeServerSelectionTimeout(); + Timeout serverSelectionTimeout = ClusterFixture.createOperationContext().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, - getOperationContext().getTimeoutContext()); + ClusterFixture.createOperationContext().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 6016ee1d1e2..25a1b904e1f 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,6 @@ import spock.lang.Specification import java.util.concurrent.CountDownLatch import static com.mongodb.ClusterFixture.CLIENT_METADATA -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 +134,7 @@ class BaseClusterSpecification extends Specification { factory.sendNotification(thirdServer, REPLICA_SET_PRIMARY, allServers) expect: - cluster.selectServer(new ReadPreferenceServerSelector(ReadPreference.secondary()), getOperationContext()) + cluster.selectServer(new ReadPreferenceServerSelector(ReadPreference.secondary()), createOperationContext()) .serverDescription.address == firstServer } @@ -171,7 +170,7 @@ class BaseClusterSpecification extends Specification { factory.sendNotification(thirdServer, 1, REPLICA_SET_PRIMARY, allServers) expect: - cluster.selectServer(new ReadPreferenceServerSelector(ReadPreference.nearest()), getOperationContext()) + cluster.selectServer(new ReadPreferenceServerSelector(ReadPreference.nearest()), createOperationContext()) .serverDescription.address == firstServer } @@ -189,7 +188,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()), getOperationContext()) + cluster.selectServer(new ReadPreferenceServerSelector(ReadPreference.secondary()), createOperationContext()) .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 60c7bd3d81d..d1e6c454bc9 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.getOperationContext().getServerDeprioritization(), + ClusterFixture.createOperationContext().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 32937fc863e..3872f6cb1e2 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,6 @@ import java.util.concurrent.CountDownLatch import java.util.regex.Matcher import java.util.regex.Pattern -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 +77,7 @@ class DefaultConnectionPoolSpecification extends Specification { pool.ready() expect: - pool.get(getOperationContext()) != null + pool.get(createOperationContext()) != null } def 'should reuse released connection'() throws InterruptedException { @@ -86,7 +85,7 @@ class DefaultConnectionPoolSpecification extends Specification { pool = new DefaultConnectionPool(SERVER_ID, connectionFactory, builder().maxSize(1).build(), mockSdamProvider(), OPERATION_CONTEXT_FACTORY) pool.ready() - def operationContext = getOperationContext() + def operationContext = createOperationContext() when: pool.get(operationContext).close() @@ -103,7 +102,7 @@ class DefaultConnectionPoolSpecification extends Specification { pool.ready() when: - pool.get(getOperationContext()).close() + pool.get(createOperationContext()).close() then: !connectionFactory.getCreatedConnections().get(0).isClosed() @@ -221,7 +220,7 @@ class DefaultConnectionPoolSpecification extends Specification { when: pool.ready() - pool.get(getOperationContext()) + pool.get(createOperationContext()) then: 1 * listener.connectionCreated { it.connectionId.serverId == SERVER_ID } @@ -240,7 +239,7 @@ class DefaultConnectionPoolSpecification extends Specification { connectionDescription.getConnectionId() >> id connection.getDescription() >> connectionDescription connection.opened() >> false - def operationContext = getOperationContext() + def operationContext = createOperationContext() when: 'connection pool is created' pool = new DefaultConnectionPool(SERVER_ID, connectionFactory, settings, mockSdamProvider(), OPERATION_CONTEXT_FACTORY) @@ -353,7 +352,7 @@ class DefaultConnectionPoolSpecification extends Specification { when: pool.ready() - pool.get(getOperationContext()).close() + pool.get(createOperationContext()).close() //not cool - but we have no way of waiting for connection to become idle Thread.sleep(500) pool.close(); @@ -388,7 +387,7 @@ 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 operationContext = createOperationContext() def listener = Mock(ConnectionPoolListener) def connection = Mock(InternalConnection) connection.getDescription() >> new ConnectionDescription(SERVER_ID) @@ -438,7 +437,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(getOperationContext()) + def connection = pool.get(createOperationContext()) connection.close() when: @@ -466,7 +465,7 @@ class DefaultConnectionPoolSpecification extends Specification { def 'should fire connection pool events on check out and check in'() { given: - def operationContext = getOperationContext() + def operationContext = createOperationContext() def listener = Mock(ConnectionPoolListener) pool = new DefaultConnectionPool(SERVER_ID, connectionFactory, builder().maxSize(1) .addConnectionPoolListener(listener).build(), mockSdamProvider(), OPERATION_CONTEXT_FACTORY) @@ -497,7 +496,7 @@ class DefaultConnectionPoolSpecification extends Specification { connection.close() when: - connection = pool.get(getOperationContext()) + connection = pool.get(createOperationContext()) then: 1 * listener.connectionCheckedOut { it.connectionId.serverId == SERVER_ID } @@ -511,7 +510,7 @@ 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 operationContext = createOperationContext() def listener = Mock(ConnectionPoolListener) def connection = Mock(InternalConnection) connection.getDescription() >> new ConnectionDescription(SERVER_ID) @@ -569,7 +568,7 @@ class DefaultConnectionPoolSpecification extends Specification { when: try { - pool.get(getOperationContext()) + pool.get(createOperationContext()) } catch (MongoConnectionPoolClearedException e) { caught = e } @@ -584,7 +583,7 @@ class DefaultConnectionPoolSpecification extends Specification { CompletableFuture caught = new CompletableFuture<>() when: - pool.getAsync(getOperationContext()) { InternalConnection result, Throwable t -> + pool.getAsync(createOperationContext()) { InternalConnection result, Throwable t -> if (t != null) { caught.complete(t) } @@ -604,7 +603,7 @@ class DefaultConnectionPoolSpecification extends Specification { when: pool.invalidate(cause) try { - pool.get(getOperationContext()) + pool.get(createOperationContext()) } catch (MongoConnectionPoolClearedException e) { caught = e } @@ -635,7 +634,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(getOperationContext()) + def connection = pool.get(createOperationContext()) pool.close() when: @@ -679,7 +678,7 @@ class DefaultConnectionPoolSpecification extends Specification { pool.ready() when: - def connection = pool.get(getOperationContext()) + def connection = pool.get(createOperationContext()) def connectionLatch = selectConnectionAsync(pool) connection.close() @@ -689,7 +688,7 @@ class DefaultConnectionPoolSpecification extends Specification { def 'when getting a connection asynchronously should send MongoTimeoutException to callback after timeout period'() { given: - def operationContext = getOperationContext() + def operationContext = createOperationContext() pool = new DefaultConnectionPool(SERVER_ID, connectionFactory, builder().maxSize(1).maxWaitTime(5, MILLISECONDS).build(), mockSdamProvider(), OPERATION_CONTEXT_FACTORY) pool.ready() @@ -727,7 +726,7 @@ class DefaultConnectionPoolSpecification extends Specification { selectConnectionAsync(pool).get() } - def selectConnectionAsync(DefaultConnectionPool pool, operationContext = getOperationContext()) { + def selectConnectionAsync(DefaultConnectionPool pool, operationContext = createOperationContext()) { def serverLatch = new ConnectionLatch() pool.getAsync(operationContext) { InternalConnection result, Throwable e -> serverLatch.connection = result 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 72575b544c4..26348f16198 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 @@ -42,7 +42,7 @@ class DefaultServerConnectionSpecification extends Specification { def codec = new BsonDocumentCodec() def executor = Mock(ProtocolExecutor) def connection = new DefaultServerConnection(internalConnection, executor, ClusterConnectionMode.MULTIPLE) - def operationContext = ClusterFixture.getOperationContext() + def operationContext = ClusterFixture.createOperationContext() when: 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 dfaa2545ee7..8fdf8de3ad5 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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(getOperationContext()) + def receivedConnection = server.getConnection(createOperationContext()) then: receivedConnection @@ -100,7 +100,7 @@ class DefaultServerSpecification extends Specification { when: def callback = new SupplyingCallback() - server.getConnectionAsync(getOperationContext(), callback) + server.getConnectionAsync(createOperationContext(), callback) then: callback.get() == connection @@ -117,7 +117,7 @@ class DefaultServerSpecification extends Specification { server.close() when: - server.getConnection(getOperationContext()) + server.getConnection(createOperationContext()) 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(getOperationContext()) { + server.getConnectionAsync(createOperationContext()) { 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(getOperationContext()) >> { throw exceptionToThrow } + connectionPool.get(createOperationContext()) >> { 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(getOperationContext()) + server.getConnection(createOperationContext()) then: def e = thrown(MongoException) @@ -267,7 +267,7 @@ class DefaultServerSpecification extends Specification { def server = defaultServer(connectionPool, serverMonitor) when: - server.getConnection(getOperationContext()) + server.getConnection(createOperationContext()) 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(getOperationContext()) { + server.getConnectionAsync(createOperationContext()) { 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(getOperationContext()) { + server.getConnectionAsync(createOperationContext()) { 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(getOperationContext()) + def testConnection = (TestConnection) server.getConnection(createOperationContext()) 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 = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().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 93e98ef4336..10074ba9d3c 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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(getOperationContext()) + connection.open(createOperationContext()) connection } @@ -132,7 +132,7 @@ class InternalStreamConnectionSpecification extends Specification { .lastUpdateTimeNanos(connection.getInitialServerDescription().getLastUpdateTime(NANOSECONDS)) .build() when: - connection.open(getOperationContext()) + connection.open(createOperationContext()) then: connection.opened() @@ -159,7 +159,7 @@ class InternalStreamConnectionSpecification extends Specification { .build() when: - connection.openAsync(getOperationContext(), futureResultCallback) + connection.openAsync(createOperationContext(), futureResultCallback) futureResultCallback.get() then: @@ -177,7 +177,7 @@ class InternalStreamConnectionSpecification extends Specification { failedInitializer) when: - connection.open(getOperationContext()) + connection.open(createOperationContext()) then: thrown MongoInternalException @@ -195,7 +195,7 @@ class InternalStreamConnectionSpecification extends Specification { when: def futureResultCallback = new FutureResultCallback() - connection.openAsync(getOperationContext(), futureResultCallback) + connection.openAsync(createOperationContext(), futureResultCallback) futureResultCallback.get() then: @@ -212,14 +212,14 @@ class InternalStreamConnectionSpecification extends Specification { def (buffers2, messageId2) = helper.hello() when: - connection.sendMessage(buffers1, messageId1, getOperationContext()) + connection.sendMessage(buffers1, messageId1, createOperationContext()) then: connection.isClosed() thrown MongoSocketWriteException when: - connection.sendMessage(buffers2, messageId2, getOperationContext()) + connection.sendMessage(buffers2, messageId2, createOperationContext()) then: thrown MongoSocketClosedException @@ -243,7 +243,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.sendMessageAsync(buffers1, messageId1, getOperationContext(), sndCallbck1) + connection.sendMessageAsync(buffers1, messageId1, createOperationContext(), sndCallbck1) sndCallbck1.get(10, SECONDS) then: @@ -251,7 +251,7 @@ class InternalStreamConnectionSpecification extends Specification { connection.isClosed() when: - connection.sendMessageAsync(buffers2, messageId2, getOperationContext(), sndCallbck2) + connection.sendMessageAsync(buffers2, messageId2, createOperationContext(), sndCallbck2) sndCallbck2.get(10, SECONDS) then: @@ -267,16 +267,16 @@ class InternalStreamConnectionSpecification extends Specification { def (buffers2, messageId2) = helper.hello() when: - connection.sendMessage(buffers1, messageId1, getOperationContext()) - connection.sendMessage(buffers2, messageId2, getOperationContext()) - connection.receiveMessage(messageId1, getOperationContext()) + connection.sendMessage(buffers1, messageId1, createOperationContext()) + connection.sendMessage(buffers2, messageId2, createOperationContext()) + connection.receiveMessage(messageId1, createOperationContext()) then: connection.isClosed() thrown MongoSocketReadException when: - connection.receiveMessage(messageId2, getOperationContext()) + connection.receiveMessage(messageId2, createOperationContext()) then: thrown MongoSocketClosedException @@ -289,7 +289,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.receiveMessage(1, getOperationContext()) + connection.receiveMessage(1, createOperationContext()) then: thrown(MongoInternalException) @@ -306,7 +306,7 @@ class InternalStreamConnectionSpecification extends Specification { def callback = new FutureResultCallback() when: - connection.receiveMessageAsync(1, getOperationContext(), callback) + connection.receiveMessageAsync(1, createOperationContext(), callback) callback.get() then: @@ -321,7 +321,7 @@ class InternalStreamConnectionSpecification extends Specification { Thread.currentThread().interrupt() when: - connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, getOperationContext()) + connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, createOperationContext()) then: Thread.interrupted() @@ -335,7 +335,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, getOperationContext()) + connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, createOperationContext()) then: !Thread.interrupted() @@ -350,7 +350,7 @@ class InternalStreamConnectionSpecification extends Specification { Thread.currentThread().interrupt() when: - connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, getOperationContext()) + connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, createOperationContext()) then: Thread.interrupted() @@ -365,7 +365,7 @@ class InternalStreamConnectionSpecification extends Specification { Thread.currentThread().interrupt() when: - connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, getOperationContext()) + connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, createOperationContext()) then: Thread.interrupted() @@ -379,7 +379,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, getOperationContext()) + connection.sendMessage([new ByteBufNIO(ByteBuffer.allocate(1))], 1, createOperationContext()) then: thrown(MongoSocketWriteException) @@ -393,7 +393,7 @@ class InternalStreamConnectionSpecification extends Specification { Thread.currentThread().interrupt() when: - connection.receiveMessage(1, getOperationContext()) + connection.receiveMessage(1, createOperationContext()) then: Thread.interrupted() @@ -407,7 +407,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.receiveMessage(1, getOperationContext()) + connection.receiveMessage(1, createOperationContext()) then: !Thread.interrupted() @@ -422,7 +422,7 @@ class InternalStreamConnectionSpecification extends Specification { Thread.currentThread().interrupt() when: - connection.receiveMessage(1, getOperationContext()) + connection.receiveMessage(1, createOperationContext()) then: Thread.interrupted() @@ -437,7 +437,7 @@ class InternalStreamConnectionSpecification extends Specification { Thread.currentThread().interrupt() when: - connection.receiveMessage(1, getOperationContext()) + connection.receiveMessage(1, createOperationContext()) then: Thread.interrupted() @@ -451,7 +451,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.receiveMessage(1, getOperationContext()) + connection.receiveMessage(1, createOperationContext()) then: thrown(MongoSocketReadException) @@ -464,7 +464,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.receiveMessage(1, getOperationContext().withTimeoutContext( + connection.receiveMessage(1, createOperationContext().withTimeoutContext( new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT))) then: @@ -482,7 +482,7 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.receiveMessage(1, getOperationContext().withTimeoutContext( + connection.receiveMessage(1, createOperationContext().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 = getOperationContext().withTimeoutContext( + def operationContext = createOperationContext().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 = getOperationContext().withTimeoutContext( + def operationContext = createOperationContext().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, getOperationContext(), sndCallbck1) - connection.sendMessageAsync(buffers2, messageId2, getOperationContext(), sndCallbck2) - connection.receiveMessageAsync(messageId1, getOperationContext(), rcvdCallbck1) - connection.receiveMessageAsync(messageId2, getOperationContext(), rcvdCallbck2) + connection.sendMessageAsync(buffers1, messageId1, createOperationContext(), sndCallbck1) + connection.sendMessageAsync(buffers2, messageId2, createOperationContext(), sndCallbck2) + connection.receiveMessageAsync(messageId1, createOperationContext(), rcvdCallbck1) + connection.receiveMessageAsync(messageId2, createOperationContext(), rcvdCallbck2) rcvdCallbck1.get(1, SECONDS) then: @@ -588,14 +588,14 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.receiveMessage(1, getOperationContext()) + connection.receiveMessage(1, createOperationContext()) then: connection.isClosed() thrown MongoSocketReadException when: - connection.receiveMessage(1, getOperationContext()) + connection.receiveMessage(1, createOperationContext()) then: thrown MongoSocketClosedException @@ -620,9 +620,9 @@ class InternalStreamConnectionSpecification extends Specification { def connection = getOpenedConnection() when: - connection.sendMessageAsync(buffers1, messageId1, getOperationContext(), sndCallbck1) - connection.sendMessageAsync(buffers2, messageId2, getOperationContext(), sndCallbck2) - connection.receiveMessageAsync(messageId1, getOperationContext(), rcvdCallbck1) + connection.sendMessageAsync(buffers1, messageId1, createOperationContext(), sndCallbck1) + connection.sendMessageAsync(buffers2, messageId2, createOperationContext(), sndCallbck2) + connection.receiveMessageAsync(messageId1, createOperationContext(), rcvdCallbck1) rcvdCallbck1.get(1, SECONDS) then: @@ -630,7 +630,7 @@ class InternalStreamConnectionSpecification extends Specification { connection.isClosed() when: - connection.receiveMessageAsync(messageId2, getOperationContext(), rcvdCallbck2) + connection.receiveMessageAsync(messageId2, createOperationContext(), 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(), getOperationContext()) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createOperationContext()) then: thrown(MongoCommandException) @@ -677,7 +677,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), createOperationContext(), 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, getOperationContext(), sndCallbck) + connection.sendMessageAsync(buffers, messageId, createOperationContext(), 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(), getOperationContext()) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createOperationContext()) then: commandListener.eventsWereDelivered([ @@ -753,7 +753,7 @@ class InternalStreamConnectionSpecification extends Specification { when: connection.sendAndReceive(commandMessage, { BsonReader reader, DecoderContext decoderContext -> throw new CodecConfigurationException('') - }, getOperationContext()) + }, createOperationContext()) then: thrown(CodecConfigurationException) @@ -783,7 +783,7 @@ class InternalStreamConnectionSpecification extends Specification { 1 * advanceClusterTime(BsonDocument.parse(response).getDocument('$clusterTime')) getReadConcern() >> ReadConcern.DEFAULT } - def operationContext = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().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 = getOperationContext().withSessionContext(sessionContext) + def operationContext = createOperationContext().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(), getOperationContext()) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createOperationContext()) 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(), getOperationContext()) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createOperationContext()) 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(), getOperationContext()) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createOperationContext()) then: def e = thrown(MongoSocketException) @@ -902,7 +902,7 @@ class InternalStreamConnectionSpecification extends Specification { stream.read(_, _) >> helper.reply(response) when: - connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), getOperationContext()) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createOperationContext()) then: def e = thrown(MongoCommandException) @@ -923,7 +923,7 @@ class InternalStreamConnectionSpecification extends Specification { stream.read(90, _) >> helper.defaultReply() when: - connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), getOperationContext()) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createOperationContext()) 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(), getOperationContext()) + connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createOperationContext()) then: thrown(MongoCommandException) @@ -1005,7 +1005,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), createOperationContext(), callback) callback.get() then: @@ -1038,7 +1038,7 @@ class InternalStreamConnectionSpecification extends Specification { when: connection.sendAndReceiveAsync(commandMessage, { BsonReader reader, DecoderContext decoderContext -> throw new CodecConfigurationException('') - }, getOperationContext(), callback) + }, createOperationContext(), callback) callback.get() then: @@ -1065,7 +1065,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), createOperationContext(), callback) callback.get() then: @@ -1093,7 +1093,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), createOperationContext(), callback) callback.get() then: @@ -1124,7 +1124,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), createOperationContext(), callback) callback.get() then: @@ -1156,7 +1156,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), createOperationContext(), callback) callback.get() then: @@ -1187,7 +1187,7 @@ class InternalStreamConnectionSpecification extends Specification { } when: - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), getOperationContext(), callback) + connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), createOperationContext(), 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 9924edafd9b..5a7bcd3e492 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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(getOperationContext()) - provider.get(getOperationContext()).close() + provider.get(createOperationContext()) + provider.get(createOperationContext()).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 5528907f503..87dd1581045 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 @@ -16,6 +16,7 @@ package com.mongodb.internal.connection; +import com.mongodb.ClusterFixture; import com.mongodb.MongoClientException; import com.mongodb.MongoConfigurationException; import com.mongodb.MongoException; @@ -52,7 +53,6 @@ import java.util.concurrent.atomic.AtomicReference; import static com.mongodb.ClusterFixture.CLIENT_METADATA; -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), getOperationContext()); + ServerTuple serverTuple = cluster.selectServer(mock(ServerSelector.class), ClusterFixture.createOperationContext()); // then assertServerTupleExpectations(serverAddress, expectedServer, serverTuple); // when FutureResultCallback callback = new FutureResultCallback<>(); - cluster.selectServerAsync(mock(ServerSelector.class), getOperationContext(), callback); + cluster.selectServerAsync(mock(ServerSelector.class), ClusterFixture.createOperationContext(), 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), getOperationContext()); + ServerTuple serverTuple = cluster.selectServer(mock(ServerSelector.class), ClusterFixture.createOperationContext()); // then assertServerTupleExpectations(resolvedServerAddress, expectedServer, serverTuple); @@ -159,7 +159,7 @@ public void shouldSelectServerAsynchronouslyWhenThereIsSRVLookup() { // when FutureResultCallback callback = new FutureResultCallback<>(); - cluster.selectServerAsync(mock(ServerSelector.class), getOperationContext(), callback); + cluster.selectServerAsync(mock(ServerSelector.class), ClusterFixture.createOperationContext(), 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), - getOperationContext())); + ClusterFixture.createOperationContext())); 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), getOperationContext(), callback); + cluster.selectServerAsync(mock(ServerSelector.class), ClusterFixture.createOperationContext(), 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 d4ec64661ee..de12c35af5e 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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 = getOperationContext() + def operationContext = createOperationContext() 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 = getOperationContext() + def operationContext = createOperationContext() 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 = getOperationContext() + def operationContext = createOperationContext() 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 = getOperationContext() + def operationContext = createOperationContext() 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 5c286372c25..535cd5fdff6 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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( - getOperationContext().getTimeoutContext().computeServerSelectionTimeout(), - getOperationContext().getTimeoutContext()) + createOperationContext().getTimeoutContext().computeServerSelectionTimeout(), + createOperationContext().getTimeoutContext()) then: thrown(IllegalStateException) @@ -386,7 +386,7 @@ class MultiServerClusterSpecification extends Specification { cluster.close() when: - cluster.selectServer(new WritableServerSelector(), getOperationContext()) + cluster.selectServer(new WritableServerSelector(), createOperationContext()) 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 258a0fbde30..a535262b4b4 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 @@ -16,6 +16,7 @@ package com.mongodb.internal.connection; +import com.mongodb.ClusterFixture; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.async.FutureResultCallback; @@ -30,7 +31,6 @@ import java.util.List; import java.util.concurrent.ExecutionException; -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, getOperationContext()); + subject.authenticate(connection, connectionDescription, ClusterFixture.createOperationContext()); validateMessages(); } @@ -64,7 +64,7 @@ public void testSuccessfulAuthenticationAsync() throws ExecutionException, Inter enqueueSuccessfulReply(); FutureResultCallback futureCallback = new FutureResultCallback<>(); - subject.authenticateAsync(connection, connectionDescription, getOperationContext(), futureCallback); + subject.authenticateAsync(connection, connectionDescription, ClusterFixture.createOperationContext(), futureCallback); futureCallback.get(); validateMessages(); 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 0ebd1d2b9b9..90cd8da3412 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 @@ -16,6 +16,7 @@ package com.mongodb.internal.connection; +import com.mongodb.ClusterFixture; import com.mongodb.ServerAddress; import com.mongodb.connection.ClusterType; import com.mongodb.connection.ServerDescription; @@ -32,7 +33,6 @@ import java.util.Collection; import java.util.stream.Collectors; -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 = getOperationContext().getTimeoutContext().computeServerSelectionTimeout(); + Timeout serverSelectionTimeout = ClusterFixture.createOperationContext().getTimeoutContext().computeServerSelectionTimeout(); DefaultServer server = (DefaultServer) getCluster() - .getServersSnapshot(serverSelectionTimeout, getOperationContext().getTimeoutContext()) + .getServersSnapshot(serverSelectionTimeout, ClusterFixture.createOperationContext().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 9fe84995d7a..ab70f0d53ad 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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(getOperationContext() + cluster.getServersSnapshot(createOperationContext() .getTimeoutContext() .computeServerSelectionTimeout(), - getOperationContext().getTimeoutContext()).getServer(firstServer) == factory.getServer(firstServer) + createOperationContext().getTimeoutContext()).getServer(firstServer) == factory.getServer(firstServer) cleanup: cluster?.close() @@ -95,8 +95,8 @@ class SingleServerClusterSpecification extends Specification { cluster.close() when: - cluster.getServersSnapshot(getOperationContext().getTimeoutContext().computeServerSelectionTimeout(), - getOperationContext().getTimeoutContext()) + cluster.getServersSnapshot(createOperationContext().getTimeoutContext().computeServerSelectionTimeout(), + createOperationContext().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(), getOperationContext()) + cluster.selectServer(new WritableServerSelector(), createOperationContext()) 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 0e84acb1943..379d60a2fe7 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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(getOperationContext()) + connection.open(createOperationContext()) then: connection.openedAt <= System.currentTimeMillis() @@ -65,7 +65,7 @@ class UsageTrackingConnectionSpecification extends Specification { connection.openedAt == Long.MAX_VALUE when: - connection.openAsync(getOperationContext(), futureResultCallback) + connection.openAsync(createOperationContext(), futureResultCallback) futureResultCallback.get() then: @@ -80,7 +80,7 @@ class UsageTrackingConnectionSpecification extends Specification { connection.lastUsedAt == Long.MAX_VALUE when: - connection.open(getOperationContext()) + connection.open(createOperationContext()) then: connection.lastUsedAt <= System.currentTimeMillis() @@ -96,7 +96,7 @@ class UsageTrackingConnectionSpecification extends Specification { connection.lastUsedAt == Long.MAX_VALUE when: - connection.openAsync(getOperationContext(), futureResultCallback) + connection.openAsync(createOperationContext(), 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(getOperationContext()) + connection.open(createOperationContext()) def openedLastUsedAt = connection.lastUsedAt when: - connection.sendMessage([], 1, getOperationContext()) + connection.sendMessage([], 1, createOperationContext()) 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(getOperationContext()) + connection.open(createOperationContext()) def openedLastUsedAt = connection.lastUsedAt def futureResultCallback = new FutureResultCallback() when: - connection.sendMessageAsync([], 1, getOperationContext(), futureResultCallback) + connection.sendMessageAsync([], 1, createOperationContext(), 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(getOperationContext()) + connection.open(createOperationContext()) def openedLastUsedAt = connection.lastUsedAt when: - connection.receiveMessage(1, getOperationContext()) + connection.receiveMessage(1, createOperationContext()) 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(getOperationContext()) + connection.open(createOperationContext()) def openedLastUsedAt = connection.lastUsedAt def futureResultCallback = new FutureResultCallback() when: - connection.receiveMessageAsync(1, getOperationContext(), futureResultCallback) + connection.receiveMessageAsync(1, createOperationContext(), 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(getOperationContext()) + connection.open(createOperationContext()) 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(), getOperationContext()) + MessageSettings.builder().build(), SINGLE, null), new BsonDocumentCodec(), createOperationContext()) 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(getOperationContext()) + connection.open(createOperationContext()) 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(), getOperationContext(), futureResultCallback) + new BsonDocumentCodec(), createOperationContext(), 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 9346e529e2e..0259b41930a 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 @@ -16,6 +16,7 @@ package com.mongodb.internal.connection; +import com.mongodb.ClusterFixture; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.async.FutureResultCallback; @@ -32,7 +33,6 @@ import java.util.List; import java.util.concurrent.ExecutionException; -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, getOperationContext()); + .authenticate(connection, connectionDescriptionThreeSix, ClusterFixture.createOperationContext()); validateMessages(); } @@ -69,7 +69,7 @@ public void testSuccessfulAuthenticationAsync() throws ExecutionException, Inter FutureResultCallback futureCallback = new FutureResultCallback<>(); new X509Authenticator(getCredentialWithCache(), MULTIPLE, getServerApi()).authenticateAsync(connection, - connectionDescriptionThreeSix, getOperationContext(), futureCallback); + connectionDescriptionThreeSix, ClusterFixture.createOperationContext(), 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 3d971461de3..80d0b2c0411 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 @@ -16,6 +16,7 @@ package com.mongodb.internal.connection; +import com.mongodb.ClusterFixture; import com.mongodb.MongoCredential; import com.mongodb.MongoSecurityException; import com.mongodb.ServerAddress; @@ -31,7 +32,6 @@ import java.util.List; -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, getOperationContext()); + subject.authenticate(connection, connectionDescription, ClusterFixture.createOperationContext()); fail(); } catch (MongoSecurityException e) { // all good @@ -70,7 +70,7 @@ public void testFailedAuthenticationAsync() { enqueueFailedAuthenticationReply(); FutureResultCallback futureCallback = new FutureResultCallback<>(); - subject.authenticateAsync(connection, connectionDescription, getOperationContext(), futureCallback); + subject.authenticateAsync(connection, connectionDescription, ClusterFixture.createOperationContext(), futureCallback); try { futureCallback.get(); @@ -92,7 +92,7 @@ private void enqueueFailedAuthenticationReply() { public void testSuccessfulAuthentication() { enqueueSuccessfulAuthenticationReply(); - subject.authenticate(connection, connectionDescription, getOperationContext()); + subject.authenticate(connection, connectionDescription, ClusterFixture.createOperationContext()); validateMessages(); } @@ -102,7 +102,7 @@ public void testSuccessfulAuthenticationAsync() { enqueueSuccessfulAuthenticationReply(); FutureResultCallback futureCallback = new FutureResultCallback<>(); - subject.authenticateAsync(connection, connectionDescription, getOperationContext(), futureCallback); + subject.authenticateAsync(connection, connectionDescription, ClusterFixture.createOperationContext(), 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, getOperationContext()); + subject.authenticate(connection, connectionDescription, ClusterFixture.createOperationContext()); 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 aa3a2d70d50..9142a097678 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 @@ -15,6 +15,7 @@ */ package com.mongodb.internal.mockito; +import com.mongodb.ClusterFixture; import com.mongodb.internal.binding.ReadBinding; import com.mongodb.internal.operation.ListCollectionsOperation; import org.bson.BsonDocument; @@ -24,7 +25,6 @@ import org.mockito.Mockito; import org.mockito.internal.stubbing.answers.ThrowsException; -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, getOperationContext())); + assertThrows(NullPointerException.class, () -> operation.execute(binding, ClusterFixture.createOperationContext())); } @Test void mockObjectWithThrowsException() { ReadBinding binding = Mockito.mock(ReadBinding.class, new ThrowsException(new AssertionError("Insufficient stubbing for " + ReadBinding.class))); - assertThrows(AssertionError.class, () -> operation.execute(binding, getOperationContext())); + assertThrows(AssertionError.class, () -> operation.execute(binding, ClusterFixture.createOperationContext())); } @Test void mockObjectWithInsufficientStubbingDetector() { ReadBinding binding = MongoMockito.mock(ReadBinding.class); - assertThrows(AssertionError.class, () -> operation.execute(binding, getOperationContext())); + assertThrows(AssertionError.class, () -> operation.execute(binding, ClusterFixture.createOperationContext())); } @Test void stubbingWithThrowsException() { ReadBinding binding = Mockito.mock(ReadBinding.class, new ThrowsException(new AssertionError("Unfortunately, you cannot do stubbing"))); - assertThrows(AssertionError.class, () -> when(binding.getReadConnectionSource(getOperationContext())).thenReturn(null)); + assertThrows(AssertionError.class, () -> when(binding.getReadConnectionSource(ClusterFixture.createOperationContext())).thenReturn(null)); } @Test void stubbingWithInsufficientStubbingDetector() { MongoMockito.mock(ReadBinding.class, bindingMock -> - when(bindingMock.getReadConnectionSource(getOperationContext())).thenReturn(null) + when(bindingMock.getReadConnectionSource(ClusterFixture.createOperationContext())).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 4e488a69bee..6080f8bb727 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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 = getOperationContext().withSessionContext( + def operationContext = createOperationContext().withSessionContext( Stub(SessionContext) { hasSession() >> true hasActiveTransaction() >> false @@ -116,7 +116,7 @@ class AsyncOperationHelperSpecification extends Specification { def connectionDescription = Stub(ConnectionDescription) when: - executeCommandAsync(asyncWriteBinding, getOperationContext(), dbName, command, connection, { t, conn -> t }, callback) + executeCommandAsync(asyncWriteBinding, createOperationContext(), 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, getOperationContext(), dbName, commandCreator, decoder, function, false, callback) + executeRetryableReadAsync(asyncReadBinding, createOperationContext(), 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 0a7083bb65a..18a66816abf 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.getOperationContext()); + ClientBulkWriteResult result = op.execute(binding, ClusterFixture.createOperationContext()); //then assertEquals( @@ -176,7 +176,7 @@ void shouldUseDefaultNumberOfModifiedDocumentsWhenMissingInCursor() { false, getDefaultCodecRegistry()); //when - ClientBulkWriteResult result = op.execute(binding, ClusterFixture.getOperationContext()); + ClientBulkWriteResult result = op.execute(binding, ClusterFixture.createOperationContext()); //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 ae86661fe2e..aa4db2372ff 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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, getOperationContext().withSessionContext(sessionContext)) + operation.execute(writeBinding, createOperationContext().withSessionContext(sessionContext)) then: def e = thrown(MongoTimeoutException) @@ -64,7 +64,7 @@ class CommitTransactionOperationUnitSpecification extends OperationUnitSpecifica def callback = new FutureResultCallback() when: - operation.executeAsync(writeBinding, getOperationContext().withSessionContext(sessionContext), callback) + operation.executeAsync(writeBinding, createOperationContext().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 9c7a9d3fcd7..26fd6e6eab5 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 @@ -15,6 +15,7 @@ */ package com.mongodb.internal.operation; +import com.mongodb.ClusterFixture; import com.mongodb.MongoNamespace; import com.mongodb.ServerCursor; import com.mongodb.internal.binding.AsyncConnectionSource; @@ -24,7 +25,6 @@ import com.mongodb.internal.mockito.MongoMockito; import org.junit.jupiter.api.Test; -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(getOperationContext()); - cursorResourceManager.close(getOperationContext()); + cursorResourceManager.close(ClusterFixture.createOperationContext()); + cursorResourceManager.close(ClusterFixture.createOperationContext()); cursorResourceManager.setServerCursor(null); }); } finally { - cursorResourceManager.endOperation(getOperationContext()); + cursorResourceManager.endOperation(ClusterFixture.createOperationContext()); } } } 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 ff09b40246a..ca7730ff2b6 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 @@ -15,6 +15,7 @@ */ package com.mongodb.internal.operation; +import com.mongodb.ClusterFixture; import com.mongodb.MongoNamespace; import com.mongodb.ReadPreference; import com.mongodb.ServerAddress; @@ -39,7 +40,6 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; -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(), getOperationContext()); + operation.execute(mocks.readBinding(), ClusterFixture.createOperationContext()); 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 d71739b8f7c..ac51ebcede5 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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, getOperationContext().withSessionContext(noTransactionSessionContext)) - !canRetryRead(retryableServerDescription, getOperationContext().withSessionContext(activeTransactionSessionContext)) + canRetryRead(retryableServerDescription, createOperationContext().withSessionContext(noTransactionSessionContext)) + !canRetryRead(retryableServerDescription, createOperationContext().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 4df237b0710..52934c3bfad 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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 = getOperationContext() + def operationContext = createOperationContext() .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 = getOperationContext() + def operationContext = createOperationContext() .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 41e60240ece..8b66947c026 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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, getOperationContext(), dbName, command, decoder, function) + executeCommand(writeBinding, createOperationContext(), 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 = getOperationContext() + def operationContext = createOperationContext() .withSessionContext(Stub(SessionContext) { hasSession() >> true hasActiveTransaction() >> false @@ -132,7 +132,7 @@ class SyncOperationHelperSpecification extends Specification { def connectionDescription = Stub(ConnectionDescription) when: - executeRetryableRead(readBinding, getOperationContext(), dbName, commandCreator, decoder, function, false) + executeRetryableRead(readBinding, createOperationContext(), 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 189fcc07ce0..495523f90a3 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 @@ -17,10 +17,10 @@ package com.mongodb.internal.session; import com.mongodb.ClientSessionOptions; +import com.mongodb.ClusterFixture; import com.mongodb.session.ClientSession; import org.junit.jupiter.api.Test; -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(), getOperationContext()); + ServerSessionPool serverSessionPool = new ServerSessionPool(getCluster(), ClusterFixture.createOperationContext()); 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(), getOperationContext()); + ServerSessionPool serverSessionPool = new ServerSessionPool(getCluster(), ClusterFixture.createOperationContext()); 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 962b60bdffb..0fc4564d322 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.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext 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, getOperationContext(), clock) + def pool = new ServerSessionPool(cluster, createOperationContext(), 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, getOperationContext(), clock) + def pool = new ServerSessionPool(cluster, createOperationContext(), 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, getOperationContext(), clock) + def pool = new ServerSessionPool(cluster, createOperationContext(), 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, getOperationContext(), clock) + def pool = new ServerSessionPool(cluster, createOperationContext(), 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 622900490ff..b483e326081 100644 --- a/driver-legacy/src/test/functional/com/mongodb/DBTest.java +++ b/driver-legacy/src/test/functional/com/mongodb/DBTest.java @@ -31,7 +31,6 @@ import java.util.Locale; import java.util.UUID; -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 +344,7 @@ public void shouldApplyUuidRepresentationToCommandEncodingAndDecoding() { BsonDocument getCollectionInfo(final String collectionName) { return new ListCollectionsOperation<>(getDefaultDatabaseName(), new BsonDocumentCodec()) - .filter(new BsonDocument("name", new BsonString(collectionName))).execute(getBinding(), getOperationContext()).next().get(0); + .filter(new BsonDocument("name", new BsonString(collectionName))).execute(getBinding(), ClusterFixture.createOperationContext()).next().get(0); } private boolean isCapped(final DBCollection collection) { diff --git a/driver-legacy/src/test/functional/com/mongodb/LegacyMixedBulkWriteOperationSpecification.groovy b/driver-legacy/src/test/functional/com/mongodb/LegacyMixedBulkWriteOperationSpecification.groovy index 6a9c511c3bc..2db1da67e22 100644 --- a/driver-legacy/src/test/functional/com/mongodb/LegacyMixedBulkWriteOperationSpecification.groovy +++ b/driver-legacy/src/test/functional/com/mongodb/LegacyMixedBulkWriteOperationSpecification.groovy @@ -184,7 +184,7 @@ class LegacyMixedBulkWriteOperationSpecification extends OperationFunctionalSpec def insert = new InsertRequest(new BsonDocument('_id', new BsonInt32(1))) def binding = getBinding() createBulkWriteOperationForInsert(getNamespace(), true, ACKNOWLEDGED, false, asList(insert)) - .execute(binding, ClusterFixture.getOperationContext(binding.getReadPreference())) + .execute(binding, ClusterFixture.createOperationContext(binding.getReadPreference())) def replacement = new UpdateRequest(new BsonDocument('_id', new BsonInt32(1)), new BsonDocument('_id', new BsonInt32(1)).append('x', new BsonInt32(1)), REPLACE) 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 df996b6088e..0fcbb5ac31a 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 @@ -32,14 +32,14 @@ import com.mongodb.internal.connection.ServerTuple import com.mongodb.reactivestreams.client.ClientSession import spock.lang.Specification -import static com.mongodb.ClusterFixture.getOperationContext +import static com.mongodb.ClusterFixture.createOperationContext class ClientSessionBindingSpecification extends Specification { def 'should return the session context from the connection source'() { given: def session = Stub(ClientSession) - def operationContext = ClusterFixture.getOperationContext() + def operationContext = ClusterFixture.createOperationContext() def wrappedBinding = Mock(AsyncClusterAwareReadWriteBinding); wrappedBinding.retain() >> wrappedBinding def binding = new ClientSessionBinding(session, false, wrappedBinding) @@ -90,10 +90,10 @@ class ClientSessionBindingSpecification extends Specification { def wrappedBinding = createStubBinding() def binding = new ClientSessionBinding(session, true, wrappedBinding) def futureResultCallback = new FutureResultCallback() - binding.getReadConnectionSource(getOperationContext(), futureResultCallback) + binding.getReadConnectionSource(createOperationContext(), futureResultCallback) def readConnectionSource = futureResultCallback.get() futureResultCallback = new FutureResultCallback() - binding.getWriteConnectionSource(getOperationContext(), futureResultCallback) + binding.getWriteConnectionSource(createOperationContext(), 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 02b81be8c7f..f2ecac0c170 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 @@ -30,7 +30,7 @@ class ClientSessionBindingSpecification extends Specification { def 'should call underlying wrapped binding'() { given: def session = Stub(ClientSession) - def operationContext = ClusterFixture.getOperationContext() + def operationContext = ClusterFixture.createOperationContext() def wrappedBinding = Mock(ClusterBinding); def binding = new ClientSessionBinding(session, false, wrappedBinding) @@ -76,7 +76,7 @@ class ClientSessionBindingSpecification extends Specification { def session = Mock(ClientSession) def wrappedBinding = createStubBinding() def binding = new ClientSessionBinding(session, true, wrappedBinding) - def operationContext = ClusterFixture.getOperationContext() + def operationContext = ClusterFixture.createOperationContext() def readConnectionSource = binding.getReadConnectionSource(operationContext) def writeConnectionSource = binding.getWriteConnectionSource(operationContext) 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 82749134253..3ec9a889e29 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.getOperationContext().withTimeoutContext(timeoutContext) + def operationContext = ClusterFixture.createOperationContext().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.getOperationContext().withTimeoutContext(timeoutContext) + def operationContext = ClusterFixture.createOperationContext().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.getOperationContext().withTimeoutContext(timeoutContext) + def operationContext = ClusterFixture.createOperationContext().withTimeoutContext(timeoutContext) def operationTimeout = Mock(Timeout) timeoutContext.getTimeout() >> operationTimeout From 021c262787eb25b527bdfd9427d1df46f4c44a30 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 14:07:46 -0800 Subject: [PATCH 11/43] Remove craeteNewOperationContext. --- .../test/functional/com/mongodb/ClusterFixture.java | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java index 82d5ff6029f..0ae2fadc40b 100644 --- a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java +++ b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java @@ -376,7 +376,9 @@ public static ReadWriteBinding getBinding(final Cluster cluster) { } public static ReadWriteBinding getBinding(final TimeoutSettings timeoutSettings) { - return getBinding(getCluster(), ReadPreference.primary(), createNewOperationContext(timeoutSettings)); + return getBinding(getCluster(), + ReadPreference.primary(), + createOperationContext().withTimeoutContext(new TimeoutContext(timeoutSettings))); } public static ReadWriteBinding getBinding(final OperationContext operationContext) { @@ -387,10 +389,6 @@ public static ReadWriteBinding getBinding(final ReadPreference readPreference) { return getBinding(getCluster(), readPreference, createOperationContext()); } - public static OperationContext createNewOperationContext(final TimeoutSettings timeoutSettings) { - return createOperationContext().withTimeoutContext(new TimeoutContext(timeoutSettings)); - } - private static ReadWriteBinding getBinding(final Cluster cluster, final ReadPreference readPreference, final OperationContext operationContext) { @@ -425,7 +423,7 @@ public static AsyncReadWriteBinding getAsyncBinding() { } public static AsyncReadWriteBinding getAsyncBinding(final TimeoutSettings timeoutSettings) { - return getAsyncBinding(createNewOperationContext(timeoutSettings)); + return getAsyncBinding(createOperationContext().withTimeoutContext(new TimeoutContext(timeoutSettings))); } public static AsyncReadWriteBinding getAsyncBinding(final OperationContext operationContext) { From 08b346662e8ac17a5a71ae26c474643d71fa2170 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 14:10:50 -0800 Subject: [PATCH 12/43] Change visibility modifier. --- .../src/main/com/mongodb/internal/connection/BaseCluster.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 6ac8541e51c..27ca59611d5 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java +++ b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java @@ -67,6 +67,7 @@ import static com.mongodb.connection.ServerDescription.MIN_DRIVER_SERVER_VERSION; import static com.mongodb.connection.ServerDescription.MIN_DRIVER_WIRE_VERSION; import static com.mongodb.internal.Locks.withInterruptibleLock; +import static com.mongodb.internal.VisibleForTesting.AccessModifier.PACKAGE; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; import static com.mongodb.internal.connection.EventHelper.wouldDescriptionsGenerateEquivalentEvents; import static com.mongodb.internal.event.EventListenerHelper.singleClusterListener; @@ -113,7 +114,7 @@ public abstract class BaseCluster implements Cluster { private volatile boolean isClosed; private volatile ClusterDescription description; - @VisibleForTesting(otherwise = PRIVATE) + @VisibleForTesting(otherwise = PACKAGE) protected BaseCluster(final ClusterId clusterId, final ClusterSettings settings, final ClusterableServerFactory serverFactory, From 98caa34ae60e5bc8283e97cd4b36bd0ee1e054dc Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 14:12:50 -0800 Subject: [PATCH 13/43] Rename applyDeprioritization method to apply. --- .../internal/connection/BaseCluster.java | 2 +- .../internal/connection/OperationContext.java | 2 +- .../ServerDeprioritizationTest.java | 38 +++++++++---------- 3 files changed, 21 insertions(+), 21 deletions(-) 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 27ca59611d5..a5a44c4ecf3 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java +++ b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java @@ -364,7 +364,7 @@ private static ServerSelector getCompleteServerSelector( final ClusterSettings settings) { List selectors = Stream.of( getRaceConditionPreFilteringSelector(serversSnapshot), - serverDeprioritization.applyDeprioritization(serverSelector), + serverDeprioritization.apply(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 d647d6ab0a0..7bf8f023180 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -252,7 +252,7 @@ public ServerDeprioritization() { * selects using the wrapped selector again with all {@link ServerDescription}s, including deprioritized ones. * */ - ServerSelector applyDeprioritization(final ServerSelector wrappedSelector) { + ServerSelector apply(final ServerSelector wrappedSelector) { return new DeprioritizingSelector(wrappedSelector); } 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 ee75b9c726e..bfd10334085 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 @@ -85,9 +85,9 @@ private static Stream selectNoneDeprioritized() { void selectNoneDeprioritized(final List selectorResult) { ServerSelector wrappedSelector = createAssertingSelector(ALL_SERVERS, selectorResult); assertAll( - () -> 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)) + () -> assertEquals(selectorResult, serverDeprioritization.apply(wrappedSelector).select(SHARDED_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.apply(wrappedSelector).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.apply(wrappedSelector).select(UNKNOWN_CLUSTER)) ); } @@ -96,10 +96,10 @@ 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)) + () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.apply(wrappedSelector).select(STANDALONE_CLUSTER)), + () -> assertEquals(emptyList(), serverDeprioritization.apply(emptyListWrappedSelector).select(STANDALONE_CLUSTER)), + () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.apply(wrappedSelector).select(LOAD_BALANCED_CLUSTER)), + () -> assertEquals(emptyList(), serverDeprioritization.apply(emptyListWrappedSelector).select(LOAD_BALANCED_CLUSTER)) ); } @@ -119,9 +119,9 @@ void selectSomeDeprioritized(final List selectorResult) { List expectedWrappedSelectorFilteredInput = asList(SERVER_A, SERVER_C); ServerSelector selector = createAssertingSelector(expectedWrappedSelectorFilteredInput, 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)) + () -> assertEquals(selectorResult, serverDeprioritization.apply(selector).select(SHARDED_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.apply(selector).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.apply(selector).select(UNKNOWN_CLUSTER)) ); } @@ -133,9 +133,9 @@ void selectAllDeprioritized(final List selectorResult) { 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)) + () -> assertEquals(selectorResult, serverDeprioritization.apply(selector).select(SHARDED_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.apply(selector).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.apply(selector).select(UNKNOWN_CLUSTER)) ); } @@ -144,9 +144,9 @@ void selectAllDeprioritizedSingleServerCluster() { deprioritize(SERVER_A); ServerSelector selector = createAssertingSelector(singletonList(SERVER_A), singletonList(SERVER_A)); assertAll( - () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector).select(STANDALONE_CLUSTER)), + () -> assertEquals(singletonList(SERVER_A), serverDeprioritization.apply(selector).select(STANDALONE_CLUSTER)), () -> assertEquals(singletonList(SERVER_A), - serverDeprioritization.applyDeprioritization(selector).select(LOAD_BALANCED_CLUSTER)) + serverDeprioritization.apply(selector).select(LOAD_BALANCED_CLUSTER)) ); } @@ -171,9 +171,9 @@ public List select(final ClusterDescription clusterDescriptio }; 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)) + () -> assertEquals(selectorResult, serverDeprioritization.apply(selector.get()).select(SHARDED_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.apply(selector.get()).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.apply(selector.get()).select(UNKNOWN_CLUSTER)) ); } @@ -183,7 +183,7 @@ void onAttemptFailureIgnoresIfPoolClearedException() { serverDeprioritization.onAttemptFailure( new MongoConnectionPoolClearedException(new ServerId(new ClusterId(), new ServerAddress()), null)); ServerSelector selector = createAssertingSelector(ALL_SERVERS, singletonList(SERVER_A)); - assertEquals(singletonList(SERVER_A), serverDeprioritization.applyDeprioritization(selector).select(SHARDED_CLUSTER)); + assertEquals(singletonList(SERVER_A), serverDeprioritization.apply(selector).select(SHARDED_CLUSTER)); } @Test From a6587fad997e664558bb42b14a5ecc985710983a Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 14:49:13 -0800 Subject: [PATCH 14/43] Add TODO comments for performance optimization. --- .../com/mongodb/internal/connection/OperationContext.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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 7bf8f023180..6ce3e559e98 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -285,21 +285,26 @@ private DeprioritizingSelector(final ServerSelector wrappedSelector) { public List select(final ClusterDescription clusterDescription) { List serverDescriptions = clusterDescription.getServerDescriptions(); + // TODO-JAVA-5908: Evaluate whether the early-return optimization a meaningful performance impact on server selection. if (serverDescriptions.size() == 1 || deprioritized.isEmpty()) { return wrappedSelector.select(clusterDescription); } + // TODO-JAVA-5908: Evaluate whether using a loop instead of Stream a meaningful performance impact on server selection. List nonDeprioritizedServerDescriptions = serverDescriptions .stream() .filter(serverDescription -> !deprioritized.contains(serverDescription.getAddress())) .collect(toList()); + // TODO-JAVA-5908: Evaluate whether the early-return optimization a meaningful performance impact on server selection. if (nonDeprioritizedServerDescriptions.isEmpty()) { return wrappedSelector.select(clusterDescription); } List selected = wrappedSelector.select( - new ClusterDescription(clusterDescription.getConnectionMode(), clusterDescription.getType(), + new ClusterDescription( + clusterDescription.getConnectionMode(), + clusterDescription.getType(), nonDeprioritizedServerDescriptions, clusterDescription.getClusterSettings(), clusterDescription.getServerSettings())); From 2bc1b2eee2b76b8a4f380691f2abd4536c1b5bdc Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 14:50:44 -0800 Subject: [PATCH 15/43] Add empty line. --- .../mongodb/internal/connection/ServerDeprioritizationTest.java | 1 + 1 file changed, 1 insertion(+) 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 bfd10334085..2936d67a40f 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 @@ -80,6 +80,7 @@ private static Stream selectNoneDeprioritized() { of(Named.of(generateArgumentName(ALL_SERVERS), ALL_SERVERS)) ); } + @ParameterizedTest @MethodSource void selectNoneDeprioritized(final List selectorResult) { From 8a8bf0a1cf39786218ae533087196476ffdf7184 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 14:54:47 -0800 Subject: [PATCH 16/43] Return ALL_SERVERS from selector. --- .../internal/connection/ServerDeprioritizationTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 2936d67a40f..1c7cf3b9aa4 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 @@ -183,8 +183,8 @@ void onAttemptFailureIgnoresIfPoolClearedException() { serverDeprioritization.updateCandidate(SERVER_A.getAddress()); serverDeprioritization.onAttemptFailure( new MongoConnectionPoolClearedException(new ServerId(new ClusterId(), new ServerAddress()), null)); - ServerSelector selector = createAssertingSelector(ALL_SERVERS, singletonList(SERVER_A)); - assertEquals(singletonList(SERVER_A), serverDeprioritization.apply(selector).select(SHARDED_CLUSTER)); + ServerSelector selector = createAssertingSelector(ALL_SERVERS, ALL_SERVERS); + assertEquals(ALL_SERVERS, serverDeprioritization.apply(selector).select(SHARDED_CLUSTER)); } @Test From cf5c48446c8ce92fcc95197d4deefa1c2a1ab318 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 14:57:27 -0800 Subject: [PATCH 17/43] Make heartbeatFrequencyMS a local variable. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 e53e1559487..280964e1b6e 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -78,7 +78,6 @@ public class ServerSelectionSelectionTest { private final String description; private final BsonDocument definition; private final ClusterDescription clusterDescription; - private final long heartbeatFrequencyMS; private final boolean error; private final List deprioritizedServerAddresses; @@ -92,7 +91,8 @@ public class ServerSelectionSelectionTest { public ServerSelectionSelectionTest(final String description, final BsonDocument definition) { this.description = description; this.definition = definition; - this.heartbeatFrequencyMS = definition.getNumber("heartbeatFrequencyMS", new BsonInt64(10000)).longValue(); + + long heartbeatFrequencyMS = definition.getNumber("heartbeatFrequencyMS", new BsonInt64(10000)).longValue(); this.error = definition.getBoolean("error", BsonBoolean.FALSE).getValue(); this.clusterDescription = buildClusterDescription(definition.getDocument("topology_description"), ServerSettings.builder().heartbeatFrequency(heartbeatFrequencyMS, TimeUnit.MILLISECONDS).build()); From 32609f64b111d63e3e8c4169b90862dc773510a5 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 15:07:33 -0800 Subject: [PATCH 18/43] Revert to assumeFalse. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 280964e1b6e..a5e78ab79e7 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -68,7 +68,7 @@ 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.Assume.assumeFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.when; @@ -102,7 +102,7 @@ public ServerSelectionSelectionTest(final String description, final BsonDocument @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")); + assumeFalse(description.endsWith("/max-staleness/tests/ReplicaSetWithPrimary/MaxStalenessWithModePrimary.json")); ServerTuple serverTuple; ServerSelector serverSelector = getServerSelector(); OperationContext operationContext = createOperationContext(); From 7d3d8625b5330827dcadad9795b67bb794946a2e Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 17:13:07 -0800 Subject: [PATCH 19/43] Use Junit4. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) 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 a5e78ab79e7..b4883b297e1 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -46,7 +46,6 @@ 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; @@ -69,7 +68,7 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.when; // See https://github.com/mongodb/specifications/tree/master/source/server-selection/tests @@ -352,7 +351,7 @@ public ServersSnapshot getServersSnapshot(final Timeout serverSelectionTimeout, @Override public void onChange(final ServerDescriptionChangedEvent event) { // We do not expect this to be called during server selection. - Assertions.fail(); + fail(); } } } From eff9e2351ff95bafec29cd7d203d720dad4281cf Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 17:17:32 -0800 Subject: [PATCH 20/43] Convert comment to a class documentation comment. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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 b4883b297e1..da29e00b39f 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -71,7 +71,9 @@ import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.when; -// See https://github.com/mongodb/specifications/tree/master/source/server-selection/tests +/** + * See Server Selection Tests. + */ @RunWith(Parameterized.class) public class ServerSelectionSelectionTest { private final String description; From 78d685d92d6d7b0b41ca312127f5852561853058 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 17:18:46 -0800 Subject: [PATCH 21/43] Remove deprioritizedServerAddresses field. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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 da29e00b39f..b5cda4e903c 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -80,7 +80,6 @@ public class ServerSelectionSelectionTest { private final BsonDocument definition; private final ClusterDescription clusterDescription; 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")); @@ -97,7 +96,6 @@ 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 @@ -299,7 +297,7 @@ private OperationContext createOperationContext() { OperationContext.simpleOperationContext( new TimeoutContext(TIMEOUT_SETTINGS.withServerSelectionTimeoutMS(SERVER_SELECTION_TIMEOUT_MS))); OperationContext.ServerDeprioritization serverDeprioritization = operationContext.getServerDeprioritization(); - for (ServerAddress address : deprioritizedServerAddresses) { + for (ServerAddress address : extractDeprioritizedServerAddresses(definition)) { serverDeprioritization.updateCandidate(address); serverDeprioritization.onAttemptFailure(new MongoConfigurationException("test")); } From ff279de7fdfdb3a2464288ad7216a9db8f7b729c Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 17:36:34 -0800 Subject: [PATCH 22/43] Move inLatencyWindowServers to pre-try. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 b5cda4e903c..6c559d8f2e2 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -106,6 +106,8 @@ public void shouldPassAllOutcomes() { ServerSelector serverSelector = getServerSelector(); OperationContext operationContext = createOperationContext(); Cluster.ServersSnapshot serversSnapshot = createServersSnapshot(clusterDescription); + List inLatencyWindowServers = buildServerDescriptions(definition.getArray("in_latency_window", new BsonArray())); + try (BaseCluster cluster = createTestCluster(clusterDescription, serversSnapshot);) { serverTuple = cluster.selectServer(serverSelector, operationContext); if (error) { @@ -117,13 +119,11 @@ public void shouldPassAllOutcomes() { } 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; } - List inLatencyWindowServers = buildServerDescriptions(definition.getArray("in_latency_window")); assertNotNull(serverTuple); assertTrue(inLatencyWindowServers.stream().anyMatch(s -> s.equals(serverTuple.getServerDescription()))); } From 2f06765f5ab0700acc19aea436220d2b21250c4f Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 17:36:49 -0800 Subject: [PATCH 23/43] Remove unnecessary symbol. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 6c559d8f2e2..ede2619f600 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -108,7 +108,7 @@ public void shouldPassAllOutcomes() { Cluster.ServersSnapshot serversSnapshot = createServersSnapshot(clusterDescription); List inLatencyWindowServers = buildServerDescriptions(definition.getArray("in_latency_window", new BsonArray())); - try (BaseCluster cluster = createTestCluster(clusterDescription, serversSnapshot);) { + try (BaseCluster cluster = createTestCluster(clusterDescription, serversSnapshot)) { serverTuple = cluster.selectServer(serverSelector, operationContext); if (error) { fail("Should have thrown exception"); From cdee4fa0b661bad765f35336bbd181992cb1f9eb Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 18:20:48 -0800 Subject: [PATCH 24/43] Add assertion context. --- .../ServerSelectionSelectionTest.java | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) 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 ede2619f600..8154a19c756 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -65,6 +65,7 @@ import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS; import static com.mongodb.connection.ServerDescription.MIN_DRIVER_WIRE_VERSION; +import static java.lang.String.format; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.junit.Assume.assumeFalse; @@ -111,21 +112,21 @@ public void shouldPassAllOutcomes() { try (BaseCluster cluster = createTestCluster(clusterDescription, serversSnapshot)) { serverTuple = cluster.selectServer(serverSelector, operationContext); if (error) { - fail("Should have thrown exception"); + fail(format("Should have thrown exception")); } } catch (MongoConfigurationException e) { if (!error) { - fail("Should not have thrown exception: " + e); + fail(format("Should not have thrown exception: %s", e)); } return; } catch (MongoTimeoutException mongoTimeoutException) { - assertTrue("Expected emtpy but was " + inLatencyWindowServers.size() + " " + definition.toJson( - JsonWriterSettings.builder() - .indent(true).build()), inLatencyWindowServers.isEmpty()); + assertTrue(format("Expected empty but was %s", inLatencyWindowServers.size()), + inLatencyWindowServers.isEmpty()); return; } - assertNotNull(serverTuple); - assertTrue(inLatencyWindowServers.stream().anyMatch(s -> s.equals(serverTuple.getServerDescription()))); + assertNotNull(format("Server tuple should not be null"), serverTuple); + assertTrue(format("Selected server should be in latency window"), + inLatencyWindowServers.stream().anyMatch(s -> s.equals(serverTuple.getServerDescription()))); } @Parameterized.Parameters(name = "{0}") @@ -354,4 +355,9 @@ public void onChange(final ServerDescriptionChangedEvent event) { fail(); } } + + private String format(final String messageFormat, final Object... args) { + String message = String.format(messageFormat, args); + return message + "\nTest Definition:\n" + definition.toJson(JsonWriterSettings.builder().indent(true).build()); + } } From 12ceda72e123d7887c62f4d3eff53bcb4a8d19c1 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 18:32:19 -0800 Subject: [PATCH 25/43] Remove redundant comment. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 1 - 1 file changed, 1 deletion(-) 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 8154a19c756..8c107605ac5 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -132,7 +132,6 @@ public void shouldPassAllOutcomes() { @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")) { String resourcePath = testDocument.getString("resourcePath").getValue(); data.add(new Object[]{resourcePath, testDocument}); From b16bfb0d6bc6563e459538803de66f6a3abe24b1 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 18:35:55 -0800 Subject: [PATCH 26/43] Use immediate timeout. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) 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 8c107605ac5..05a90b93552 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -82,7 +82,6 @@ public class ServerSelectionSelectionTest { private final ClusterDescription clusterDescription; private final boolean error; - 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")); @@ -295,7 +294,7 @@ private static List extractDeprioritizedServerAddresses(final Bso private OperationContext createOperationContext() { OperationContext operationContext = OperationContext.simpleOperationContext( - new TimeoutContext(TIMEOUT_SETTINGS.withServerSelectionTimeoutMS(SERVER_SELECTION_TIMEOUT_MS))); + new TimeoutContext(TIMEOUT_SETTINGS.withServerSelectionTimeoutMS(0))); OperationContext.ServerDeprioritization serverDeprioritization = operationContext.getServerDeprioritization(); for (ServerAddress address : extractDeprioritizedServerAddresses(definition)) { serverDeprioritization.updateCandidate(address); From a7fc3fc93994c863808057a1bd0ba7116d10098c Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 18:38:54 -0800 Subject: [PATCH 27/43] Use MongoException instead of MongoConfigurationException. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 05a90b93552..2d2d5b1006c 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -18,6 +18,7 @@ import com.mongodb.ClusterFixture; import com.mongodb.MongoConfigurationException; +import com.mongodb.MongoException; import com.mongodb.MongoTimeoutException; import com.mongodb.ReadPreference; import com.mongodb.ServerAddress; @@ -298,7 +299,7 @@ private OperationContext createOperationContext() { OperationContext.ServerDeprioritization serverDeprioritization = operationContext.getServerDeprioritization(); for (ServerAddress address : extractDeprioritizedServerAddresses(definition)) { serverDeprioritization.updateCandidate(address); - serverDeprioritization.onAttemptFailure(new MongoConfigurationException("test")); + serverDeprioritization.onAttemptFailure(new MongoException("test")); } return operationContext; } From 1d15a73e7489643e632d5e77feb3ac763cbb00a8 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 18:40:44 -0800 Subject: [PATCH 28/43] Remove createTestCluster method. --- .../mongodb/connection/ServerSelectionSelectionTest.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) 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 2d2d5b1006c..8262dcb5750 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -109,7 +109,7 @@ public void shouldPassAllOutcomes() { Cluster.ServersSnapshot serversSnapshot = createServersSnapshot(clusterDescription); List inLatencyWindowServers = buildServerDescriptions(definition.getArray("in_latency_window", new BsonArray())); - try (BaseCluster cluster = createTestCluster(clusterDescription, serversSnapshot)) { + try (BaseCluster cluster = new TestCluster(clusterDescription, serversSnapshot)) { serverTuple = cluster.selectServer(serverSelector, operationContext); if (error) { fail(format("Should have thrown exception")); @@ -316,11 +316,7 @@ private static Cluster.ServersSnapshot createServersSnapshot( 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) { + private static void validateTestDescriptionFields(final Set actualFields, final Set knownFields) { Set unknownFields = new HashSet<>(actualFields); unknownFields.removeAll(knownFields); if (!unknownFields.isEmpty()) { From 3e2c0cd0dde21f1fe9b175049574245e1da87293 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 18:42:34 -0800 Subject: [PATCH 29/43] Use com.mongodb.assertions.Assertions.fail for a Fake cluster. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 8262dcb5750..ae2fc273a26 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -24,6 +24,7 @@ import com.mongodb.ServerAddress; import com.mongodb.Tag; import com.mongodb.TagSet; +import com.mongodb.assertions.Assertions; import com.mongodb.event.ServerDescriptionChangedEvent; import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.connection.BaseCluster; @@ -346,8 +347,7 @@ public ServersSnapshot getServersSnapshot(final Timeout serverSelectionTimeout, @Override public void onChange(final ServerDescriptionChangedEvent event) { - // We do not expect this to be called during server selection. - fail(); + Assertions.fail(); } } From 9a84fc0c0921643ef1f90316a17e6cc74cad1d32 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 18:50:42 -0800 Subject: [PATCH 30/43] Change message. --- .../com/mongodb/connection/ServerSelectionSelectionTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 ae2fc273a26..50023bdaed5 100644 --- a/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/connection/ServerSelectionSelectionTest.java @@ -126,7 +126,7 @@ public void shouldPassAllOutcomes() { return; } assertNotNull(format("Server tuple should not be null"), serverTuple); - assertTrue(format("Selected server should be in latency window"), + assertTrue(format("Selected server should be in latency window. Selected server: %s", serverTuple.getServerDescription()), inLatencyWindowServers.stream().anyMatch(s -> s.equals(serverTuple.getServerDescription()))); } From 36c83c3fea99a566b31d541cc2c5acfb48cdbcb8 Mon Sep 17 00:00:00 2001 From: Viacheslav Babanin Date: Wed, 4 Mar 2026 18:51:50 -0800 Subject: [PATCH 31/43] Update driver-core/src/test/unit/com/mongodb/internal/connection/ServerDeprioritizationTest.java Co-authored-by: Valentin Kovalenko --- .../ServerDeprioritizationTest.java | 33 ++++++++----------- 1 file changed, 14 insertions(+), 19 deletions(-) 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 1c7cf3b9aa4..0048d084e72 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 @@ -155,26 +155,21 @@ void selectAllDeprioritizedSingleServerCluster() { @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; - } - }; - + Supplier selectorSupplier = () -> MongoMockito.mock(ServerSelector.class, tuner -> + Mockito.when(tuner.select(any(ClusterDescription.class))) + .thenAnswer(invocation -> { + assertEquals(asList(SERVER_A, SERVER_C), invocation.getArgument(0).getServerDescriptions()); + return emptyList(); + }) + .thenAnswer(invocation -> { + assertEquals(ALL_SERVERS, invocation.getArgument(0).getServerDescriptions()); + return selectorResult; + }) + ); assertAll( - () -> assertEquals(selectorResult, serverDeprioritization.apply(selector.get()).select(SHARDED_CLUSTER)), - () -> assertEquals(selectorResult, serverDeprioritization.apply(selector.get()).select(REPLICA_SET_CLUSTER)), - () -> assertEquals(selectorResult, serverDeprioritization.apply(selector.get()).select(UNKNOWN_CLUSTER)) + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selectorSupplier.get()).select(SHARDED_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selectorSupplier.get()).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selectorSupplier.get()).select(UNKNOWN_CLUSTER)) ); } From 9b81ebd2276c06538c8d65866ac687be686e1128 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 19:15:21 -0800 Subject: [PATCH 32/43] Use MongoMockito. --- .../internal/connection/ServerDeprioritizationTest.java | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) 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 0048d084e72..5ceeecb946b 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,6 +25,7 @@ import com.mongodb.connection.ServerDescription; import com.mongodb.connection.ServerId; import com.mongodb.internal.connection.OperationContext.ServerDeprioritization; +import com.mongodb.internal.mockito.MongoMockito; import com.mongodb.selector.ServerSelector; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Named; @@ -32,6 +33,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.Mockito; import java.util.List; import java.util.function.Supplier; @@ -48,6 +50,7 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.params.provider.Arguments.of; +import static org.mockito.ArgumentMatchers.any; final class ServerDeprioritizationTest { private static final ServerDescription SERVER_A = serverDescription("a"); @@ -167,9 +170,9 @@ void selectWithRetryWhenWrappedReturnsEmpty(final List select }) ); assertAll( - () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selectorSupplier.get()).select(SHARDED_CLUSTER)), - () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selectorSupplier.get()).select(REPLICA_SET_CLUSTER)), - () -> assertEquals(selectorResult, serverDeprioritization.applyDeprioritization(selectorSupplier.get()).select(UNKNOWN_CLUSTER)) + () -> assertEquals(selectorResult, serverDeprioritization.apply(selectorSupplier.get()).select(SHARDED_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.apply(selectorSupplier.get()).select(REPLICA_SET_CLUSTER)), + () -> assertEquals(selectorResult, serverDeprioritization.apply(selectorSupplier.get()).select(UNKNOWN_CLUSTER)) ); } From 2df458066c70b30b404be398d18bcbe875859c94 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 19:15:37 -0800 Subject: [PATCH 33/43] Remove TODO. --- .../com/mongodb/internal/operation/ChangeStreamBatchCursor.java | 2 -- 1 file changed, 2 deletions(-) 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 d2c643699fa..cb6672c06ca 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursor.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursor.java @@ -87,8 +87,6 @@ final class ChangeStreamBatchCursor implements AggregateResponseBatchCursor Date: Wed, 4 Mar 2026 19:16:41 -0800 Subject: [PATCH 34/43] Use withNewServerDeprioritization. --- .../com/mongodb/internal/connection/OperationContext.java | 4 ++-- .../mongodb/internal/operation/ChangeStreamBatchCursor.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) 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 6ce3e559e98..89a0ef679b1 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -116,8 +116,8 @@ public OperationContext withOperationName(final String operationName) { // 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, + public OperationContext withNewServerDeprioritization() { + return new OperationContext(id, requestContext, sessionContext, timeoutContext, new ServerDeprioritization(), tracingManager, serverApi, operationName, tracingSpan); } 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 cb6672c06ca..226deafa9fa 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursor.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursor.java @@ -87,7 +87,7 @@ final class ChangeStreamBatchCursor implements AggregateResponseBatchCursor Date: Wed, 4 Mar 2026 19:17:34 -0800 Subject: [PATCH 35/43] Make ServerDeprioritization private. --- .../main/com/mongodb/internal/connection/OperationContext.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) 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 89a0ef679b1..afa54d4dc72 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -237,8 +237,7 @@ public static final class ServerDeprioritization { private ServerAddress candidate; private final Set deprioritized; - @VisibleForTesting(otherwise = PRIVATE) - public ServerDeprioritization() { + private ServerDeprioritization() { candidate = null; deprioritized = new HashSet<>(); } From cd67117e3900e36111076888ef823e57178e135c Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 19:20:26 -0800 Subject: [PATCH 36/43] Remove unused methods. --- .../internal/connection/OperationContext.java | 25 ++----------------- 1 file changed, 2 insertions(+), 23 deletions(-) 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 afa54d4dc72..c2bdccd787b 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -77,7 +77,7 @@ public OperationContext(final RequestContext requestContext, final SessionContex null); } - public static OperationContext simpleOperationContext( + static OperationContext simpleOperationContext( final TimeoutSettings timeoutSettings, @Nullable final ServerApi serverApi) { return new OperationContext( IgnorableRequestContext.INSTANCE, @@ -160,8 +160,7 @@ public void setTracingSpan(final Span tracingSpan) { this.tracingSpan = tracingSpan; } - @VisibleForTesting(otherwise = VisibleForTesting.AccessModifier.PRIVATE) - public OperationContext(final long id, + private OperationContext(final long id, final RequestContext requestContext, final SessionContext sessionContext, final TimeoutContext timeoutContext, @@ -182,26 +181,6 @@ public OperationContext(final long id, this.tracingSpan = tracingSpan; } - @VisibleForTesting(otherwise = VisibleForTesting.AccessModifier.PRIVATE) - public OperationContext(final long id, - final RequestContext requestContext, - final SessionContext sessionContext, - final TimeoutContext timeoutContext, - final TracingManager tracingManager, - @Nullable final ServerApi serverApi, - @Nullable final String operationName) { - this.id = id; - this.serverDeprioritization = new ServerDeprioritization(); - this.requestContext = requestContext; - this.sessionContext = sessionContext; - this.timeoutContext = timeoutContext; - this.tracingManager = tracingManager; - this.serverApi = serverApi; - this.operationName = operationName; - this.tracingSpan = null; - } - - /** * @return The same {@link ServerDeprioritization} if called on the same {@link OperationContext}. */ From 431089451276dbb18e4b8c8b04fc6cfd6e0195bd Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 19:48:48 -0800 Subject: [PATCH 37/43] Reuse OperationContext. --- .../connection/ConnectionSpecification.groovy | 17 ++++++++++------- ...bstractServerDiscoveryAndMonitoringTest.java | 5 +++-- .../MultiServerClusterSpecification.groovy | 5 +++-- .../ServerDiscoveryAndMonitoringTest.java | 5 +++-- 4 files changed, 19 insertions(+), 13 deletions(-) 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 c73f37f8d5f..5dd6145f063 100644 --- a/driver-core/src/test/functional/com/mongodb/connection/ConnectionSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/connection/ConnectionSpecification.groovy @@ -17,6 +17,7 @@ package com.mongodb.connection import com.mongodb.OperationFunctionalSpecification +import com.mongodb.internal.connection.OperationContext import com.mongodb.internal.operation.CommandReadOperation import org.bson.BsonDocument import org.bson.BsonInt32 @@ -32,8 +33,9 @@ class ConnectionSpecification extends OperationFunctionalSpecification { def 'should have id'() { when: - def source = getBinding().getReadConnectionSource(createOperationContext()) - def connection = source.getConnection(createOperationContext()) + def operationContext = createOperationContext() + def source = getBinding().getReadConnectionSource(operationContext) + def connection = source.getConnection(operationContext) then: connection.getDescription().getConnectionId() != null @@ -45,13 +47,14 @@ class ConnectionSpecification extends OperationFunctionalSpecification { def 'should have description'() { when: - def commandResult = getHelloResult() + def operationContext = createOperationContext() + def commandResult = getHelloResult(operationContext) def expectedMaxMessageSize = commandResult.getNumber('maxMessageSizeBytes', new BsonInt32(getDefaultMaxMessageSize())).intValue() def expectedMaxBatchCount = commandResult.getNumber('maxWriteBatchSize', new BsonInt32(getDefaultMaxWriteBatchSize())).intValue() - def source = getBinding().getReadConnectionSource(createOperationContext()) - def connection = source.getConnection(createOperationContext()) + def source = getBinding().getReadConnectionSource(operationContext) + def connection = source.getConnection(operationContext) then: connection.description.serverAddress == source.getServerDescription().getAddress() @@ -64,8 +67,8 @@ class ConnectionSpecification extends OperationFunctionalSpecification { connection?.release() source?.release() } - private static BsonDocument getHelloResult() { + private static BsonDocument getHelloResult(OperationContext operationContext) { new CommandReadOperation('admin', new BsonDocument(LEGACY_HELLO, new BsonInt32(1)), - new BsonDocumentCodec()).execute(getBinding(), createOperationContext()) + new BsonDocumentCodec()).execute(getBinding(), operationContext) } } 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 0769939fd2a..d1b1f27a901 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 @@ -82,7 +82,8 @@ protected void applyResponse(final BsonArray response) { } protected void applyApplicationError(final BsonDocument applicationError) { - Timeout serverSelectionTimeout = ClusterFixture.createOperationContext().getTimeoutContext().computeServerSelectionTimeout(); + OperationContext operationContext = ClusterFixture.createOperationContext(); + Timeout serverSelectionTimeout = operationContext.getTimeoutContext().computeServerSelectionTimeout(); ServerAddress serverAddress = new ServerAddress(applicationError.getString("address").getValue()); TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS); int errorGeneration = applicationError.getNumber("generation", @@ -98,7 +99,7 @@ protected void applyApplicationError(final BsonDocument applicationError) { switch (type) { case "command": exception = getCommandFailureException(applicationError.getDocument("response"), serverAddress, - ClusterFixture.createOperationContext().getTimeoutContext()); + operationContext.getTimeoutContext()); break; case "network": exception = new MongoSocketReadException("Read error", serverAddress, new IOException()); 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 535cd5fdff6..737aead0300 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 @@ -93,11 +93,12 @@ class MultiServerClusterSpecification extends Specification { def cluster = new MultiServerCluster(CLUSTER_ID, ClusterSettings.builder().hosts(Arrays.asList(firstServer)).mode(MULTIPLE).build(), factory, CLIENT_METADATA) cluster.close() + def operationContext = createOperationContext() when: cluster.getServersSnapshot( - createOperationContext().getTimeoutContext().computeServerSelectionTimeout(), - createOperationContext().getTimeoutContext()) + operationContext.getTimeoutContext().computeServerSelectionTimeout(), + operationContext.getTimeoutContext()) then: thrown(IllegalStateException) 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 90cd8da3412..095372a6cee 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 @@ -154,9 +154,10 @@ private void assertServer(final String serverName, final BsonDocument expectedSe if (expectedServerDescriptionDocument.isDocument("pool")) { int expectedGeneration = expectedServerDescriptionDocument.getDocument("pool").getNumber("generation").intValue(); - Timeout serverSelectionTimeout = ClusterFixture.createOperationContext().getTimeoutContext().computeServerSelectionTimeout(); + OperationContext operationContext = ClusterFixture.createOperationContext(); + Timeout serverSelectionTimeout = operationContext.getTimeoutContext().computeServerSelectionTimeout(); DefaultServer server = (DefaultServer) getCluster() - .getServersSnapshot(serverSelectionTimeout, ClusterFixture.createOperationContext().getTimeoutContext()) + .getServersSnapshot(serverSelectionTimeout, operationContext.getTimeoutContext()) .getServer(new ServerAddress(serverName)); assertEquals(expectedGeneration, server.getConnectionPool().getGeneration()); } From f57616d2e184630aec5a7a94b470a6bdd90b9723 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 19:49:23 -0800 Subject: [PATCH 38/43] Use a documentation comment. --- .../com/mongodb/internal/connection/OperationContext.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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 c2bdccd787b..ab27baa940f 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -114,8 +114,10 @@ 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. + /** + * 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 withNewServerDeprioritization() { return new OperationContext(id, requestContext, sessionContext, timeoutContext, new ServerDeprioritization(), tracingManager, serverApi, operationName, tracingSpan); From 0a4f04fe765d858e8402a4b23693d2046f8c19b3 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 19:50:09 -0800 Subject: [PATCH 39/43] Use VisibleForTesting(otherwise = PROTECTED). --- .../src/main/com/mongodb/internal/connection/BaseCluster.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 a5a44c4ecf3..436ce8ece8e 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java +++ b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java @@ -69,6 +69,7 @@ import static com.mongodb.internal.Locks.withInterruptibleLock; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PACKAGE; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; +import static com.mongodb.internal.VisibleForTesting.AccessModifier.PROTECTED; import static com.mongodb.internal.connection.EventHelper.wouldDescriptionsGenerateEquivalentEvents; import static com.mongodb.internal.event.EventListenerHelper.singleClusterListener; import static com.mongodb.internal.logging.LogMessage.Component.SERVER_SELECTION; @@ -95,7 +96,7 @@ import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.stream.Collectors.toList; -@VisibleForTesting(otherwise = PRIVATE) +@VisibleForTesting(otherwise = PROTECTED) public abstract class BaseCluster implements Cluster { private static final Logger LOGGER = Loggers.getLogger("cluster"); private static final StructuredLogger STRUCTURED_LOGGER = new StructuredLogger("cluster"); From c736e6a06f78d63748e0a41f2ce5282dd3dc9718 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 19:52:09 -0800 Subject: [PATCH 40/43] Reuse OperatioContext. --- .../com/mongodb/internal/connection/OperationContext.java | 1 - .../operation/CommandBatchCursorFunctionalTest.java | 6 ++++-- 2 files changed, 4 insertions(+), 3 deletions(-) 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 ab27baa940f..fee3bb105b2 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -40,7 +40,6 @@ 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; /** 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 21e903abc34..946e5504db3 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 @@ -27,6 +27,7 @@ import com.mongodb.client.model.OperationTest; import com.mongodb.internal.binding.ConnectionSource; import com.mongodb.internal.connection.Connection; +import com.mongodb.internal.connection.OperationContext; import com.mongodb.internal.validator.NoOpFieldNameValidator; import org.bson.BsonArray; import org.bson.BsonBoolean; @@ -86,8 +87,9 @@ void setup() { .collect(Collectors.toList()); getCollectionHelper().insertDocuments(documents); - connectionSource = getBinding().getWriteConnectionSource(ClusterFixture.createOperationContext()); - connection = connectionSource.getConnection(ClusterFixture.createOperationContext()); + OperationContext operationContext = ClusterFixture.createOperationContext(); + connectionSource = getBinding().getWriteConnectionSource(operationContext); + connection = connectionSource.getConnection(operationContext); } @AfterEach From c97cb65c6a5046797993d09c562d5805dfc22935 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 20:26:11 -0800 Subject: [PATCH 41/43] Change comments. --- .../com/mongodb/internal/connection/OperationContext.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 fee3bb105b2..274d31a0c16 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -264,18 +264,18 @@ private DeprioritizingSelector(final ServerSelector wrappedSelector) { public List select(final ClusterDescription clusterDescription) { List serverDescriptions = clusterDescription.getServerDescriptions(); - // TODO-JAVA-5908: Evaluate whether the early-return optimization a meaningful performance impact on server selection. + // TODO-JAVA-5908: Evaluate whether using the early-return optimization has a meaningful performance impact on server selection. if (serverDescriptions.size() == 1 || deprioritized.isEmpty()) { return wrappedSelector.select(clusterDescription); } - // TODO-JAVA-5908: Evaluate whether using a loop instead of Stream a meaningful performance impact on server selection. + // TODO-JAVA-5908: Evaluate whether using a loop instead of Stream has a meaningful performance impact on server selection. List nonDeprioritizedServerDescriptions = serverDescriptions .stream() .filter(serverDescription -> !deprioritized.contains(serverDescription.getAddress())) .collect(toList()); - // TODO-JAVA-5908: Evaluate whether the early-return optimization a meaningful performance impact on server selection. + // TODO-JAVA-5908: Evaluate whether the early-return optimization has a meaningful performance impact on server selection. if (nonDeprioritizedServerDescriptions.isEmpty()) { return wrappedSelector.select(clusterDescription); } From 012aa6b2ec793c115358394e1433ebf978b3ebc9 Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Wed, 4 Mar 2026 20:27:24 -0800 Subject: [PATCH 42/43] Change comments. --- .../main/com/mongodb/internal/connection/OperationContext.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 274d31a0c16..9042bc3b2c3 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OperationContext.java @@ -275,7 +275,7 @@ public List select(final ClusterDescription clusterDescriptio .filter(serverDescription -> !deprioritized.contains(serverDescription.getAddress())) .collect(toList()); - // TODO-JAVA-5908: Evaluate whether the early-return optimization has a meaningful performance impact on server selection. + // TODO-JAVA-5908: Evaluate whether using the early-return optimization has a meaningful performance impact on server selection. if (nonDeprioritizedServerDescriptions.isEmpty()) { return wrappedSelector.select(clusterDescription); } From 676770742d4a6cac67a0aa936621970525fb4c8d Mon Sep 17 00:00:00 2001 From: "slav.babanin" Date: Thu, 5 Mar 2026 11:28:42 -0800 Subject: [PATCH 43/43] Use createOperationContext. --- .../AggregateOperationSpecification.groovy | 4 +-- .../CreateViewOperationSpecification.groovy | 3 +- .../DropDatabaseOperationSpecification.groovy | 6 ++-- .../FindOperationSpecification.groovy | 4 +-- ...stCollectionsOperationSpecification.groovy | 35 ++++++++++--------- .../ListIndexesOperationSpecification.groovy | 12 +++---- ...ameCollectionOperationSpecification.groovy | 7 ++-- 7 files changed, 37 insertions(+), 34 deletions(-) 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 7ddc5a83e97..a39b7ca6448 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 @@ -355,7 +355,7 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification { def binding = ClusterFixture.getBinding() new CommandReadOperation<>(getDatabaseName(), new BsonDocument('profile', new BsonInt32(2)), - new BsonDocumentCodec()).execute(binding, getOperationContext(binding.getReadPreference())) + new BsonDocumentCodec()).execute(binding, createOperationContext(binding.getReadPreference())) def expectedComment = 'this is a comment' def operation = new AggregateOperation(getNamespace(), [], new DocumentCodec()) .comment(new BsonString(expectedComment)) @@ -371,7 +371,7 @@ class AggregateOperationSpecification extends OperationFunctionalSpecification { cleanup: binding = ClusterFixture.getBinding() new CommandReadOperation<>(getDatabaseName(), new BsonDocument('profile', new BsonInt32(0)), - new BsonDocumentCodec()).execute(binding, getOperationContext(binding.getReadPreference())) + new BsonDocumentCodec()).execute(binding, createOperationContext(binding.getReadPreference())) profileCollectionHelper.drop() where: diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/CreateViewOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/CreateViewOperationSpecification.groovy index 7877fd653a5..3e90c21363e 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/CreateViewOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/CreateViewOperationSpecification.groovy @@ -29,6 +29,7 @@ import org.bson.BsonString import org.bson.codecs.BsonDocumentCodec import spock.lang.IgnoreIf +import static com.mongodb.ClusterFixture.createOperationContext import static com.mongodb.ClusterFixture.getBinding import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet @@ -123,7 +124,7 @@ class CreateViewOperationSpecification extends OperationFunctionalSpecification def getCollectionInfo(String collectionName) { def binding = getBinding() new ListCollectionsOperation(databaseName, new BsonDocumentCodec()).filter(new BsonDocument('name', - new BsonString(collectionName))).execute(binding, getOperationContext(binding.getReadPreference())).tryNext()?.head() + new BsonString(collectionName))).execute(binding, createOperationContext(binding.getReadPreference())).tryNext()?.head() } def collectionNameExists(String collectionName) { diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/DropDatabaseOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/DropDatabaseOperationSpecification.groovy index 8cecd74e468..955b5efcaa3 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/DropDatabaseOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/DropDatabaseOperationSpecification.groovy @@ -16,7 +16,6 @@ package com.mongodb.internal.operation - import com.mongodb.MongoWriteConcernException import com.mongodb.OperationFunctionalSpecification import com.mongodb.WriteConcern @@ -25,6 +24,7 @@ import org.bson.Document import org.bson.codecs.DocumentCodec import spock.lang.IgnoreIf +import static com.mongodb.ClusterFixture.createOperationContext import static com.mongodb.ClusterFixture.configureFailPoint import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.ClusterFixture.getBinding @@ -79,7 +79,7 @@ class DropDatabaseOperationSpecification extends OperationFunctionalSpecificatio def binding = getBinding() when: - async ? executeAsync(operation) : operation.execute(binding, getOperationContext(binding.getReadPreference())) + async ? executeAsync(operation) : operation.execute(binding, createOperationContext(binding.getReadPreference())) then: def ex = thrown(MongoWriteConcernException) @@ -92,7 +92,7 @@ class DropDatabaseOperationSpecification extends OperationFunctionalSpecificatio def databaseNameExists(String databaseName) { new ListDatabasesOperation(new DocumentCodec()).execute(binding, - getOperationContext(binding.getReadPreference())).next()*.name.contains(databaseName) + createOperationContext(binding.getReadPreference())).next()*.name.contains(databaseName) } } 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 1b8490632c3..c584ee463f9 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 @@ -389,7 +389,7 @@ class FindOperationSpecification extends OperationFunctionalSpecification { def binding = getBinding() new CommandReadOperation<>(getDatabaseName(), new BsonDocument('profile', new BsonInt32(2)), - new BsonDocumentCodec()).execute(binding, getOperationContext(binding.getReadPreference())) + new BsonDocumentCodec()).execute(binding, createOperationContext(binding.getReadPreference())) def expectedComment = 'this is a comment' def operation = new FindOperation(getNamespace(), new DocumentCodec()) .comment(new BsonString(expectedComment)) @@ -404,7 +404,7 @@ class FindOperationSpecification extends OperationFunctionalSpecification { cleanup: new CommandReadOperation<>(getDatabaseName(), new BsonDocument('profile', new BsonInt32(0)), new BsonDocumentCodec()) - .execute(binding, getOperationContext(binding.getReadPreference())) + .execute(binding, createOperationContext(binding.getReadPreference())) profileCollectionHelper.drop() where: 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 aa27242dd8c..b44b341d202 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 @@ -44,6 +44,7 @@ import org.bson.Document import org.bson.codecs.Decoder import org.bson.codecs.DocumentCodec +import static com.mongodb.ClusterFixture.createOperationContext import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.ClusterFixture.getBinding import static org.junit.jupiter.api.Assertions.assertEquals @@ -59,7 +60,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def binding = getBinding() when: - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) then: !cursor.hasNext() @@ -97,7 +98,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def binding = getBinding() when: - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) def collections = cursor.next() def names = collections*.get('name') @@ -120,7 +121,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def binding = getBinding() when: - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference()) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference()) ) def collections = cursor.next() def names = collections*.get('name') @@ -142,7 +143,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def binding = getBinding() when: - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) def collections = cursor.next() def names = collections*.get('name') @@ -160,7 +161,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def binding = getBinding() when: - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) def collection = cursor.next()[0] then: @@ -177,7 +178,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def binding = getBinding() when: - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) def collection = cursor.next()[0] then: @@ -194,7 +195,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def binding = getBinding() when: - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) def collection = cursor.next()[0] then: @@ -226,14 +227,14 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def binding = getBinding() given: new DropDatabaseOperation(databaseName, WriteConcern.ACKNOWLEDGED) - .execute(binding, getOperationContext(binding.getReadPreference())) + .execute(binding, createOperationContext(binding.getReadPreference())) addSeveralIndexes() def operation = new ListCollectionsOperation(databaseName, new DocumentCodec()).batchSize(2) when: binding = getBinding() - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) then: cursor.hasNext() @@ -246,13 +247,13 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def binding = getBinding() given: new DropDatabaseOperation(databaseName, WriteConcern.ACKNOWLEDGED) - .execute(binding, getOperationContext(binding.getReadPreference())) + .execute(binding, createOperationContext(binding.getReadPreference())) addSeveralIndexes() def operation = new ListCollectionsOperation(databaseName, new DocumentCodec()).batchSize(2) when: binding = getBinding() - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) def list = cursorToListWithNext(cursor) then: @@ -271,14 +272,14 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica def binding = getBinding() given: new DropDatabaseOperation(databaseName, WriteConcern.ACKNOWLEDGED) - .execute(binding, getOperationContext(binding.getReadPreference())) + .execute(binding, createOperationContext(binding.getReadPreference())) addSeveralIndexes() def operation = new ListCollectionsOperation(databaseName, new DocumentCodec()).batchSize(2) when: binding = getBinding() - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) then: cursor.hasNext() @@ -297,13 +298,13 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica given: def binding = getBinding() new DropDatabaseOperation(databaseName, WriteConcern.ACKNOWLEDGED) - .execute(binding, getOperationContext(binding.getReadPreference())) + .execute(binding, createOperationContext(binding.getReadPreference())) addSeveralIndexes() def operation = new ListCollectionsOperation(databaseName, new DocumentCodec()).batchSize(2) when: binding = getBinding() - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) def list = cursorToListWithTryNext(cursor) then: @@ -317,7 +318,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica given: def binding = getBinding() new DropDatabaseOperation(databaseName, WriteConcern.ACKNOWLEDGED) - .execute(binding, getOperationContext(binding.getReadPreference())) + .execute(binding, createOperationContext(binding.getReadPreference())) addSeveralIndexes() def operation = new ListCollectionsOperation(databaseName, new DocumentCodec()).batchSize(2) @@ -343,7 +344,7 @@ class ListCollectionsOperationSpecification extends OperationFunctionalSpecifica when: def binding = getBinding() - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) def collections = cursor.next() then: 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 e22fcd6d396..823de9bfd91 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 @@ -57,7 +57,7 @@ class ListIndexesOperationSpecification extends OperationFunctionalSpecification def binding = getBinding() when: - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) then: !cursor.hasNext() @@ -86,7 +86,7 @@ class ListIndexesOperationSpecification extends OperationFunctionalSpecification def binding = getBinding() when: - BatchCursor indexes = operation.execute(binding, getOperationContext(binding.getReadPreference())) + BatchCursor indexes = operation.execute(binding, createOperationContext(binding.getReadPreference())) then: def firstBatch = indexes.next() @@ -121,11 +121,11 @@ class ListIndexesOperationSpecification extends OperationFunctionalSpecification def binding = getBinding() new CreateIndexesOperation(namespace, [new IndexRequest(new BsonDocument('unique', new BsonInt32(1))).unique(true)], null).execute(binding, - getOperationContext(binding.getReadPreference())) + createOperationContext(binding.getReadPreference())) when: binding = getBinding() - BatchCursor cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + BatchCursor cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) then: def indexes = cursor.next() @@ -145,7 +145,7 @@ class ListIndexesOperationSpecification extends OperationFunctionalSpecification def binding = getBinding() new CreateIndexesOperation(namespace, [new IndexRequest(new BsonDocument('unique', new BsonInt32(1))).unique(true)], null).execute(binding, - getOperationContext(binding.getReadPreference())) + createOperationContext(binding.getReadPreference())) when: def cursor = executeAsync(operation) @@ -171,7 +171,7 @@ class ListIndexesOperationSpecification extends OperationFunctionalSpecification def binding = getBinding() when: - def cursor = operation.execute(binding, getOperationContext(binding.getReadPreference())) + def cursor = operation.execute(binding, createOperationContext(binding.getReadPreference())) def collections = cursor.next() then: diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/RenameCollectionOperationSpecification.groovy b/driver-core/src/test/functional/com/mongodb/internal/operation/RenameCollectionOperationSpecification.groovy index e79f35b76ee..080861047f1 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/RenameCollectionOperationSpecification.groovy +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/RenameCollectionOperationSpecification.groovy @@ -26,6 +26,7 @@ import org.bson.Document import org.bson.codecs.DocumentCodec import spock.lang.IgnoreIf +import static com.mongodb.ClusterFixture.createOperationContext import static com.mongodb.ClusterFixture.executeAsync import static com.mongodb.ClusterFixture.getBinding import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet @@ -37,7 +38,7 @@ class RenameCollectionOperationSpecification extends OperationFunctionalSpecific def cleanup() { def binding = getBinding() new DropCollectionOperation(new MongoNamespace(getDatabaseName(), 'newCollection'), - WriteConcern.ACKNOWLEDGED).execute(binding, getOperationContext(binding.getReadPreference())) + WriteConcern.ACKNOWLEDGED).execute(binding, createOperationContext(binding.getReadPreference())) } def 'should return rename a collection'() { @@ -86,7 +87,7 @@ class RenameCollectionOperationSpecification extends OperationFunctionalSpecific def binding = getBinding() when: - async ? executeAsync(operation) : operation.execute(binding, getOperationContext(binding.getReadPreference())) + async ? executeAsync(operation) : operation.execute(binding, createOperationContext(binding.getReadPreference())) then: def ex = thrown(MongoWriteConcernException) @@ -100,7 +101,7 @@ class RenameCollectionOperationSpecification extends OperationFunctionalSpecific def collectionNameExists(String collectionName) { def binding = getBinding() def cursor = new ListCollectionsOperation(databaseName, new DocumentCodec()).execute(binding, - getOperationContext(binding.getReadPreference())) + createOperationContext(binding.getReadPreference())) if (!cursor.hasNext()) { return false }