From bb1a40bc2468b41abfef251bbd1dd953914c594e Mon Sep 17 00:00:00 2001 From: Andre Masella Date: Mon, 26 Oct 2026 14:41:09 -0400 Subject: [PATCH] Remove experimental CSOT APIs JAVA-6325 Removes all user-facing client-side operation timeout methods and classes. --- .../com/mongodb/ClientEncryptionSettings.java | 94 -- .../com/mongodb/ClientSessionOptions.java | 63 +- .../main/com/mongodb/ConnectionString.java | 50 +- .../main/com/mongodb/MongoClientSettings.java | 89 +- .../MongoOperationTimeoutException.java | 63 - .../main/com/mongodb/TransactionOptions.java | 79 - .../mongodb/client/cursor/TimeoutMode.java | 44 - .../com/mongodb/internal/ExceptionUtils.java | 5 - .../com/mongodb/internal/TimeoutContext.java | 234 +-- .../com/mongodb/internal/TimeoutSettings.java | 77 +- .../internal/client/model/FindOptions.java | 45 +- .../connection/AbstractProtocolExecutor.java | 3 +- .../internal/connection/BaseCluster.java | 4 +- .../internal/connection/CommandHelper.java | 9 +- .../connection/DefaultConnectionPool.java | 36 +- .../InternalOperationContextFactory.java | 11 +- .../connection/InternalStreamConnection.java | 85 +- .../connection/LoadBalancedCluster.java | 21 +- .../connection/OidcAuthenticator.java | 13 - .../internal/connection/ProtocolHelper.java | 27 +- .../connection/SaslAuthenticator.java | 3 - .../internal/connection/SocketStream.java | 4 - .../AbstractWriteSearchIndexOperation.java | 4 +- .../operation/AggregateOperation.java | 6 - .../operation/AggregateOperationImpl.java | 48 +- .../AggregateToCollectionOperation.java | 10 +- .../operation/AsyncCommandBatchCursor.java | 11 - .../operation/AsyncCommandCursor.java | 5 +- .../operation/AsyncOperationHelper.java | 26 +- .../operation/ChangeStreamBatchCursor.java | 26 +- .../ChangeStreamBatchCursorHelper.java | 4 +- .../operation/ChangeStreamOperation.java | 31 +- .../operation/ClientBulkWriteOperation.java | 3 - .../operation/CommandBatchCursor.java | 13 - .../internal/operation/CommandCursor.java | 7 - .../operation/CommandOperationHelper.java | 7 +- .../operation/CommitTransactionOperation.java | 3 +- .../operation/CreateCollectionOperation.java | 4 +- .../operation/CreateIndexesOperation.java | 4 +- .../operation/CreateViewOperation.java | 4 +- .../operation/DropCollectionOperation.java | 4 +- .../operation/DropDatabaseOperation.java | 4 +- .../operation/DropIndexOperation.java | 5 +- .../operation/ExplainCommandOperation.java | 17 +- .../internal/operation/FindOperation.java | 43 +- .../operation/ListCollectionsOperation.java | 38 +- .../operation/ListIndexesOperation.java | 38 +- .../MapReduceToCollectionOperation.java | 13 +- .../operation/MixedBulkWriteOperation.java | 9 +- .../internal/operation/OperationHelper.java | 10 - .../internal/operation/Operations.java | 27 +- .../operation/RenameCollectionOperation.java | 4 +- .../internal/operation/SpecRetryPolicy.java | 5 - .../operation/SyncOperationHelper.java | 19 +- .../operation/TransactionOperation.java | 7 +- .../operation/WriteConcernHelper.java | 5 +- .../session/BaseClientSessionImpl.java | 20 +- .../com/mongodb/ClusterFixture.java | 13 +- .../connection/DefaultConnectionPoolTest.java | 28 - .../SocketStreamHelperSpecification.groovy | 27 - ...AsyncCommandBatchCursorFunctionalTest.java | 37 +- .../AsyncCommandBatchCursorTest.java | 6 +- .../operation/AsyncCommandCursorTest.java | 68 +- .../CommandBatchCursorFunctionalTest.java | 49 +- .../FindOperationSpecification.groovy | 2 +- .../mongodb/AbstractConnectionStringTest.java | 3 - ...ientEncryptionSettingsSpecification.groovy | 22 - .../ClientSessionOptionsSpecification.groovy | 18 - .../MongoClientSettingsSpecification.groovy | 34 +- .../TransactionOptionsSpecification.groovy | 22 - .../test/unit/com/mongodb/UriOptionsTest.java | 3 + .../mongodb/internal/TimeoutContextTest.java | 208 +-- .../mongodb/internal/TimeoutSettingsTest.java | 5 - ...tractServerDiscoveryAndMonitoringTest.java | 4 +- .../BaseClusterSpecification.groovy | 9 - .../connection/CommandMessageTest.java | 31 - ...ternalStreamConnectionSpecification.groovy | 106 -- .../InternalStreamConnectionTest.java | 100 -- .../connection/LoadBalancedClusterTest.java | 28 - .../ProtocolHelperSpecification.groovy | 34 +- .../connection/TestInternalConnection.java | 2 +- ...hangeStreamBatchCursorSpecification.groovy | 16 +- ...syncCommandBatchCursorSpecification.groovy | 25 +- .../BulkWriteBatchSpecification.groovy | 2 +- ...hangeStreamBatchCursorSpecification.groovy | 4 +- .../ChangeStreamBatchCursorTest.java | 253 +--- .../CommandBatchCursorSpecification.groovy | 29 +- .../operation/CommandBatchCursorTest.java | 6 +- .../internal/operation/CommandCursorTest.java | 53 +- .../syncadapter/SyncAggregateIterable.kt | 5 - .../syncadapter/SyncDistinctIterable.kt | 4 - .../coroutine/syncadapter/SyncFindIterable.kt | 2 - .../SyncListCollectionsIterable.kt | 4 - .../syncadapter/SyncListDatabasesIterable.kt | 4 - .../syncadapter/SyncListIndexesIterable.kt | 4 - .../SyncListSearchIndexesIterable.kt | 4 - .../syncadapter/SyncMapReduceIterable.kt | 4 - .../coroutine/syncadapter/SyncMongoCluster.kt | 6 - .../syncadapter/SyncMongoCollection.kt | 5 - .../syncadapter/SyncMongoDatabase.kt | 6 - .../syncadapter/SyncMongoIterable.kt | 2 - .../kotlin/client/coroutine/AggregateFlow.kt | 16 - .../kotlin/client/coroutine/DistinctFlow.kt | 16 - .../kotlin/client/coroutine/FindFlow.kt | 21 - .../client/coroutine/ListCollectionsFlow.kt | 18 - .../client/coroutine/ListDatabasesFlow.kt | 16 - .../client/coroutine/ListIndexesFlow.kt | 16 - .../client/coroutine/ListSearchIndexesFlow.kt | 18 - .../kotlin/client/coroutine/MapReduceFlow.kt | 16 - .../kotlin/client/coroutine/MongoClient.kt | 11 - .../kotlin/client/coroutine/MongoCluster.kt | 39 - .../client/coroutine/MongoCollection.kt | 39 - .../kotlin/client/coroutine/MongoDatabase.kt | 51 - .../client/coroutine/AggregateFlowTest.kt | 10 +- .../client/coroutine/DistinctFlowTest.kt | 3 - .../kotlin/client/coroutine/FindFlowTest.kt | 3 - .../coroutine/ListCollectionsFlowTest.kt | 3 - .../client/coroutine/ListDatabasesFlowTest.kt | 3 - .../client/coroutine/ListIndexesFlowTest.kt | 3 - .../client/coroutine/MapReduceFlowTest.kt | 9 +- .../syncadapter/SyncAggregateIterable.kt | 4 - .../syncadapter/SyncDistinctIterable.kt | 4 - .../client/syncadapter/SyncFindIterable.kt | 2 - .../SyncListCollectionsIterable.kt | 4 - .../syncadapter/SyncListDatabasesIterable.kt | 4 - .../syncadapter/SyncListIndexesIterable.kt | 4 - .../SyncListSearchIndexesIterable.kt | 4 - .../client/syncadapter/SyncMongoCluster.kt | 6 - .../client/syncadapter/SyncMongoCollection.kt | 5 - .../client/syncadapter/SyncMongoDatabase.kt | 6 - .../kotlin/client/AggregateIterable.kt | 24 - .../mongodb/kotlin/client/DistinctIterable.kt | 16 - .../com/mongodb/kotlin/client/FindIterable.kt | 24 - .../kotlin/client/ListCollectionsIterable.kt | 19 - .../kotlin/client/ListDatabasesIterable.kt | 19 - .../kotlin/client/ListIndexesIterable.kt | 19 - .../client/ListSearchIndexesIterable.kt | 19 - .../com/mongodb/kotlin/client/MongoClient.kt | 11 - .../com/mongodb/kotlin/client/MongoCluster.kt | 46 - .../mongodb/kotlin/client/MongoCollection.kt | 45 - .../com/mongodb/kotlin/client/MongoCursor.kt | 8 - .../mongodb/kotlin/client/MongoDatabase.kt | 63 - .../kotlin/client/AggregateIterableTest.kt | 3 - .../kotlin/client/DistinctIterableTest.kt | 3 - .../mongodb/kotlin/client/FindIterableTest.kt | 3 - .../client/ListCollectionsIterableTest.kt | 3 - .../client/ListDatabasesIterableTest.kt | 3 - .../kotlin/client/ListIndexesIterableTest.kt | 3 - driver-legacy/src/main/com/mongodb/DB.java | 5 - .../src/main/com/mongodb/MongoClient.java | 5 +- .../main/com/mongodb/MongoClientOptions.java | 69 - .../src/main/com/mongodb/MongoClientURI.java | 11 +- .../MongoClientOptionsSpecification.groovy | 6 - .../MongoClientURISpecification.groovy | 7 +- .../client/AggregatePublisher.java | 24 - .../client/DistinctPublisher.java | 17 - .../reactivestreams/client/FindPublisher.java | 24 - .../client/ListCollectionsPublisher.java | 17 - .../client/ListDatabasesPublisher.java | 17 - .../client/ListIndexesPublisher.java | 17 - .../client/ListSearchIndexesPublisher.java | 17 - .../client/MapReducePublisher.java | 24 - .../reactivestreams/client/MongoCluster.java | 52 - .../client/MongoCollection.java | 52 - .../reactivestreams/client/MongoDatabase.java | 76 - .../client/gridfs/GridFSBucket.java | 52 - .../internal/AggregatePublisherImpl.java | 11 +- .../client/internal/BatchCursorPublisher.java | 24 +- .../internal/ClientSessionPublisherImpl.java | 15 +- .../internal/DistinctPublisherImpl.java | 7 - .../client/internal/FindPublisherImpl.java | 8 - .../ListCollectionsPublisherImpl.java | 11 +- .../internal/ListDatabasesPublisherImpl.java | 7 - .../internal/ListIndexesPublisherImpl.java | 10 +- .../ListSearchIndexesPublisherImpl.java | 7 - .../internal/MapReducePublisherImpl.java | 7 - .../client/internal/MongoClientImpl.java | 12 - .../client/internal/MongoClusterImpl.java | 16 - .../client/internal/MongoCollectionImpl.java | 12 - .../client/internal/MongoDatabaseImpl.java | 13 - .../internal/MongoOperationPublisher.java | 18 - .../client/internal/TimeoutHelper.java | 118 -- .../crypt/CollectionInfoRetriever.java | 11 +- .../client/internal/crypt/CommandMarker.java | 15 +- .../client/internal/crypt/Crypt.java | 85 +- .../internal/crypt/CryptConnection.java | 6 +- .../internal/crypt/KeyManagementService.java | 41 +- .../client/internal/crypt/KeyRetriever.java | 7 +- .../internal/gridfs/GridFSBucketImpl.java | 35 +- .../gridfs/GridFSDownloadPublisherImpl.java | 38 +- .../gridfs/GridFSPublisherCreator.java | 129 +- .../gridfs/GridFSUploadPublisherImpl.java | 87 +- .../internal/vault/ClientEncryptionImpl.java | 58 +- .../ClientSideOperationTimeoutProseTest.java | 605 -------- ...eOperationsEncryptionTimeoutProseTest.java | 38 - .../syncadapter/SyncAggregateIterable.java | 7 - .../syncadapter/SyncDistinctIterable.java | 7 - .../client/syncadapter/SyncFindIterable.java | 7 - .../client/syncadapter/SyncGridFSBucket.java | 11 - .../SyncListCollectionsIterable.java | 7 - .../SyncListDatabasesIterable.java | 7 - .../syncadapter/SyncListIndexesIterable.java | 7 - .../SyncListSearchIndexesIterable.java | 7 - .../syncadapter/SyncMapReduceIterable.java | 7 - .../client/syncadapter/SyncMongoClient.java | 11 - .../client/syncadapter/SyncMongoCluster.java | 11 - .../syncadapter/SyncMongoCollection.java | 11 - .../client/syncadapter/SyncMongoDatabase.java | 11 - .../ClientSideOperationTimeoutTest.java | 158 -- .../client/internal/MongoClusterImplTest.java | 6 - .../internal/MongoCollectionImplTest.java | 5 - .../internal/MongoDatabaseImplTest.java | 6 - .../internal/MongoOperationPublisherTest.java | 15 +- .../client/internal/TimeoutHelperTest.java | 185 +-- .../gridfs/GridFSQueryFilterTest.java | 10 - .../gridfs/GridFSUploadPublisherImplTest.java | 144 -- .../syncadapter/SyncAggregateIterable.scala | 7 +- .../syncadapter/SyncDistinctIterable.scala | 5 - .../scala/syncadapter/SyncFindIterable.scala | 5 - .../SyncListCollectionsIterable.scala | 7 +- .../SyncListDatabasesIterable.scala | 7 +- .../syncadapter/SyncListIndexesIterable.scala | 7 +- .../SyncListSearchIndexesIterable.scala | 7 +- .../syncadapter/SyncMapReduceIterable.scala | 7 +- .../scala/syncadapter/SyncMongoCluster.scala | 12 +- .../syncadapter/SyncMongoCollection.scala | 12 - .../scala/syncadapter/SyncMongoDatabase.scala | 12 - .../mongodb/scala/AggregateObservable.scala | 23 - .../mongodb/scala/DistinctObservable.scala | 18 - .../org/mongodb/scala/FindObservable.scala | 23 - .../scala/ListCollectionsObservable.scala | 18 - .../scala/ListDatabasesObservable.scala | 18 - .../mongodb/scala/ListIndexesObservable.scala | 18 - .../scala/ListSearchIndexesObservable.scala | 23 - .../mongodb/scala/MapReduceObservable.scala | 18 - .../org/mongodb/scala/MongoCluster.scala | 38 - .../org/mongodb/scala/MongoCollection.scala | 39 - .../org/mongodb/scala/MongoDatabase.scala | 51 - .../mongodb/scala/gridfs/GridFSBucket.scala | 72 - .../scala/gridfs/GridFSFindObservable.scala | 2 +- .../scala/org/mongodb/scala/package.scala | 23 - .../scala/AggregateObservableSpec.scala | 3 - .../scala/ChangeStreamObservableSpec.scala | 1 - .../scala/DistinctObservableSpec.scala | 3 - .../mongodb/scala/FindObservableSpec.scala | 3 - .../scala/ListCollectionsObservableSpec.scala | 3 - .../scala/ListDatabasesObservableSpec.scala | 3 - .../scala/ListIndexesObservableSpec.scala | 3 - .../scala/MapReduceObservableSpec.scala | 3 - .../com/mongodb/client/AggregateIterable.java | 28 - .../com/mongodb/client/DistinctIterable.java | 18 - .../main/com/mongodb/client/FindIterable.java | 25 - .../client/ListCollectionsIterable.java | 17 - .../mongodb/client/ListDatabasesIterable.java | 17 - .../mongodb/client/ListIndexesIterable.java | 17 - .../client/ListSearchIndexesIterable.java | 17 - .../com/mongodb/client/MapReduceIterable.java | 17 - .../client/MongoChangeStreamCursor.java | 10 - .../main/com/mongodb/client/MongoCluster.java | 58 - .../com/mongodb/client/MongoCollection.java | 57 - .../com/mongodb/client/MongoDatabase.java | 82 -- .../mongodb/client/gridfs/GridFSBucket.java | 83 -- .../client/gridfs/GridFSBucketImpl.java | 145 +- .../gridfs/GridFSDownloadStreamImpl.java | 32 +- .../client/gridfs/GridFSUploadStreamImpl.java | 30 +- .../internal/AggregateIterableImpl.java | 21 +- .../client/internal/ClientEncryptionImpl.java | 47 +- .../client/internal/ClientSessionImpl.java | 38 +- .../internal/CollectionInfoRetriever.java | 7 +- .../client/internal/CommandMarker.java | 16 +- .../com/mongodb/client/internal/Crypt.java | 52 +- .../client/internal/CryptConnection.java | 8 +- .../client/internal/DistinctIterableImpl.java | 7 - .../client/internal/FindIterableImpl.java | 8 - .../client/internal/KeyManagementService.java | 107 +- .../mongodb/client/internal/KeyRetriever.java | 7 +- .../internal/ListCollectionsIterableImpl.java | 9 +- .../internal/ListDatabasesIterableImpl.java | 7 - .../internal/ListIndexesIterableImpl.java | 9 +- .../ListSearchIndexesIterableImpl.java | 6 - .../internal/MapReduceIterableImpl.java | 7 - .../client/internal/MongoClientImpl.java | 12 - .../client/internal/MongoClusterImpl.java | 18 - .../client/internal/MongoCollectionImpl.java | 16 - .../client/internal/MongoDatabaseImpl.java | 15 - .../client/internal/MongoIterableImpl.java | 24 +- .../client/internal/TimeoutHelper.java | 70 - ...tClientSideOperationsTimeoutProseTest.java | 1288 ----------------- .../ClientSideOperationTimeoutProseTest.java | 71 - .../ClientSideOperationTimeoutTest.java | 61 - .../client/WithTransactionProseTest.java | 44 - ...eOperationsEncryptionTimeoutProseTest.java | 397 ----- ...eOperationsEncryptionTimeoutProseTest.java | 35 - .../com/mongodb/client/unified/Entities.java | 26 - .../mongodb/client/unified/ErrorMatcher.java | 7 +- .../client/unified/UnifiedCrudHelper.java | 94 +- .../client/unified/UnifiedGridFSHelper.java | 7 +- .../mongodb/client/unified/UnifiedHelper.java | 11 - .../unified/UnifiedTestModifications.java | 295 +--- .../OidcAuthenticationProseTests.java | 115 -- .../client/MongoClientSpecification.groovy | 2 +- .../gridfs/GridFSBucketQueryFilterTest.java | 7 +- .../gridfs/GridFSBucketSpecification.groovy | 18 +- .../GridFSDownloadStreamSpecification.groovy | 30 +- .../GridFSUploadStreamSpecification.groovy | 20 +- .../CryptConnectionSpecification.groovy | 19 +- .../internal/KeyManagementServiceTest.java | 70 - .../internal/MongoClusterSpecification.groovy | 19 - .../MongoCollectionSpecification.groovy | 21 - .../MongoDatabaseSpecification.groovy | 23 - .../client/internal/TimeoutHelperTest.java | 192 --- 311 files changed, 694 insertions(+), 9944 deletions(-) delete mode 100644 driver-core/src/main/com/mongodb/MongoOperationTimeoutException.java delete mode 100644 driver-core/src/main/com/mongodb/client/cursor/TimeoutMode.java delete mode 100644 driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/TimeoutHelper.java delete mode 100644 driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideOperationTimeoutProseTest.java delete mode 100644 driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/csot/ClientSideOperationsEncryptionTimeoutProseTest.java delete mode 100644 driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ClientSideOperationTimeoutTest.java delete mode 100644 driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/gridfs/GridFSUploadPublisherImplTest.java delete mode 100644 driver-sync/src/main/com/mongodb/client/internal/TimeoutHelper.java delete mode 100644 driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideOperationsTimeoutProseTest.java delete mode 100644 driver-sync/src/test/functional/com/mongodb/client/ClientSideOperationTimeoutProseTest.java delete mode 100644 driver-sync/src/test/functional/com/mongodb/client/ClientSideOperationTimeoutTest.java delete mode 100644 driver-sync/src/test/functional/com/mongodb/client/csot/AbstractClientSideOperationsEncryptionTimeoutProseTest.java delete mode 100644 driver-sync/src/test/functional/com/mongodb/client/csot/ClientSideOperationsEncryptionTimeoutProseTest.java delete mode 100644 driver-sync/src/test/unit/com/mongodb/client/internal/KeyManagementServiceTest.java delete mode 100644 driver-sync/src/test/unit/com/mongodb/client/internal/TimeoutHelperTest.java diff --git a/driver-core/src/main/com/mongodb/ClientEncryptionSettings.java b/driver-core/src/main/com/mongodb/ClientEncryptionSettings.java index df4fa117ffd..4375d22676a 100644 --- a/driver-core/src/main/com/mongodb/ClientEncryptionSettings.java +++ b/driver-core/src/main/com/mongodb/ClientEncryptionSettings.java @@ -16,9 +16,7 @@ package com.mongodb; -import com.mongodb.annotations.Alpha; import com.mongodb.annotations.NotThreadSafe; -import com.mongodb.annotations.Reason; import com.mongodb.lang.Nullable; import javax.net.ssl.SSLContext; @@ -29,9 +27,7 @@ import static com.mongodb.assertions.Assertions.assertTrue; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.internal.TimeoutSettings.convertAndValidateTimeout; import static java.util.Collections.unmodifiableMap; -import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * The client-side settings for data key creation and explicit encryption. @@ -52,8 +48,6 @@ public final class ClientEncryptionSettings { @Nullable private final KmsConnectCallback kmsConnectCallback; @Nullable - private final Long timeoutMS; - @Nullable private final Long keyExpirationMS; /** @@ -70,8 +64,6 @@ public static final class Builder { @Nullable private KmsConnectCallback kmsConnectCallback; @Nullable - private Long timeoutMS; - @Nullable private Long keyExpirationMS; /** @@ -172,48 +164,6 @@ public Builder keyExpiration(@Nullable final Long keyExpiration, final TimeUnit return this; } - /** - * Sets the time limit for the full execution of an operation. - * - * - * - *

Note: - *

- * - * @param timeout the timeout - * @param timeUnit the time unit - * @return this - * @since 5.2 - * @see #getTimeout - */ - @Alpha(Reason.CLIENT) - public ClientEncryptionSettings.Builder timeout(final long timeout, final TimeUnit timeUnit) { - this.timeoutMS = convertAndValidateTimeout(timeout, timeUnit); - return this; - } - /** * Build an instance of {@code ClientEncryptionSettings}. * @@ -381,49 +331,6 @@ public Long getKeyExpiration(final TimeUnit timeUnit) { return keyExpirationMS == null ? null : timeUnit.convert(keyExpirationMS, TimeUnit.MILLISECONDS); } - /** - * The time limit for the full execution of an operation. - * - *

If set the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

- * - * - * - *

Note: - *

- * - * @param timeUnit the time unit - * @return the timeout in the given time unit - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - @Nullable - public Long getTimeout(final TimeUnit timeUnit) { - return timeoutMS == null ? null : timeUnit.convert(timeoutMS, MILLISECONDS); - } - private ClientEncryptionSettings(final Builder builder) { this.keyVaultMongoClientSettings = notNull("keyVaultMongoClientSettings", builder.keyVaultMongoClientSettings); this.keyVaultNamespace = notNull("keyVaultNamespace", builder.keyVaultNamespace); @@ -431,7 +338,6 @@ private ClientEncryptionSettings(final Builder builder) { this.kmsProviderPropertySuppliers = notNull("kmsProviderPropertySuppliers", builder.kmsProviderPropertySuppliers); this.kmsProviderSslContextMap = notNull("kmsProviderSslContextMap", builder.kmsProviderSslContextMap); this.kmsConnectCallback = builder.kmsConnectCallback; - this.timeoutMS = builder.timeoutMS; this.keyExpirationMS = builder.keyExpirationMS; } diff --git a/driver-core/src/main/com/mongodb/ClientSessionOptions.java b/driver-core/src/main/com/mongodb/ClientSessionOptions.java index 0f2f6796db4..6d3d2b17167 100644 --- a/driver-core/src/main/com/mongodb/ClientSessionOptions.java +++ b/driver-core/src/main/com/mongodb/ClientSessionOptions.java @@ -16,19 +16,14 @@ package com.mongodb; -import com.mongodb.annotations.Alpha; import com.mongodb.annotations.Immutable; import com.mongodb.annotations.NotThreadSafe; -import com.mongodb.annotations.Reason; import com.mongodb.lang.Nullable; import com.mongodb.session.ClientSession; import java.util.Objects; -import java.util.concurrent.TimeUnit; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.internal.TimeoutSettings.convertAndValidateTimeout; -import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * The options to apply to a {@code ClientSession}. @@ -43,7 +38,6 @@ public final class ClientSessionOptions { private final Boolean causallyConsistent; private final Boolean snapshot; - private final Long defaultTimeoutMS; private final TransactionOptions defaultTransactionOptions; /** @@ -83,30 +77,6 @@ public TransactionOptions getDefaultTransactionOptions() { return defaultTransactionOptions; } - /** - * Gets the default time limit for the following operations executed on the session: - * - * - * - *

Note: When using synchronous API, this timeout does not limit socket writes, therefore - * there is a possibility that the operation might not be timed out when expected. This limitation does not - * apply to the reactive streams API. - * - * @param timeUnit the time unit - * @return the default timeout - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - @Nullable - public Long getDefaultTimeout(final TimeUnit timeUnit) { - return defaultTimeoutMS == null ? null : timeUnit.convert(defaultTimeoutMS, MILLISECONDS); - } - @Override public boolean equals(final Object o) { if (this == o) { @@ -118,13 +88,12 @@ public boolean equals(final Object o) { final ClientSessionOptions that = (ClientSessionOptions) o; return Objects.equals(causallyConsistent, that.causallyConsistent) && Objects.equals(snapshot, that.snapshot) - && Objects.equals(defaultTimeoutMS, that.defaultTimeoutMS) && Objects.equals(defaultTransactionOptions, that.defaultTransactionOptions); } @Override public int hashCode() { - return Objects.hash(causallyConsistent, snapshot, defaultTimeoutMS, defaultTransactionOptions); + return Objects.hash(causallyConsistent, snapshot, defaultTransactionOptions); } @Override @@ -132,7 +101,6 @@ public String toString() { return "ClientSessionOptions{" + "causallyConsistent=" + causallyConsistent + ", snapshot=" + snapshot - + ", defaultTimeoutMS=" + defaultTimeoutMS + ", defaultTransactionOptions=" + defaultTransactionOptions + '}'; } @@ -159,7 +127,6 @@ public static Builder builder(final ClientSessionOptions options) { builder.causallyConsistent = options.isCausallyConsistent(); builder.snapshot = options.isSnapshot(); builder.defaultTransactionOptions = options.getDefaultTransactionOptions(); - builder.defaultTimeoutMS = options.defaultTimeoutMS; return builder; } @@ -170,7 +137,6 @@ public static Builder builder(final ClientSessionOptions options) { public static final class Builder { private Boolean causallyConsistent; private Boolean snapshot; - private Long defaultTimeoutMS; private TransactionOptions defaultTransactionOptions = TransactionOptions.builder().build(); /** @@ -219,32 +185,6 @@ public Builder defaultTransactionOptions(final TransactionOptions defaultTransac return this; } - /** - * Sets the default time limit for the following operations executed on the session: - * - *

- * - *

Note: When using synchronous API, this timeout does not limit socket writes, therefore - * there is a possibility that the operation might not be timed out when expected. This limitation does not - * apply to the reactive streams API. - * - * @param defaultTimeout the timeout - * @param timeUnit the time unit - * @return this - * @since 5.2 - * @see #getDefaultTimeout - */ - @Alpha(Reason.CLIENT) - public Builder defaultTimeout(final long defaultTimeout, final TimeUnit timeUnit) { - this.defaultTimeoutMS = convertAndValidateTimeout(defaultTimeout, timeUnit, "defaultTimeout"); - return this; - } - /** * Build the session options instance. * @@ -267,6 +207,5 @@ private ClientSessionOptions(final Builder builder) { : Boolean.valueOf(!builder.snapshot); this.snapshot = builder.snapshot; this.defaultTransactionOptions = builder.defaultTransactionOptions; - this.defaultTimeoutMS = builder.defaultTimeoutMS; } } diff --git a/driver-core/src/main/com/mongodb/ConnectionString.java b/driver-core/src/main/com/mongodb/ConnectionString.java index 356fd9ca2a8..e71a83bd78e 100644 --- a/driver-core/src/main/com/mongodb/ConnectionString.java +++ b/driver-core/src/main/com/mongodb/ConnectionString.java @@ -16,7 +16,6 @@ package com.mongodb; -import com.mongodb.annotations.Alpha; import com.mongodb.annotations.Beta; import com.mongodb.annotations.Reason; import com.mongodb.connection.ClusterSettings; @@ -145,12 +144,9 @@ *

  • {@code sslInvalidHostNameAllowed=true|false}: Whether to allow invalid host names for TLS connections.
  • *
  • {@code tlsAllowInvalidHostnames=true|false}: Whether to allow invalid host names for TLS connections. Supersedes the * sslInvalidHostNameAllowed option
  • - *
  • {@code timeoutMS=ms}: Time limit for the full execution of an operation. Note: This parameter is part of an {@linkplain Alpha Alpha API} and may be - * subject to changes or even removal in future releases.
  • *
  • {@code connectTimeoutMS=ms}: How long a connection can take to be opened before timing out.
  • *
  • {@code socketTimeoutMS=ms}: How long a receive on a socket can take before timing out. - * This option is the same as {@link SocketSettings#getReadTimeout(TimeUnit)}. - * Deprecated, use {@code timeoutMS} instead.
  • + * This option is the same as {@link SocketSettings#getReadTimeout(TimeUnit)}. *
  • {@code maxIdleTimeMS=ms}: Maximum idle time of a pooled connection. A connection that exceeds this limit will be closed
  • *
  • {@code maxLifeTimeMS=ms}: Maximum life time of a pooled connection. A connection that exceeds this limit will be closed
  • * @@ -170,7 +166,7 @@ *
  • {@code waitQueueTimeoutMS=ms}: The maximum duration to wait until either: * an {@linkplain ConnectionCheckedOutEvent in-use connection} becomes {@linkplain ConnectionCheckedInEvent available}, * or a {@linkplain ConnectionCreatedEvent connection is created} and begins to be {@linkplain ConnectionReadyEvent established}. - * See {@link #getMaxWaitTime()} for more details. . Deprecated, use {@code timeoutMS} instead.
  • + * See {@link #getMaxWaitTime()} for more details. *
  • {@code maxConnecting=n}: The maximum number of connections a pool may be establishing concurrently.
  • * *

    Write concern configuration:

    @@ -198,7 +194,7 @@ *
  • {@code wtimeoutMS=ms} * *
  • * @@ -339,7 +335,6 @@ public class ConnectionString { private Integer maxConnectionLifeTime; private Integer maxConnecting; private Integer connectTimeout; - private Long timeout; private Integer socketTimeout; private Boolean sslEnabled; private Boolean sslInvalidHostnameAllowed; @@ -584,7 +579,6 @@ private String createRedactedConnectionString(@Nullable final String userName, f static { GENERAL_OPTIONS_KEYS.add("minpoolsize"); GENERAL_OPTIONS_KEYS.add("maxpoolsize"); - GENERAL_OPTIONS_KEYS.add("timeoutms"); GENERAL_OPTIONS_KEYS.add("sockettimeoutms"); GENERAL_OPTIONS_KEYS.add("waitqueuetimeoutms"); GENERAL_OPTIONS_KEYS.add("connecttimeoutms"); @@ -712,9 +706,6 @@ private void translateOptions(final Map> optionsMap) { case "sockettimeoutms": socketTimeout = parseInteger(value, "sockettimeoutms"); break; - case "timeoutms": - timeout = parseLong(value, "timeoutms"); - break; case "proxyhost": proxyHost = value; break; @@ -1700,38 +1691,6 @@ public Integer getMaxConnecting() { return maxConnecting; } - /** - * The time limit for the full execution of an operation in milliseconds. - * - *

    If set the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

    - * - * - * - * @return the time limit for the full execution of an operation in milliseconds or null. - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - @Nullable - public Long getTimeout() { - return timeout; - } - /** * Gets the socket connect timeout specified in the connection string. * @return the socket connect timeout @@ -1945,7 +1904,6 @@ public boolean equals(final Object o) { && Objects.equals(maxConnectionLifeTime, that.maxConnectionLifeTime) && Objects.equals(maxConnecting, that.maxConnecting) && Objects.equals(connectTimeout, that.connectTimeout) - && Objects.equals(timeout, that.timeout) && Objects.equals(socketTimeout, that.socketTimeout) && Objects.equals(proxyHost, that.proxyHost) && Objects.equals(proxyPort, that.proxyPort) @@ -1970,7 +1928,7 @@ public boolean equals(final Object o) { public int hashCode() { return Objects.hash(credential, isSrvProtocol, hosts, database, collection, directConnection, readPreference, writeConcern, retryWrites, retryReads, maxAdaptiveRetries, enableOverloadRetargeting, readConcern, minConnectionPoolSize, maxConnectionPoolSize, maxWaitTime, - maxConnectionIdleTime, maxConnectionLifeTime, maxConnecting, connectTimeout, timeout, socketTimeout, sslEnabled, + maxConnectionIdleTime, maxConnectionLifeTime, maxConnecting, connectTimeout, socketTimeout, sslEnabled, sslInvalidHostnameAllowed, requiredReplicaSetName, serverSelectionTimeout, localThreshold, heartbeatFrequency, serverMonitoringMode, applicationName, compressorList, uuidRepresentation, srvServiceName, srvMaxHosts, srvAllowedHostsSuffix, proxyHost, proxyPort, proxyUsername, proxyPassword); diff --git a/driver-core/src/main/com/mongodb/MongoClientSettings.java b/driver-core/src/main/com/mongodb/MongoClientSettings.java index aab66c2dfd8..ca3471c5789 100644 --- a/driver-core/src/main/com/mongodb/MongoClientSettings.java +++ b/driver-core/src/main/com/mongodb/MongoClientSettings.java @@ -55,12 +55,9 @@ import java.util.Collections; import java.util.List; import java.util.Objects; -import java.util.concurrent.TimeUnit; -import static com.mongodb.assertions.Assertions.isTrue; import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.internal.TimeoutSettings.convertAndValidateTimeout; import static java.util.Arrays.asList; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.bson.codecs.configuration.CodecRegistries.fromProviders; @@ -124,8 +121,6 @@ public final class MongoClientSettings { private final DnsClient dnsClient; private final InetAddressResolver inetAddressResolver; private final ObservabilitySettings observabilitySettings; - @Nullable - private final Long timeoutMS; /** * Gets the default codec registry. It includes the following providers: @@ -245,7 +240,6 @@ public static final class Builder { private int heartbeatConnectTimeoutMS; private int heartbeatSocketTimeoutMS; - private Long timeoutMS; private ContextProvider contextProvider; private DnsClient dnsClient; @@ -271,7 +265,6 @@ private Builder(final MongoClientSettings settings) { uuidRepresentation = settings.getUuidRepresentation(); serverApi = settings.getServerApi(); dnsClient = settings.getDnsClient(); - timeoutMS = settings.getTimeout(MILLISECONDS); inetAddressResolver = settings.getInetAddressResolver(); transportSettings = settings.getTransportSettings(); observabilitySettings = settings.getObservabilitySettings(); @@ -342,9 +335,6 @@ public Builder applyConnectionString(final ConnectionString connectionString) { if (connectionString.getWriteConcern() != null) { writeConcern = connectionString.getWriteConcern(); } - if (connectionString.getTimeout() != null) { - timeoutMS = connectionString.getTimeout(); - } return this; } @@ -835,41 +825,6 @@ public Builder inetAddressResolver(@Nullable final InetAddressResolver inetAddre } - /** - * Sets the time limit for the full execution of an operation. - * - * - * - *

    Note: When using synchronous API, this timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. This limitation does not apply to the reactive streams API. - * - * @param timeout the timeout - * @param timeUnit the time unit - * @return this - * @since 5.2 - * @see #getTimeout - */ - @Alpha(Reason.CLIENT) - public Builder timeout(final long timeout, final TimeUnit timeUnit) { - this.timeoutMS = convertAndValidateTimeout(timeout, timeUnit); - return this; - } - // Package-private to provide interop with MongoClientOptions Builder heartbeatConnectTimeoutMS(final int heartbeatConnectTimeoutMS) { this.heartbeatConnectTimeoutMS = heartbeatConnectTimeoutMS; @@ -1087,42 +1042,6 @@ public ServerApi getServerApi() { return serverApi; } - /** - * The time limit for the full execution of an operation. - * - *

    If set the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

    - * - * - * - *

    Note: When using synchronous API, this timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. This limitation does not apply to the reactive streams API. - * - * @param timeUnit the time unit - * @return the timeout in the given time unit - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - @Nullable - public Long getTimeout(final TimeUnit timeUnit) { - return timeoutMS == null ? null : timeUnit.convert(timeoutMS, MILLISECONDS); - } - /** * Gets the auto-encryption settings. *

    @@ -1287,8 +1206,7 @@ public boolean equals(final Object o) { && Objects.equals(autoEncryptionSettings, that.autoEncryptionSettings) && Objects.equals(dnsClient, that.dnsClient) && Objects.equals(inetAddressResolver, that.inetAddressResolver) - && Objects.equals(contextProvider, that.contextProvider) - && Objects.equals(timeoutMS, that.timeoutMS); + && Objects.equals(contextProvider, that.contextProvider); } @Override @@ -1298,7 +1216,7 @@ public int hashCode() { commandListeners, codecRegistry, loggerSettings, clusterSettings, socketSettings, heartbeatSocketSettings, connectionPoolSettings, serverSettings, sslSettings, applicationName, compressorList, uuidRepresentation, serverApi, autoEncryptionSettings, heartbeatSocketTimeoutSetExplicitly, - heartbeatConnectTimeoutSetExplicitly, dnsClient, inetAddressResolver, contextProvider, timeoutMS); + heartbeatConnectTimeoutSetExplicitly, dnsClient, inetAddressResolver, contextProvider); } @@ -1331,12 +1249,10 @@ public String toString() { + ", dnsClient=" + dnsClient + ", inetAddressResolver=" + inetAddressResolver + ", contextProvider=" + contextProvider - + ", timeoutMS=" + timeoutMS + '}'; } private MongoClientSettings(final Builder builder) { - isTrue("timeoutMS > 0 ", builder.timeoutMS == null || builder.timeoutMS >= 0); readPreference = builder.readPreference; writeConcern = builder.writeConcern; retryWrites = builder.retryWrites; @@ -1374,6 +1290,5 @@ private MongoClientSettings(final Builder builder) { heartbeatSocketTimeoutSetExplicitly = builder.heartbeatSocketTimeoutMS != 0; heartbeatConnectTimeoutSetExplicitly = builder.heartbeatConnectTimeoutMS != 0; contextProvider = builder.contextProvider; - timeoutMS = builder.timeoutMS; } } diff --git a/driver-core/src/main/com/mongodb/MongoOperationTimeoutException.java b/driver-core/src/main/com/mongodb/MongoOperationTimeoutException.java deleted file mode 100644 index 9d46814c3da..00000000000 --- a/driver-core/src/main/com/mongodb/MongoOperationTimeoutException.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mongodb; - -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.lang.Nullable; - -import java.util.concurrent.TimeUnit; - -/** - * Exception thrown to indicate that a MongoDB operation has exceeded the specified timeout for - * the full execution of operation. - * - *

    The {@link MongoOperationTimeoutException} might provide information about the underlying - * cause of the timeout, if available. For example, if retries are attempted due to transient failures, - * and a timeout occurs in any of the attempts, the exception from one of the retries may be appended - * as the cause to this {@link MongoOperationTimeoutException}. - * - *

    The key difference between {@link MongoOperationTimeoutException} and {@link MongoExecutionTimeoutException} - * lies in the nature of these exceptions. {@link MongoExecutionTimeoutException} indicates a server-side timeout - * capped by a user-specified number. These server errors are transformed into the new {@link MongoOperationTimeoutException}. - * On the other hand, {@link MongoOperationTimeoutException} denotes a timeout during the execution of the entire operation. - * - * @see MongoClientSettings.Builder#timeout(long, TimeUnit) - * @see MongoClientSettings#getTimeout(TimeUnit) - * @since 5.2 - */ -@Alpha(Reason.CLIENT) -public final class MongoOperationTimeoutException extends MongoTimeoutException { - private static final long serialVersionUID = 1L; - - /** - * Construct a new instance. - * - * @param message the message - */ - public MongoOperationTimeoutException(final String message) { - super(message); - } - - /** - * Construct a new instance - * @param message the message - * @param cause the cause - */ - public MongoOperationTimeoutException(final String message, @Nullable final Throwable cause) { - super(message, cause); - } -} diff --git a/driver-core/src/main/com/mongodb/TransactionOptions.java b/driver-core/src/main/com/mongodb/TransactionOptions.java index ed3c88ece60..edadb7b6200 100644 --- a/driver-core/src/main/com/mongodb/TransactionOptions.java +++ b/driver-core/src/main/com/mongodb/TransactionOptions.java @@ -16,9 +16,7 @@ package com.mongodb; -import com.mongodb.annotations.Alpha; import com.mongodb.annotations.Immutable; -import com.mongodb.annotations.Reason; import com.mongodb.lang.Nullable; import java.util.Objects; @@ -26,7 +24,6 @@ import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.internal.TimeoutSettings.convertAndValidateTimeoutNullable; import static java.util.concurrent.TimeUnit.MILLISECONDS; /** @@ -45,7 +42,6 @@ public final class TransactionOptions { private final WriteConcern writeConcern; private final ReadPreference readPreference; private final Long maxCommitTimeMS; - private final Long timeoutMS; /** * Gets the read concern. @@ -95,37 +91,6 @@ public Long getMaxCommitTime(final TimeUnit timeUnit) { return timeUnit.convert(maxCommitTimeMS, MILLISECONDS); } - /** - * The time limit for the full execution of the transaction. - * - *

    If set the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

    - * - * - * - *

    Note: When using synchronous API, this timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. This limitation does not apply to the reactive streams API. - * - * @param timeUnit the time unit - * @return the timeout in the given time unit - * @since 5.2 - */ - @Nullable - @Alpha(Reason.CLIENT) - public Long getTimeout(final TimeUnit timeUnit) { - notNull("timeUnit", timeUnit); - if (timeoutMS == null) { - return null; - } - return timeUnit.convert(timeoutMS, MILLISECONDS); - } - /** * Gets an instance of a builder * @@ -155,9 +120,6 @@ public static TransactionOptions merge(final TransactionOptions options, final T .maxCommitTime(options.getMaxCommitTime(MILLISECONDS) == null ? defaultOptions.getMaxCommitTime(MILLISECONDS) : options.getMaxCommitTime(MILLISECONDS), MILLISECONDS) - .timeout(options.getTimeout(MILLISECONDS) == null - ? defaultOptions.getTimeout(MILLISECONDS) : options.getTimeout(MILLISECONDS), - MILLISECONDS) .build(); } @@ -172,9 +134,6 @@ public boolean equals(final Object o) { TransactionOptions that = (TransactionOptions) o; - if (!Objects.equals(timeoutMS, that.timeoutMS)) { - return false; - } if (!Objects.equals(maxCommitTimeMS, that.maxCommitTimeMS)) { return false; } @@ -197,7 +156,6 @@ public int hashCode() { result = 31 * result + (writeConcern != null ? writeConcern.hashCode() : 0); result = 31 * result + (readPreference != null ? readPreference.hashCode() : 0); result = 31 * result + (maxCommitTimeMS != null ? maxCommitTimeMS.hashCode() : 0); - result = 31 * result + (timeoutMS != null ? timeoutMS.hashCode() : 0); return result; } @@ -208,7 +166,6 @@ public String toString() { + ", writeConcern=" + writeConcern + ", readPreference=" + readPreference + ", maxCommitTimeMS=" + maxCommitTimeMS - + ", timeoutMS=" + timeoutMS + '}'; } @@ -220,8 +177,6 @@ public static final class Builder { private WriteConcern writeConcern; private ReadPreference readPreference; private Long maxCommitTimeMS; - @Nullable - private Long timeoutMS; /** * Sets the read concern. @@ -276,39 +231,6 @@ public Builder maxCommitTime(@Nullable final Long maxCommitTime, final TimeUnit return this; } - /** - * Sets the time limit for the full execution of the operations for this transaction. - * - *

    - * - *

    Note: When using synchronous API, this timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. This limitation does not apply to the reactive streams API. - * - * @param timeout the timeout - * @param timeUnit the time unit - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public Builder timeout(@Nullable final Long timeout, final TimeUnit timeUnit) { - this.timeoutMS = convertAndValidateTimeoutNullable(timeout, timeUnit); - return this; - } - /** * Build the transaction options instance. * @@ -328,6 +250,5 @@ private TransactionOptions(final Builder builder) { writeConcern = builder.writeConcern; readPreference = builder.readPreference; maxCommitTimeMS = builder.maxCommitTimeMS; - timeoutMS = builder.timeoutMS; } } diff --git a/driver-core/src/main/com/mongodb/client/cursor/TimeoutMode.java b/driver-core/src/main/com/mongodb/client/cursor/TimeoutMode.java deleted file mode 100644 index cdaa92d4923..00000000000 --- a/driver-core/src/main/com/mongodb/client/cursor/TimeoutMode.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.mongodb.client.cursor; - -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; - -import java.util.concurrent.TimeUnit; - -/** - * The timeout mode for a cursor - * - *

    For operations that create cursors, {@code timeoutMS} can either cap the lifetime of the cursor or be applied separately to the - * original operation and all next calls. - *

    - * @see com.mongodb.MongoClientSettings#getTimeout(TimeUnit) - * @since 5.2 - */ -@Alpha(Reason.CLIENT) -public enum TimeoutMode { - - /** - * The timeout lasts for the lifetime of the cursor - */ - CURSOR_LIFETIME, - - /** - * The timeout is reset for each batch iteration of the cursor - */ - ITERATION -} diff --git a/driver-core/src/main/com/mongodb/internal/ExceptionUtils.java b/driver-core/src/main/com/mongodb/internal/ExceptionUtils.java index 6a0d08ba123..d787106bfcb 100644 --- a/driver-core/src/main/com/mongodb/internal/ExceptionUtils.java +++ b/driver-core/src/main/com/mongodb/internal/ExceptionUtils.java @@ -17,7 +17,6 @@ package com.mongodb.internal; import com.mongodb.MongoCommandException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoSocketException; import org.bson.BsonArray; import org.bson.BsonDocument; @@ -44,10 +43,6 @@ public static boolean isMongoSocketException(final Throwable e) { return e instanceof MongoSocketException; } - public static boolean isOperationTimeoutFromSocketException(final Throwable e) { - return e instanceof MongoOperationTimeoutException && e.getCause() instanceof MongoSocketException; - } - /** * We must always propagate {@link Error}s, instead of wrapping them in / replacing them with {@link Exception}s, or swallowing them. *

    diff --git a/driver-core/src/main/com/mongodb/internal/TimeoutContext.java b/driver-core/src/main/com/mongodb/internal/TimeoutContext.java index 2e2917485a4..2e7f7aca1a5 100644 --- a/driver-core/src/main/com/mongodb/internal/TimeoutContext.java +++ b/driver-core/src/main/com/mongodb/internal/TimeoutContext.java @@ -15,8 +15,6 @@ */ package com.mongodb.internal; -import com.mongodb.MongoClientException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.internal.connection.CommandMessage; import com.mongodb.internal.time.StartTime; import com.mongodb.internal.time.Timeout; @@ -26,12 +24,8 @@ import java.util.Objects; import java.util.function.LongConsumer; -import static com.mongodb.assertions.Assertions.assertNotNull; -import static com.mongodb.assertions.Assertions.assertNull; -import static com.mongodb.assertions.Assertions.assertTrue; import static com.mongodb.assertions.Assertions.isTrue; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; -import static com.mongodb.internal.time.Timeout.ZeroSemantics.ZERO_DURATION_MEANS_INFINITE; import static java.util.concurrent.TimeUnit.MILLISECONDS; /** @@ -43,132 +37,52 @@ public class TimeoutContext { public static final String DEFAULT_TIMEOUT_MESSAGE = "Operation exceeded the timeout limit."; private static final int NO_ROUND_TRIP_TIME_MS = 0; private final TimeoutSettings timeoutSettings; - /** - * Is {@code null} iff {@link #timeoutSettings}{@code .}{@link TimeoutSettings#getTimeoutMS() getTimeoutMS()} is {@code null}. - */ - @Nullable - private final Timeout timeout; @Nullable private final MaxTimeSupplier maxTimeSupplier; private final boolean isMaintenanceContext; private final long minRoundTripTimeMS; - public static MongoOperationTimeoutException createMongoRoundTripTimeoutException() { - return createMongoTimeoutException("Remaining timeoutMS is less than or equal to the server's minimum round trip time."); - } - - public static MongoOperationTimeoutException createMongoTimeoutException(final String message) { - return new MongoOperationTimeoutException(message); - } - - public static T throwMongoTimeoutException(final String message) { - throw new MongoOperationTimeoutException(message); - } - public static T throwMongoTimeoutException() { - throw new MongoOperationTimeoutException(DEFAULT_TIMEOUT_MESSAGE); - } - - public static MongoOperationTimeoutException createMongoTimeoutException(final Throwable cause) { - return createMongoTimeoutException(DEFAULT_TIMEOUT_MESSAGE, cause); - } - - public static MongoOperationTimeoutException createMongoTimeoutException(final String message, @Nullable final Throwable cause) { - if (cause instanceof MongoOperationTimeoutException) { - return (MongoOperationTimeoutException) cause; - } - return new MongoOperationTimeoutException(message, cause); - } - - public static TimeoutContext createMaintenanceTimeoutContext(final TimeoutSettings timeoutSettings) { - return new TimeoutContext(true, timeoutSettings, startTimeout(timeoutSettings.getTimeoutMS())); - } - public static TimeoutContext createTimeoutContext(final ClientSession session, final TimeoutSettings timeoutSettings) { TimeoutContext sessionTimeoutContext = session.getTimeoutContext(); if (sessionTimeoutContext != null) { TimeoutSettings sessionTimeoutSettings = sessionTimeoutContext.timeoutSettings; - if (timeoutSettings.getGenerationId() > sessionTimeoutSettings.getGenerationId()) { - throw new MongoClientException("Cannot change the timeoutMS during a transaction."); - } - // Check for any legacy operation timeouts - if (sessionTimeoutSettings.getTimeoutMS() == null) { - if (timeoutSettings.getMaxTimeMS() != 0) { - sessionTimeoutSettings = sessionTimeoutSettings.withMaxTimeMS(timeoutSettings.getMaxTimeMS()); - } - if (timeoutSettings.getMaxAwaitTimeMS() != 0) { - sessionTimeoutSettings = sessionTimeoutSettings.withMaxAwaitTimeMS(timeoutSettings.getMaxAwaitTimeMS()); - } - if (timeoutSettings.getMaxCommitTimeMS() != null) { - sessionTimeoutSettings = sessionTimeoutSettings.withMaxCommitMS(timeoutSettings.getMaxCommitTimeMS()); - } - return new TimeoutContext(sessionTimeoutSettings); + if (timeoutSettings.getMaxTimeMS() != 0) { + sessionTimeoutSettings = sessionTimeoutSettings.withMaxTimeMS(timeoutSettings.getMaxTimeMS()); } - return sessionTimeoutContext; + if (timeoutSettings.getMaxAwaitTimeMS() != 0) { + sessionTimeoutSettings = sessionTimeoutSettings.withMaxAwaitTimeMS(timeoutSettings.getMaxAwaitTimeMS()); + } + if (timeoutSettings.getMaxCommitTimeMS() != null) { + sessionTimeoutSettings = sessionTimeoutSettings.withMaxCommitMS(timeoutSettings.getMaxCommitTimeMS()); + } + return new TimeoutContext(sessionTimeoutSettings); } return new TimeoutContext(timeoutSettings); } public TimeoutContext(final TimeoutSettings timeoutSettings) { - this(false, timeoutSettings, startTimeout(timeoutSettings.getTimeoutMS())); + this(false, timeoutSettings); } private TimeoutContext(final boolean isMaintenanceContext, - final TimeoutSettings timeoutSettings, - @Nullable final Timeout timeout) { + final TimeoutSettings timeoutSettings) { this(isMaintenanceContext, NO_ROUND_TRIP_TIME_MS, timeoutSettings, - null, - timeout); + null + ); } private TimeoutContext(final boolean isMaintenanceContext, final long minRoundTripTimeMS, final TimeoutSettings timeoutSettings, @Nullable final MaxTimeSupplier maxTimeSupplier) { - this(isMaintenanceContext, - minRoundTripTimeMS, - timeoutSettings, - maxTimeSupplier, - startTimeout(timeoutSettings.getTimeoutMS())); - } - - private TimeoutContext(final boolean isMaintenanceContext, - final long minRoundTripTimeMS, - final TimeoutSettings timeoutSettings, - @Nullable final MaxTimeSupplier maxTimeSupplier, - @Nullable final Timeout timeout) { - assertTrue((timeoutSettings.getTimeoutMS() == null) == (timeout == null)); this.isMaintenanceContext = isMaintenanceContext; this.timeoutSettings = timeoutSettings; this.minRoundTripTimeMS = minRoundTripTimeMS; this.maxTimeSupplier = maxTimeSupplier; - this.timeout = timeout; - } - - /** - * Allows for the differentiation between users explicitly setting a global operation timeout via {@code timeoutMS}. - * - * @return true iff {@link #getTimeoutSettings()}{@code .}{@link TimeoutSettings#getTimeoutMS() getTimeoutMS()} is not {@code null}. - * @see #getTimeout() - */ - public boolean hasTimeoutMS() { - return timeoutSettings.getTimeoutMS() != null; - } - - /** - * Runs the runnable if the timeout is expired. - * @param onExpired the runnable to run - */ - public void onExpired(final Runnable onExpired) { - Timeout.nullAsInfinite(timeout).onExpired(onExpired); - } - - @Nullable - public Timeout timeoutIncludingRoundTrip() { - return timeout == null ? null : timeout.shortenBy(minRoundTripTimeMS, MILLISECONDS); } /** @@ -180,29 +94,13 @@ public Timeout timeoutIncludingRoundTrip() { */ @VisibleForTesting(otherwise = PRIVATE) public long timeoutOrAlternative(final long alternativeTimeoutMS) { - if (timeout == null) { return alternativeTimeoutMS; - } else { - return timeout.call(MILLISECONDS, - () -> 0L, - (ms) -> ms, - () -> throwMongoTimeoutException()); - } } public TimeoutSettings getTimeoutSettings() { return timeoutSettings; } - /** - * @return {@code null} iff {@link #hasTimeoutMS()} is {@code false}. - * @see #hasTimeoutMS() - */ - @Nullable - public Timeout getTimeout() { - return timeout; - } - public long getMaxAwaitTimeMS() { return timeoutSettings.getMaxAwaitTimeMS(); } @@ -227,10 +125,7 @@ public int getConnectTimeoutMs() { return (int) connectTimeoutMS; } - return Math.toIntExact(Timeout.nullAsInfinite(timeout).call(MILLISECONDS, - () -> connectTimeoutMS, - (ms) -> connectTimeoutMS == 0 ? ms : Math.min(ms, connectTimeoutMS), - () -> throwMongoTimeoutException())); + return Math.toIntExact(connectTimeoutMS); } /** @@ -243,8 +138,7 @@ public TimeoutContext withMaxTimeAsMaxAwaitTimeOverride() { isMaintenanceContext, minRoundTripTimeMS, timeoutSettings, - timeoutSettings::getMaxAwaitTimeMS, - timeout); + timeoutSettings::getMaxAwaitTimeMS); } /** @@ -253,31 +147,26 @@ public TimeoutContext withMaxTimeAsMaxAwaitTimeOverride() { * in {@link CommandMessage} as an extra element before we send it to the server. *

    * Suitable for static user-defined values only (i.e. {@code MaxAwaitTimeMS}), - * not for running timeouts that adjust dynamically (CSOT). - *

    - * If remaining CSOT timeout is less than this static timeout, then CSOT timeout will be used. + * not for running timeouts that adjust dynamically. */ public TimeoutContext withMaxTimeOverride(final long maxTimeMS) { return new TimeoutContext( isMaintenanceContext, minRoundTripTimeMS, timeoutSettings, - () -> maxTimeMS, - timeout); + () -> maxTimeMS); } /** * Creates {@link TimeoutContext} with the default maxTimeMS behaviour in {@link #runMaxTimeMS(LongConsumer)}: - * - if timeoutMS is set, the remaining timeoutMS will be used as the maxTimeMS. - * - if timeoutMS is not set, the {@link TimeoutSettings#getMaxTimeMS()} will be used. + * the {@link TimeoutSettings#getMaxTimeMS()} will be used. */ public TimeoutContext withDefaultMaxTime() { return new TimeoutContext( isMaintenanceContext, minRoundTripTimeMS, timeoutSettings, - null, - timeout); + null); } /** @@ -289,8 +178,7 @@ public TimeoutContext withDisabledMaxTime() { isMaintenanceContext, minRoundTripTimeMS, timeoutSettings, - () -> 0, - timeout); + () -> 0); } /** @@ -302,8 +190,7 @@ public TimeoutContext withMaxTimeAsMaxCommitTime() { isMaintenanceContext, minRoundTripTimeMS, timeoutSettings, - () -> getMaxCommitTimeMS(), - timeout); + () -> getMaxCommitTimeMS()); } @@ -318,8 +205,7 @@ public TimeoutContext withMinRoundTripTime(final long minRoundTripTimeMS) { isMaintenanceContext, minRoundTripTimeMS, timeoutSettings, - maxTimeSupplier, - timeout); + maxTimeSupplier); } /** @@ -337,31 +223,12 @@ public TimeoutContext withNewlyStartedMaintenanceTimeout() { maxTimeSupplier); } - /** - * Returns the timeout context to use for the handshake process - * - * @return a new timeout context with the cached computed server selection timeout if available or this - */ - public TimeoutContext withComputedServerSelectionTimeout() { - if (this.hasTimeoutMS()) { - Timeout serverSelectionTimeout = StartTime.now() - .timeoutAfterOrInfiniteIfNegative(getTimeoutSettings().getServerSelectionTimeoutMS(), MILLISECONDS); - if (isMaintenanceContext) { - return new TimeoutContext(false, timeoutSettings, serverSelectionTimeout); - } - return new TimeoutContext(false, timeoutSettings, Timeout.earliest(serverSelectionTimeout, timeout)); - } - - return this; - } - public TimeoutContext withMinRoundTripTimeMS(final long minRoundTripTimeMS) { isTrue("'minRoundTripTimeMS' must be a positive number", minRoundTripTimeMS >= 0); return new TimeoutContext(isMaintenanceContext, minRoundTripTimeMS, timeoutSettings, - maxTimeSupplier, - timeout); + maxTimeSupplier); } public TimeoutContext withNewlyStartedTimeout() { @@ -373,9 +240,6 @@ public TimeoutContext withNewlyStartedTimeout() { } public TimeoutContext withAdditionalReadTimeout(final int additionalReadTimeout) { - // Only used outside timeoutMS usage - assertNull(timeout); - // Check existing read timeout is infinite if (timeoutSettings.getReadTimeoutMS() == 0) { return this; @@ -390,7 +254,6 @@ public String toString() { return "TimeoutContext{" + "isMaintenanceContext=" + isMaintenanceContext + ", timeoutSettings=" + timeoutSettings - + ", timeout=" + timeout + ", minRoundTripTimeMS=" + minRoundTripTimeMS + '}'; } @@ -406,21 +269,12 @@ public boolean equals(final Object o) { final TimeoutContext that = (TimeoutContext) o; return isMaintenanceContext == that.isMaintenanceContext && minRoundTripTimeMS == that.minRoundTripTimeMS - && Objects.equals(timeoutSettings, that.timeoutSettings) - && Objects.equals(timeout, that.timeout); + && Objects.equals(timeoutSettings, that.timeoutSettings); } @Override public int hashCode() { - return Objects.hash(isMaintenanceContext, timeoutSettings, timeout, minRoundTripTimeMS); - } - - @Nullable - public static Timeout startTimeout(@Nullable final Long timeoutMS) { - if (timeoutMS != null) { - return Timeout.expiresIn(timeoutMS, MILLISECONDS, ZERO_DURATION_MEANS_INFINITE); - } - return null; + return Objects.hash(isMaintenanceContext, timeoutSettings, minRoundTripTimeMS); } /** @@ -429,24 +283,16 @@ public static Timeout startTimeout(@Nullable final Long timeoutMS) { *

    Caches the computed server selection timeout if: *

    * * @return the timeout context */ public Timeout computeServerSelectionTimeout() { - if (hasTimeoutMS()) { - return assertNotNull(timeout); - } - return StartTime.now().timeoutAfterOrInfiniteIfNegative(getTimeoutSettings().getServerSelectionTimeoutMS(), MILLISECONDS); } public Timeout startMaxWaitTimeout(final StartTime checkoutStart) { - if (hasTimeoutMS()) { - return assertNotNull(timeout); - } final long ms = getTimeoutSettings().getMaxWaitTimeMS(); return checkoutStart.timeoutAfterOrInfiniteIfNegative(ms, MILLISECONDS); } @@ -455,38 +301,12 @@ public void runMaxTimeMS(final LongConsumer onRemaining) { if (maxTimeSupplier != null) { long maxTimeMS = maxTimeSupplier.get(); if (maxTimeMS > 0) { - runMinTimeout(onRemaining, maxTimeMS); + onRemaining.accept(maxTimeMS); } return; } - if (timeout == null) { - runWithFixedTimeout(timeoutSettings.getMaxTimeMS(), onRemaining); - return; - } - assertNotNull(timeoutIncludingRoundTrip()) - .run(MILLISECONDS, - () -> {}, - onRemaining, - () -> { - throw createMongoRoundTripTimeoutException(); - }); - - } + runWithFixedTimeout(timeoutSettings.getMaxTimeMS(), onRemaining); - private void runMinTimeout(final LongConsumer onRemaining, final long fixedMs) { - Timeout timeout = timeoutIncludingRoundTrip(); - if (timeout != null) { - timeout.run(MILLISECONDS, () -> { - onRemaining.accept(fixedMs); - }, - (remainingMs) -> { - onRemaining.accept(Math.min(remainingMs, fixedMs)); - }, () -> { - throwMongoTimeoutException(); - }); - } else { - onRemaining.accept(fixedMs); - } } private static void runWithFixedTimeout(final long ms, final LongConsumer onRemaining) { diff --git a/driver-core/src/main/com/mongodb/internal/TimeoutSettings.java b/driver-core/src/main/com/mongodb/internal/TimeoutSettings.java index e1f0bc0b795..6a6aa2a23e8 100644 --- a/driver-core/src/main/com/mongodb/internal/TimeoutSettings.java +++ b/driver-core/src/main/com/mongodb/internal/TimeoutSettings.java @@ -23,7 +23,6 @@ import java.util.concurrent.atomic.AtomicLong; import static com.mongodb.assertions.Assertions.isTrueArgument; -import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * Timeout Settings. @@ -35,8 +34,6 @@ public class TimeoutSettings { private final long generationId; private final long serverSelectionTimeoutMS; private final long connectTimeoutMS; - @Nullable - private final Long timeoutMS; // Deprecated configuration timeout options private final long readTimeoutMS; // aka socketTimeoutMS @@ -52,29 +49,12 @@ public class TimeoutSettings { public static final TimeoutSettings DEFAULT = create(MongoClientSettings.builder().build()); - @Nullable - public static Long convertAndValidateTimeoutNullable(@Nullable final Long timeout, final TimeUnit timeUnit) { - return timeout == null ? null : convertAndValidateTimeout(timeout, timeUnit, "timeout"); - } - - public static long convertAndValidateTimeout(final long timeout, final TimeUnit timeUnit) { - return convertAndValidateTimeout(timeout, timeUnit, "timeout"); - } - - public static long convertAndValidateTimeout(final long timeout, final TimeUnit timeUnit, final String fieldName) { - return isTrueArgument(fieldName + " was too small. After conversion it was rounded to 0 milliseconds, " - + " which would result in an unintended infinite timeout.", - () -> MILLISECONDS.convert(timeout, timeUnit), - (timeoutMS) -> timeout == 0 && timeoutMS == 0 || timeoutMS > 0); - } - @SuppressWarnings("deprecation") public static TimeoutSettings create(final MongoClientSettings settings) { return new TimeoutSettings( settings.getClusterSettings().getServerSelectionTimeout(TimeUnit.MILLISECONDS), settings.getSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS), settings.getSocketSettings().getReadTimeout(TimeUnit.MILLISECONDS), - settings.getTimeout(TimeUnit.MILLISECONDS), settings.getConnectionPoolSettings().getMaxWaitTime(TimeUnit.MILLISECONDS)); } @@ -83,37 +63,25 @@ public static TimeoutSettings createHeartbeatSettings(final MongoClientSettings settings.getClusterSettings().getServerSelectionTimeout(TimeUnit.MILLISECONDS), settings.getHeartbeatSocketSettings().getConnectTimeout(TimeUnit.MILLISECONDS), settings.getHeartbeatSocketSettings().getReadTimeout(TimeUnit.MILLISECONDS), - settings.getTimeout(TimeUnit.MILLISECONDS), settings.getConnectionPoolSettings().getMaxWaitTime(TimeUnit.MILLISECONDS)); } public TimeoutSettings(final long serverSelectionTimeoutMS, final long connectTimeoutMS, final long readTimeoutMS, - @Nullable final Long timeoutMS, final long maxWaitTimeMS) { - this(-1, timeoutMS, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, 0, 0, null, null, maxWaitTimeMS); - } - - TimeoutSettings(@Nullable final Long timeoutMS, final long serverSelectionTimeoutMS, final long connectTimeoutMS, - final long readTimeoutMS, final long maxAwaitTimeMS, final long maxTimeMS, @Nullable final Long maxCommitTimeMS, - @Nullable final Long wTimeoutMS, final long maxWaitTimeMS) { - this(timeoutMS != null ? NEXT_ID.incrementAndGet() : -1, timeoutMS, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, - maxAwaitTimeMS, maxTimeMS, maxCommitTimeMS, wTimeoutMS, maxWaitTimeMS); + final long maxWaitTimeMS) { + this(-1, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, 0, 0, null, null, maxWaitTimeMS); } - private TimeoutSettings(final long generationId, @Nullable final Long timeoutMS, final long serverSelectionTimeoutMS, + private TimeoutSettings(final long generationId, final long serverSelectionTimeoutMS, final long connectTimeoutMS, final long readTimeoutMS, final long maxAwaitTimeMS, final long maxTimeMS, @Nullable final Long maxCommitTimeMS, @Nullable final Long wTimeoutMS, final long maxWaitTimeMS) { - isTrueArgument("timeoutMS must be >= 0", timeoutMS == null || timeoutMS >= 0); isTrueArgument("maxAwaitTimeMS must be >= 0", maxAwaitTimeMS >= 0); isTrueArgument("maxTimeMS must be >= 0", maxTimeMS >= 0); - isTrueArgument("timeoutMS must be greater than maxAwaitTimeMS", timeoutMS == null || timeoutMS == 0 - || timeoutMS > maxAwaitTimeMS); isTrueArgument("maxCommitTimeMS must be >= 0", maxCommitTimeMS == null || maxCommitTimeMS >= 0); this.generationId = generationId; this.serverSelectionTimeoutMS = serverSelectionTimeoutMS; this.connectTimeoutMS = connectTimeoutMS; - this.timeoutMS = timeoutMS; this.maxAwaitTimeMS = maxAwaitTimeMS; this.readTimeoutMS = readTimeoutMS; this.maxTimeMS = maxTimeMS; @@ -123,60 +91,51 @@ private TimeoutSettings(final long generationId, @Nullable final Long timeoutMS, } public TimeoutSettings connectionOnly() { - return new TimeoutSettings(serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, null, maxWaitTimeMS); - } - - public TimeoutSettings withTimeout(@Nullable final Long timeout, final TimeUnit timeUnit) { - return withTimeoutMS(convertAndValidateTimeoutNullable(timeout, timeUnit)); - } - - TimeoutSettings withTimeoutMS(@Nullable final Long timeoutMS) { - return new TimeoutSettings(timeoutMS, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, - maxTimeMS, maxCommitTimeMS, wTimeoutMS, maxWaitTimeMS); + return new TimeoutSettings(serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxWaitTimeMS); } public TimeoutSettings withMaxTimeMS(final long maxTimeMS) { - return new TimeoutSettings(generationId, timeoutMS, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, + return new TimeoutSettings(generationId, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, maxTimeMS, maxCommitTimeMS, wTimeoutMS, maxWaitTimeMS); } public TimeoutSettings withMaxAwaitTimeMS(final long maxAwaitTimeMS) { - return new TimeoutSettings(generationId, timeoutMS, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, + return new TimeoutSettings(generationId, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, maxTimeMS, maxCommitTimeMS, wTimeoutMS, maxWaitTimeMS); } public TimeoutSettings withMaxTimeAndMaxAwaitTimeMS(final long maxTimeMS, final long maxAwaitTimeMS) { - return new TimeoutSettings(generationId, timeoutMS, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, + return new TimeoutSettings(generationId, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, maxTimeMS, maxCommitTimeMS, wTimeoutMS, maxWaitTimeMS); } public TimeoutSettings withMaxCommitMS(@Nullable final Long maxCommitTimeMS) { - return new TimeoutSettings(generationId, timeoutMS, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, + return new TimeoutSettings(generationId, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, maxTimeMS, maxCommitTimeMS, wTimeoutMS, maxWaitTimeMS); } public TimeoutSettings withWTimeoutMS(@Nullable final Long wTimeoutMS) { - return new TimeoutSettings(timeoutMS, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, + return new TimeoutSettings(generationId, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, maxTimeMS, maxCommitTimeMS, wTimeoutMS, maxWaitTimeMS); } public TimeoutSettings withReadTimeoutMS(final long readTimeoutMS) { - return new TimeoutSettings(generationId, timeoutMS, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, + return new TimeoutSettings(generationId, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, maxTimeMS, maxCommitTimeMS, wTimeoutMS, maxWaitTimeMS); } public TimeoutSettings withConnectTimeoutMS(final long connectTimeoutMS) { - return new TimeoutSettings(generationId, timeoutMS, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, + return new TimeoutSettings(generationId, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, maxTimeMS, maxCommitTimeMS, wTimeoutMS, maxWaitTimeMS); } public TimeoutSettings withServerSelectionTimeoutMS(final long serverSelectionTimeoutMS) { - return new TimeoutSettings(timeoutMS, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, + return new TimeoutSettings(generationId, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, maxTimeMS, maxCommitTimeMS, wTimeoutMS, maxWaitTimeMS); } public TimeoutSettings withMaxWaitTimeMS(final long maxWaitTimeMS) { - return new TimeoutSettings(timeoutMS, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, + return new TimeoutSettings(generationId, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxAwaitTimeMS, maxTimeMS, maxCommitTimeMS, wTimeoutMS, maxWaitTimeMS); } @@ -188,11 +147,6 @@ public long getConnectTimeoutMS() { return connectTimeoutMS; } - @Nullable - public Long getTimeoutMS() { - return timeoutMS; - } - public long getMaxAwaitTimeMS() { return maxAwaitTimeMS; } @@ -235,7 +189,6 @@ public long getGenerationId() { public String toString() { return "TimeoutSettings{" + "generationId=" + generationId - + ", timeoutMS=" + timeoutMS + ", serverSelectionTimeoutMS=" + serverSelectionTimeoutMS + ", connectTimeoutMS=" + connectTimeoutMS + ", readTimeoutMS=" + readTimeoutMS @@ -258,13 +211,13 @@ public boolean equals(final Object o) { final TimeoutSettings that = (TimeoutSettings) o; return serverSelectionTimeoutMS == that.serverSelectionTimeoutMS && connectTimeoutMS == that.connectTimeoutMS && readTimeoutMS == that.readTimeoutMS && maxWaitTimeMS == that.maxWaitTimeMS && maxTimeMS == that.maxTimeMS - && maxAwaitTimeMS == that.maxAwaitTimeMS && Objects.equals(timeoutMS, that.timeoutMS) + && maxAwaitTimeMS == that.maxAwaitTimeMS && Objects.equals(wTimeoutMS, that.wTimeoutMS) && Objects.equals(maxCommitTimeMS, that.maxCommitTimeMS); } @Override public int hashCode() { - return Objects.hash(generationId, serverSelectionTimeoutMS, connectTimeoutMS, timeoutMS, readTimeoutMS, maxWaitTimeMS, wTimeoutMS, maxTimeMS, + return Objects.hash(generationId, serverSelectionTimeoutMS, connectTimeoutMS, readTimeoutMS, maxWaitTimeMS, wTimeoutMS, maxTimeMS, maxAwaitTimeMS, maxCommitTimeMS); } } diff --git a/driver-core/src/main/com/mongodb/internal/client/model/FindOptions.java b/driver-core/src/main/com/mongodb/internal/client/model/FindOptions.java index 1c7f3ef9858..3a87434e9ed 100644 --- a/driver-core/src/main/com/mongodb/internal/client/model/FindOptions.java +++ b/driver-core/src/main/com/mongodb/internal/client/model/FindOptions.java @@ -17,9 +17,6 @@ package com.mongodb.internal.client.model; import com.mongodb.CursorType; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.lang.Nullable; import org.bson.BsonString; @@ -57,7 +54,6 @@ public final class FindOptions { private boolean returnKey; private boolean showRecordId; private Boolean allowDiskUse; - private TimeoutMode timeoutMode; /** * Construct a new instance. @@ -70,8 +66,7 @@ public FindOptions() { final int batchSize, final int limit, final Bson projection, final long maxTimeMS, final long maxAwaitTimeMS, final int skip, final Bson sort, final CursorType cursorType, final boolean noCursorTimeout, final boolean partial, final Collation collation, final BsonValue comment, final Bson hint, final String hintString, final Bson variables, - final Bson max, final Bson min, final boolean returnKey, final boolean showRecordId, final Boolean allowDiskUse, - final TimeoutMode timeoutMode) { + final Bson max, final Bson min, final boolean returnKey, final boolean showRecordId, final Boolean allowDiskUse) { this.batchSize = batchSize; this.limit = limit; this.projection = projection; @@ -92,13 +87,12 @@ public FindOptions() { this.returnKey = returnKey; this.showRecordId = showRecordId; this.allowDiskUse = allowDiskUse; - this.timeoutMode = timeoutMode; } //CHECKSTYLE:ON public FindOptions withBatchSize(final int batchSize) { return new FindOptions(batchSize, limit, projection, maxTimeMS, maxAwaitTimeMS, skip, sort, cursorType, noCursorTimeout, - partial, collation, comment, hint, hintString, variables, max, min, returnKey, showRecordId, allowDiskUse, timeoutMode); + partial, collation, comment, hint, hintString, variables, max, min, returnKey, showRecordId, allowDiskUse); } /** @@ -230,41 +224,6 @@ public FindOptions batchSize(final int batchSize) { return this; } - /** - * Sets the timeoutMode for the cursor. - * - *

    - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@code MongoDatabase} or via {@code MongoCollection} - *

    - *

    - * If the {@code timeout} is set then: - *

    - *

    - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public FindOptions timeoutMode(final TimeoutMode timeoutMode) { - this.timeoutMode = timeoutMode; - return this; - } - - /** - * @see #timeoutMode(TimeoutMode) - * @return timeout mode - */ - @Alpha(Reason.CLIENT) - @Nullable - public TimeoutMode getTimeoutMode() { - return timeoutMode; - } - /** * Gets a document describing the fields to return for all matching documents. * diff --git a/driver-core/src/main/com/mongodb/internal/connection/AbstractProtocolExecutor.java b/driver-core/src/main/com/mongodb/internal/connection/AbstractProtocolExecutor.java index ba200933860..0fdf5d788cb 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/AbstractProtocolExecutor.java +++ b/driver-core/src/main/com/mongodb/internal/connection/AbstractProtocolExecutor.java @@ -19,7 +19,6 @@ import com.mongodb.internal.session.SessionContext; import static com.mongodb.internal.ExceptionUtils.isMongoSocketException; -import static com.mongodb.internal.ExceptionUtils.isOperationTimeoutFromSocketException; /** *

    This class is not part of the public API and may be removed or changed at any time

    @@ -30,6 +29,6 @@ protected boolean shouldMarkSessionDirty(final Throwable e, final SessionContext if (!sessionContext.hasSession()) { return false; } - return isMongoSocketException(e) || isOperationTimeoutFromSocketException(e); + return isMongoSocketException(e); } } 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 e9dfccc3388..cf570fe3250 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java +++ b/driver-core/src/main/com/mongodb/internal/connection/BaseCluster.java @@ -20,7 +20,6 @@ import com.mongodb.MongoException; import com.mongodb.MongoIncompatibleDriverException; import com.mongodb.MongoInterruptedException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoTimeoutException; import com.mongodb.ServerAddress; import com.mongodb.UnixServerAddress; @@ -432,8 +431,7 @@ private void logAndThrowTimeoutException( "Timed out while waiting for a server that matches %s. Client view of cluster state is %s", serverSelector, clusterDescription.getShortDescription()); - MongoTimeoutException exception = operationContext.getTimeoutContext().hasTimeoutMS() - ? new MongoOperationTimeoutException(message) : new MongoTimeoutException(message); + MongoTimeoutException exception = new MongoTimeoutException(message); logServerSelectionFailed(operationContext, clusterId, exception, serverSelector, clusterDescription); throw exception; diff --git a/driver-core/src/main/com/mongodb/internal/connection/CommandHelper.java b/driver-core/src/main/com/mongodb/internal/connection/CommandHelper.java index 51a6c5f0213..8ff42e0966f 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/CommandHelper.java +++ b/driver-core/src/main/com/mongodb/internal/connection/CommandHelper.java @@ -125,15 +125,12 @@ private static CommandMessage getCommandMessage(final String database, final Bso /** - * Appends a user-defined maxTimeMS to the command if CSOT is not enabled. + * Appends a user-defined maxTimeMS to the command. * This is necessary when maxTimeMS must be explicitly set on the command being explained, - * rather than appending it lazily to the explain command in the {@link CommandMessage} via {@link TimeoutContext#setMaxTimeOverride(long)}. - * This ensures backwards compatibility with pre-CSOT behavior. + * rather than appending it lazily to the explain command in the {@link CommandMessage}. */ public static void applyMaxTimeMS(final TimeoutContext timeoutContext, final BsonDocument command) { - if (!timeoutContext.hasTimeoutMS()) { - command.append("maxTimeMS", new BsonInt64(timeoutContext.getTimeoutSettings().getMaxTimeMS())); - } + command.append("maxTimeMS", new BsonInt64(timeoutContext.getTimeoutSettings().getMaxTimeMS())); } private CommandHelper() { diff --git a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java index a0a8bbe6e2d..5a1cd6ba102 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java +++ b/driver-core/src/main/com/mongodb/internal/connection/DefaultConnectionPool.java @@ -42,7 +42,6 @@ import com.mongodb.event.ConnectionPoolListener; import com.mongodb.event.ConnectionPoolReadyEvent; import com.mongodb.event.ConnectionReadyEvent; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.VisibleForTesting; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.connection.SdamServerDescriptionManager.SdamIssue; @@ -99,7 +98,6 @@ import static com.mongodb.event.ConnectionClosedEvent.Reason.ERROR; import static com.mongodb.internal.Locks.lockInterruptibly; import static com.mongodb.internal.Locks.withLock; -import static com.mongodb.internal.TimeoutContext.createMongoTimeoutException; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; import static com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback; import static com.mongodb.internal.connection.ConcurrentPool.INFINITE_SIZE; @@ -195,7 +193,7 @@ public InternalConnection get(final OperationContext operationContext) { Timeout maxWaitTimeout = operationContext.getTimeoutContext().startMaxWaitTimeout(checkoutStart); try { stateAndGeneration.throwIfClosedOrPaused(); - PooledConnection connection = getPooledConnection(maxWaitTimeout, checkoutStart, operationContext.getTimeoutContext()); + PooledConnection connection = getPooledConnection(maxWaitTimeout, checkoutStart); if (!connection.opened()) { connection = openConcurrencyLimiter.openOrGetAvailable(operationContext, connection, maxWaitTimeout, checkoutStart); } @@ -227,13 +225,13 @@ public void getAsync(final OperationContext operationContext, final SingleResult eventSendingCallback.onResult(null, e); return; } - asyncWorkManager.enqueue(new Task(maxWaitTimeout, checkoutStart, operationContext.getTimeoutContext(), t -> { + asyncWorkManager.enqueue(new Task(maxWaitTimeout, checkoutStart, t -> { if (t != null) { eventSendingCallback.onResult(null, t); } else { PooledConnection connection; try { - connection = getPooledConnection(maxWaitTimeout, checkoutStart, operationContext.getTimeoutContext()); + connection = getPooledConnection(maxWaitTimeout, checkoutStart); } catch (Exception e) { eventSendingCallback.onResult(null, e); return; @@ -333,8 +331,7 @@ public int getGeneration() { } private PooledConnection getPooledConnection(final Timeout maxWaitTimeout, - final StartTime startTime, - final TimeoutContext timeoutContext) throws MongoTimeoutException { + final StartTime startTime) throws MongoTimeoutException { try { UsageTrackingInternalConnection internalConnection = maxWaitTimeout.call(NANOSECONDS, () -> pool.get(-1L, NANOSECONDS), @@ -349,7 +346,7 @@ private PooledConnection getPooledConnection(final Timeout maxWaitTimeout, } return new PooledConnection(internalConnection); } catch (MongoTimeoutException e) { - throw createTimeoutException(startTime, e, timeoutContext); + throw createTimeoutException(startTime, e); } } @@ -364,8 +361,7 @@ private PooledConnection getPooledConnectionImmediate() { } private MongoTimeoutException createTimeoutException(final StartTime startTime, - @Nullable final MongoTimeoutException cause, - final TimeoutContext timeoutContext) { + @Nullable final MongoTimeoutException cause) { long elapsedMs = startTime.elapsed().toMillis(); int numPinnedToCursor = pinnedStatsManager.getNumPinnedToCursor(); int numPinnedToTransaction = pinnedStatsManager.getNumPinnedToTransaction(); @@ -410,7 +406,7 @@ private MongoTimeoutException createTimeoutException(final StartTime startTime, numOtherInUse); } - return timeoutContext.hasTimeoutMS() ? createMongoTimeoutException(errorMessage, cause) : new MongoTimeoutException(errorMessage, cause); + return new MongoTimeoutException(errorMessage, cause); } @VisibleForTesting(otherwise = PRIVATE) @@ -431,7 +427,7 @@ void doMaintenance() { if (shouldEnsureMinSize()) { pool.ensureMinSize(settings.getMinSize(), newConnection -> { try { - OperationContext operationContext = operationContextFactory.createMaintenanceContext(); + OperationContext operationContext = operationContextFactory.create(); openConcurrencyLimiter.openImmediatelyAndTryHandOverOrRelease(operationContext, new PooledConnection(newConnection)); } catch (MongoException | MongoOpenConnectionInternalException e) { RuntimeException actualException = e instanceof MongoOpenConnectionInternalException @@ -975,8 +971,8 @@ private PooledConnection openWithConcurrencyLimit(final OperationContext operati PooledConnection availableConnection; try {//phase one availableConnection = acquirePermitOrGetAvailableOpenedConnection( - mode == OpenWithConcurrencyLimitMode.TRY_GET_AVAILABLE, maxWaitTimeout, startTime, - operationContext.getTimeoutContext()); + mode == OpenWithConcurrencyLimitMode.TRY_GET_AVAILABLE, maxWaitTimeout, startTime + ); } catch (Exception e) { connection.closeSilently(); throw e; @@ -1019,7 +1015,7 @@ void openWithConcurrencyLimitAsync( PooledConnection availableConnection; try {//phase one availableConnection = - acquirePermitOrGetAvailableOpenedConnection(true, maxWaitTimeout, startTime, operationContext.getTimeoutContext()); + acquirePermitOrGetAvailableOpenedConnection(true, maxWaitTimeout, startTime); } catch (Exception e) { connection.closeSilently(); callback.onResult(null, e); @@ -1050,8 +1046,7 @@ void openWithConcurrencyLimitAsync( */ @Nullable private PooledConnection acquirePermitOrGetAvailableOpenedConnection(final boolean tryGetAvailable, - final Timeout maxWaitTimeout, final StartTime startTime, - final TimeoutContext timeoutContext) + final Timeout maxWaitTimeout, final StartTime startTime) throws MongoTimeoutException, MongoInterruptedException { PooledConnection availableConnection = null; boolean expressedDesireToGetAvailableConnection = false; @@ -1080,7 +1075,7 @@ private PooledConnection acquirePermitOrGetAvailableOpenedConnection(final boole & (availableConnection = tryGetAvailable ? tryGetAvailableConnection() : null) == null) { Timeout.onExistsAndExpired(maxWaitTimeout, () -> { - throw createTimeoutException(startTime, null, timeoutContext); + throw createTimeoutException(startTime, null); }); maxWaitTimeout.awaitOn(permitAvailableOrHandedOverOrClosedOrPausedCondition, () -> "acquiring permit or getting available opened connection"); @@ -1401,15 +1396,12 @@ final class Task { private final Timeout timeout; private final StartTime startTime; private final Consumer action; - private final TimeoutContext timeoutContext; private boolean completed; Task(final Timeout timeout, final StartTime startTime, - final TimeoutContext timeoutContext, final Consumer action) { this.timeout = timeout; - this.timeoutContext = timeoutContext; this.startTime = startTime; this.action = action; } @@ -1423,7 +1415,7 @@ void failAsClosed() { } void failAsTimedOut() { - doComplete(() -> createTimeoutException(startTime, null, timeoutContext)); + doComplete(() -> createTimeoutException(startTime, null)); } private void doComplete(final Supplier failureSupplier) { diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalOperationContextFactory.java b/driver-core/src/main/com/mongodb/internal/connection/InternalOperationContextFactory.java index 851ca5a38ca..26f8e510700 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalOperationContextFactory.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalOperationContextFactory.java @@ -16,7 +16,6 @@ package com.mongodb.internal.connection; import com.mongodb.ServerApi; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.thread.AsyncClientExecutor; import com.mongodb.lang.Nullable; @@ -40,17 +39,9 @@ public InternalOperationContextFactory( } /** - * @return a simple operation context without timeoutMS + * @return a simple operation context */ OperationContext create() { return simpleOperationContext(timeoutSettings.connectionOnly(), serverApi, clientExecutor); } - - /** - * @return a simple operation context with timeoutMS if set at the MongoClientSettings level - */ - - OperationContext createMaintenanceContext() { - return create().withTimeoutContext(TimeoutContext.createMaintenanceTimeoutContext(timeoutSettings)); - } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java index bdeba4211a4..614d42ea3c7 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java +++ b/driver-core/src/main/com/mongodb/internal/connection/InternalStreamConnection.java @@ -24,12 +24,10 @@ import com.mongodb.MongoExecutionTimeoutException; import com.mongodb.MongoInternalException; import com.mongodb.MongoInterruptedException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoSocketClosedException; import com.mongodb.MongoSocketReadException; import com.mongodb.MongoSocketReadTimeoutException; import com.mongodb.MongoSocketWriteException; -import com.mongodb.MongoSocketWriteTimeoutException; import com.mongodb.ServerAddress; import com.mongodb.annotations.NotThreadSafe; import com.mongodb.connection.AsyncCompletionHandler; @@ -52,7 +50,6 @@ import com.mongodb.internal.logging.StructuredLogger; import com.mongodb.internal.observability.micrometer.Span; import com.mongodb.internal.session.SessionContext; -import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; import com.mongodb.observability.micrometer.MongodbObservationContext; import org.bson.BsonBinaryReader; @@ -81,7 +78,6 @@ import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.internal.ExceptionUtils.mapUnlessError; import static com.mongodb.internal.ExceptionUtils.rethrowIfError; -import static com.mongodb.internal.TimeoutContext.createMongoTimeoutException; import static com.mongodb.internal.async.AsyncRunnable.beginAsync; import static com.mongodb.internal.async.ErrorHandlingResultCallback.errorHandlingCallback; import static com.mongodb.internal.connection.Authenticator.shouldAuthenticate; @@ -171,18 +167,6 @@ public InternalStreamConnection(final ClusterConnectionMode clusterConnectionMod LoggerSettings.builder().build(), commandListener, connectionInitializer, false); } - public InternalStreamConnection(final ClusterConnectionMode clusterConnectionMode, - @Nullable final Authenticator authenticator, - final boolean isMonitoringConnection, - final ServerId serverId, - final ConnectionGenerationSupplier connectionGenerationSupplier, - final StreamFactory streamFactory, final List compressorList, - final LoggerSettings loggerSettings, - final CommandListener commandListener, final InternalConnectionInitializer connectionInitializer) { - this(clusterConnectionMode, authenticator, isMonitoringConnection, serverId, connectionGenerationSupplier, - streamFactory, compressorList, loggerSettings, commandListener, connectionInitializer, false); - } - public InternalStreamConnection(final ClusterConnectionMode clusterConnectionMode, @Nullable final Authenticator authenticator, final boolean isMonitoringConnection, @@ -555,9 +539,6 @@ private void sendCommandMessage(final CommandMessage message, final ByteBufferBs private void trySendMessage(final CommandMessage message, final ByteBufferBsonOutput bsonOutput, final OperationContext operationContext) { - Timeout.onExistsAndExpired(operationContext.getTimeoutContext().timeoutIncludingRoundTrip(), () -> { - throw TimeoutContext.createMongoRoundTripTimeoutException(); - }); List byteBuffers = bsonOutput.getByteBuffers(); try { sendMessage(byteBuffers, message.getId(), operationContext); @@ -608,13 +589,13 @@ private T processCommandResponse(final Decoder decoder, final ResponseBuf updateSessionContext(operationContext.getSessionContext(), responseBuffers); if (!isCommandOk(responseBuffers)) { throw getCommandFailureException(responseBuffers.getResponseDocument(responseTo, - new BsonDocumentCodec()), description.getServerAddress(), operationContext.getTimeoutContext()); + new BsonDocumentCodec()), description.getServerAddress()); } commandEventSender.sendSucceededEvent(responseBuffers); commandSuccessful = true; - T commandResult = getCommandResult(decoder, responseBuffers, responseTo, operationContext.getTimeoutContext()); + T commandResult = getCommandResult(decoder, responseBuffers, responseTo); hasMoreToCome = responseBuffers.getReplyHeader().hasMoreToCome(); if (hasMoreToCome) { responseTo = responseBuffers.getReplyHeader().getRequestId(); @@ -646,8 +627,7 @@ private void recordTracingError(@Nullable final Span tracingSpan, final Throwabl * Determines whether a failure raised while processing a command response leaves the connection * reusable. This predicate is only ever applied to post-read failures — those raised after * {@link #receiveResponseBuffers} (sync) or the {@code MessageHeaderCallback} (async) has fully read - * the framed response off the wire. Read-path failures (including a CSOT read-timeout translated to - * {@link MongoOperationTimeoutException}) are handled separately: the read path closes the connection + * the framed response off the wire. Read-path failures are handled separately: the read path closes the connection * itself and never routes through this predicate, so no verdict here can leave a desynchronized stream * in the pool. The types below are reusable because the stream remains synchronized: *
      @@ -655,8 +635,6 @@ private void recordTracingError(@Nullable final Span tracingSpan, final Throwabl *
    • {@link MongoExecutionTimeoutException} — a server-side {@code MaxTimeMSExpired} ({@code ok: 0}) * error response; derived from the fully-read response body
    • *
    • {@link MongoWriteConcernWithResponseException} — a write concern error carrying the response
    • - *
    • {@link MongoOperationTimeoutException} — a write concern timeout, or a server-side - * {@code MaxTimeMSExpired} ({@code ok: 0}) timeout wrapped for CSOT; both are derived from the response body
    • *
    • {@link BsonSerializationException} — a corrupt BSON body whose exact byte count was still consumed
    • *
    * Any other failure (e.g. a responseTo mismatch or an unexpected error) may have left the stream @@ -666,7 +644,6 @@ private static boolean connectionIsReusable(final Throwable failure) { return failure instanceof MongoCommandException || failure instanceof MongoExecutionTimeoutException || failure instanceof MongoWriteConcernWithResponseException - || failure instanceof MongoOperationTimeoutException || failure instanceof BsonSerializationException; } @@ -784,13 +761,6 @@ private void sendCommandMessageAsync(final int messageId, final Decoder d final SingleResultCallback callback, final ByteBufferBsonOutput bsonOutput, final CommandEventSender commandEventSender, final boolean responseExpected) { boolean[] shouldReturn = {false}; - Timeout.onExistsAndExpired(operationContext.getTimeoutContext().timeoutIncludingRoundTrip(), () -> { - bsonOutput.close(); - MongoOperationTimeoutException operationTimeoutException = TimeoutContext.createMongoRoundTripTimeoutException(); - commandEventSender.sendFailedEvent(operationTimeoutException); - callback.onResult(null, operationTimeoutException); - shouldReturn[0] = true; - }); if (shouldReturn[0]) { return; } @@ -825,12 +795,12 @@ private void sendCommandMessageAsync(final int messageId, final Decoder d if (!commandOk) { throw getCommandFailureException( responseBuffers.getResponseDocument(messageId, new BsonDocumentCodec()), - description.getServerAddress(), operationContext.getTimeoutContext()); + description.getServerAddress()); } commandEventSender.sendSucceededEvent(responseBuffers); commandSuccessful = true; - commandResult = getCommandResult(decoder, responseBuffers, messageId, operationContext.getTimeoutContext()); + commandResult = getCommandResult(decoder, responseBuffers, messageId); } catch (Throwable localThrowable) { failure = localThrowable; } finally { @@ -865,15 +835,11 @@ private void assertResponseToMatches(final ResponseBuffers responseBuffers, fina private T getCommandResult(final Decoder decoder, final ResponseBuffers responseBuffers, - final int messageId, - final TimeoutContext timeoutContext) { + final int messageId) { T result = new ReplyMessage<>(responseBuffers, decoder, messageId).getDocument(); MongoException writeConcernBasedError = createSpecialWriteConcernException(responseBuffers, - description.getServerAddress(), - timeoutContext); - if (writeConcernBasedError instanceof MongoOperationTimeoutException) { - throw writeConcernBasedError; - } + description.getServerAddress() + ); if (writeConcernBasedError != null) { throw new MongoWriteConcernWithResponseException(writeConcernBasedError, result); } @@ -890,7 +856,7 @@ public void sendMessage(final List byteBuffers, final int lastRequestId stream.write(byteBuffers, operationContext); } catch (Throwable t) { close(); - throwTranslatedWriteException(t, operationContext); + throwTranslatedWriteException(t); } } @@ -911,7 +877,7 @@ public void sendMessageAsync( }, Throwable.class, (t, c) -> { try { close(); - throwTranslatedWriteException(t, operationContext); + throwTranslatedWriteException(t); } catch (Throwable translatedException) { c.completeExceptionally(translatedException); } @@ -964,12 +930,12 @@ public void completed(@Nullable final ByteBuf buffer) { @Override public void failed(final Throwable t) { close(); - callback.onResult(null, mapUnlessError(t, e -> translateReadException(e, operationContext))); + callback.onResult(null, mapUnlessError(t, e -> translateReadException(e))); } }); } catch (Throwable t) { close(); - callback.onResult(null, mapUnlessError(t, e -> translateReadException(e, operationContext))); + callback.onResult(null, mapUnlessError(t, e -> translateReadException(e))); } } @@ -993,17 +959,8 @@ private void updateSessionContext(final SessionContext sessionContext, final Res } } - private void throwTranslatedWriteException(final Throwable e, final OperationContext operationContext) { + private void throwTranslatedWriteException(final Throwable e) { rethrowIfError(e); - if (operationContext.getTimeoutContext().hasTimeoutMS()) { - if (e instanceof MongoSocketWriteTimeoutException) { - throw createMongoTimeoutException(e); - } else if (e instanceof SocketTimeoutException) { - // A blocking (SSL) write can surface the socket read-timeout as a bare SocketTimeoutException; - // mirror translateReadException so it is reported as a timeout rather than a generic write error. - throw createMongoTimeoutException(createWriteTimeoutException((SocketTimeoutException) e)); - } - } if (e instanceof MongoException) { throw (MongoException) e; @@ -1018,19 +975,7 @@ private void throwTranslatedWriteException(final Throwable e, final OperationCon } } - private MongoSocketWriteTimeoutException createWriteTimeoutException(final SocketTimeoutException e) { - return new MongoSocketWriteTimeoutException("Timeout while sending message", getServerAddress(), e); - } - - private MongoException translateReadException(final Throwable e, final OperationContext operationContext) { - if (operationContext.getTimeoutContext().hasTimeoutMS()) { - if (e instanceof SocketTimeoutException) { - return createMongoTimeoutException(createReadTimeoutException((SocketTimeoutException) e)); - } else if (e instanceof MongoSocketReadTimeoutException) { - return createMongoTimeoutException((e)); - } - } - + private MongoException translateReadException(final Throwable e) { if (e instanceof MongoException) { return (MongoException) e; } @@ -1095,7 +1040,7 @@ private ResponseBuffers receiveResponseBuffers(final OperationContext operationC } close(); rethrowIfError(t); - throw translateReadException(t, operationContext); + throw translateReadException(t); } } diff --git a/driver-core/src/main/com/mongodb/internal/connection/LoadBalancedCluster.java b/driver-core/src/main/com/mongodb/internal/connection/LoadBalancedCluster.java index 69c899396cf..0c86d1cb3ed 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/LoadBalancedCluster.java +++ b/driver-core/src/main/com/mongodb/internal/connection/LoadBalancedCluster.java @@ -19,7 +19,6 @@ import com.mongodb.MongoClientException; import com.mongodb.MongoException; import com.mongodb.MongoInterruptedException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoTimeoutException; import com.mongodb.ServerAddress; import com.mongodb.annotations.ThreadSafe; @@ -193,7 +192,7 @@ public ServersSnapshot getServersSnapshot( final Timeout serverSelectionTimeout, final TimeoutContext timeoutContext) { isTrue("open", !isClosed()); - waitForSrv(serverSelectionTimeout, timeoutContext); + waitForSrv(serverSelectionTimeout); ClusterableServer server = assertNotNull(this.server); return serverAddress -> server; } @@ -219,7 +218,7 @@ public ClientMetadata getClientMetadata() { public ServerTuple selectServer(final ServerSelector serverSelector, final OperationContext operationContext) { isTrue("open", !isClosed()); Timeout computedServerSelectionTimeout = operationContext.getTimeoutContext().computeServerSelectionTimeout(); - waitForSrv(computedServerSelectionTimeout, operationContext.getTimeoutContext()); + waitForSrv(computedServerSelectionTimeout); if (srvRecordResolvedToMultipleHosts) { throw createResolvedToMultipleHostsException(); } @@ -231,7 +230,7 @@ public ServerTuple selectServer(final ServerSelector serverSelector, final Opera return serverTuple; } - private void waitForSrv(final Timeout serverSelectionTimeout, final TimeoutContext timeoutContext) { + private void waitForSrv(final Timeout serverSelectionTimeout) { if (initializationCompleted) { return; } @@ -241,7 +240,7 @@ private void waitForSrv(final Timeout serverSelectionTimeout, final TimeoutConte throw createShutdownException(); } serverSelectionTimeout.onExpired(() -> { - throw createTimeoutException(timeoutContext); + throw createTimeoutException(); }); serverSelectionTimeout.awaitOn(condition, () -> format("resolving SRV records for %s", settings.getSrvHost())); } @@ -324,7 +323,7 @@ private MongoClientException createResolvedToMultipleHostsException() { + "to multiple hosts"); } - private MongoTimeoutException createTimeoutException(final TimeoutContext timeoutContext) { + private MongoTimeoutException createTimeoutException() { MongoException localSrvResolutionException = srvResolutionException; String message; if (localSrvResolutionException == null) { @@ -333,11 +332,11 @@ private MongoTimeoutException createTimeoutException(final TimeoutContext timeou message = format("Timed out while waiting to resolve SRV records for %s. " + "Resolution exception was '%s'", settings.getSrvHost(), localSrvResolutionException); } - return createTimeoutException(timeoutContext, message); + return createTimeoutException(message); } - private static MongoTimeoutException createTimeoutException(final TimeoutContext timeoutContext, final String message) { - return timeoutContext.hasTimeoutMS() ? new MongoOperationTimeoutException(message) : new MongoTimeoutException(message); + private static MongoTimeoutException createTimeoutException(final String message) { + return new MongoTimeoutException(message); } private void notifyWaitQueueHandler(final ServerSelectionRequest request) { @@ -399,9 +398,7 @@ public void run() { } finally { lock.unlock(); } - timeoutList.forEach(request -> request.onError(createTimeoutException(request - .getOperationContext() - .getTimeoutContext()))); + timeoutList.forEach(request -> request.onError(createTimeoutException())); timeoutList.clear(); } diff --git a/driver-core/src/main/com/mongodb/internal/connection/OidcAuthenticator.java b/driver-core/src/main/com/mongodb/internal/connection/OidcAuthenticator.java index 5920bbc8756..83a58eca495 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/OidcAuthenticator.java +++ b/driver-core/src/main/com/mongodb/internal/connection/OidcAuthenticator.java @@ -47,12 +47,10 @@ import java.nio.file.Files; import java.nio.file.Paths; import java.time.Duration; -import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import static com.mongodb.AuthenticationMechanism.MONGODB_OIDC; @@ -68,7 +66,6 @@ import static com.mongodb.assertions.Assertions.assertFalse; import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.assertions.Assertions.assertTrue; -import static com.mongodb.internal.TimeoutContext.throwMongoTimeoutException; import static com.mongodb.internal.async.AsyncRunnable.beginAsync; import static com.mongodb.internal.connection.OidcAuthenticator.OidcValidator.validateBeforeUse; import static java.lang.String.format; @@ -129,16 +126,6 @@ private Duration getCallbackTimeout(final TimeoutContext timeoutContext) { if (isHumanCallback()) { return HUMAN_CALLBACK_TIMEOUT; } - - if (timeoutContext.hasTimeoutMS()) { - return assertNotNull(timeoutContext.getTimeout()).call(TimeUnit.MILLISECONDS, - () -> - // we can get here if server selection timeout was set to infinite. - ChronoUnit.FOREVER.getDuration(), - (remainingMs) -> Duration.ofMillis(remainingMs), - () -> throwMongoTimeoutException()); - - } return CALLBACK_TIMEOUT; } diff --git a/driver-core/src/main/com/mongodb/internal/connection/ProtocolHelper.java b/driver-core/src/main/com/mongodb/internal/connection/ProtocolHelper.java index c6ad5f451a0..2389efac9e6 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/ProtocolHelper.java +++ b/driver-core/src/main/com/mongodb/internal/connection/ProtocolHelper.java @@ -32,7 +32,6 @@ import com.mongodb.event.CommandStartedEvent; import com.mongodb.event.CommandSucceededEvent; import com.mongodb.internal.IgnorableRequestContext; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.diagnostics.logging.Logger; import com.mongodb.internal.diagnostics.logging.Loggers; import com.mongodb.lang.Nullable; @@ -86,13 +85,12 @@ static boolean isCommandOk(final ResponseBuffers responseBuffers) { @Nullable static MongoException createSpecialWriteConcernException(final ResponseBuffers responseBuffers, - final ServerAddress serverAddress, - final TimeoutContext timeoutContext) { + final ServerAddress serverAddress) { BsonValue writeConcernError = getField(createBsonReader(responseBuffers), "writeConcernError"); if (writeConcernError == null) { return null; } else { - return createSpecialException(writeConcernError.asDocument(), serverAddress, "errmsg", timeoutContext); + return createSpecialException(writeConcernError.asDocument(), serverAddress, "errmsg"); } } @@ -201,9 +199,8 @@ private static boolean isCommandOk(@Nullable final BsonValue okValue) { } } - static MongoException getCommandFailureException(final BsonDocument response, final ServerAddress serverAddress, - final TimeoutContext timeoutContext) { - MongoException specialException = createSpecialException(response, serverAddress, "errmsg", timeoutContext); + static MongoException getCommandFailureException(final BsonDocument response, final ServerAddress serverAddress) { + MongoException specialException = createSpecialException(response, serverAddress, "errmsg"); if (specialException != null) { return specialException; } @@ -218,9 +215,8 @@ static String getErrorMessage(final BsonDocument response, final String errorMes return response.getString(errorMessageFieldName, new BsonString("")).getValue(); } - static MongoException getQueryFailureException(final BsonDocument errorDocument, final ServerAddress serverAddress, - final TimeoutContext timeoutContext) { - MongoException specialException = createSpecialException(errorDocument, serverAddress, "$err", timeoutContext); + static MongoException getQueryFailureException(final BsonDocument errorDocument, final ServerAddress serverAddress) { + MongoException specialException = createSpecialException(errorDocument, serverAddress, "$err"); if (specialException != null) { return specialException; } @@ -247,26 +243,21 @@ static MessageSettings getMessageSettings(final ConnectionDescription connection @Nullable public static MongoException createSpecialException(@Nullable final BsonDocument response, final ServerAddress serverAddress, - final String errorMessageFieldName, - final TimeoutContext timeoutContext) { + final String errorMessageFieldName) { if (response == null) { return null; } int errorCode = getErrorCode(response); String errorMessage = getErrorMessage(response, errorMessageFieldName); if (ErrorCategory.fromErrorCode(errorCode) == ErrorCategory.EXECUTION_TIMEOUT) { - MongoExecutionTimeoutException mongoExecutionTimeoutException = new MongoExecutionTimeoutException(errorCode, errorMessage, response); - if (timeoutContext.hasTimeoutMS()) { - return TimeoutContext.createMongoTimeoutException(mongoExecutionTimeoutException); - } - return mongoExecutionTimeoutException; + return new MongoExecutionTimeoutException(errorCode, errorMessage, response); } else if (isNodeIsRecoveringError(errorCode, errorMessage)) { return new MongoNodeIsRecoveringException(response, serverAddress); } else if (isNotPrimaryError(errorCode, errorMessage)) { return new MongoNotPrimaryException(response, serverAddress); } else if (response.containsKey("writeConcernError")) { MongoException writeConcernException = createSpecialException(response.getDocument("writeConcernError"), serverAddress, - "errmsg", timeoutContext); + "errmsg"); if (writeConcernException != null && response.isArray("errorLabels")) { for (BsonValue errorLabel : response.getArray("errorLabels")) { writeConcernException.addLabel(errorLabel.asString().getValue()); diff --git a/driver-core/src/main/com/mongodb/internal/connection/SaslAuthenticator.java b/driver-core/src/main/com/mongodb/internal/connection/SaslAuthenticator.java index 050a4862b17..f3a789ecfc4 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/SaslAuthenticator.java +++ b/driver-core/src/main/com/mongodb/internal/connection/SaslAuthenticator.java @@ -20,7 +20,6 @@ import com.mongodb.MongoCredential; import com.mongodb.MongoException; import com.mongodb.MongoInterruptedException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoSecurityException; import com.mongodb.ServerAddress; import com.mongodb.ServerApi; @@ -285,8 +284,6 @@ private void disposeOfSaslClient(final SaslClient saslClient) { protected MongoException wrapException(final Throwable t) { if (t instanceof MongoInterruptedException) { return (MongoInterruptedException) t; - } else if (t instanceof MongoOperationTimeoutException) { - return (MongoOperationTimeoutException) t; } else if (t instanceof MongoSecurityException) { return (MongoSecurityException) t; } else { diff --git a/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java b/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java index 764f41034f2..491093ce242 100644 --- a/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java +++ b/driver-core/src/main/com/mongodb/internal/connection/SocketStream.java @@ -46,7 +46,6 @@ import static com.mongodb.assertions.Assertions.assertTrue; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.internal.TimeoutContext.throwMongoTimeoutException; import static com.mongodb.internal.connection.ServerAddressHelper.getSocketAddresses; import static com.mongodb.internal.connection.SocketStreamHelper.configureSocket; import static com.mongodb.internal.connection.SslHelper.configureSslSocket; @@ -204,9 +203,6 @@ public ByteBuf getBuffer(final int size) { public void write(final List buffers, final OperationContext operationContext) throws IOException { for (final ByteBuf cur : buffers) { outputStream.write(cur.array(), 0, cur.limit()); - operationContext.getTimeoutContext().onExpired(() -> { - throwMongoTimeoutException("Socket write exceeded the timeout limit."); - }); } } diff --git a/driver-core/src/main/com/mongodb/internal/operation/AbstractWriteSearchIndexOperation.java b/driver-core/src/main/com/mongodb/internal/operation/AbstractWriteSearchIndexOperation.java index 375280c90c7..1d0fb84efad 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AbstractWriteSearchIndexOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AbstractWriteSearchIndexOperation.java @@ -74,7 +74,7 @@ public Void execute(final WriteBinding binding, final OperationContext operation try { executeCommand(binding, operationContextWithMinRtt, namespace.getDatabaseName(), buildCommand(), connection, - writeConcernErrorTransformer(operationContextWithMinRtt.getTimeoutContext())); + writeConcernErrorTransformer()); } catch (MongoCommandException mongoCommandException) { swallowOrThrow(mongoCommandException); } @@ -94,7 +94,7 @@ public void executeAsync(final AsyncWriteBinding binding, final OperationContext withAsyncSourceAndConnection(binding::getWriteConnectionSource, false, operationContext, supplierCallback, (connectionSource, connection, operationContextWithMinRtt, cb) -> executeCommandAsync(binding, operationContextWithMinRtt, namespace.getDatabaseName(), buildCommand(), - connection, writeConcernErrorTransformerAsync(operationContextWithMinRtt.getTimeoutContext()), + connection, writeConcernErrorTransformerAsync(), (result, commandExecutionError) -> { try { swallowOrThrow(commandExecutionError); diff --git a/driver-core/src/main/com/mongodb/internal/operation/AggregateOperation.java b/driver-core/src/main/com/mongodb/internal/operation/AggregateOperation.java index 07ce3ce62bb..bf47a7f662d 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AggregateOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AggregateOperation.java @@ -18,7 +18,6 @@ import com.mongodb.ExplainVerbosity; import com.mongodb.MongoNamespace; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.async.AsyncBatchCursor; import com.mongodb.internal.async.SingleResultCallback; @@ -132,11 +131,6 @@ public AggregateOperation hint(@Nullable final BsonValue hint) { return this; } - public AggregateOperation timeoutMode(@Nullable final TimeoutMode timeoutMode) { - wrapped.timeoutMode(timeoutMode); - return this; - } - @Override public String getCommandName() { return wrapped.getCommandName(); diff --git a/driver-core/src/main/com/mongodb/internal/operation/AggregateOperationImpl.java b/driver-core/src/main/com/mongodb/internal/operation/AggregateOperationImpl.java index 0442571f41c..20e36886d5d 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AggregateOperationImpl.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AggregateOperationImpl.java @@ -16,12 +16,9 @@ package com.mongodb.internal.operation; -import com.mongodb.CursorType; import com.mongodb.MongoNamespace; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.TimeoutContext; -import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.async.AsyncBatchCursor; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.binding.AsyncReadBinding; @@ -47,7 +44,6 @@ import static com.mongodb.internal.operation.AsyncOperationHelper.executeRetryableReadAsync; import static com.mongodb.internal.operation.CommandOperationHelper.CommandCreator; import static com.mongodb.internal.operation.OperationHelper.LOGGER; -import static com.mongodb.internal.operation.OperationHelper.applyTimeoutModeToOperationContext; import static com.mongodb.internal.operation.OperationReadConcernHelper.appendReadConcernToCommand; import static com.mongodb.internal.operation.SyncOperationHelper.CommandReadTransformer; import static com.mongodb.internal.operation.SyncOperationHelper.executeRetryableRead; @@ -73,8 +69,6 @@ class AggregateOperationImpl implements ReadOperationCursor { private BsonValue comment; private BsonValue hint; private BsonDocument variables; - private TimeoutMode timeoutMode; - private CursorType cursorType; AggregateOperationImpl(final MongoNamespace namespace, final List pipeline, final Decoder decoder, final AggregationLevel aggregationLevel, @@ -152,19 +146,6 @@ AggregateOperationImpl retryReads(final boolean retryReads) { return this; } - /** - * When {@link TimeoutContext#hasTimeoutMS()} then {@link TimeoutSettings#getMaxAwaitTimeMS()} usage in {@code getMore} commands - * depends on the type of cursor. For {@link CursorType#TailableAwait} it is used, for others it is not. - * {@link CursorType#TailableAwait} is used mainly for change streams in {@link AggregateOperationImpl}. - * - * @param cursorType - * @return this - */ - AggregateOperationImpl cursorType(final CursorType cursorType) { - this.cursorType = cursorType; - return this; - } - boolean getRetryReads() { return retryReads; } @@ -174,13 +155,6 @@ BsonValue getHint() { return hint; } - public AggregateOperationImpl timeoutMode(@Nullable final TimeoutMode timeoutMode) { - if (timeoutMode != null) { - this.timeoutMode = timeoutMode; - } - return this; - } - AggregateOperationImpl hint(@Nullable final BsonValue hint) { isTrueArgument("BsonString or BsonDocument", hint == null || hint.isDocument() || hint.isString()); this.hint = hint; @@ -199,7 +173,7 @@ public MongoNamespace getNamespace() { @Override public BatchCursor execute(final ReadBinding binding, final OperationContext operationContext) { - return executeRetryableRead(binding, applyTimeoutModeToOperationContext(timeoutMode, operationContext), namespace.getDatabaseName(), + return executeRetryableRead(binding, operationContext, namespace.getDatabaseName(), getCommandCreator(), CommandResultDocumentCodec.create(decoder, FIELD_NAMES_WITH_RESULT), transformer(), retryReads, maxAdaptiveRetriesSetting); } @@ -207,7 +181,7 @@ public BatchCursor execute(final ReadBinding binding, final OperationContext @Override public void executeAsync(final AsyncReadBinding binding, final OperationContext operationContext, final SingleResultCallback> callback) { SingleResultCallback> errHandlingCallback = errorHandlingCallback(callback, LOGGER); - executeRetryableReadAsync(binding, applyTimeoutModeToOperationContext(timeoutMode, operationContext), namespace.getDatabaseName(), + executeRetryableReadAsync(binding, operationContext, namespace.getDatabaseName(), getCommandCreator(), CommandResultDocumentCodec.create(decoder, FIELD_NAMES_WITH_RESULT), asyncTransformer(), retryReads, maxAdaptiveRetriesSetting, errHandlingCallback); @@ -248,7 +222,7 @@ BsonDocument getCommand(final OperationContext operationContext, final int maxWi private CommandReadTransformer> transformer() { return (result, source, connection, operationContext) -> - new CommandBatchCursor<>(getTimeoutMode(), getMaxTimeForCursor(operationContext.getTimeoutContext()), operationContext, new CommandCursor<>( + new CommandBatchCursor<>(getMaxTimeForCursor(operationContext.getTimeoutContext()), operationContext, new CommandCursor<>( result, batchSize != null ? batchSize : 0, decoder, comment, source, connection, retryReads, maxAdaptiveRetriesSetting @@ -257,27 +231,15 @@ private CommandReadTransformer> transformer( private CommandReadTransformerAsync> asyncTransformer() { return (result, source, connection, operationContext) -> - new AsyncCommandBatchCursor<>(getTimeoutMode(), getMaxTimeForCursor(operationContext.getTimeoutContext()), + new AsyncCommandBatchCursor<>(getMaxTimeForCursor(operationContext.getTimeoutContext()), operationContext, new AsyncCommandCursor<>( result, batchSize != null ? batchSize : 0, decoder, comment, source, connection, retryReads, maxAdaptiveRetriesSetting )); } - private TimeoutMode getTimeoutMode() { - TimeoutMode localTimeoutMode = timeoutMode; - if (localTimeoutMode == null) { - localTimeoutMode = TimeoutMode.CURSOR_LIFETIME; - } - return localTimeoutMode; - } - private long getMaxTimeForCursor(final TimeoutContext timeoutContext) { - long maxAwaitTimeMS = timeoutContext.getMaxAwaitTimeMS(); - if (timeoutContext.hasTimeoutMS()){ - return CursorType.TailableAwait == cursorType ? maxAwaitTimeMS : 0; - } - return maxAwaitTimeMS; + return timeoutContext.getMaxAwaitTimeMS(); } interface AggregateTarget { diff --git a/driver-core/src/main/com/mongodb/internal/operation/AggregateToCollectionOperation.java b/driver-core/src/main/com/mongodb/internal/operation/AggregateToCollectionOperation.java index 763c9d1a78f..e25a39d3658 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AggregateToCollectionOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AggregateToCollectionOperation.java @@ -20,7 +20,6 @@ import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.binding.AsyncReadBinding; @@ -162,11 +161,6 @@ public AggregateToCollectionOperation hint(@Nullable final BsonValue hint) { return this; } - public AggregateToCollectionOperation timeoutMode(@Nullable final TimeoutMode timeoutMode) { - isTrueArgument("timeoutMode cannot be ITERATION.", timeoutMode == null || timeoutMode.equals(TimeoutMode.CURSOR_LIFETIME)); - return this; - } - @Override public String getCommandName() { return COMMAND_NAME; @@ -249,7 +243,7 @@ private CommandOperationHelper.CommandCreator getCommandCreator() { private static CommandReadTransformer transformer() { return (result, source, connection, operationContext) -> { throwOnWriteConcernError(result, connection.getDescription().getServerAddress(), - connection.getDescription().getMaxWireVersion(), operationContext.getTimeoutContext()); + connection.getDescription().getMaxWireVersion()); return null; }; } @@ -257,7 +251,7 @@ private static CommandReadTransformer transformer() { private static CommandReadTransformerAsync asyncTransformer() { return (result, source, connection, operationContext) -> { throwOnWriteConcernError(result, connection.getDescription().getServerAddress(), - connection.getDescription().getMaxWireVersion(), operationContext.getTimeoutContext()); + connection.getDescription().getMaxWireVersion()); return null; }; } diff --git a/driver-core/src/main/com/mongodb/internal/operation/AsyncCommandBatchCursor.java b/driver-core/src/main/com/mongodb/internal/operation/AsyncCommandBatchCursor.java index f390981694e..255d01c2a50 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AsyncCommandBatchCursor.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AsyncCommandBatchCursor.java @@ -16,7 +16,6 @@ package com.mongodb.internal.operation; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.async.AsyncAggregateResponseBatchCursor; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.connection.OperationContext; @@ -28,25 +27,21 @@ public class AsyncCommandBatchCursor implements AsyncAggregateResponseBatchCursor { - private final TimeoutMode timeoutMode; private OperationContext operationContext; private AsyncCursor wrapped; AsyncCommandBatchCursor( - final TimeoutMode timeoutMode, final long maxTimeMs, final OperationContext operationContext, final AsyncCursor wrapped) { this.operationContext = operationContext.withOverride(timeoutContext -> timeoutContext.withMaxTimeOverride(maxTimeMs)); - this.timeoutMode = timeoutMode; this.wrapped = wrapped; } @Override public void next(final SingleResultCallback> callback) { - resetTimeout(); wrapped.next(operationContext, callback); } @@ -96,12 +91,6 @@ public int getMaxWireVersion() { return wrapped.getMaxWireVersion(); } - private void resetTimeout() { - if (timeoutMode == TimeoutMode.ITERATION) { - operationContext = operationContext.withNewlyStartedTimeout(); - } - } - AsyncCursor getWrapped() { return wrapped; } diff --git a/driver-core/src/main/com/mongodb/internal/operation/AsyncCommandCursor.java b/driver-core/src/main/com/mongodb/internal/operation/AsyncCommandCursor.java index 6a4ef41a43e..74320b5be85 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AsyncCommandCursor.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AsyncCommandCursor.java @@ -20,7 +20,6 @@ import com.mongodb.MongoCommandException; import com.mongodb.MongoException; import com.mongodb.MongoNamespace; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoSocketException; import com.mongodb.ReadPreference; import com.mongodb.ServerAddress; @@ -323,9 +322,7 @@ void executeWithConnection(final OperationContext operationContext, final As } private void handleException(final AsyncConnection connection, final Throwable exception) { - if (exception instanceof MongoOperationTimeoutException && exception.getCause() instanceof MongoSocketException) { - onCorruptedConnection(connection, (MongoSocketException) exception.getCause()); - } else if (exception instanceof MongoSocketException) { + if (exception instanceof MongoSocketException) { onCorruptedConnection(connection, (MongoSocketException) exception); } } diff --git a/driver-core/src/main/com/mongodb/internal/operation/AsyncOperationHelper.java b/driver-core/src/main/com/mongodb/internal/operation/AsyncOperationHelper.java index bbce5a1010a..59b2ff5eb38 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/AsyncOperationHelper.java +++ b/driver-core/src/main/com/mongodb/internal/operation/AsyncOperationHelper.java @@ -20,10 +20,8 @@ import com.mongodb.MongoException; import com.mongodb.ReadPreference; import com.mongodb.assertions.Assertions; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.connection.ConnectionDescription; import com.mongodb.connection.ServerDescription; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.async.AsyncBatchCursor; import com.mongodb.internal.async.MutableValue; import com.mongodb.internal.async.SingleResultCallback; @@ -92,13 +90,12 @@ static void withAsyncReadConnectionSource(final AsyncReadBinding binding, final } static void withAsyncConnection(final AsyncWriteBinding binding, - final OperationContext originalOperationContext, + final OperationContext operationContext, final AsyncCallableWithConnection callable) { - OperationContext serverSelectionOperationContext = originalOperationContext.withOverride(TimeoutContext::withComputedServerSelectionTimeout); binding.getWriteConnectionSource( - serverSelectionOperationContext, + operationContext, errorHandlingCallback( - new AsyncCallableWithConnectionCallback(callable, serverSelectionOperationContext, originalOperationContext), + new AsyncCallableWithConnectionCallback(callable, operationContext, operationContext), OperationHelper.LOGGER)); } @@ -113,18 +110,16 @@ static void withAsyncSourceAndConnection( final AsyncCallbackTriFunction asyncFunction) { SingleResultCallback errorHandlingCallback = errorHandlingCallback(callback, OperationHelper.LOGGER); - OperationContext serverSelectionOperationContext = - operationContext.withOverride(TimeoutContext::withComputedServerSelectionTimeout); withAsyncSuppliedResource( sourceAsyncFunction, wrapConnectionSourceException, - serverSelectionOperationContext, + operationContext, errorHandlingCallback, (source, sourceReleasingCallback) -> withAsyncSuppliedResource( source::getConnection, wrapConnectionSourceException, - serverSelectionOperationContext.withMinRoundTripTime(source.getServerDescription()), + operationContext.withMinRoundTripTime(source.getServerDescription()), sourceReleasingCallback, (connection, connectionAndSourceReleasingCallback) -> asyncFunction.apply( @@ -367,12 +362,12 @@ static AsyncCallbackSupplier decorateWithRetriesAsync( }; } - static CommandWriteTransformerAsync writeConcernErrorTransformerAsync(final TimeoutContext timeoutContext) { + static CommandWriteTransformerAsync writeConcernErrorTransformerAsync() { return (result, connection) -> { assertNotNull(result); throwOnWriteConcernError(result, connection.getDescription().getServerAddress(), - connection.getDescription().getMaxWireVersion(), - timeoutContext); + connection.getDescription().getMaxWireVersion() + ); return null; }; } @@ -382,8 +377,7 @@ static CommandReadTransformerAsync> asyncS new AsyncSingleBatchCursor<>(BsonDocumentWrapperHelper.toList(result, fieldName), 0); } - static AsyncBatchCursor cursorDocumentToAsyncBatchCursor(final TimeoutMode timeoutMode, - final BsonDocument cursorDocument, + static AsyncBatchCursor cursorDocumentToAsyncBatchCursor(final BsonDocument cursorDocument, final int batchSize, final Decoder decoder, @Nullable final BsonValue comment, @@ -392,7 +386,7 @@ static AsyncBatchCursor cursorDocumentToAsyncBatchCursor(final TimeoutMod final OperationContext operationContext, final boolean retryReads, @Nullable final Integer maxAdaptiveRetriesSetting) { - return new AsyncCommandBatchCursor<>(timeoutMode, 0, operationContext, new AsyncCommandCursor<>( + return new AsyncCommandBatchCursor<>(0, operationContext, new AsyncCommandCursor<>( cursorDocument, batchSize, decoder, comment, source, connection, retryReads, maxAdaptiveRetriesSetting )); } 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 21e90a989f8..42fe288f706 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursor.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursor.java @@ -18,7 +18,6 @@ import com.mongodb.MongoChangeStreamException; import com.mongodb.MongoException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.ReadPreference; import com.mongodb.ServerAddress; import com.mongodb.ServerCursor; @@ -53,11 +52,6 @@ *

    * If an error occurring during any of these method calls is not resumable, it is immediately propagated to the caller, and the {@link ChangeStreamBatchCursor} * is closed and invalidated on the server. Server errors that occur during this invalidation process are not propagated to the caller. - *

    - * A {@link MongoOperationTimeoutException} does not invalidate the {@link ChangeStreamBatchCursor}, but is immediately propagated to the caller. - * Subsequent method call will attempt to resume operation by establishing a new change stream on the server, without doing {@code getMore} - * request first. - *

    */ final class ChangeStreamBatchCursor implements AggregateResponseBatchCursor { private ReadBinding binding; @@ -71,13 +65,6 @@ final class ChangeStreamBatchCursor implements AggregateResponseBatchCursor changeStreamOperation, final Cursor wrapped, final ReadBinding binding, @@ -93,7 +80,6 @@ final class ChangeStreamBatchCursor implements AggregateResponseBatchCursor getWrapped() { @@ -224,17 +210,15 @@ R resumeableOperation(final BiFunction, OperationCon OperationContext operationContextWithNewlyStartedTimeout = initialOperationContext.withNewlyStartedTimeout(); try { R result = execute(function, operationContextWithNewlyStartedTimeout); - lastOperationTimedOut = false; return result; } catch (Throwable exception) { - lastOperationTimedOut = isTimeoutException(exception); throw exception; } } private R execute(final BiFunction, OperationContext, R> function, final OperationContext operationContext) { - boolean shouldBeResumed = hasPreviousNextTimedOut(); + boolean shouldBeResumed = false; while (true) { if (shouldBeResumed) { resumeChangeStream(operationContext); @@ -266,14 +250,6 @@ private void resumeChangeStream(final OperationContext operationContext) { binding.release(); // release the new change stream batch cursor's reference to the binding } - private boolean hasPreviousNextTimedOut() { - return lastOperationTimedOut && !closed.get(); - } - - private static boolean isTimeoutException(final Throwable exception) { - return exception instanceof MongoOperationTimeoutException; - } - /** * Does not retain wrapped {link @ReadBinding} as it serves as a wrapper only. */ diff --git a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursorHelper.java b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursorHelper.java index 1bed2ed2b0f..922161cf9ee 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursorHelper.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamBatchCursorHelper.java @@ -22,7 +22,6 @@ import com.mongodb.MongoException; import com.mongodb.MongoInterruptedException; import com.mongodb.MongoNotPrimaryException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoSocketException; import com.mongodb.internal.VisibleForTesting; @@ -40,8 +39,7 @@ final class ChangeStreamBatchCursorHelper { static final String RESUMABLE_CHANGE_STREAM_ERROR_LABEL = "ResumableChangeStreamError"; static boolean isResumableError(final Throwable t, final int maxWireVersion) { - if (!(t instanceof MongoException) || (t instanceof MongoChangeStreamException) || (t instanceof MongoInterruptedException) - || (t instanceof MongoOperationTimeoutException)) { + if (!(t instanceof MongoException) || (t instanceof MongoChangeStreamException) || (t instanceof MongoInterruptedException)) { return false; } else if (t instanceof MongoNotPrimaryException || t instanceof MongoCursorNotFoundException || t instanceof MongoSocketException | t instanceof MongoClientException) { diff --git a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamOperation.java b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamOperation.java index c94dccebf50..dee38851cae 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ChangeStreamOperation.java @@ -16,12 +16,10 @@ package com.mongodb.internal.operation; -import com.mongodb.CursorType; import com.mongodb.MongoNamespace; import com.mongodb.client.model.Collation; import com.mongodb.client.model.changestream.FullDocument; import com.mongodb.client.model.changestream.FullDocumentBeforeChange; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.VisibleForTesting; import com.mongodb.internal.async.AsyncBatchCursor; import com.mongodb.internal.async.SingleResultCallback; @@ -46,7 +44,6 @@ import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.client.cursor.TimeoutMode.CURSOR_LIFETIME; /** * An operation that executes an {@code $changeStream} aggregation. @@ -77,7 +74,7 @@ public ChangeStreamOperation(final MongoNamespace namespace, final FullDocument final ChangeStreamLevel changeStreamLevel, @Nullable final Integer maxAdaptiveRetriesSetting) { this.wrapped = new AggregateOperationImpl<>(namespace, pipeline, RAW_BSON_DOCUMENT_CODEC, getAggregateTarget(), - getPipelineCreator(), maxAdaptiveRetriesSetting).cursorType(CursorType.TailableAwait); + getPipelineCreator(), maxAdaptiveRetriesSetting); this.fullDocument = notNull("fullDocument", fullDocument); this.fullDocumentBeforeChange = notNull("fullDocumentBeforeChange", fullDocumentBeforeChange); this.decoder = notNull("decoder", decoder); @@ -173,28 +170,6 @@ public ChangeStreamOperation showExpandedEvents(final boolean showExpandedEve return this; } - /** - * Gets an aggregate operation with consideration for timeout settings. - *

    - * Change streams act similarly to tailable awaitData cursors, with identical timeoutMS option behavior. - * Key distinctions include: - * - The timeoutMS option must be applied at the start of the aggregate operation for change streams. - * - Change streams support resumption on next() calls. The driver handles automatic resumption for transient errors. - *

    - * - * As a result, when {@code timeoutContext.hasTimeoutMS()} the CURSOR_LIFETIME setting is utilized to manage the underlying cursor's - * lifespan in change streams. - * - * @param timeoutContext - * @return An AggregateOperationImpl - */ - private AggregateOperationImpl getAggregateOperation(final TimeoutContext timeoutContext) { - if (timeoutContext.hasTimeoutMS()) { - return wrapped.timeoutMode(CURSOR_LIFETIME); - } - return wrapped; - } - @Override public String getCommandName() { return wrapped.getCommandName(); @@ -202,7 +177,7 @@ public String getCommandName() { @Override public BatchCursor execute(final ReadBinding binding, final OperationContext operationContext) { - Cursor cursor = ((CommandBatchCursor) getAggregateOperation(operationContext.getTimeoutContext()) + Cursor cursor = ((CommandBatchCursor) wrapped .execute(binding, operationContext)) .getWrapped(); @@ -220,7 +195,7 @@ public BatchCursor execute(final ReadBinding binding, final OperationContext @Override public void executeAsync(final AsyncReadBinding binding, final OperationContext operationContext, final SingleResultCallback> callback) { - getAggregateOperation(operationContext.getTimeoutContext()).executeAsync(binding, operationContext, (result, t) -> { + wrapped.executeAsync(binding, operationContext, (result, t) -> { if (t != null) { callback.onResult(null, t); } else { diff --git a/driver-core/src/main/com/mongodb/internal/operation/ClientBulkWriteOperation.java b/driver-core/src/main/com/mongodb/internal/operation/ClientBulkWriteOperation.java index d60528d6e3e..cb2f1959cc1 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ClientBulkWriteOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ClientBulkWriteOperation.java @@ -28,7 +28,6 @@ import com.mongodb.WriteConcern; import com.mongodb.WriteError; import com.mongodb.bulk.WriteConcernError; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.bulk.ClientBulkWriteOptions; import com.mongodb.client.model.bulk.ClientBulkWriteResult; import com.mongodb.client.model.bulk.ClientDeleteResult; @@ -512,7 +511,6 @@ private List> exhaustBulkWriteCommandOkResponseCursor( final Connection connection, final ClientBulkWriteCommandOkResponse response) { try (BatchCursor cursor = cursorDocumentToBatchCursor( - TimeoutMode.CURSOR_LIFETIME, response.getDocument(), SERVER_DEFAULT_CURSOR_BATCH_SIZE, codecRegistry.get(BsonDocument.class), @@ -535,7 +533,6 @@ private void exhaustBulkWriteCommandOkResponseCursorAsync( final SingleResultCallback>> callback) { beginAsync().>>thenSupply(c -> { AsyncBatchCursor cursor = cursorDocumentToAsyncBatchCursor( - TimeoutMode.CURSOR_LIFETIME, response.getDocument(), SERVER_DEFAULT_CURSOR_BATCH_SIZE, codecRegistry.get(BsonDocument.class), diff --git a/driver-core/src/main/com/mongodb/internal/operation/CommandBatchCursor.java b/driver-core/src/main/com/mongodb/internal/operation/CommandBatchCursor.java index 32f4785516d..6910e724ac9 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/CommandBatchCursor.java +++ b/driver-core/src/main/com/mongodb/internal/operation/CommandBatchCursor.java @@ -18,7 +18,6 @@ import com.mongodb.ServerAddress; import com.mongodb.ServerCursor; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.connection.OperationContext; import com.mongodb.lang.Nullable; import org.bson.BsonDocument; @@ -28,30 +27,25 @@ class CommandBatchCursor implements AggregateResponseBatchCursor { - private final TimeoutMode timeoutMode; private OperationContext operationContext; private Cursor wrapped; CommandBatchCursor( - final TimeoutMode timeoutMode, final long maxTimeMs, final OperationContext operationContext, final Cursor wrapped) { this.operationContext = operationContext.withOverride(timeoutContext -> timeoutContext.withMaxTimeOverride(maxTimeMs)); - this.timeoutMode = timeoutMode; this.wrapped = wrapped; } @Override public boolean hasNext() { - resetTimeout(); return wrapped.hasNext(operationContext); } @Override public List next() { - resetTimeout(); return wrapped.next(operationContext); } @@ -86,7 +80,6 @@ public void close() { @Nullable @Override public List tryNext() { - resetTimeout(); return wrapped.tryNext(operationContext); } @@ -123,12 +116,6 @@ public int getMaxWireVersion() { return wrapped.getMaxWireVersion(); } - private void resetTimeout() { - if (timeoutMode == TimeoutMode.ITERATION) { - operationContext = operationContext.withNewlyStartedTimeout(); - } - } - Cursor getWrapped() { return wrapped; } diff --git a/driver-core/src/main/com/mongodb/internal/operation/CommandCursor.java b/driver-core/src/main/com/mongodb/internal/operation/CommandCursor.java index 75f4f3bbf8a..a532971fd71 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/CommandCursor.java +++ b/driver-core/src/main/com/mongodb/internal/operation/CommandCursor.java @@ -19,7 +19,6 @@ import com.mongodb.MongoCommandException; import com.mongodb.MongoException; import com.mongodb.MongoNamespace; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoSocketException; import com.mongodb.ReadPreference; import com.mongodb.ServerAddress; @@ -335,12 +334,6 @@ void executeWithConnection(final Consumer action, final OperationCon } catch (MongoSocketException e) { onCorruptedConnection(connection, e); throw e; - } catch (MongoOperationTimeoutException e) { - Throwable cause = e.getCause(); - if (cause instanceof MongoSocketException) { - onCorruptedConnection(connection, (MongoSocketException) cause); - } - throw e; } finally { connection.release(); } diff --git a/driver-core/src/main/com/mongodb/internal/operation/CommandOperationHelper.java b/driver-core/src/main/com/mongodb/internal/operation/CommandOperationHelper.java index f7d4c30b694..6b114d22ac7 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/CommandOperationHelper.java +++ b/driver-core/src/main/com/mongodb/internal/operation/CommandOperationHelper.java @@ -29,7 +29,6 @@ import com.mongodb.connection.ServerDescription; import com.mongodb.internal.async.function.RetryControl; import com.mongodb.internal.connection.OperationContext; -import com.mongodb.internal.operation.SpecRetryPolicy.ExplicitMaxRetries; import com.mongodb.internal.session.SessionContext; import com.mongodb.lang.Nullable; import org.bson.BsonDocument; @@ -38,7 +37,6 @@ import java.util.Optional; import static com.mongodb.internal.operation.SpecRetryPolicy.ExplicitMaxRetries.RETRIES_LIMITED_BY_INDIVIDUAL_POLICIES; -import static com.mongodb.internal.operation.SpecRetryPolicy.ExplicitMaxRetries.NO_RETRIES_LIMIT; import static java.util.Arrays.asList; @SuppressWarnings("overloads") @@ -78,12 +76,9 @@ BsonDocument create( static RetryControl createSpecRetryControl( final SpecRetryPolicy.IndividualPolicies policies, final OperationContext operationContext) { - ExplicitMaxRetries explicitMaxRetries = operationContext.getTimeoutContext().hasTimeoutMS() - ? NO_RETRIES_LIMIT - : RETRIES_LIMITED_BY_INDIVIDUAL_POLICIES; return new RetryControl<>(new SpecRetryPolicy( policies, - explicitMaxRetries, + RETRIES_LIMITED_BY_INDIVIDUAL_POLICIES, operationContext.getServerDeprioritization())); } diff --git a/driver-core/src/main/com/mongodb/internal/operation/CommitTransactionOperation.java b/driver-core/src/main/com/mongodb/internal/operation/CommitTransactionOperation.java index c04b2c8c4ce..573ea4fa9a4 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/CommitTransactionOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/CommitTransactionOperation.java @@ -147,12 +147,11 @@ CommandCreator getCommandCreator() { @Override protected Function getRetryCommandModifier(final OperationContext operationContext) { - TimeoutContext timeoutContext = operationContext.getTimeoutContext(); return command -> { if (!assertNotNull(operationContext.getSessionContext().getOverloadRetryPolicyState().getCommitScoped()) .observedErrorsAndTheyAreAllRetryableOverloadErrors()) { WriteConcern retryWriteConcern = getWriteConcern().withW("majority"); - if (retryWriteConcern.getWTimeout(MILLISECONDS) == null && !timeoutContext.hasTimeoutMS()) { + if (retryWriteConcern.getWTimeout(MILLISECONDS) == null) { retryWriteConcern = retryWriteConcern.withWTimeout(10000, MILLISECONDS); } command.put("writeConcern", retryWriteConcern.asDocument()); diff --git a/driver-core/src/main/com/mongodb/internal/operation/CreateCollectionOperation.java b/driver-core/src/main/com/mongodb/internal/operation/CreateCollectionOperation.java index c83fb13b397..6c98a9bac68 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/CreateCollectionOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/CreateCollectionOperation.java @@ -267,7 +267,7 @@ public Void execute(final WriteBinding binding, final OperationContext operation return withConnection(binding, operationContext, (connection, connectionScopedOperationContext) -> { checkEncryptedFieldsSupported(connection.getDescription()); executeCommand(binding, connectionScopedOperationContext, databaseName, commandCreator.get(), connection, - writeConcernErrorTransformer(connectionScopedOperationContext.getTimeoutContext())); + writeConcernErrorTransformer()); return null; }); }); @@ -457,7 +457,7 @@ public void onResult(@Nullable final Void result, @Nullable final Throwable t) { } executeCommandAsync(binding, connectionScopedOperationContext, databaseName, nextCommandFunction.get(), connection, - writeConcernErrorTransformerAsync(connectionScopedOperationContext.getTimeoutContext()), + writeConcernErrorTransformerAsync(), connectionReleasingCallback); } }); diff --git a/driver-core/src/main/com/mongodb/internal/operation/CreateIndexesOperation.java b/driver-core/src/main/com/mongodb/internal/operation/CreateIndexesOperation.java index b5a9e78bea6..d816ebdefcc 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/CreateIndexesOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/CreateIndexesOperation.java @@ -138,7 +138,7 @@ public Void execute(final WriteBinding binding, final OperationContext operation Supplier retryingCommandExecutor = decorateWithRetries(retryControl, operationContext, () -> { retryControl.getPolicy().onCommand(this::getCommandName); return executeCommand(binding, operationContext, namespace.getDatabaseName(), getCommandCreator(), - writeConcernErrorTransformer(operationContext.getTimeoutContext())); + writeConcernErrorTransformer()); }); try { return retryingCommandExecutor.get(); @@ -155,7 +155,7 @@ public void executeAsync(final AsyncWriteBinding binding, final OperationContext AsyncCallbackSupplier retryingCommandExecutor = decorateWithRetriesAsync(retryControl, operationContext, supplierCallback -> { retryControl.getPolicy().onCommand(this::getCommandName); executeCommandAsync(binding, operationContext, namespace.getDatabaseName(), getCommandCreator(), - writeConcernErrorTransformerAsync(operationContext.getTimeoutContext()), supplierCallback); + writeConcernErrorTransformerAsync(), supplierCallback); }); retryingCommandExecutor.get((result, t) -> { if (t != null) { diff --git a/driver-core/src/main/com/mongodb/internal/operation/CreateViewOperation.java b/driver-core/src/main/com/mongodb/internal/operation/CreateViewOperation.java index b2e95daf7ef..a80860fd9db 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/CreateViewOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/CreateViewOperation.java @@ -161,7 +161,7 @@ public Void execute(final WriteBinding binding, final OperationContext operation retryControl.getPolicy().onCommand(this::getCommandName); return withConnection(binding, operationContext, (connection, operationContextWithMinRtt) -> { executeCommand(binding, operationContextWithMinRtt, databaseName, getCommand(), new BsonDocumentCodec(), - writeConcernErrorTransformer(operationContextWithMinRtt.getTimeoutContext())); + writeConcernErrorTransformer()); return null; }); }); @@ -181,7 +181,7 @@ public void executeAsync(final AsyncWriteBinding binding, final OperationContext } else { SingleResultCallback wrappedCallback = releasingCallback(errHandlingCallback, connection); executeCommandAsync(binding, operationContextWithMinRtt, databaseName, getCommand(), connection, - writeConcernErrorTransformerAsync(operationContextWithMinRtt.getTimeoutContext()), + writeConcernErrorTransformerAsync(), wrappedCallback); } })); diff --git a/driver-core/src/main/com/mongodb/internal/operation/DropCollectionOperation.java b/driver-core/src/main/com/mongodb/internal/operation/DropCollectionOperation.java index ea1296bb2b6..90a0482b102 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/DropCollectionOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/DropCollectionOperation.java @@ -123,7 +123,7 @@ public Void execute(final WriteBinding binding, final OperationContext operation return withConnection(binding, operationContext, (connection, connectionScopedOperationContext) -> { try { executeCommand(binding, connectionScopedOperationContext, namespace.getDatabaseName(), commandCreator.get(), - connection, writeConcernErrorTransformer(connectionScopedOperationContext.getTimeoutContext())); + connection, writeConcernErrorTransformer()); } catch (MongoCommandException e) { rethrowIfNotNamespaceError(e); } @@ -288,7 +288,7 @@ public void onResult(@Nullable final Void result, @Nullable final Throwable t) { SingleResultCallback connectionReleasingCallback = releasingCallback(supplierCallback, connection); executeCommandAsync(binding, connectionScopedOperationContext, namespace.getDatabaseName(), nextCommandFunction.get(), connection, - writeConcernErrorTransformerAsync(connectionScopedOperationContext.getTimeoutContext()), + writeConcernErrorTransformerAsync(), connectionReleasingCallback); } }); diff --git a/driver-core/src/main/com/mongodb/internal/operation/DropDatabaseOperation.java b/driver-core/src/main/com/mongodb/internal/operation/DropDatabaseOperation.java index b08290f476c..06d3c7db503 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/DropDatabaseOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/DropDatabaseOperation.java @@ -96,7 +96,7 @@ public Void execute(final WriteBinding binding, final OperationContext operation retryControl.getPolicy().onCommand(this::getCommandName); return withConnection(binding, operationContext, (connection, operationContextWithMinRtt) -> { executeCommand(binding, operationContextWithMinRtt, databaseName, getCommand(operationContext), connection, - writeConcernErrorTransformer(operationContextWithMinRtt.getTimeoutContext())); + writeConcernErrorTransformer()); return null; }); }); @@ -115,7 +115,7 @@ public void executeAsync(final AsyncWriteBinding binding, final OperationContext errHandlingCallback.onResult(null, t); } else { executeCommandAsync(binding, operationContextWithMinRtt, databaseName, getCommand(operationContext), connection, - writeConcernErrorTransformerAsync(operationContextWithMinRtt.getTimeoutContext()), + writeConcernErrorTransformerAsync(), releasingCallback(errHandlingCallback, connection)); } })); diff --git a/driver-core/src/main/com/mongodb/internal/operation/DropIndexOperation.java b/driver-core/src/main/com/mongodb/internal/operation/DropIndexOperation.java index 2e9cc1c4d4c..40c5b422057 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/DropIndexOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/DropIndexOperation.java @@ -109,8 +109,7 @@ public Void execute(final WriteBinding binding, final OperationContext operation operationContext); Supplier retryingCommandExecutor = decorateWithRetries(retryControl, operationContext, () -> { retryControl.getPolicy().onCommand(this::getCommandName); - executeCommand(binding, operationContext, namespace.getDatabaseName(), getCommandCreator(), writeConcernErrorTransformer( - operationContext.getTimeoutContext())); + executeCommand(binding, operationContext, namespace.getDatabaseName(), getCommandCreator(), writeConcernErrorTransformer()); return null; }); try { @@ -130,7 +129,7 @@ public void executeAsync(final AsyncWriteBinding binding, final OperationContext AsyncCallbackSupplier retryingCommandExecutor = decorateWithRetriesAsync(retryControl, operationContext, supplierCallback -> { retryControl.getPolicy().onCommand(this::getCommandName); executeCommandAsync(binding, operationContext, namespace.getDatabaseName(), getCommandCreator(), - writeConcernErrorTransformerAsync(operationContext.getTimeoutContext()), supplierCallback); + writeConcernErrorTransformerAsync(), supplierCallback); }); retryingCommandExecutor.get((result, t) -> { if (t != null && !isNamespaceError(t)) { diff --git a/driver-core/src/main/com/mongodb/internal/operation/ExplainCommandOperation.java b/driver-core/src/main/com/mongodb/internal/operation/ExplainCommandOperation.java index d652f4a5200..0887a3ed4f0 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ExplainCommandOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ExplainCommandOperation.java @@ -16,6 +16,7 @@ package com.mongodb.internal.operation; +import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.binding.AsyncReadBinding; import com.mongodb.internal.binding.ReadBinding; @@ -40,24 +41,12 @@ public ExplainCommandOperation(final String databaseName, final String commandNa @Override public T execute(final ReadBinding binding, final OperationContext operationContext) { - return super.execute(binding, operationContext.withOverride(timeoutContext -> { - if (!timeoutContext.hasTimeoutMS()) { - return timeoutContext.withDisabledMaxTime(); - } - - return timeoutContext; - })); + return super.execute(binding, operationContext.withOverride(TimeoutContext::withDisabledMaxTime)); } @Override public void executeAsync(final AsyncReadBinding binding, final OperationContext operationContext, final SingleResultCallback callback) { - super.executeAsync(binding, operationContext.withOverride(timeoutContext -> { - if (!timeoutContext.hasTimeoutMS()) { - return timeoutContext.withDisabledMaxTime(); - } - - return timeoutContext; - }), callback); + super.executeAsync(binding, operationContext.withOverride(TimeoutContext::withDisabledMaxTime), callback); } } diff --git a/driver-core/src/main/com/mongodb/internal/operation/FindOperation.java b/driver-core/src/main/com/mongodb/internal/operation/FindOperation.java index cef61e5672b..3834546b6fd 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/FindOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/FindOperation.java @@ -21,7 +21,6 @@ import com.mongodb.MongoCommandException; import com.mongodb.MongoNamespace; import com.mongodb.MongoQueryException; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.async.AsyncBatchCursor; @@ -93,7 +92,6 @@ public class FindOperation implements ReadOperationExplainable { private boolean returnKey; private boolean showRecordId; private Boolean allowDiskUse; - private TimeoutMode timeoutMode; public FindOperation( final MongoNamespace namespace, @@ -176,13 +174,6 @@ public FindOperation cursorType(final CursorType cursorType) { return this; } - public FindOperation timeoutMode(@Nullable final TimeoutMode timeoutMode) { - if (timeoutMode != null) { - this.timeoutMode = timeoutMode; - } - return this; - } - public boolean isNoCursorTimeout() { return noCursorTimeout; } @@ -298,11 +289,6 @@ public String getCommandName() { @Override public BatchCursor execute(final ReadBinding binding, final OperationContext operationContext) { - IllegalStateException invalidTimeoutModeException = invalidTimeoutModeException(); - if (invalidTimeoutModeException != null) { - throw invalidTimeoutModeException; - } - OperationContext findOperationContext = getFindOperationContext(operationContext); RetryControl retryControl = createSpecRetryControl( new SpecRetryPolicy.IndividualPolicies(retryReads).includeRead(findOperationContext).includeOverload(maxAdaptiveRetriesSetting), @@ -325,12 +311,6 @@ public BatchCursor execute(final ReadBinding binding, final OperationContext @Override public void executeAsync(final AsyncReadBinding binding, final OperationContext operationContext, final SingleResultCallback> callback) { - IllegalStateException invalidTimeoutModeException = invalidTimeoutModeException(); - if (invalidTimeoutModeException != null) { - callback.onResult(null, invalidTimeoutModeException); - return; - } - OperationContext findOperationContext = getFindOperationContext(operationContext); RetryControl retryControl = createSpecRetryControl( new SpecRetryPolicy.IndividualPolicies(retryReads).includeRead(findOperationContext).includeOverload(maxAdaptiveRetriesSetting), @@ -465,16 +445,9 @@ private boolean isAwaitData() { return cursorType == CursorType.TailableAwait; } - private TimeoutMode getTimeoutMode() { - if (timeoutMode == null) { - return isTailableCursor() ? TimeoutMode.ITERATION : TimeoutMode.CURSOR_LIFETIME; - } - return timeoutMode; - } - private CommandReadTransformer> transformer() { return (result, source, connection, operationContext) -> - new CommandBatchCursor<>(getTimeoutMode(), getMaxTimeForCursor(operationContext), operationContext, + new CommandBatchCursor<>(getMaxTimeForCursor(operationContext), operationContext, new CommandCursor<>( result, batchSize, decoder, comment, source, connection, retryReads, maxAdaptiveRetriesSetting @@ -483,7 +456,7 @@ private CommandReadTransformer> transformer( private CommandReadTransformerAsync> asyncTransformer() { return (result, source, connection, operationContext) -> - new AsyncCommandBatchCursor<>(getTimeoutMode(), getMaxTimeForCursor(operationContext), operationContext, + new AsyncCommandBatchCursor<>(getMaxTimeForCursor(operationContext), operationContext, new AsyncCommandCursor<>( result, batchSize, decoder, comment, source, connection, @@ -495,18 +468,8 @@ private long getMaxTimeForCursor(final OperationContext operationContext) { return cursorType == CursorType.TailableAwait ? operationContext.getTimeoutContext().getMaxAwaitTimeMS() : 0; } - @Nullable - private IllegalStateException invalidTimeoutModeException() { - if (isTailableCursor()) { - if (timeoutMode == TimeoutMode.CURSOR_LIFETIME) { - return new IllegalStateException("Tailable cursors only support the ITERATION value for the timeoutMode option."); - } - } - return null; - } - private boolean shouldDisableMaxTimeMS() { - return isTailableCursor() && !isAwaitData() || timeoutMode == TimeoutMode.ITERATION; + return isTailableCursor() && !isAwaitData(); } private OperationContext getFindOperationContext(final OperationContext operationContext) { diff --git a/driver-core/src/main/com/mongodb/internal/operation/ListCollectionsOperation.java b/driver-core/src/main/com/mongodb/internal/operation/ListCollectionsOperation.java index 938c103ddac..eac9c1be271 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ListCollectionsOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ListCollectionsOperation.java @@ -18,7 +18,6 @@ import com.mongodb.MongoCommandException; import com.mongodb.MongoNamespace; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.VisibleForTesting; import com.mongodb.internal.async.AsyncBatchCursor; import com.mongodb.internal.async.SingleResultCallback; @@ -54,7 +53,6 @@ import static com.mongodb.internal.operation.DocumentHelper.putIfNotNull; import static com.mongodb.internal.operation.DocumentHelper.putIfTrue; import static com.mongodb.internal.operation.OperationHelper.LOGGER; -import static com.mongodb.internal.operation.OperationHelper.applyTimeoutModeToOperationContext; import static com.mongodb.internal.operation.SingleBatchCursor.createEmptySingleBatchCursor; import static com.mongodb.internal.operation.SyncOperationHelper.CommandReadTransformer; import static com.mongodb.internal.operation.SyncOperationHelper.createReadCommandAndExecute; @@ -83,7 +81,6 @@ public class ListCollectionsOperation implements ReadOperationCursor { private boolean nameOnly; private boolean authorizedCollections; private BsonValue comment; - private TimeoutMode timeoutMode = TimeoutMode.CURSOR_LIFETIME; public ListCollectionsOperation( final String databaseName, @@ -160,17 +157,6 @@ public boolean isAuthorizedCollections() { } - public TimeoutMode getTimeoutMode() { - return timeoutMode; - } - - public ListCollectionsOperation timeoutMode(@Nullable final TimeoutMode timeoutMode) { - if (timeoutMode != null) { - this.timeoutMode = timeoutMode; - } - return this; - } - @Override public String getCommandName() { return COMMAND_NAME; @@ -178,13 +164,11 @@ public String getCommandName() { @Override public BatchCursor execute(final ReadBinding binding, final OperationContext operationContext) { - OperationContext listCollectionsOperationContext = applyTimeoutModeToOperationContext(timeoutMode, operationContext); - RetryControl retryControl = createSpecRetryControl( - new SpecRetryPolicy.IndividualPolicies(retryReads).includeRead(listCollectionsOperationContext).includeOverload(maxAdaptiveRetriesSetting), - listCollectionsOperationContext); - Supplier> read = decorateWithRetries(retryControl, listCollectionsOperationContext, () -> - withSourceAndConnection(binding::getReadConnectionSource, false, listCollectionsOperationContext, (source, connection, operationContextWithMinRTT) -> { + new SpecRetryPolicy.IndividualPolicies(retryReads).includeRead(operationContext).includeOverload(maxAdaptiveRetriesSetting), + operationContext); + Supplier> read = decorateWithRetries(retryControl, operationContext, () -> + withSourceAndConnection(binding::getReadConnectionSource, false, operationContext, (source, connection, operationContextWithMinRTT) -> { try { return createReadCommandAndExecute(retryControl, operationContextWithMinRTT, source, databaseName, getCommandCreator(), createCommandDecoder(), transformer(), connection); @@ -200,15 +184,13 @@ public BatchCursor execute(final ReadBinding binding, final OperationContext @Override public void executeAsync(final AsyncReadBinding binding, final OperationContext operationContext, final SingleResultCallback> callback) { - OperationContext listCollectionsOperationContext = applyTimeoutModeToOperationContext(timeoutMode, operationContext); - RetryControl retryControl = createSpecRetryControl( - new SpecRetryPolicy.IndividualPolicies(retryReads).includeRead(listCollectionsOperationContext).includeOverload(maxAdaptiveRetriesSetting), - listCollectionsOperationContext); + new SpecRetryPolicy.IndividualPolicies(retryReads).includeRead(operationContext).includeOverload(maxAdaptiveRetriesSetting), + operationContext); binding.retain(); AsyncCallbackSupplier> asyncRead = decorateWithRetriesAsync( - retryControl, listCollectionsOperationContext, (AsyncCallbackSupplier>) funcCallback -> - withAsyncSourceAndConnection(binding::getReadConnectionSource, false, listCollectionsOperationContext, funcCallback, + retryControl, operationContext, (AsyncCallbackSupplier>) funcCallback -> + withAsyncSourceAndConnection(binding::getReadConnectionSource, false, operationContext, funcCallback, (source, connection, operationContextWithMinRtt, releasingCallback) -> { createReadCommandAndExecuteAsync(retryControl, operationContextWithMinRtt, source, databaseName, getCommandCreator(), createCommandDecoder(), asyncTransformer(), connection, @@ -227,13 +209,13 @@ public void executeAsync(final AsyncReadBinding binding, final OperationContext private CommandReadTransformer> transformer() { return (result, source, connection, operationContext) -> - cursorDocumentToBatchCursor(timeoutMode, result, batchSize, decoder, comment, source, connection, operationContext, + cursorDocumentToBatchCursor(result, batchSize, decoder, comment, source, connection, operationContext, retryReads, maxAdaptiveRetriesSetting); } private CommandReadTransformerAsync> asyncTransformer() { return (result, source, connection, operationContext) -> - cursorDocumentToAsyncBatchCursor(timeoutMode, result, batchSize, decoder, comment, source, connection, operationContext, + cursorDocumentToAsyncBatchCursor(result, batchSize, decoder, comment, source, connection, operationContext, retryReads, maxAdaptiveRetriesSetting); } diff --git a/driver-core/src/main/com/mongodb/internal/operation/ListIndexesOperation.java b/driver-core/src/main/com/mongodb/internal/operation/ListIndexesOperation.java index c3ad1d0d8b3..c6c4cbc0993 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/ListIndexesOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/ListIndexesOperation.java @@ -18,7 +18,6 @@ import com.mongodb.MongoCommandException; import com.mongodb.MongoNamespace; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.async.AsyncBatchCursor; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.async.function.AsyncCallbackSupplier; @@ -50,7 +49,6 @@ import static com.mongodb.internal.operation.CursorHelper.getCursorDocumentFromBatchSize; import static com.mongodb.internal.operation.DocumentHelper.putIfNotNull; import static com.mongodb.internal.operation.OperationHelper.LOGGER; -import static com.mongodb.internal.operation.OperationHelper.applyTimeoutModeToOperationContext; import static com.mongodb.internal.operation.SingleBatchCursor.createEmptySingleBatchCursor; import static com.mongodb.internal.operation.SyncOperationHelper.CommandReadTransformer; import static com.mongodb.internal.operation.SyncOperationHelper.createReadCommandAndExecute; @@ -73,7 +71,6 @@ public class ListIndexesOperation implements ReadOperationCursor { private final Integer maxAdaptiveRetriesSetting; private int batchSize; private BsonValue comment; - private TimeoutMode timeoutMode = TimeoutMode.CURSOR_LIFETIME; public ListIndexesOperation( final MongoNamespace namespace, @@ -112,17 +109,6 @@ public ListIndexesOperation comment(@Nullable final BsonValue comment) { return this; } - public TimeoutMode getTimeoutMode() { - return timeoutMode; - } - - public ListIndexesOperation timeoutMode(@Nullable final TimeoutMode timeoutMode) { - if (timeoutMode != null) { - this.timeoutMode = timeoutMode; - } - return this; - } - @Override public String getCommandName() { return COMMAND_NAME; @@ -135,13 +121,11 @@ public MongoNamespace getNamespace() { @Override public BatchCursor execute(final ReadBinding binding, final OperationContext operationContext) { - OperationContext listIndexesOperationContext = applyTimeoutModeToOperationContext(timeoutMode, operationContext); - RetryControl retryControl = createSpecRetryControl( - new SpecRetryPolicy.IndividualPolicies(retryReads).includeRead(listIndexesOperationContext).includeOverload(maxAdaptiveRetriesSetting), - listIndexesOperationContext); - Supplier> read = decorateWithRetries(retryControl, listIndexesOperationContext, () -> - withSourceAndConnection(binding::getReadConnectionSource, false, listIndexesOperationContext, (source, connection, operationContextWithMinRTT) -> { + new SpecRetryPolicy.IndividualPolicies(retryReads).includeRead(operationContext).includeOverload(maxAdaptiveRetriesSetting), + operationContext); + Supplier> read = decorateWithRetries(retryControl, operationContext, () -> + withSourceAndConnection(binding::getReadConnectionSource, false, operationContext, (source, connection, operationContextWithMinRTT) -> { try { return createReadCommandAndExecute(retryControl, operationContextWithMinRTT, source, namespace.getDatabaseName(), getCommandCreator(), createCommandDecoder(), transformer(), connection); @@ -156,15 +140,13 @@ public BatchCursor execute(final ReadBinding binding, final OperationContext @Override public void executeAsync(final AsyncReadBinding binding, final OperationContext operationContext, final SingleResultCallback> callback) { - OperationContext listIndexesOperationContext = applyTimeoutModeToOperationContext(timeoutMode, operationContext); - RetryControl retryControl = createSpecRetryControl( - new SpecRetryPolicy.IndividualPolicies(retryReads).includeRead(listIndexesOperationContext).includeOverload(maxAdaptiveRetriesSetting), - listIndexesOperationContext); + new SpecRetryPolicy.IndividualPolicies(retryReads).includeRead(operationContext).includeOverload(maxAdaptiveRetriesSetting), + operationContext); binding.retain(); AsyncCallbackSupplier> asyncRead = decorateWithRetriesAsync( - retryControl, listIndexesOperationContext, (AsyncCallbackSupplier>) funcCallback -> - withAsyncSourceAndConnection(binding::getReadConnectionSource, false, listIndexesOperationContext, funcCallback, + retryControl, operationContext, (AsyncCallbackSupplier>) funcCallback -> + withAsyncSourceAndConnection(binding::getReadConnectionSource, false, operationContext, funcCallback, (source, connection, operationContextWithMinRtt, releasingCallback) -> { createReadCommandAndExecuteAsync(retryControl, operationContextWithMinRtt, source, namespace.getDatabaseName(), getCommandCreator(), createCommandDecoder(), @@ -194,13 +176,13 @@ private CommandCreator getCommandCreator() { private CommandReadTransformer> transformer() { return (result, source, connection, operationContext) -> - cursorDocumentToBatchCursor(timeoutMode, result, batchSize, decoder, comment, source, connection, operationContext, + cursorDocumentToBatchCursor(result, batchSize, decoder, comment, source, connection, operationContext, retryReads, maxAdaptiveRetriesSetting); } private CommandReadTransformerAsync> asyncTransformer() { return (result, source, connection, operationContext) -> - cursorDocumentToAsyncBatchCursor(timeoutMode, result, batchSize, decoder, comment, source, connection, operationContext, + cursorDocumentToAsyncBatchCursor(result, batchSize, decoder, comment, source, connection, operationContext, retryReads, maxAdaptiveRetriesSetting); } diff --git a/driver-core/src/main/com/mongodb/internal/operation/MapReduceToCollectionOperation.java b/driver-core/src/main/com/mongodb/internal/operation/MapReduceToCollectionOperation.java index ea495300b59..e91c9cf5533 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/MapReduceToCollectionOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/MapReduceToCollectionOperation.java @@ -20,7 +20,6 @@ import com.mongodb.MongoNamespace; import com.mongodb.WriteConcern; import com.mongodb.client.model.Collation; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.binding.AsyncWriteBinding; import com.mongodb.internal.binding.WriteBinding; @@ -222,14 +221,14 @@ public MapReduceStatistics execute(final WriteBinding binding, final OperationCo operationContext, namespace.getDatabaseName(), getCommandCreator(), - transformer(operationContext.getTimeoutContext())); + transformer()); } @Override public void executeAsync(final AsyncWriteBinding binding, final OperationContext operationContext, final SingleResultCallback callback) { executeCommandAsync(binding, operationContext, namespace.getDatabaseName(), getCommandCreator(), - transformerAsync(operationContext.getTimeoutContext()), callback); + transformerAsync(), callback); } /** @@ -251,18 +250,18 @@ private ExplainCommandOperation createExplainableOperation(final E }, new BsonDocumentCodec()); } - private CommandWriteTransformer transformer(final TimeoutContext timeoutContext) { + private CommandWriteTransformer transformer() { return (result, connection) -> { throwOnWriteConcernError(result, connection.getDescription().getServerAddress(), - connection.getDescription().getMaxWireVersion(), timeoutContext); + connection.getDescription().getMaxWireVersion()); return MapReduceHelper.createStatistics(result); }; } - private CommandWriteTransformerAsync transformerAsync(final TimeoutContext timeoutContext) { + private CommandWriteTransformerAsync transformerAsync() { return (result, connection) -> { throwOnWriteConcernError(result, connection.getDescription().getServerAddress(), - connection.getDescription().getMaxWireVersion(), timeoutContext); + connection.getDescription().getMaxWireVersion()); return MapReduceHelper.createStatistics(result); }; } diff --git a/driver-core/src/main/com/mongodb/internal/operation/MixedBulkWriteOperation.java b/driver-core/src/main/com/mongodb/internal/operation/MixedBulkWriteOperation.java index 29c3b16bf0f..f7fad129fb7 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/MixedBulkWriteOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/MixedBulkWriteOperation.java @@ -451,7 +451,7 @@ private void executeBatch( NoOpFieldNameValidator.INSTANCE, null, batch.getDecoder(), operationContext.withOperationName(commandName), shouldExpectResponse(batch, effectiveWriteConcern), batch.getPayload()); - addResultOrThrowWriteConcernWithResponseException(batch, result, connection.getDescription(), operationContext); + addResultOrThrowWriteConcernWithResponseException(batch, result, connection.getDescription()); } private void executeBatchAsync( @@ -469,7 +469,7 @@ private void executeBatchAsync( batch.getDecoder(), operationContext.withOperationName(commandName), shouldExpectResponse(batch, effectiveWriteConcern), batch.getPayload(), commandCallback); }).thenConsume((result, consumeCommandResultCallback) -> { - addResultOrThrowWriteConcernWithResponseException(batch, result, connection.getDescription(), operationContext); + addResultOrThrowWriteConcernWithResponseException(batch, result, connection.getDescription()); consumeCommandResultCallback.complete(consumeCommandResultCallback); }).finish(c); }).finish(callback); @@ -482,11 +482,10 @@ private boolean shouldExpectResponse(final BulkWriteBatch batch, final WriteConc private static void addResultOrThrowWriteConcernWithResponseException( final BulkWriteBatch batch, @Nullable final BsonDocument result, - final ConnectionDescription connectionDescription, - final OperationContext operationContext) throws MongoWriteConcernWithResponseException { + final ConnectionDescription connectionDescription) throws MongoWriteConcernWithResponseException { if (batch.isWriteRetryRequirementsMet()) { MongoException writeConcernBasedError = ProtocolHelper.createSpecialException( - result, connectionDescription.getServerAddress(), "errMsg", operationContext.getTimeoutContext()); + result, connectionDescription.getServerAddress(), "errMsg"); if (writeConcernBasedError != null) { assertNotNull(result); addRetryableWriteErrorLabelIfNeeded(writeConcernBasedError, connectionDescription.getMaxWireVersion()); diff --git a/driver-core/src/main/com/mongodb/internal/operation/OperationHelper.java b/driver-core/src/main/com/mongodb/internal/operation/OperationHelper.java index a8eb4a17439..d5092db2110 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/OperationHelper.java +++ b/driver-core/src/main/com/mongodb/internal/operation/OperationHelper.java @@ -20,11 +20,9 @@ import com.mongodb.MongoClientException; import com.mongodb.MongoException; import com.mongodb.WriteConcern; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.connection.ConnectionDescription; import com.mongodb.connection.ServerType; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.async.function.AsyncCallbackFunction; import com.mongodb.internal.bulk.DeleteRequest; @@ -181,14 +179,6 @@ static boolean isReadRetryRequirementsMet(final boolean retryReadsSetting, final return true; } - static OperationContext applyTimeoutModeToOperationContext(final TimeoutMode timeoutMode, - final OperationContext operationContext) { - if (timeoutMode == TimeoutMode.ITERATION) { - return operationContext.withOverride(TimeoutContext::withDisabledMaxTime); - } - return operationContext; - } - /** * Returns the {@link MongoException} that carries or should carry * the {@linkplain MongoException#getCode() error code} and {@linkplain MongoException#getErrorLabels() error labels}. diff --git a/driver-core/src/main/com/mongodb/internal/operation/Operations.java b/driver-core/src/main/com/mongodb/internal/operation/Operations.java index 8e1e4ab61cb..ddc23b56986 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/Operations.java +++ b/driver-core/src/main/com/mongodb/internal/operation/Operations.java @@ -22,7 +22,6 @@ import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; import com.mongodb.bulk.BulkWriteResult; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.BulkWriteOptions; import com.mongodb.client.model.ClusteredIndexOptions; import com.mongodb.client.model.Collation; @@ -135,9 +134,6 @@ public Operations(@Nullable final MongoNamespace namespace, final Class docum this.timeoutSettings = timeoutSettings; WriteConcern writeConcernToUse = writeConcern; - if (timeoutSettings.getTimeoutMS() != null) { - writeConcernToUse = assertNotNull(WriteConcernHelper.cloneWithoutTimeout(writeConcern)); - } this.writeConcern = writeConcernToUse; } @@ -288,8 +284,7 @@ private FindOperation createFindOperation(final MongoNamespace findNamesp .max(toBsonDocument(options.getMax())) .returnKey(options.isReturnKey()) .showRecordId(options.isShowRecordId()) - .allowDiskUse(options.isAllowDiskUse()) - .timeoutMode(options.getTimeoutMode()); + .allowDiskUse(options.isAllowDiskUse()); if (options.getHint() != null) { operation.hint(toBsonDocument(options.getHint())); @@ -317,7 +312,7 @@ public ReadOperationCursor distinct(final String fieldName, @Nullable fin } public ReadOperationExplainable aggregate(final List pipeline, final Class resultClass, - @Nullable final TimeoutMode timeoutMode, @Nullable final Integer batchSize, + @Nullable final Integer batchSize, final Collation collation, @Nullable final Bson hint, @Nullable final String hintString, final BsonValue comment, final Bson variables, final Boolean allowDiskUse, final AggregationLevel aggregationLevel) { return new AggregateOperation<>(assertNotNull(namespace), @@ -329,11 +324,10 @@ public ReadOperationExplainable aggregate(final List pipe .collation(collation) .hint(hint != null ? toBsonDocument(hint) : (hintString != null ? new BsonString(hintString) : null)) .comment(comment) - .let(toBsonDocument(variables)) - .timeoutMode(timeoutMode); + .let(toBsonDocument(variables)); } - public ReadOperationSimple aggregateToCollection(final List pipeline, @Nullable final TimeoutMode timeoutMode, + public ReadOperationSimple aggregateToCollection(final List pipeline, final Boolean allowDiskUse, final Boolean bypassDocumentValidation, final Collation collation, @Nullable final Bson hint, @Nullable final String hintString, final BsonValue comment, final Bson variables, final AggregationLevel aggregationLevel) { return new AggregateToCollectionOperation(assertNotNull(namespace), @@ -344,8 +338,7 @@ public ReadOperationSimple aggregateToCollection(final List dropIndex(final Bson keys, final DropIndexOptions ig public ReadOperationCursor listCollections(final String databaseName, final Class resultClass, final Bson filter, final boolean collectionNamesOnly, final boolean authorizedCollections, @Nullable final Integer batchSize, - final BsonValue comment, @Nullable final TimeoutMode timeoutMode) { + final BsonValue comment) { return new ListCollectionsOperation<>(databaseName, codecRegistry.get(resultClass), maxAdaptiveRetriesSetting) .retryReads(retryReads) .filter(toBsonDocument(filter)) .nameOnly(collectionNamesOnly) .authorizedCollections(authorizedCollections) .batchSize(batchSize == null ? 0 : batchSize) - .comment(comment) - .timeoutMode(timeoutMode); + .comment(comment); } public ReadOperationCursor listDatabases(final Class resultClass, final Bson filter, @@ -789,14 +781,13 @@ public ReadOperationCursor listDatabases(final Class resultClass, fina } public ReadOperationCursor listIndexes(final Class resultClass, @Nullable final Integer batchSize, - final BsonValue comment, @Nullable final TimeoutMode timeoutMode) { + final BsonValue comment) { return new ListIndexesOperation<>(assertNotNull(namespace), codecRegistry.get(resultClass), maxAdaptiveRetriesSetting) .retryReads(retryReads) .batchSize(batchSize == null ? 0 : batchSize) - .comment(comment) - .timeoutMode(timeoutMode); + .comment(comment); } public ReadOperationCursor changeStream(final FullDocument fullDocument, diff --git a/driver-core/src/main/com/mongodb/internal/operation/RenameCollectionOperation.java b/driver-core/src/main/com/mongodb/internal/operation/RenameCollectionOperation.java index 81a5fa0803f..cd8f31f5a13 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/RenameCollectionOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/RenameCollectionOperation.java @@ -114,7 +114,7 @@ public Void execute(final WriteBinding binding, final OperationContext operation return withConnection(binding, operationContext, (connection, operationContextWithMinRtt) -> executeCommand(binding, operationContextWithMinRtt, "admin", getCommand(), connection, - writeConcernErrorTransformer(operationContextWithMinRtt.getTimeoutContext()))); + writeConcernErrorTransformer())); }); return retryingCommandExecutor.get(); } @@ -131,7 +131,7 @@ public void executeAsync(final AsyncWriteBinding binding, final OperationContext errHandlingCallback.onResult(null, t); } else { executeCommandAsync(binding, operationContextWithMinRtt, "admin", getCommand(), assertNotNull(connection), - writeConcernErrorTransformerAsync(operationContextWithMinRtt.getTimeoutContext()), + writeConcernErrorTransformerAsync(), releasingCallback(errHandlingCallback, connection)); } })); diff --git a/driver-core/src/main/com/mongodb/internal/operation/SpecRetryPolicy.java b/driver-core/src/main/com/mongodb/internal/operation/SpecRetryPolicy.java index 7a20d755103..e01f757bc72 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/SpecRetryPolicy.java +++ b/driver-core/src/main/com/mongodb/internal/operation/SpecRetryPolicy.java @@ -19,7 +19,6 @@ import com.mongodb.MongoCommandException; import com.mongodb.MongoConnectionPoolClearedException; import com.mongodb.MongoException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoSecurityException; import com.mongodb.MongoServerException; import com.mongodb.MongoSocketException; @@ -51,7 +50,6 @@ import static com.mongodb.assertions.Assertions.assertNull; import static com.mongodb.assertions.Assertions.assertTrue; import static com.mongodb.assertions.Assertions.fail; -import static com.mongodb.internal.TimeoutContext.createMongoTimeoutException; import static com.mongodb.internal.operation.CommandOperationHelper.DEFAULT_MAX_ADAPTIVE_RETRIES; import static com.mongodb.internal.operation.CommandOperationHelper.NO_WRITES_PERFORMED_ERROR_LABEL; import static com.mongodb.internal.operation.CommandOperationHelper.RETRYABLE_WRITE_ERROR_LABEL; @@ -257,9 +255,6 @@ private Throwable decideProspectiveFailedResult( } else { throw fail(toString()); } - if (mostRecentAttemptFailedResult instanceof MongoOperationTimeoutException) { - newProspectiveFailedResult = createMongoTimeoutException(newProspectiveFailedResult); - } return newProspectiveFailedResult; } diff --git a/driver-core/src/main/com/mongodb/internal/operation/SyncOperationHelper.java b/driver-core/src/main/com/mongodb/internal/operation/SyncOperationHelper.java index 08c5c1ce5ea..a33ba0a1f51 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/SyncOperationHelper.java +++ b/driver-core/src/main/com/mongodb/internal/operation/SyncOperationHelper.java @@ -18,9 +18,7 @@ import com.mongodb.MongoException; import com.mongodb.ReadPreference; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.connection.ConnectionDescription; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.VisibleForTesting; import com.mongodb.internal.async.MutableValue; import com.mongodb.internal.async.function.RetryControl; @@ -99,9 +97,7 @@ interface CommandWriteTransformer { static T withReadConnectionSource(final ReadBinding binding, final OperationContext operationContext, final CallableWithSource callable) { - OperationContext serverSelectionOperationContext = - operationContext.withOverride(TimeoutContext::withComputedServerSelectionTimeout); - ConnectionSource source = binding.getReadConnectionSource(serverSelectionOperationContext); + ConnectionSource source = binding.getReadConnectionSource(operationContext); try { return callable.call(source, operationContext.withMinRoundTripTime(source.getServerDescription())); } finally { @@ -129,17 +125,15 @@ static R withSourceAndConnection( final boolean wrapConnectionSourceException, final OperationContext operationContext, final ExecutionFunction function) throws ResourceSupplierInternalException { - OperationContext serverSelectionOperationContext = - operationContext.withOverride(TimeoutContext::withComputedServerSelectionTimeout); return withSuppliedResource( sourceFunction, wrapConnectionSourceException, - serverSelectionOperationContext, + operationContext, source -> withSuppliedResource( source::getConnection, wrapConnectionSourceException, - serverSelectionOperationContext.withMinRoundTripTime(source.getServerDescription()), + operationContext.withMinRoundTripTime(source.getServerDescription()), connection -> function.apply( source, connection, @@ -361,11 +355,11 @@ static Supplier decorateWithRetries( } - static CommandWriteTransformer writeConcernErrorTransformer(final TimeoutContext timeoutContext) { + static CommandWriteTransformer writeConcernErrorTransformer() { return (result, connection) -> { assertNotNull(result); throwOnWriteConcernError(result, connection.getDescription().getServerAddress(), - connection.getDescription().getMaxWireVersion(), timeoutContext); + connection.getDescription().getMaxWireVersion()); return null; }; } @@ -377,7 +371,6 @@ static CommandReadTransformer> singleBatchCurso } static BatchCursor cursorDocumentToBatchCursor( - final TimeoutMode timeoutMode, final BsonDocument cursorDocument, final int batchSize, final Decoder decoder, @@ -388,7 +381,7 @@ static BatchCursor cursorDocumentToBatchCursor( final OperationContext operationContext, final boolean retryReads, @Nullable final Integer maxAdaptiveRetriesSetting) { - return new CommandBatchCursor<>(timeoutMode, 0, operationContext, new CommandCursor<>( + return new CommandBatchCursor<>(0, operationContext, new CommandCursor<>( cursorDocument, batchSize, decoder, comment, source, connection, retryReads, maxAdaptiveRetriesSetting )); diff --git a/driver-core/src/main/com/mongodb/internal/operation/TransactionOperation.java b/driver-core/src/main/com/mongodb/internal/operation/TransactionOperation.java index ce5e49deb99..01686164284 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/TransactionOperation.java +++ b/driver-core/src/main/com/mongodb/internal/operation/TransactionOperation.java @@ -18,7 +18,6 @@ import com.mongodb.Function; import com.mongodb.WriteConcern; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.async.SingleResultCallback; import com.mongodb.internal.binding.AsyncWriteBinding; import com.mongodb.internal.binding.WriteBinding; @@ -61,19 +60,17 @@ public WriteConcern getWriteConcern() { @Override public Void execute(final WriteBinding binding, final OperationContext operationContext) { isTrue("in transaction", operationContext.getSessionContext().hasActiveTransaction()); - TimeoutContext timeoutContext = operationContext.getTimeoutContext(); return executeRetryableWrite(binding, operationContext, "admin", null, NoOpFieldNameValidator.INSTANCE, new BsonDocumentCodec(), getCommandCreator(), - writeConcernErrorTransformer(timeoutContext), getRetryCommandModifier(operationContext), true, maxAdaptiveRetriesSetting); + writeConcernErrorTransformer(), getRetryCommandModifier(operationContext), true, maxAdaptiveRetriesSetting); } @Override public void executeAsync(final AsyncWriteBinding binding, final OperationContext operationContext, final SingleResultCallback callback) { isTrue("in transaction", operationContext.getSessionContext().hasActiveTransaction()); - TimeoutContext timeoutContext = operationContext.getTimeoutContext(); executeRetryableWriteAsync(binding, operationContext, "admin", null, NoOpFieldNameValidator.INSTANCE, new BsonDocumentCodec(), getCommandCreator(), - writeConcernErrorTransformerAsync(timeoutContext), getRetryCommandModifier(operationContext), + writeConcernErrorTransformerAsync(), getRetryCommandModifier(operationContext), true, maxAdaptiveRetriesSetting, errorHandlingCallback(callback, LOGGER)); } diff --git a/driver-core/src/main/com/mongodb/internal/operation/WriteConcernHelper.java b/driver-core/src/main/com/mongodb/internal/operation/WriteConcernHelper.java index b28f69938c2..2eb5c9d4315 100644 --- a/driver-core/src/main/com/mongodb/internal/operation/WriteConcernHelper.java +++ b/driver-core/src/main/com/mongodb/internal/operation/WriteConcernHelper.java @@ -22,7 +22,6 @@ import com.mongodb.WriteConcern; import com.mongodb.WriteConcernResult; import com.mongodb.bulk.WriteConcernError; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.connection.ProtocolHelper; import com.mongodb.lang.Nullable; import org.bson.BsonArray; @@ -61,9 +60,9 @@ public static WriteConcern cloneWithoutTimeout(@Nullable final WriteConcern writ } public static void throwOnWriteConcernError(final BsonDocument result, final ServerAddress serverAddress, - final int maxWireVersion, final TimeoutContext timeoutContext) { + final int maxWireVersion) { if (hasWriteConcernError(result)) { - MongoException exception = ProtocolHelper.createSpecialException(result, serverAddress, "errmsg", timeoutContext); + MongoException exception = ProtocolHelper.createSpecialException(result, serverAddress, "errmsg"); if (exception == null) { exception = createWriteConcernException(result, serverAddress); } diff --git a/driver-core/src/main/com/mongodb/internal/session/BaseClientSessionImpl.java b/driver-core/src/main/com/mongodb/internal/session/BaseClientSessionImpl.java index 41199244fd3..5ab7a1b0249 100644 --- a/driver-core/src/main/com/mongodb/internal/session/BaseClientSessionImpl.java +++ b/driver-core/src/main/com/mongodb/internal/session/BaseClientSessionImpl.java @@ -21,7 +21,6 @@ import com.mongodb.MongoException; import com.mongodb.ServerAddress; import com.mongodb.TransactionOptions; -import com.mongodb.WriteConcern; import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.async.function.RetryControl; @@ -33,7 +32,6 @@ import org.bson.BsonDocument; import org.bson.BsonTimestamp; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; @@ -66,14 +64,6 @@ public class BaseClientSessionImpl implements ClientSession { @Nullable private TimeoutContext timeoutContext; - protected static boolean hasTimeoutMS(@Nullable final TimeoutContext timeoutContext) { - return timeoutContext != null && timeoutContext.hasTimeoutMS(); - } - - protected static boolean hasWTimeoutMS(@Nullable final WriteConcern writeConcern) { - return writeConcern != null && writeConcern.getWTimeout(TimeUnit.MILLISECONDS) != null; - } - public BaseClientSessionImpl(final ServerSessionPool serverSessionPool, final Object originator, final ClientSessionOptions options) { this.serverSessionPool = serverSessionPool; this.originator = originator; @@ -236,16 +226,8 @@ protected void resetTimeout() { } protected TimeoutSettings getTimeoutSettings(final TransactionOptions transactionOptions, final TimeoutSettings timeoutSettings) { - Long transactionTimeoutMS = transactionOptions.getTimeout(MILLISECONDS); - Long defaultTimeoutMS = getOptions().getDefaultTimeout(MILLISECONDS); - Long clientTimeoutMS = timeoutSettings.getTimeoutMS(); - - Long timeoutMS = transactionTimeoutMS != null ? transactionTimeoutMS - : defaultTimeoutMS != null ? defaultTimeoutMS : clientTimeoutMS; - return timeoutSettings - .withMaxCommitMS(transactionOptions.getMaxCommitTime(MILLISECONDS)) - .withTimeout(timeoutMS, MILLISECONDS); + .withMaxCommitMS(transactionOptions.getMaxCommitTime(MILLISECONDS)); } @Override diff --git a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java index 54c836197fa..0eda26c4e2a 100644 --- a/driver-core/src/test/functional/com/mongodb/ClusterFixture.java +++ b/driver-core/src/test/functional/com/mongodb/ClusterFixture.java @@ -119,15 +119,11 @@ public final class ClusterFixture { private static final String MONGODB_OCSP_SHOULD_SUCCEED = "org.mongodb.test.ocsp.tls.should.succeed"; private static final String DEFAULT_DATABASE_NAME = "JavaDriverTest"; private static final int COMMAND_NOT_FOUND_ERROR_CODE = 59; - /** Factor by which CSOT timeout/block values are widened on Windows, whose slower TLS setup eats tight budgets. */ - public static final int WINDOWS_CSOT_TIMEOUT_MULTIPLIER = 10; public static final long TIMEOUT = 120L; public static final Duration TIMEOUT_DURATION = Duration.ofSeconds(TIMEOUT); public static final ClientMetadata CLIENT_METADATA = new ClientMetadata("test", MongoDriverInformation.builder().build()); - public static final TimeoutSettings TIMEOUT_SETTINGS = new TimeoutSettings(30_000, 10_000, 0, null, SECONDS.toMillis(5)); - public static final TimeoutSettings TIMEOUT_SETTINGS_WITH_TIMEOUT = TIMEOUT_SETTINGS.withTimeout(TIMEOUT, SECONDS); - public static final TimeoutSettings TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT = TIMEOUT_SETTINGS.withTimeout(0L, MILLISECONDS); + public static final TimeoutSettings TIMEOUT_SETTINGS = new TimeoutSettings(30_000, 10_000, 0, SECONDS.toMillis(5)); public static final TimeoutSettings TIMEOUT_SETTINGS_WITH_MAX_TIME = TIMEOUT_SETTINGS.withMaxTimeMS(100); public static final TimeoutSettings TIMEOUT_SETTINGS_WITH_MAX_AWAIT_TIME = TIMEOUT_SETTINGS.withMaxAwaitTimeMS(101); public static final TimeoutSettings TIMEOUT_SETTINGS_WITH_MAX_TIME_AND_AWAIT_TIME = @@ -830,11 +826,4 @@ public static boolean isWindows() { return System.getProperty("os.name", "").startsWith("Windows"); } - /** - * Scales a CSOT timeout / failpoint-block value by {@link #WINDOWS_CSOT_TIMEOUT_MULTIPLIER} on Windows (unchanged - * elsewhere). Scale a test's timeout and its blockTimeMS together to preserve which command times out. - */ - public static int scaleForWindows(final int millis) { - return isWindows() ? millis * WINDOWS_CSOT_TIMEOUT_MULTIPLIER : millis; - } } 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 5187f692459..baceb9571fa 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 @@ -72,7 +72,6 @@ import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -135,33 +134,6 @@ public void shouldThrowOnTimeout() throws InterruptedException { assertTrue(connectionGetter.isGotTimeout()); } - @Test - public void shouldNotUseMaxAwaitTimeMSWhenTimeoutMsIsSet() throws InterruptedException { - // given - provider = new DefaultConnectionPool(SERVER_ID, connectionFactory, - ConnectionPoolSettings.builder() - .maxSize(1) - .build(), - mockSdamProvider(), OPERATION_CONTEXT_FACTORY); - provider.ready(); - TimeoutSettings timeoutSettings = TIMEOUT_SETTINGS - .withTimeout(100L, MILLISECONDS) - .withMaxWaitTimeMS(50); - - InternalConnection internalConnection = provider.get(createOperationContext(timeoutSettings)); - - // when - TimeoutTrackingConnectionGetter connectionGetter = new TimeoutTrackingConnectionGetter(provider, timeoutSettings); - cachedExecutor.execute(connectionGetter); - - sleep(70); // wait for more than maxWaitTimeMS but less than timeoutMs. - internalConnection.close(); - connectionGetter.getLatch().await(); - - // then - assertFalse(connectionGetter.isGotTimeout()); - } - @Test public void shouldThrowOnPoolClosed() { provider = new DefaultConnectionPool(SERVER_ID, connectionFactory, 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 600be598080..b598b28d357 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 @@ -18,11 +18,8 @@ package com.mongodb.internal.connection import com.mongodb.ClusterFixture import com.mongodb.MongoInternalException -import com.mongodb.MongoOperationTimeoutException import com.mongodb.connection.SocketSettings import com.mongodb.connection.SslSettings -import com.mongodb.internal.TimeoutContext -import com.mongodb.internal.TimeoutSettings import jdk.net.ExtendedSocketOptions import spock.lang.IgnoreIf import spock.lang.Specification @@ -82,30 +79,6 @@ class SocketStreamHelperSpecification extends Specification { socket?.close() } - def 'should throw MongoOperationTimeoutException during initialization when timeoutMS expires'() { - given: - Socket socket = SocketFactory.default.createSocket() - - when: - SocketStreamHelper.initialize( - createOperationContext().withTimeoutContext(new TimeoutContext( - new TimeoutSettings( - 1, - 100, - 100, - 1, - 100))), - socket, getSocketAddresses(getPrimary(), new DefaultInetAddressResolver()).get(0), - SocketSettings.builder().build(), SslSettings.builder().build()) - - then: - thrown(MongoOperationTimeoutException) - - cleanup: - socket?.close() - } - - def 'should connect socket()'() { given: Socket socket = SocketFactory.default.createSocket() 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 6fab0c5e216..019bde2d6fc 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 @@ -23,7 +23,6 @@ import com.mongodb.ReadPreference; import com.mongodb.ServerCursor; import com.mongodb.async.FutureResultCallback; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.CreateCollectionOptions; import com.mongodb.client.model.Filters; import com.mongodb.client.model.OperationTest; @@ -111,7 +110,7 @@ void cleanup() { void shouldExhaustCursorAsyncWithMultipleBatches() { // given BsonDocument commandResult = executeFindCommand(0, 3); // Fetch in batches of size 3 - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new AsyncCommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); // when @@ -133,7 +132,7 @@ void shouldExhaustCursorAsyncWithMultipleBatches() { void shouldExhaustCursorAsyncWithClosedCursor() { // given BsonDocument commandResult = executeFindCommand(0, 3); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new AsyncCommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); cursor.close(); @@ -156,7 +155,7 @@ void shouldExhaustCursorAsyncWithEmptyCursor() { getCollectionHelper().deleteMany(Filters.empty()); BsonDocument commandResult = executeFindCommand(0, 3); // No documents to fetch - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new AsyncCommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); // when @@ -175,7 +174,7 @@ void theServerCursorShouldNotBeNull() { BsonDocument commandResult = executeFindCommand(2); AsyncCommandCursor coreCursor = new AsyncCommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), coreCursor); assertNotNull(coreCursor.getServerCursor()); @@ -187,7 +186,7 @@ void shouldGetExceptionsForOperationsOnTheCursorAfterClosing() { BsonDocument commandResult = executeFindCommand(5); AsyncCommandCursor coreCursor = new AsyncCommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), coreCursor); cursor.close(); @@ -202,7 +201,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, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new AsyncCommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); cursorNext(); @@ -216,7 +215,7 @@ void shouldThrowAnExceptionWhenGoingOffTheEnd() { @DisplayName("test normal exhaustion") void testNormalExhaustion() { BsonDocument commandResult = executeFindCommand(); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new AsyncCommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertEquals(10, cursorFlatten().size()); @@ -227,7 +226,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, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new AsyncCommandCursor<>(commandResult, batchSize, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); @@ -246,7 +245,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, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(maxTimeMS, ClusterFixture.createOperationContext(), new AsyncCommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertFalse(cursor.isClosed()); @@ -269,7 +268,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, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new AsyncCommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); CountDownLatch latch = new CountDownLatch(1); @@ -304,7 +303,7 @@ void shouldKillCursorIfLimitIsReachedOnInitialQuery() { BsonDocument commandResult = executeFindCommand(5, 10); AsyncCommandCursor coreCursor = new AsyncCommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), coreCursor); assertNotNull(cursorNext()); @@ -319,7 +318,7 @@ void shouldKillCursorIfLimitIsReachedOnGetMore() { BsonDocument commandResult = executeFindCommand(5, 3); AsyncCommandCursor coreCursor = new AsyncCommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection, false, null); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), coreCursor); ServerCursor serverCursor = coreCursor.getServerCursor(); @@ -341,7 +340,7 @@ void shouldReleaseConnectionSourceIfLimitIsReachedOnInitialQuery() { BsonDocument commandResult = executeFindCommand(5, 10); AsyncCommandCursor coreCursor = new AsyncCommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), coreCursor); assertDoesNotThrow(() -> checkReferenceCountReachesTarget(connectionSource, 1)); @@ -354,7 +353,7 @@ void shouldReleaseConnectionSourceIfLimitIsReachedOnInitialQuery() { void shouldReleaseConnectionSourceIfLimitIsReachedOnGetMore() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 3); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new AsyncCommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertNotNull(cursorNext()); @@ -367,7 +366,7 @@ void shouldReleaseConnectionSourceIfLimitIsReachedOnGetMore() { @DisplayName("test limit with get more") void testLimitWithGetMore() { BsonDocument commandResult = executeFindCommand(5, 2); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new AsyncCommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertNotNull(cursorNext()); @@ -390,7 +389,7 @@ void testLimitWithLargeDocuments() { ); BsonDocument commandResult = executeFindCommand(300, 0); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new AsyncCommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertEquals(300, cursorFlatten().size()); @@ -400,7 +399,7 @@ void testLimitWithLargeDocuments() { @DisplayName("should respect batch size") void shouldRespectBatchSize() { BsonDocument commandResult = executeFindCommand(2); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new AsyncCommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertEquals(2, cursor.getBatchSize()); @@ -419,7 +418,7 @@ void shouldThrowCursorNotFoundException() throws Throwable { BsonDocument commandResult = executeFindCommand(2); AsyncCommandCursor coreCursor = new AsyncCommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null); - cursor = new AsyncCommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new AsyncCommandBatchCursor<>(0, ClusterFixture.createOperationContext(), coreCursor); ServerCursor serverCursor = coreCursor.getServerCursor(); diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/AsyncCommandBatchCursorTest.java b/driver-core/src/test/functional/com/mongodb/internal/operation/AsyncCommandBatchCursorTest.java index 1b35cf1a326..d317474dd79 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/AsyncCommandBatchCursorTest.java +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/AsyncCommandBatchCursorTest.java @@ -17,7 +17,6 @@ package com.mongodb.internal.operation; import com.mongodb.MongoClientSettings; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.IgnorableRequestContext; import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.TimeoutSettings; @@ -31,7 +30,6 @@ import java.time.Duration; -import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -46,8 +44,9 @@ class AsyncCommandBatchCursorTest { @BeforeEach void setUp() { coreCursor = mock(AsyncCursor.class); + MongoClientSettings.Builder builder = MongoClientSettings.builder(); timeoutContext = spy(new TimeoutContext(TimeoutSettings.create( - MongoClientSettings.builder().timeout(TIMEOUT.toMillis(), MILLISECONDS).build()))); + builder.build()))); operationContext = spy(new OperationContext( IgnorableRequestContext.INSTANCE, NoOpSessionContext.INSTANCE, @@ -80,7 +79,6 @@ void closeShouldResetTimeoutContextToDefaultMaxTime(final int maxTimeMS) { private AsyncCommandBatchCursor createBatchCursor(final long maxTimeMS) { return new AsyncCommandBatchCursor<>( - TimeoutMode.CURSOR_LIFETIME, maxTimeMS, operationContext, coreCursor); diff --git a/driver-core/src/test/functional/com/mongodb/internal/operation/AsyncCommandCursorTest.java b/driver-core/src/test/functional/com/mongodb/internal/operation/AsyncCommandCursorTest.java index 44d0ec149be..f438490a109 100644 --- a/driver-core/src/test/functional/com/mongodb/internal/operation/AsyncCommandCursorTest.java +++ b/driver-core/src/test/functional/com/mongodb/internal/operation/AsyncCommandCursorTest.java @@ -18,7 +18,6 @@ import com.mongodb.MongoClientSettings; import com.mongodb.MongoNamespace; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoSocketException; import com.mongodb.ServerAddress; import com.mongodb.connection.ConnectionDescription; @@ -48,7 +47,6 @@ import java.util.concurrent.atomic.AtomicInteger; import static com.mongodb.internal.operation.OperationUnitSpecification.getMaxWireVersionForServerVersion; -import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -58,7 +56,6 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -88,7 +85,7 @@ class AsyncCommandCursorTest { @BeforeEach void setUp() { timeoutContext = spy(new TimeoutContext(TimeoutSettings.create( - MongoClientSettings.builder().timeout(TIMEOUT.toMillis(), MILLISECONDS).build()))); + MongoClientSettings.builder().build()))); operationContext = spy(new OperationContext( IgnorableRequestContext.INSTANCE, NoOpSessionContext.INSTANCE, @@ -138,69 +135,6 @@ void shouldSkipKillsCursorsCommandWhenNetworkErrorOccurs() { verify(mockConnection, times(1)).commandAsync(eq(NAMESPACE.getDatabaseName()), any(), any(), any(), any(), any(), any()); } - - @Test - void shouldNotSkipKillsCursorsCommandWhenTimeoutExceptionDoesNotHaveNetworkErrorCause() { - //given - doAnswer(invocation -> { - SingleResultCallback argument = invocation.getArgument(6); - argument.onResult(null, new MongoOperationTimeoutException("test")); - return null; - }).when(mockConnection).commandAsync(eq(NAMESPACE.getDatabaseName()), any(), any(), any(), any(), any(), any()); - when(serverDescription.getType()).thenReturn(ServerType.LOAD_BALANCER); - - AsyncCursor commandBatchCursor = createBatchCursor(); - - //when - commandBatchCursor.next(operationContext, (result, t) -> { - assertNull(result); - assertNotNull(t); - assertEquals(MongoOperationTimeoutException.class, t.getClass()); - }); - - commandBatchCursor.close(operationContext); - - - //then - verify(mockConnection, times(2)).commandAsync(any(), - any(), any(), any(), any(), any(), any()); - verify(mockConnection, times(1)).commandAsync(eq(NAMESPACE.getDatabaseName()), - argThat(bsonDocument -> bsonDocument.containsKey("getMore")), any(), any(), any(), any(), any()); - verify(mockConnection, times(1)).commandAsync(eq(NAMESPACE.getDatabaseName()), - argThat(bsonDocument -> bsonDocument.containsKey("killCursors")), any(), any(), any(), any(), any()); - } - - @Test - void shouldSkipKillsCursorsCommandWhenTimeoutExceptionHaveNetworkErrorCause() { - //given - doAnswer(invocation -> { - SingleResultCallback argument = invocation.getArgument(6); - argument.onResult(null, new MongoOperationTimeoutException("test", new MongoSocketException("test", new ServerAddress()))); - return null; - }).when(mockConnection).commandAsync(eq(NAMESPACE.getDatabaseName()), any(), any(), any(), any(), any(), any()); - when(serverDescription.getType()).thenReturn(ServerType.LOAD_BALANCER); - - AsyncCursor commandBatchCursor = createBatchCursor(); - - //when - commandBatchCursor.next(operationContext, (result, t) -> { - assertNull(result); - assertNotNull(t); - assertEquals(MongoOperationTimeoutException.class, t.getClass()); - }); - - commandBatchCursor.close(operationContext); - - //then - verify(mockConnection, times(1)).commandAsync(any(), - any(), any(), any(), any(), any(), any()); - verify(mockConnection, times(1)).commandAsync(eq(NAMESPACE.getDatabaseName()), - argThat(bsonDocument -> bsonDocument.containsKey("getMore")), any(), any(), any(), any(), any()); - verify(mockConnection, never()).commandAsync(eq(NAMESPACE.getDatabaseName()), - argThat(bsonDocument -> bsonDocument.containsKey("killCursors")), any(), any(), any(), any(), any()); - } - - @Test void shouldReleaseConnectionBetweenEmptyGetMoreResponses() { AtomicInteger callCount = new AtomicInteger(); 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 927b2d1b840..fbc6dc65ed2 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 @@ -21,7 +21,6 @@ import com.mongodb.MongoQueryException; import com.mongodb.ReadPreference; import com.mongodb.ServerCursor; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.CreateCollectionOptions; import com.mongodb.client.model.Filters; import com.mongodb.client.model.OperationTest; @@ -110,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); // when @@ -128,7 +127,7 @@ void shouldExhaustCursorWithMultipleBatches() { void shouldExhaustCursorWithClosedCursor() { // given BsonDocument commandResult = executeFindCommand(0, 3); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); cursor.close(); @@ -144,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); // when @@ -158,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertNotNull(cursor.getServerCursor()); @@ -168,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertNotNull(cursor.getServerAddress()); @@ -178,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); cursor.close(); @@ -193,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); cursor.next(); @@ -205,7 +204,7 @@ void shouldThrowAnExceptionWhenGoingOffTheEnd() { @DisplayName("test cursor remove") void testCursorRemove() { BsonDocument commandResult = executeFindCommand(); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertThrows(UnsupportedOperationException.class, () -> cursor.remove()); @@ -215,7 +214,7 @@ void testCursorRemove() { @DisplayName("test normal exhaustion") void testNormalExhaustion() { BsonDocument commandResult = executeFindCommand(); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertEquals(10, cursorFlatten().size()); @@ -226,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertEquals(expectedTotal, cursorFlatten().size()); @@ -245,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(maxTimeMS, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertTrue(cursor.hasNext()); @@ -268,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); List nextBatch = cursor.tryNext(); @@ -294,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertTrue(cursor.hasNext()); @@ -321,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(maxTimeMS, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); List nextBatch = cursor.tryNext(); @@ -345,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); CountDownLatch latch = new CountDownLatch(1); @@ -378,7 +377,7 @@ void testTailableInterrupt() throws InterruptedException { void shouldKillCursorIfLimitIsReachedOnInitialQuery() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 10); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertNotNull(cursor.next()); @@ -391,7 +390,7 @@ void shouldKillCursorIfLimitIsReachedOnInitialQuery() { void shouldKillCursorIfLimitIsReachedOnGetMore() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 3); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); ServerCursor serverCursor = cursor.getServerCursor(); @@ -410,7 +409,7 @@ void shouldKillCursorIfLimitIsReachedOnGetMore() { void shouldReleaseConnectionSourceIfLimitIsReachedOnInitialQuery() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 10); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertNull(cursor.getServerCursor()); @@ -423,7 +422,7 @@ void shouldReleaseConnectionSourceIfLimitIsReachedOnInitialQuery() { void shouldReleaseConnectionSourceIfLimitIsReachedOnGetMore() { assumeFalse(isSharded()); BsonDocument commandResult = executeFindCommand(5, 3); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 3, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertNotNull(cursor.next()); @@ -436,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, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertNotNull(cursor.next()); @@ -457,7 +456,7 @@ void testLimitWithLargeDocuments() { ); BsonDocument commandResult = executeFindCommand(300, 0); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 0, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertEquals(300, cursorFlatten().size()); @@ -467,7 +466,7 @@ void testLimitWithLargeDocuments() { @DisplayName("should respect batch size") void shouldRespectBatchSize() { BsonDocument commandResult = executeFindCommand(2); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertEquals(2, cursor.getBatchSize()); @@ -484,7 +483,7 @@ void shouldRespectBatchSize() { @DisplayName("should throw cursor not found exception") void shouldThrowCursorNotFoundException() { BsonDocument commandResult = executeFindCommand(2); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); ServerCursor serverCursor = cursor.getServerCursor(); @@ -507,7 +506,7 @@ void shouldThrowCursorNotFoundException() { @DisplayName("should report available documents") void shouldReportAvailableDocuments() { BsonDocument commandResult = executeFindCommand(3); - cursor = new CommandBatchCursor<>(TimeoutMode.CURSOR_LIFETIME, 0, ClusterFixture.createOperationContext(), + cursor = new CommandBatchCursor<>(0, ClusterFixture.createOperationContext(), new CommandCursor<>(commandResult, 2, DOCUMENT_DECODER, null, connectionSource, connection, false, null)); assertEquals(3, cursor.available()); 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 c8b107cba2c..36f4a9e8670 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 @@ -643,7 +643,7 @@ class FindOperationSpecification extends OperationFunctionalSpecification { def 'should pass tailable and await data flags through'() { given: def (cursorType, long maxAwaitTimeMS, long maxTimeMSForCursor) = cursorDetails - def timeoutSettings = ClusterFixture.TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT.withMaxAwaitTimeMS(maxAwaitTimeMS) + def timeoutSettings = ClusterFixture.TIMEOUT_SETTINGS.withMaxAwaitTimeMS(maxAwaitTimeMS) def timeoutContext = new TimeoutContext(timeoutSettings) def operationContext = createOperationContext().withTimeoutContext(timeoutContext) diff --git a/driver-core/src/test/unit/com/mongodb/AbstractConnectionStringTest.java b/driver-core/src/test/unit/com/mongodb/AbstractConnectionStringTest.java index f05be4a0450..06171ffde37 100644 --- a/driver-core/src/test/unit/com/mongodb/AbstractConnectionStringTest.java +++ b/driver-core/src/test/unit/com/mongodb/AbstractConnectionStringTest.java @@ -131,9 +131,6 @@ protected void testValidOptions() { } else if (option.getKey().equalsIgnoreCase("replicaset")) { String expected = option.getValue().asString().getValue(); assertEquals(expected, connectionString.getRequiredReplicaSetName()); - } else if (option.getKey().equalsIgnoreCase("timeoutMS")) { - int expected = option.getValue().asInt32().getValue(); - assertEquals(expected, connectionString.getTimeout().intValue()); } else if (option.getKey().equalsIgnoreCase("serverselectiontimeoutms")) { int expected = option.getValue().asInt32().getValue(); assertEquals(expected, connectionString.getServerSelectionTimeout().intValue()); diff --git a/driver-core/src/test/unit/com/mongodb/ClientEncryptionSettingsSpecification.groovy b/driver-core/src/test/unit/com/mongodb/ClientEncryptionSettingsSpecification.groovy index 43deb3bd42c..e992fb87c5e 100644 --- a/driver-core/src/test/unit/com/mongodb/ClientEncryptionSettingsSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/ClientEncryptionSettingsSpecification.groovy @@ -19,7 +19,6 @@ package com.mongodb import spock.lang.Specification import javax.net.ssl.SSLContext -import java.util.concurrent.TimeUnit import java.util.function.Supplier class ClientEncryptionSettingsSpecification extends Specification { @@ -45,7 +44,6 @@ class ClientEncryptionSettingsSpecification extends Specification { options.getKmsProviders() == kmsProvider options.getKmsProviderPropertySuppliers() == [:] options.getKmsProviderSslContextMap() == [:] - options.getTimeout(TimeUnit.MILLISECONDS) == null when: options = ClientEncryptionSettings.builder() @@ -54,7 +52,6 @@ class ClientEncryptionSettingsSpecification extends Specification { .kmsProviders(kmsProvider) .kmsProviderPropertySuppliers(kmsProviderSupplier) .kmsProviderSslContextMap(kmsProviderSslContextMap) - .timeout(1_000, TimeUnit.MILLISECONDS) .build() then: @@ -63,24 +60,5 @@ class ClientEncryptionSettingsSpecification extends Specification { options.getKmsProviders() == kmsProvider options.getKmsProviderPropertySuppliers() == kmsProviderSupplier options.getKmsProviderSslContextMap() == kmsProviderSslContextMap - options.getTimeout(TimeUnit.MILLISECONDS) == 1_000 } - - def 'should throw an exception if the defaultTimeout is set and negative'() { - given: - def builder = ClientEncryptionSettings.builder() - - when: - builder.timeout(500, TimeUnit.NANOSECONDS) - - then: - thrown(IllegalArgumentException) - - when: - builder.timeout(-1, TimeUnit.SECONDS) - - then: - thrown(IllegalArgumentException) - } - } diff --git a/driver-core/src/test/unit/com/mongodb/ClientSessionOptionsSpecification.groovy b/driver-core/src/test/unit/com/mongodb/ClientSessionOptionsSpecification.groovy index 98bf163f9e3..738571a63fd 100644 --- a/driver-core/src/test/unit/com/mongodb/ClientSessionOptionsSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/ClientSessionOptionsSpecification.groovy @@ -18,8 +18,6 @@ package com.mongodb import spock.lang.Specification -import java.util.concurrent.TimeUnit - class ClientSessionOptionsSpecification extends Specification { def 'should have correct defaults'() { @@ -47,22 +45,6 @@ class ClientSessionOptionsSpecification extends Specification { transactionOptions << [TransactionOptions.builder().build(), TransactionOptions.builder().readConcern(ReadConcern.LOCAL).build()] } - def 'should throw an exception if the defaultTimeout is set and negative'() { - given: - def builder = ClientSessionOptions.builder() - - when: - builder.defaultTimeout(500, TimeUnit.NANOSECONDS) - - then: - thrown(IllegalArgumentException) - - when: - builder.defaultTimeout(-1, TimeUnit.SECONDS) - - then: - thrown(IllegalArgumentException) - } def 'should apply options to builder'() { expect: diff --git a/driver-core/src/test/unit/com/mongodb/MongoClientSettingsSpecification.groovy b/driver-core/src/test/unit/com/mongodb/MongoClientSettingsSpecification.groovy index 57995d26516..20683eaec3d 100644 --- a/driver-core/src/test/unit/com/mongodb/MongoClientSettingsSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/MongoClientSettingsSpecification.groovy @@ -65,7 +65,6 @@ class MongoClientSettingsSpecification extends Specification { settings.contextProvider == null settings.dnsClient == null settings.inetAddressResolver == null - settings.getTimeout(TimeUnit.MILLISECONDS) == null } @SuppressWarnings('UnnecessaryObjectReferences') @@ -159,7 +158,6 @@ class MongoClientSettingsSpecification extends Specification { .contextProvider(contextProvider) .dnsClient(dnsClient) .inetAddressResolver(inetAddressResolver) - .timeout(1000, TimeUnit.SECONDS) .build() then: @@ -182,7 +180,6 @@ class MongoClientSettingsSpecification extends Specification { settings.getContextProvider() == contextProvider settings.getDnsClient() == dnsClient settings.getInetAddressResolver() == inetAddressResolver - settings.getTimeout(TimeUnit.MILLISECONDS) == 1_000_000 } def 'should be easy to create new settings from existing'() { @@ -225,7 +222,6 @@ class MongoClientSettingsSpecification extends Specification { .contextProvider(contextProvider) .dnsClient(dnsClient) .inetAddressResolver(inetAddressResolver) - .timeout(0, TimeUnit.SECONDS) .build() then: @@ -254,30 +250,6 @@ class MongoClientSettingsSpecification extends Specification { thrown(IllegalArgumentException) } - def 'should throw an exception if the timeout is invalid'() { - given: - def builder = MongoClientSettings.builder() - - when: - builder.timeout(500, TimeUnit.NANOSECONDS) - - then: - thrown(IllegalArgumentException) - - when: - builder.timeout(-1, TimeUnit.SECONDS) - - then: - thrown(IllegalArgumentException) - - when: - def connectionString = new ConnectionString('mongodb://localhost/?timeoutMS=-1') - builder.applyConnectionString(connectionString).build() - - then: - thrown(IllegalStateException) - } - def 'should add command listeners'() { given: CommandListener commandListenerOne = Mock(CommandListener) @@ -346,7 +318,6 @@ class MongoClientSettingsSpecification extends Specification { + '&readConcernLevel=majority' + '&compressors=zlib&zlibCompressionLevel=5' + '&uuidRepresentation=standard' - + '&timeoutMS=10000' + '&proxyHost=proxy.com' + '&proxyPort=1080' + '&proxyUsername=username' @@ -410,7 +381,6 @@ class MongoClientSettingsSpecification extends Specification { .retryReads(true) .maxAdaptiveRetries(42) .uuidRepresentation(UuidRepresentation.STANDARD) - .timeout(10000, TimeUnit.MILLISECONDS) .build() then: @@ -581,7 +551,7 @@ class MongoClientSettingsSpecification extends Specification { 'maxAdaptiveRetries', 'observabilitySettings', 'readConcern', 'readPreference', 'retryReads', 'retryWrites', 'serverApi', 'serverSettingsBuilder', 'socketSettingsBuilder', 'sslSettingsBuilder', - 'timeoutMS', 'transportSettings', 'uuidRepresentation', + 'transportSettings', 'uuidRepresentation', 'writeConcern'] then: @@ -601,7 +571,7 @@ class MongoClientSettingsSpecification extends Specification { 'heartbeatSocketTimeoutMS', 'inetAddressResolver', 'maxAdaptiveRetries', 'observabilitySettings', 'readConcern', 'readPreference', 'retryReads', 'retryWrites', - 'serverApi', 'timeout', 'transportSettings', + 'serverApi', 'transportSettings', 'uuidRepresentation', 'writeConcern'] then: diff --git a/driver-core/src/test/unit/com/mongodb/TransactionOptionsSpecification.groovy b/driver-core/src/test/unit/com/mongodb/TransactionOptionsSpecification.groovy index 5b3f35f42f1..37e190432ff 100644 --- a/driver-core/src/test/unit/com/mongodb/TransactionOptionsSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/TransactionOptionsSpecification.groovy @@ -32,24 +32,6 @@ class TransactionOptionsSpecification extends Specification { options.getMaxCommitTime(TimeUnit.MILLISECONDS) == null } - def 'should throw an exception if the timeout is invalid'() { - given: - def builder = TransactionOptions.builder() - - - when: - builder.timeout(500, TimeUnit.NANOSECONDS) - - then: - thrown(IllegalArgumentException) - - when: - builder.timeout(-1, TimeUnit.SECONDS).build() - - then: - thrown(IllegalArgumentException) - } - def 'should apply options set in builder'() { when: def options = TransactionOptions.builder() @@ -57,7 +39,6 @@ class TransactionOptionsSpecification extends Specification { .writeConcern(WriteConcern.JOURNALED) .readPreference(ReadPreference.secondary()) .maxCommitTime(5, TimeUnit.SECONDS) - .timeout(null, TimeUnit.MILLISECONDS) .build() then: @@ -66,7 +47,6 @@ class TransactionOptionsSpecification extends Specification { options.readPreference == ReadPreference.secondary() options.getMaxCommitTime(TimeUnit.MILLISECONDS) == 5000 options.getMaxCommitTime(TimeUnit.SECONDS) == 5 - options.getTimeout(TimeUnit.MILLISECONDS) == null } def 'should merge'() { @@ -76,14 +56,12 @@ class TransactionOptionsSpecification extends Specification { .writeConcern(WriteConcern.MAJORITY) .readPreference(ReadPreference.secondary()) .maxCommitTime(5, TimeUnit.SECONDS) - .timeout(123, TimeUnit.MILLISECONDS) .build() def third = TransactionOptions.builder() .readConcern(ReadConcern.LOCAL) .writeConcern(WriteConcern.W2) .readPreference(ReadPreference.nearest()) .maxCommitTime(10, TimeUnit.SECONDS) - .timeout(123, TimeUnit.MILLISECONDS) .build() expect: diff --git a/driver-core/src/test/unit/com/mongodb/UriOptionsTest.java b/driver-core/src/test/unit/com/mongodb/UriOptionsTest.java index 11834fd1b97..de48c283c40 100644 --- a/driver-core/src/test/unit/com/mongodb/UriOptionsTest.java +++ b/driver-core/src/test/unit/com/mongodb/UriOptionsTest.java @@ -45,6 +45,9 @@ public void shouldPassAllOutcomes() { assumeFalse(getDescription().contains("tlsDisableOCSPEndpointCheck")); // No CANONICALIZE_HOST_NAME support https://jira.mongodb.org/browse/JAVA-4278 assumeFalse(getDescription().equals("Valid auth options are parsed correctly (GSSAPI)")); + // CSOT not implemented, so timeoutMS not supported + assumeFalse(getDescription().equals("Valid connection and timeout options are parsed correctly")); + assumeFalse(getDescription().equals("timeoutMS=0")); if (getDefinition().getBoolean("valid", BsonBoolean.TRUE).getValue()) { testValidOptions(); diff --git a/driver-core/src/test/unit/com/mongodb/internal/TimeoutContextTest.java b/driver-core/src/test/unit/com/mongodb/internal/TimeoutContextTest.java index aad29b4be73..f3181ad6695 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/TimeoutContextTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/TimeoutContextTest.java @@ -15,34 +15,20 @@ */ package com.mongodb.internal; -import com.mongodb.MongoOperationTimeoutException; -import com.mongodb.internal.time.Timeout; -import com.mongodb.lang.Nullable; import com.mongodb.session.ClientSession; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -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.function.Supplier; -import java.util.stream.Stream; - import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS; -import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT; import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS_WITH_LEGACY_SETTINGS; import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS_WITH_MAX_AWAIT_TIME; import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS_WITH_MAX_COMMIT; import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS_WITH_MAX_TIME; import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS_WITH_MAX_TIME_AND_AWAIT_TIME; -import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS_WITH_TIMEOUT; import static com.mongodb.ClusterFixture.sleep; -import static java.util.concurrent.TimeUnit.NANOSECONDS; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; final class TimeoutContextTest { @@ -58,39 +44,17 @@ public static long getMaxTimeMS(final TimeoutContext timeoutContext) { void testDefaults() { TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS); - assertFalse(timeoutContext.hasTimeoutMS()); assertEquals(0, getMaxTimeMS(timeoutContext)); assertEquals(0, timeoutContext.getMaxAwaitTimeMS()); assertEquals(0, timeoutContext.getMaxCommitTimeMS()); assertEquals(0, timeoutContext.getReadTimeoutMS()); } - @Test - @DisplayName("Uses timeoutMS if set") - void testUsesTimeoutMSIfSet() { - TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS_WITH_TIMEOUT); - - assertTrue(timeoutContext.hasTimeoutMS()); - assertTrue(getMaxTimeMS(timeoutContext) > 0); - assertEquals(0, timeoutContext.getMaxAwaitTimeMS()); - } - - @Test - @DisplayName("infinite timeoutMS") - void testInfiniteTimeoutMS() { - TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT); - - assertTrue(timeoutContext.hasTimeoutMS()); - assertEquals(0, getMaxTimeMS(timeoutContext)); - assertEquals(0, timeoutContext.getMaxAwaitTimeMS()); - } - @Test @DisplayName("MaxTimeMS set") void testMaxTimeMSSet() { TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS_WITH_MAX_TIME); - assertFalse(timeoutContext.hasTimeoutMS()); assertEquals(100, getMaxTimeMS(timeoutContext)); assertEquals(0, timeoutContext.getMaxAwaitTimeMS()); } @@ -100,7 +64,6 @@ void testMaxTimeMSSet() { void testMaxAwaitTimeMSSet() { TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS_WITH_MAX_AWAIT_TIME); - assertFalse(timeoutContext.hasTimeoutMS()); assertEquals(0, getMaxTimeMS(timeoutContext)); assertEquals(101, timeoutContext.getMaxAwaitTimeMS()); } @@ -110,7 +73,6 @@ void testMaxAwaitTimeMSSet() { void testMaxTimeMSAndMaxAwaitTimeMSSet() { TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS_WITH_MAX_TIME_AND_AWAIT_TIME); - assertFalse(timeoutContext.hasTimeoutMS()); assertEquals(101, getMaxTimeMS(timeoutContext)); assertEquals(1001, timeoutContext.getMaxAwaitTimeMS()); } @@ -120,7 +82,6 @@ void testMaxTimeMSAndMaxAwaitTimeMSSet() { void testMaxCommitTimeMSSet() { TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS_WITH_MAX_COMMIT); - assertFalse(timeoutContext.hasTimeoutMS()); assertEquals(0, getMaxTimeMS(timeoutContext)); assertEquals(0, timeoutContext.getMaxAwaitTimeMS()); assertEquals(999L, timeoutContext.getMaxCommitTimeMS()); @@ -131,34 +92,11 @@ void testMaxCommitTimeMSSet() { void testAllDeprecatedOptionsSet() { TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS_WITH_LEGACY_SETTINGS); - assertFalse(timeoutContext.hasTimeoutMS()); assertEquals(101, getMaxTimeMS(timeoutContext)); assertEquals(1001, timeoutContext.getMaxAwaitTimeMS()); assertEquals(999, timeoutContext.getMaxCommitTimeMS()); } - @Test - @DisplayName("Use timeout if available or the alternative") - void testUseTimeoutIfAvailableOrTheAlternative() { - TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS); - assertEquals(99L, timeoutContext.timeoutOrAlternative(99)); - - timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(0L)); - assertEquals(0L, timeoutContext.timeoutOrAlternative(99)); - - timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(999L)); - assertTrue(timeoutContext.timeoutOrAlternative(0) <= 999); - - timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(999L)); - assertTrue(timeoutContext.timeoutOrAlternative(999999) <= 999); - - timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS); - assertEquals(0, timeoutContext.getMaxCommitTimeMS()); - - timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(999L)); - assertTrue(timeoutContext.getMaxCommitTimeMS() <= 999); - } - @Test @DisplayName("withAdditionalReadTimeout works as expected") void testWithAdditionalReadTimeout() { @@ -171,49 +109,14 @@ void testWithAdditionalReadTimeout() { long originalValue = Long.MAX_VALUE - 100; timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS.withReadTimeoutMS(originalValue)); assertEquals(Long.MAX_VALUE, timeoutContext.withAdditionalReadTimeout(101).getReadTimeoutMS()); - - assertThrows(AssertionError.class, () -> new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(0L)).withAdditionalReadTimeout(1)); - - assertThrows(AssertionError.class, () -> new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(10_000L)).withAdditionalReadTimeout(1)); - } - - @Test - @DisplayName("Expired works as expected") - void testExpired() { - TimeoutContext smallTimeout = new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(1L)); - TimeoutContext longTimeout = - new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(9999999L)); - TimeoutContext noTimeout = new TimeoutContext(TIMEOUT_SETTINGS); - sleep(100); - assertFalse(hasExpired(noTimeout.getTimeout())); - assertFalse(hasExpired(longTimeout.getTimeout())); - assertTrue(hasExpired(smallTimeout.getTimeout())); - } - - private static boolean hasExpired(@Nullable final Timeout timeout) { - return Timeout.nullAsInfinite(timeout).call(NANOSECONDS, () -> false, (ns) -> false, () -> true); } @Test @DisplayName("throws when calculating timeout if expired") void testThrowsWhenExpired() { - TimeoutContext smallTimeout = new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(1L)); - TimeoutContext longTimeout = new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(9999999L)); TimeoutContext noTimeout = new TimeoutContext(TIMEOUT_SETTINGS); sleep(100); - assertThrows(MongoOperationTimeoutException.class, smallTimeout::getReadTimeoutMS); - assertThrows(MongoOperationTimeoutException.class, smallTimeout::getWriteTimeoutMS); - assertThrows(MongoOperationTimeoutException.class, smallTimeout::getConnectTimeoutMs); - assertThrows(MongoOperationTimeoutException.class, () -> getMaxTimeMS(smallTimeout)); - assertThrows(MongoOperationTimeoutException.class, smallTimeout::getMaxCommitTimeMS); - assertThrows(MongoOperationTimeoutException.class, () -> smallTimeout.timeoutOrAlternative(1)); - assertDoesNotThrow(longTimeout::getReadTimeoutMS); - assertDoesNotThrow(longTimeout::getWriteTimeoutMS); - assertDoesNotThrow(longTimeout::getConnectTimeoutMs); - assertDoesNotThrow(() -> getMaxTimeMS(longTimeout)); - assertDoesNotThrow(longTimeout::getMaxCommitTimeMS); - assertDoesNotThrow(() -> longTimeout.timeoutOrAlternative(1)); assertDoesNotThrow(noTimeout::getReadTimeoutMS); assertDoesNotThrow(noTimeout::getWriteTimeoutMS); assertDoesNotThrow(noTimeout::getConnectTimeoutMs); @@ -222,17 +125,6 @@ void testThrowsWhenExpired() { assertDoesNotThrow(() -> noTimeout.timeoutOrAlternative(1)); } - @Test - @DisplayName("validates minRoundTripTime for maxTimeMS") - void testValidatedMinRoundTripTime() { - Supplier supplier = () -> new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(100L)); - - assertTrue(getMaxTimeMS(supplier.get()) <= 100); - assertTrue(getMaxTimeMS(supplier.get().withMinRoundTripTime(10)) <= 90); - assertThrows(MongoOperationTimeoutException.class, () -> getMaxTimeMS(supplier.get().withMinRoundTripTimeMS(101))); - assertThrows(MongoOperationTimeoutException.class, () -> getMaxTimeMS(supplier.get().withMinRoundTripTimeMS(100))); - } - @Test @DisplayName("Test createTimeoutContext handles legacy settings") void testCreateTimeoutContextLegacy() { @@ -246,36 +138,10 @@ void testCreateTimeoutContextLegacy() { assertEquals(timeoutContext, actualTimeoutContext); } - @Test - @DisplayName("Test createTimeoutContext with timeout legacy settings") - void testCreateTimeoutContextWithTimeoutLegacy() { - TimeoutContext sessionTimeoutContext = new TimeoutContext(TIMEOUT_SETTINGS_WITH_TIMEOUT); - TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS_WITH_LEGACY_SETTINGS); - - ClientSession clientSession = Mockito.mock(ClientSession.class); - Mockito.when(clientSession.getTimeoutContext()).thenReturn(sessionTimeoutContext); - - TimeoutContext actualTimeoutContext = TimeoutContext.createTimeoutContext(clientSession, timeoutContext.getTimeoutSettings()); - assertEquals(sessionTimeoutContext, actualTimeoutContext); - } - - @Test - @DisplayName("Test createTimeoutContext with timeout") - void testCreateTimeoutContextWithTimeout() { - TimeoutContext sessionTimeoutContext = new TimeoutContext(TIMEOUT_SETTINGS_WITH_TIMEOUT); - TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS_WITH_TIMEOUT.withMaxAwaitTimeMS(123)); - - ClientSession clientSession = Mockito.mock(ClientSession.class); - Mockito.when(clientSession.getTimeoutContext()).thenReturn(sessionTimeoutContext); - - TimeoutContext actualTimeoutContext = TimeoutContext.createTimeoutContext(clientSession, timeoutContext.getTimeoutSettings()); - assertEquals(sessionTimeoutContext, actualTimeoutContext); - } - @Test @DisplayName("should override maxTimeMS when MaxTimeSupplier is set") void shouldOverrideMaximeMS() { - TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(100L).withMaxTimeMS(1)); + TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS.withMaxTimeMS(1)); timeoutContext = timeoutContext.withMaxTimeOverride(2L); @@ -285,7 +151,7 @@ void shouldOverrideMaximeMS() { @Test @DisplayName("should reset maxTimeMS to default behaviour") void shouldResetMaximeMS() { - TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS.withTimeoutMS(100L).withMaxTimeMS(1)); + TimeoutContext timeoutContext = new TimeoutContext(TIMEOUT_SETTINGS.withMaxTimeMS(100)); timeoutContext = timeoutContext.withMaxTimeOverride(1L); timeoutContext = timeoutContext.withDefaultMaxTime(); @@ -293,76 +159,6 @@ void shouldResetMaximeMS() { assertTrue(getMaxTimeMS(timeoutContext) > 1); } - static Stream shouldChooseConnectTimeoutWhenItIsLessThenTimeoutMs() { - return Stream.of( - //connectTimeoutMS, timeoutMS, expected - Arguments.of(500L, 1000L, 500L), - Arguments.of(0L, null, 0L), - Arguments.of(1000L, null, 1000L), - Arguments.of(1000L, 0L, 1000L), - Arguments.of(0L, 0L, 0L) - ); - } - - @ParameterizedTest - @MethodSource - @DisplayName("should choose connectTimeoutMS when connectTimeoutMS is less than timeoutMS") - void shouldChooseConnectTimeoutWhenItIsLessThenTimeoutMs(final Long connectTimeoutMS, - final Long timeoutMS, - final long expected) throws Exception { - // TODO-JAVA-6341: this test intermittently timesout in CI - int attempts = 3; - Exception e = null; - while (attempts-- > 0) { - try { - TimeoutContext timeoutContext = new TimeoutContext( - new TimeoutSettings(0, - connectTimeoutMS, - 0, - timeoutMS, - 0)); - - long calculatedTimeoutMS = timeoutContext.getConnectTimeoutMs(); - assertEquals(expected, calculatedTimeoutMS); - return; - } catch (Exception ex) { - if (e == null) { - e = ex; - - } - } - } - throw e; - } - - - static Stream shouldChooseTimeoutMsWhenItIsLessThenConnectTimeoutMS() { - return Stream.of( - //connectTimeoutMS, timeoutMS, expected - Arguments.of(1000L, 1000L, 999), - Arguments.of(1000L, 500L, 499L), - Arguments.of(0L, 1000L, 999L) - ); - } - - @DisplayName("should choose timeoutMS when timeoutMS is less than connectTimeoutMS") - @ParameterizedTest(name = "should choose timeoutMS when timeoutMS is less than connectTimeoutMS. " - + "Parameters: connectTimeoutMS: {0}, timeoutMS: {1}, expected: {2}") - @MethodSource - void shouldChooseTimeoutMsWhenItIsLessThenConnectTimeoutMS(final Long connectTimeoutMS, - final Long timeoutMS, - final long expected) { - TimeoutContext timeoutContext = new TimeoutContext( - new TimeoutSettings(0, - connectTimeoutMS, - 0, - timeoutMS, - 0)); - - long calculatedTimeoutMS = timeoutContext.getConnectTimeoutMs(); - assertTrue(expected - calculatedTimeoutMS <= 2); - } - private TimeoutContextTest() { } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/TimeoutSettingsTest.java b/driver-core/src/test/unit/com/mongodb/internal/TimeoutSettingsTest.java index 9bffd08542b..b738488cfa6 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/TimeoutSettingsTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/TimeoutSettingsTest.java @@ -40,7 +40,6 @@ Collection timeoutSettingsTest() { () -> assertEquals(30_000, timeoutSettings.getServerSelectionTimeoutMS()), () -> assertEquals(10_000, timeoutSettings.getConnectTimeoutMS()), () -> assertEquals(0, timeoutSettings.getReadTimeoutMS()), - () -> assertNull(timeoutSettings.getTimeoutMS()), () -> assertEquals(0, timeoutSettings.getMaxTimeMS()), () -> assertEquals(0, timeoutSettings.getMaxAwaitTimeMS()), () -> assertNull(timeoutSettings.getWTimeoutMS()) @@ -48,7 +47,6 @@ Collection timeoutSettingsTest() { }), dynamicTest("test overrides", () -> { TimeoutSettings timeoutSettings = TIMEOUT_SETTINGS - .withTimeoutMS(100L) .withMaxTimeMS(111) .withMaxAwaitTimeMS(11) .withMaxCommitMS(999L) @@ -59,7 +57,6 @@ Collection timeoutSettingsTest() { () -> assertEquals(30_000, timeoutSettings.getServerSelectionTimeoutMS()), () -> assertEquals(500, timeoutSettings.getConnectTimeoutMS()), () -> assertEquals(11_000, timeoutSettings.getReadTimeoutMS()), - () -> assertEquals(100, timeoutSettings.getTimeoutMS()), () -> assertEquals(111, timeoutSettings.getMaxTimeMS()), () -> assertEquals(11, timeoutSettings.getMaxAwaitTimeMS()), () -> assertEquals(999, timeoutSettings.getMaxCommitTimeMS()), @@ -71,10 +68,8 @@ Collection timeoutSettingsTest() { @Test public void testTimeoutSettingsValidation() { - assertThrows(IllegalArgumentException.class, () -> TIMEOUT_SETTINGS.withTimeoutMS(-1L)); assertThrows(IllegalArgumentException.class, () -> TIMEOUT_SETTINGS.withMaxAwaitTimeMS(-1)); assertThrows(IllegalArgumentException.class, () -> TIMEOUT_SETTINGS.withMaxTimeMS(-1)); - assertThrows(IllegalArgumentException.class, () -> TIMEOUT_SETTINGS.withTimeoutMS(10L).withMaxAwaitTimeMS(11)); } private TimeoutSettingsTest() { 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 52287a23d13..088251b79e4 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 @@ -98,8 +98,8 @@ protected void applyApplicationError(final BsonDocument applicationError) { switch (type) { case "command": - exception = getCommandFailureException(applicationError.getDocument("response"), serverAddress, - operationContext.getTimeoutContext()); + exception = getCommandFailureException(applicationError.getDocument("response"), serverAddress + ); 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 25a1b904e1f..4f8ae6cef8e 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 @@ -96,15 +96,6 @@ class BaseClusterSpecification extends Specification { then: 'a MongoTimeoutException is thrown' thrown(MongoTimeoutException) - - when: 'a server is selected before initialization and timeoutMS is set' - cluster.selectServer({ def clusterDescription -> [] }, - createOperationContext(TIMEOUT_SETTINGS - .withServerSelectionTimeoutMS(1) - .withTimeout(1, MILLISECONDS))) - - then: 'a MongoTimeoutException is thrown' - thrown(MongoTimeoutException) } def 'should get cluster settings'() { diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/CommandMessageTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/CommandMessageTest.java index 1d57d04b4a8..53cd73b99c0 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/CommandMessageTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/CommandMessageTest.java @@ -17,7 +17,6 @@ package com.mongodb.internal.connection; import com.mongodb.MongoNamespace; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; @@ -52,9 +51,6 @@ import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -63,33 +59,6 @@ class CommandMessageTest { private static final MongoNamespace NAMESPACE = new MongoNamespace("db.test"); private static final BsonDocument COMMAND = new BsonDocument("find", new BsonString(NAMESPACE.getCollectionName())); - @Test - void encodeShouldThrowTimeoutExceptionWhenTimeoutContextIsCalled() { - //given - CommandMessage commandMessage = new CommandMessage(NAMESPACE.getDatabaseName(), COMMAND, NoOpFieldNameValidator.INSTANCE, ReadPreference.primary(), - MessageSettings.builder() - .maxWireVersion(LATEST_WIRE_VERSION) - .serverType(ServerType.REPLICA_SET_SECONDARY) - .sessionSupported(true) - .build(), - true, EmptyMessageSequences.INSTANCE, ClusterConnectionMode.MULTIPLE, null); - - try (ByteBufferBsonOutput bsonOutput = new ByteBufferBsonOutput(new SimpleBufferProvider())) { - SessionContext sessionContext = mock(SessionContext.class); - TimeoutContext timeoutContext = mock(TimeoutContext.class, mock -> { - doThrow(new MongoOperationTimeoutException("test")).when(mock).runMaxTimeMS(any()); - }); - OperationContext operationContext = mock(OperationContext.class, mock -> { - when(mock.getSessionContext()).thenReturn(sessionContext); - when(mock.getTimeoutContext()).thenReturn(timeoutContext); - }); - - //when & then - assertThrows(MongoOperationTimeoutException.class, () -> - commandMessage.encode(bsonOutput, operationContext)); - } - } - @Test void encodeShouldNotAddExtraElementsFromTimeoutContextWhenConnectedToMongoCrypt() { //given 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 b41012ca0f5..8bc2a21bb78 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 @@ -19,13 +19,10 @@ package com.mongodb.internal.connection import com.mongodb.MongoCommandException import com.mongodb.MongoInternalException import com.mongodb.MongoInterruptedException -import com.mongodb.MongoOperationTimeoutException import com.mongodb.MongoSocketClosedException import com.mongodb.MongoSocketException import com.mongodb.MongoSocketReadException -import com.mongodb.MongoSocketReadTimeoutException import com.mongodb.MongoSocketWriteException -import com.mongodb.MongoSocketWriteTimeoutException import com.mongodb.ReadConcern import com.mongodb.ServerAddress import com.mongodb.async.FutureResultCallback @@ -40,7 +37,6 @@ import com.mongodb.event.CommandFailedEvent import com.mongodb.event.CommandStartedEvent import com.mongodb.event.CommandSucceededEvent import com.mongodb.internal.ExceptionUtils.MongoCommandExceptionUtils -import com.mongodb.internal.TimeoutContext import com.mongodb.internal.session.SessionContext import com.mongodb.internal.validator.NoOpFieldNameValidator import org.bson.BsonDocument @@ -60,7 +56,6 @@ import java.util.concurrent.ExecutorService import java.util.concurrent.Executors 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 import static com.mongodb.connection.ClusterConnectionMode.SINGLE @@ -459,107 +454,6 @@ class InternalStreamConnectionSpecification extends Specification { connection.isClosed() } - def 'Should throw timeout exception with underlying socket exception as a cause when Stream.read throws SocketException'() { - given: - stream.read(_, _) >> { throw new SocketTimeoutException() } - def connection = getOpenedConnection() - - when: - connection.receiveMessage(1, createOperationContext().withTimeoutContext( - new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT))) - - then: - def timeoutException = thrown(MongoOperationTimeoutException) - def mongoSocketReadTimeoutException = timeoutException.getCause() - mongoSocketReadTimeoutException instanceof MongoSocketReadTimeoutException - mongoSocketReadTimeoutException.getCause() instanceof SocketTimeoutException - - connection.isClosed() - } - - def 'Should throw timeout exception with underlying socket exception as a cause when Stream.write throws SocketTimeoutException'() { - given: - stream.write(_, _) >> { throw new SocketTimeoutException() } - def connection = getOpenedConnection() - def (buffers, messageId) = helper.hello() - - when: - connection.sendMessage(buffers, messageId, createOperationContext().withTimeoutContext( - new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT))) - - then: - def timeoutException = thrown(MongoOperationTimeoutException) - def mongoSocketWriteTimeoutException = timeoutException.getCause() - mongoSocketWriteTimeoutException instanceof MongoSocketWriteTimeoutException - mongoSocketWriteTimeoutException.getCause() instanceof SocketTimeoutException - - connection.isClosed() - } - - def 'Should wrap MongoSocketReadTimeoutException with MongoOperationTimeoutException'() { - given: - stream.read(_, _) >> { throw new MongoSocketReadTimeoutException("test", new ServerAddress(), null) } - def connection = getOpenedConnection() - - when: - connection.receiveMessage(1, createOperationContext().withTimeoutContext( - new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT))) - - then: - def timeoutException = thrown(MongoOperationTimeoutException) - def mongoSocketReadTimeoutException = timeoutException.getCause() - mongoSocketReadTimeoutException instanceof MongoSocketReadTimeoutException - mongoSocketReadTimeoutException.getCause() == null - - connection.isClosed() - } - - - def 'Should wrap SocketException with timeout exception when Stream.read throws SocketException async'() { - given: - stream.readAsync(_ , _, _) >> { numBytes, operationContext, handler -> - handler.failed(new SocketTimeoutException()) - } - def connection = getOpenedConnection() - def callback = new FutureResultCallback() - def operationContext = createOperationContext().withTimeoutContext( - new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT)) - when: - connection.receiveMessageAsync(1, operationContext, callback) - callback.get() - - then: - def timeoutException = thrown(MongoOperationTimeoutException) - def mongoSocketReadTimeoutException = timeoutException.getCause() - mongoSocketReadTimeoutException instanceof MongoSocketReadTimeoutException - mongoSocketReadTimeoutException.getCause() instanceof SocketTimeoutException - - connection.isClosed() - } - - def 'Should wrap MongoSocketReadTimeoutException with MongoOperationTimeoutException async'() { - given: - stream.readAsync(_, _, _) >> { numBytes, operationContext, handler -> - handler.failed(new MongoSocketReadTimeoutException("test", new ServerAddress(), null)) - } - - def connection = getOpenedConnection() - def callback = new FutureResultCallback() - def operationContext = createOperationContext().withTimeoutContext( - new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT)) - when: - connection.receiveMessageAsync(1, operationContext, callback) - callback.get() - - then: - def timeoutException = thrown(MongoOperationTimeoutException) - def mongoSocketReadTimeoutException = timeoutException.getCause() - mongoSocketReadTimeoutException instanceof MongoSocketReadTimeoutException - mongoSocketReadTimeoutException.getCause() == null - - connection.isClosed() - } - def 'should close the stream when reading the message header throws an exception asynchronously'() { given: int seen = 0 diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTest.java b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTest.java index 2abac547510..8e3e96d44e0 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/InternalStreamConnectionTest.java @@ -21,7 +21,6 @@ import com.mongodb.MongoCompressor; import com.mongodb.MongoExecutionTimeoutException; import com.mongodb.MongoInternalException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoSocketReadException; import com.mongodb.async.FutureResultCallback; import com.mongodb.connection.AsyncCompletionHandler; @@ -707,84 +706,6 @@ public void readAsync(final int numBytes, final OperationContext operationContex connection.close(); } - /** - * Verifies that a CSOT-derived write concern timeout carried by a fully-read ok: 1 response does NOT - * close the connection in the synchronous path. With CSOT enabled, a MaxTimeMSExpired (errorCode 50) - * write concern error is wrapped as {@link MongoOperationTimeoutException}, which {@code connectionIsReusable} - * whitelists because the response was fully read and the stream remains synchronized. - */ - @Test - @DisplayName("Sync: connection NOT closed on CSOT write concern timeout carried by an ok response") - void syncDoesNotCloseConnectionOnWriteConcernTimeout() { - AtomicInteger readCallCount = new AtomicInteger(); - BsonDocument response = createWriteConcernTimeoutResponse(); - - TestStream stream = new TestStream() { - @Override - public ByteBuf read(final int numBytes, final OperationContext operationContext) { - if (readCallCount.incrementAndGet() == 1) { - return createValidResponseHeader(getCommandMessageId(), response); - } else { - return createResponseBody(response); - } - } - }; - - InternalStreamConnection connection = createOpenConnection(stream); - CommandMessage commandMessage = createPingCommand(); - stream.setCommandMessageId(commandMessage.getId()); - - assertThrows(MongoOperationTimeoutException.class, - () -> connection.sendAndReceive(commandMessage, new BsonDocumentCodec(), createOperationContextWithTimeout())); - assertFalse(connection.isClosed(), - "Connection should NOT be closed on a write concern timeout (the response was fully read)"); - assertFalse(stream.wasClosed(), - "Underlying stream should NOT be closed on a write concern timeout"); - assertFalse(stream.hadUnexpectedCall()); - - connection.close(); - } - - /** - * Verifies that a CSOT-derived write concern timeout carried by a fully-read ok: 1 response does NOT - * close the connection in the asynchronous path. See {@link #syncDoesNotCloseConnectionOnWriteConcernTimeout}. - */ - @Test - @DisplayName("Async: connection NOT closed on CSOT write concern timeout carried by an ok response") - void asyncDoesNotCloseConnectionOnWriteConcernTimeout() { - AtomicInteger readAsyncCallCount = new AtomicInteger(); - BsonDocument response = createWriteConcernTimeoutResponse(); - - TestStream stream = new TestStream() { - @Override - public void readAsync(final int numBytes, final OperationContext operationContext, - final AsyncCompletionHandler handler) { - if (readAsyncCallCount.incrementAndGet() == 1) { - handler.completed(createValidResponseHeader(getCommandMessageId(), response)); - } else { - handler.completed(createResponseBody(response)); - } - } - }; - - InternalStreamConnection connection = createOpenConnection(stream); - CommandMessage commandMessage = createPingCommand(); - stream.setCommandMessageId(commandMessage.getId()); - - FutureResultCallback callback = new FutureResultCallback<>(); - connection.sendAndReceiveAsync(commandMessage, new BsonDocumentCodec(), createOperationContextWithTimeout(), callback); - - assertThrows(MongoOperationTimeoutException.class, () -> callback.get(5, TimeUnit.SECONDS)); - assertFalse(callback.wasInvokedMultipleTimes()); - - assertFalse(connection.isClosed(), - "Connection should NOT be closed on a write concern timeout (the response was fully read)"); - assertFalse(stream.wasClosed(), - "Underlying stream should NOT be closed on a write concern timeout"); - - connection.close(); - } - /** * Verifies that when a command error response (ok: 0) carries a mismatched responseTo in the * synchronous path, command monitoring receives exactly one started and one failed event. @@ -1432,16 +1353,6 @@ private void sendAndReceive(final InternalStreamConnection connection, final Com } } - /** - * Creates an operation context with CSOT enabled (timeoutMS set), so that server-side timeouts are - * wrapped as {@link MongoOperationTimeoutException}. The timeout is large enough not to expire during - * the test. - */ - private OperationContext createOperationContextWithTimeout() { - return OperationContext.simpleOperationContext( - new TimeoutSettings(0, 0, 0, 60_000L, 0)); - } - /** * Creates a successful (ok: 1) response whose writeConcernError maps to a special exception (a * not-primary error), so the driver raises {@link MongoWriteConcernWithResponseException} while the @@ -1454,17 +1365,6 @@ private static BsonDocument createWriteConcernErrorResponse() { .append("errmsg", new BsonString("not master"))); } - /** - * Creates a successful (ok: 1) response whose writeConcernError is a MaxTimeMSExpired (errorCode 50) - * timeout. With CSOT enabled it is wrapped as {@link MongoOperationTimeoutException} from the fully-read body. - */ - private static BsonDocument createWriteConcernTimeoutResponse() { - return new BsonDocument("ok", new BsonInt32(1)) - .append("writeConcernError", new BsonDocument("code", new BsonInt32(50)) - .append("codeName", new BsonString("MaxTimeMSExpired")) - .append("errmsg", new BsonString("operation exceeded time limit"))); - } - /** * Creates a generic command error response document (ok: 0). */ 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 c868a46ef96..71cf0d8638d 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 @@ -20,7 +20,6 @@ import com.mongodb.MongoClientException; import com.mongodb.MongoConfigurationException; import com.mongodb.MongoException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoTimeoutException; import com.mongodb.ServerAddress; import com.mongodb.async.FutureResultCallback; @@ -55,7 +54,6 @@ import static com.mongodb.ClusterFixture.CLIENT_METADATA; import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS; import static com.mongodb.ClusterFixture.createOperationContext; -import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -241,32 +239,6 @@ public void shouldTimeoutSelectServerWhenThereIsSRVLookup() { assertTrue(exception.getMessage().contains("while waiting to resolve SRV records for foo.bar.com")); } - @Test - public void shouldTimeoutSelectServerWhenThereIsSRVLookupAndTimeoutMsIsSet() { - // given - String srvHostName = "foo.bar.com"; - ServerAddress resolvedServerAddress = new ServerAddress("host1"); - ClusterableServer expectedServer = mock(ClusterableServer.class); - - ClusterSettings clusterSettings = ClusterSettings.builder() - .mode(ClusterConnectionMode.LOAD_BALANCED) - .srvHost(srvHostName) - .build(); - - ClusterableServerFactory serverFactory = mockServerFactory(resolvedServerAddress, expectedServer); - - DnsSrvRecordMonitorFactory dnsSrvRecordMonitorFactory = mock(DnsSrvRecordMonitorFactory.class); - when(dnsSrvRecordMonitorFactory.create(eq(srvHostName), eq(clusterSettings.getSrvServiceName()), any(), any())).thenAnswer( - invocation -> new TestDnsSrvRecordMonitor(invocation.getArgument(3)).sleepTime(Duration.ofHours(1))); - - cluster = new LoadBalancedCluster(new ClusterId(), clusterSettings, serverFactory, CLIENT_METADATA, dnsSrvRecordMonitorFactory); - - //when & then - MongoOperationTimeoutException exception = assertThrows(MongoOperationTimeoutException.class, () -> cluster.selectServer(mock(ServerSelector.class), - createOperationContext(TIMEOUT_SETTINGS.withServerSelectionTimeoutMS(5).withTimeout(10L, MILLISECONDS)))); - assertTrue(exception.getMessage().contains("while waiting to resolve SRV records for foo.bar.com")); - } - @Test public void shouldTimeoutSelectServerWhenThereIsSRVLookupException() { // given diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/ProtocolHelperSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/connection/ProtocolHelperSpecification.groovy index 7e4fee2c2cf..5cfa66aeda5 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/ProtocolHelperSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/ProtocolHelperSpecification.groovy @@ -20,10 +20,8 @@ import com.mongodb.MongoCommandException import com.mongodb.MongoExecutionTimeoutException import com.mongodb.MongoNodeIsRecoveringException import com.mongodb.MongoNotPrimaryException -import com.mongodb.MongoOperationTimeoutException import com.mongodb.MongoQueryException import com.mongodb.ServerAddress -import com.mongodb.internal.TimeoutContext import org.bson.BsonBoolean import org.bson.BsonDocument import org.bson.BsonDouble @@ -33,8 +31,6 @@ import org.bson.BsonNull import org.bson.BsonString import spock.lang.Specification -import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS -import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT import static com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException import static com.mongodb.internal.connection.ProtocolHelper.getQueryFailureException import static com.mongodb.internal.connection.ProtocolHelper.isCommandOk @@ -74,33 +70,19 @@ class ProtocolHelperSpecification extends Specification { def 'command failure exception should be MongoExecutionTimeoutException if error code is 50'() { expect: getCommandFailureException(new BsonDocument('ok', new BsonInt32(0)).append('code', new BsonInt32(50)), - new ServerAddress(), new TimeoutContext(TIMEOUT_SETTINGS)) instanceof MongoExecutionTimeoutException - } - - def 'command failure exception should be MongoOperationTimeoutException if error code is 50 and timeoutMS is set'() { - expect: - getCommandFailureException(new BsonDocument('ok', new BsonInt32(0)).append('code', new BsonInt32(50)), - new ServerAddress(), new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT)) instanceof MongoOperationTimeoutException + new ServerAddress()) instanceof MongoExecutionTimeoutException } def 'query failure exception should be MongoExecutionTimeoutException if error code is 50'() { expect: getQueryFailureException(new BsonDocument('code', new BsonInt32(50)), - new ServerAddress(), new TimeoutContext(TIMEOUT_SETTINGS)) instanceof MongoExecutionTimeoutException - } - - def 'query failure exception should be MongoOperationTimeoutException if error code is 50'() { - expect: - def exception = getQueryFailureException(new BsonDocument('code', new BsonInt32(50)), - new ServerAddress(), new TimeoutContext(TIMEOUT_SETTINGS_WITH_INFINITE_TIMEOUT)) - exception instanceof MongoOperationTimeoutException - exception.getCause() instanceof MongoExecutionTimeoutException + new ServerAddress()) instanceof MongoExecutionTimeoutException } def 'command failure exceptions should handle MongoNotPrimaryException scenarios'() { expect: getCommandFailureException( - exception, new ServerAddress(), new TimeoutContext(TIMEOUT_SETTINGS)) instanceof MongoNotPrimaryException + exception, new ServerAddress()) instanceof MongoNotPrimaryException where: exception << [ @@ -113,7 +95,7 @@ class ProtocolHelperSpecification extends Specification { def 'query failure exceptions should handle MongoNotPrimaryException scenarios'() { expect: getQueryFailureException( - exception, new ServerAddress(), new TimeoutContext(TIMEOUT_SETTINGS)) instanceof MongoNotPrimaryException + exception, new ServerAddress()) instanceof MongoNotPrimaryException where: exception << [ @@ -126,7 +108,7 @@ class ProtocolHelperSpecification extends Specification { def 'command failure exceptions should handle MongoNodeIsRecoveringException scenarios'() { expect: getCommandFailureException( - exception, new ServerAddress(), new TimeoutContext(TIMEOUT_SETTINGS)) instanceof MongoNodeIsRecoveringException + exception, new ServerAddress()) instanceof MongoNodeIsRecoveringException where: exception << [ @@ -142,7 +124,7 @@ class ProtocolHelperSpecification extends Specification { def 'query failure exceptions should handle MongoNodeIsRecoveringException scenarios'() { expect: getQueryFailureException( - exception, new ServerAddress(), new TimeoutContext(TIMEOUT_SETTINGS)) instanceof MongoNodeIsRecoveringException + exception, new ServerAddress()) instanceof MongoNodeIsRecoveringException where: exception << [ @@ -158,13 +140,13 @@ class ProtocolHelperSpecification extends Specification { def 'command failure exception should be MongoCommandException'() { expect: getCommandFailureException(new BsonDocument('ok', new BsonInt32(0)).append('errmsg', new BsonString('some other problem')), - new ServerAddress(), new TimeoutContext(TIMEOUT_SETTINGS)) instanceof MongoCommandException + new ServerAddress()) instanceof MongoCommandException } def 'query failure exception should be MongoQueryException'() { expect: getQueryFailureException(new BsonDocument('$err', new BsonString('some other problem')), - new ServerAddress(), new TimeoutContext(TIMEOUT_SETTINGS)) instanceof MongoQueryException + new ServerAddress()) instanceof MongoQueryException } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/connection/TestInternalConnection.java b/driver-core/src/test/unit/com/mongodb/internal/connection/TestInternalConnection.java index 2853780f93a..dbb70ea3ed3 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/connection/TestInternalConnection.java +++ b/driver-core/src/test/unit/com/mongodb/internal/connection/TestInternalConnection.java @@ -179,7 +179,7 @@ public T sendAndReceive(final CommandMessage message, final Decoder decod responseBuffers.reset(); if (!commandOk) { throw getCommandFailureException(getResponseDocument(responseBuffers, message, new BsonDocumentCodec()), - description.getServerAddress(), operationContext.getTimeoutContext()); + description.getServerAddress()); } return new ReplyMessage<>(responseBuffers, decoder, message.getId()).getDocument(); } diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/AsyncChangeStreamBatchCursorSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/operation/AsyncChangeStreamBatchCursorSpecification.groovy index 8d07aebdeea..0cdd726bd8e 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/AsyncChangeStreamBatchCursorSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/AsyncChangeStreamBatchCursorSpecification.groovy @@ -31,8 +31,6 @@ import org.bson.Document import org.bson.RawBsonDocument import spock.lang.Specification -import java.util.concurrent.TimeUnit - import static java.util.concurrent.TimeUnit.SECONDS class AsyncChangeStreamBatchCursorSpecification extends Specification { @@ -43,7 +41,6 @@ class AsyncChangeStreamBatchCursorSpecification extends Specification { def binding = Mock(AsyncReadBinding) def operationContext = getOperationContext() operationContext.getTracingManager() >> TracingManager.NO_OP - operationContext.getTimeoutContext().hasTimeoutMS() >> hasTimeoutMS def callback = Stub(SingleResultCallback) AsyncCursor wrapped = Mock(AsyncCursor) @@ -76,9 +73,6 @@ class AsyncChangeStreamBatchCursorSpecification extends Specification { then: 0 * wrapped.close() 0 * binding.release() - - where: - hasTimeoutMS << [true, false] } def 'should not close the cursor in next if the cursor was closed before next completed'() { @@ -86,7 +80,6 @@ class AsyncChangeStreamBatchCursorSpecification extends Specification { def binding = Mock(AsyncReadBinding) def operationContext = getOperationContext() operationContext.getTracingManager() >> TracingManager.NO_OP - operationContext.getTimeoutContext().hasTimeoutMS() >> hasTimeoutMS def callback = Stub(SingleResultCallback) AsyncCursor wrapped = Mock(AsyncCursor) @@ -109,9 +102,6 @@ class AsyncChangeStreamBatchCursorSpecification extends Specification { then: cursor.isClosed() - - where: - hasTimeoutMS << [true, false] } def 'should throw a MongoException when next/tryNext is called after the cursor is closed'() { @@ -119,7 +109,6 @@ class AsyncChangeStreamBatchCursorSpecification extends Specification { def binding = Mock(AsyncReadBinding) def operationContext = getOperationContext() operationContext.getTracingManager() >> TracingManager.NO_OP - operationContext.getTimeoutContext().hasTimeoutMS() >> hasTimeoutMS AsyncCursor wrapped = Mock(AsyncCursor) def cursor = new AsyncChangeStreamBatchCursor(changeStreamOpertation, @@ -135,9 +124,6 @@ class AsyncChangeStreamBatchCursorSpecification extends Specification { then: def exception = thrown(MongoException) exception.getMessage() == 'next() called after the cursor was closed.' - - where: - hasTimeoutMS << [true, false] } List nextBatch(AsyncChangeStreamBatchCursor cursor) { @@ -148,7 +134,7 @@ class AsyncChangeStreamBatchCursorSpecification extends Specification { OperationContext getOperationContext() { def timeoutContext = Spy(new TimeoutContext(TimeoutSettings.create( - MongoClientSettings.builder().timeout(3, TimeUnit.SECONDS).build()))) + MongoClientSettings.builder().build()))) Spy(new OperationContext( IgnorableRequestContext.INSTANCE, NoOpSessionContext.INSTANCE, diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/AsyncCommandBatchCursorSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/operation/AsyncCommandBatchCursorSpecification.groovy index d268d2df6c1..d7ec3e8e39e 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/AsyncCommandBatchCursorSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/AsyncCommandBatchCursorSpecification.groovy @@ -23,7 +23,6 @@ import com.mongodb.MongoNamespace import com.mongodb.ServerAddress import com.mongodb.ServerCursor import com.mongodb.async.FutureResultCallback -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.connection.ConnectionDescription import com.mongodb.connection.ServerConnectionState import com.mongodb.connection.ServerDescription @@ -46,8 +45,6 @@ import org.bson.Document import org.bson.codecs.DocumentCodec import spock.lang.Specification -import java.util.concurrent.TimeUnit - import static OperationUnitSpecification.getMaxWireVersionForServerVersion import static com.mongodb.ReadPreference.primary import static com.mongodb.internal.operation.CommandBatchCursorHelper.MESSAGE_IF_CLOSED_AS_CURSOR @@ -80,7 +77,7 @@ class AsyncCommandBatchCursorSpecification extends Specification { initialConnection, false, null) - def cursor = new AsyncCommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, maxTimeMS, operationContext, commandCoreCursor) + def cursor = new AsyncCommandBatchCursor(maxTimeMS, operationContext, commandCoreCursor) then: 1 * timeoutContext.withMaxTimeOverride(*_) @@ -119,7 +116,7 @@ class AsyncCommandBatchCursorSpecification extends Specification { def connectionSource = getAsyncConnectionSource(connection) def operationContext = getOperationContext() def commandCoreCursor = new AsyncCommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new AsyncCommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new AsyncCommandBatchCursor(0, operationContext, commandCoreCursor) when: cursor.close() @@ -150,7 +147,7 @@ class AsyncCommandBatchCursorSpecification extends Specification { when: def firstBatch = createCommandResult(FIRST_BATCH, 0) def commandCoreCursor = new AsyncCommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new AsyncCommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new AsyncCommandBatchCursor(0, operationContext, commandCoreCursor) then: nextBatch(cursor) == FIRST_BATCH @@ -181,7 +178,7 @@ class AsyncCommandBatchCursorSpecification extends Specification { when: def firstBatch = createCommandResult([], CURSOR_ID) def commandCoreCursor = new AsyncCommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new AsyncCommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new AsyncCommandBatchCursor(0, operationContext, commandCoreCursor) def batch = nextBatch(cursor) then: @@ -231,7 +228,7 @@ class AsyncCommandBatchCursorSpecification extends Specification { when: def commandCoreCursor = new AsyncCommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new AsyncCommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new AsyncCommandBatchCursor(0, operationContext, commandCoreCursor) def batch = nextBatch(cursor) then: @@ -286,7 +283,7 @@ class AsyncCommandBatchCursorSpecification extends Specification { when: def commandCoreCursor = new AsyncCommandCursor<>(createCommandResult(FIRST_BATCH, 42), 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new AsyncCommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new AsyncCommandBatchCursor(0, operationContext, commandCoreCursor) def batch = nextBatch(cursor) then: @@ -322,7 +319,7 @@ class AsyncCommandBatchCursorSpecification extends Specification { when: def commandCoreCursor = new AsyncCommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new AsyncCommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new AsyncCommandBatchCursor(0, operationContext, commandCoreCursor) def batch = nextBatch(cursor) then: @@ -362,7 +359,7 @@ class AsyncCommandBatchCursorSpecification extends Specification { def connectionSource = getAsyncConnectionSourceWithResult(ServerType.STANDALONE) { [null, MONGO_EXCEPTION] } def firstBatch = createCommandResult() def commandCoreCursor = new AsyncCommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new AsyncCommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new AsyncCommandBatchCursor(0, operationContext, commandCoreCursor) when: cursor.close() @@ -382,7 +379,7 @@ class AsyncCommandBatchCursorSpecification extends Specification { when: def firstBatch = createCommandResult() def commandCoreCursor = new AsyncCommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new AsyncCommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new AsyncCommandBatchCursor(0, operationContext, commandCoreCursor) then: nextBatch(cursor) @@ -409,7 +406,7 @@ class AsyncCommandBatchCursorSpecification extends Specification { when: def firstBatch = createCommandResult() def commandCoreCursor = new AsyncCommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new AsyncCommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new AsyncCommandBatchCursor(0, operationContext, commandCoreCursor) then: connectionSource.getCount() == 1 @@ -571,7 +568,7 @@ class AsyncCommandBatchCursorSpecification extends Specification { OperationContext getOperationContext() { def timeoutContext = Spy(new TimeoutContext(TimeoutSettings.create( - MongoClientSettings.builder().timeout(3, TimeUnit.SECONDS).build()))) + MongoClientSettings.builder().build()))) Spy(new OperationContext( IgnorableRequestContext.INSTANCE, NoOpSessionContext.INSTANCE, diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/BulkWriteBatchSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/operation/BulkWriteBatchSpecification.groovy index a7eaacda36c..0128688df2c 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/BulkWriteBatchSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/BulkWriteBatchSpecification.groovy @@ -49,7 +49,7 @@ import static com.mongodb.internal.bulk.WriteRequest.Type.REPLACE import static com.mongodb.internal.bulk.WriteRequest.Type.UPDATE class BulkWriteBatchSpecification extends Specification { - private static final TimeoutContext TIMEOUT_CONTEXT = new TimeoutContext(new TimeoutSettings(0, 0, 0, 0, 0)) + private static final TimeoutContext TIMEOUT_CONTEXT = new TimeoutContext(new TimeoutSettings(0, 0, 0, 0)) def namespace = new MongoNamespace('db.coll') def serverDescription = ServerDescription.builder().address(new ServerAddress()).state(CONNECTED) .logicalSessionTimeoutMinutes(30) diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/ChangeStreamBatchCursorSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/operation/ChangeStreamBatchCursorSpecification.groovy index 5f2d023c5a7..d4123e13509 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/ChangeStreamBatchCursorSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/ChangeStreamBatchCursorSpecification.groovy @@ -28,8 +28,6 @@ import org.bson.BsonInt32 import org.bson.RawBsonDocument import spock.lang.Specification -import java.util.concurrent.TimeUnit - import static java.util.Collections.emptyList class ChangeStreamBatchCursorSpecification extends Specification { @@ -81,7 +79,7 @@ class ChangeStreamBatchCursorSpecification extends Specification { OperationContext getOperationContext() { def timeoutContext = Spy(new TimeoutContext(TimeoutSettings.create( - MongoClientSettings.builder().timeout(3, TimeUnit.SECONDS).build()))) + MongoClientSettings.builder().build()))) Spy(new OperationContext( IgnorableRequestContext.INSTANCE, NoOpSessionContext.INSTANCE, diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/ChangeStreamBatchCursorTest.java b/driver-core/src/test/unit/com/mongodb/internal/operation/ChangeStreamBatchCursorTest.java index 947e125667a..e06ca6dcde2 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/ChangeStreamBatchCursorTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/ChangeStreamBatchCursorTest.java @@ -15,9 +15,7 @@ */ package com.mongodb.internal.operation; -import com.mongodb.MongoException; import com.mongodb.MongoNotPrimaryException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.ServerAddress; import com.mongodb.connection.ServerDescription; import com.mongodb.internal.IgnorableRequestContext; @@ -32,37 +30,25 @@ import org.bson.BsonInt32; import org.bson.Document; import org.bson.RawBsonDocument; -import org.bson.assertions.Assertions; import org.bson.codecs.DocumentCodec; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.mockito.ArgumentCaptor; import java.util.ArrayList; -import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; -import java.util.function.Consumer; import static com.mongodb.ClusterFixture.sleep; -import static com.mongodb.internal.operation.CommandBatchCursorHelper.MESSAGE_IF_CLOSED_AS_CURSOR; -import static java.lang.String.format; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @@ -96,8 +82,6 @@ void shouldReturnResultOnNext() { //then assertEquals(RESULT_FROM_NEW_CURSOR, next); - assertTimeoutWasRefreshedForOperation(operationContextCaptor -> - verify(this.cursor).next(operationContextCaptor.capture())); verify(this.cursor, times(1)).next(any()); verify(this.cursor, atLeastOnce()).getPostBatchResumeToken(); @@ -106,60 +90,6 @@ void shouldReturnResultOnNext() { verifyNoMoreInteractions(changeStreamOperation); } - @Test - @DisplayName("should throw timeout exception without resume attempt on next") - void shouldThrowTimeoutExceptionWithoutResumeAttemptOnNext() { - when(cursor.next(any())).thenThrow(new MongoOperationTimeoutException("timeout")); - ChangeStreamBatchCursor cursor = createChangeStreamCursor(); - //when - assertThrows(MongoOperationTimeoutException.class, cursor::next); - - //then - verify(this.cursor, times(1)).next(any()); - verify(this.cursor, atLeastOnce()).getPostBatchResumeToken(); - verifyNoMoreInteractions(this.cursor); - verifyNoResumeAttemptCalled(); - } - - @Test - @DisplayName("should not refresh timeout on next() after cursor close() when resume attempt is made") - void shouldNotRefreshTimeoutOnNextAfterCloseWhenResumeAttemptIsMade() { - // given - when(cursor.next(any())).thenThrow(new MongoOperationTimeoutException("timeout")); - ChangeStreamBatchCursor cursor = createChangeStreamCursor(); - // when - assertThrows(MongoOperationTimeoutException.class, cursor::next); - // trigger resume attempt to close the cursor - cursor.next(); - - // then - TimeoutContext timeoutContextForClose = captureTimeoutContext(captor -> verify(this.cursor) - .close(captor.capture())); - TimeoutContext timeoutContextForNext = captureTimeoutContext(captor -> verify(newCursor) - .next(captor.capture())); - assertEquals(timeoutContextForNext.getTimeout(), timeoutContextForClose.getTimeout(), - "Timeout should not be refreshed on close after resume attempt"); - } - - @Test - @DisplayName("should not refresh timeout on close() after cursor next() when resume attempt is made") - void shouldNotRefreshTimeoutOnCloseAfterNextWhenResumeAttemptIsMade() { - // given - when(cursor.next(any())).thenThrow(new MongoNotPrimaryException(new BsonDocument(), new ServerAddress())); - ChangeStreamBatchCursor cursor = createChangeStreamCursor(); - - // when - cursor.next(); - - // then - TimeoutContext timeoutContextForNext = captureTimeoutContext(captor -> verify(this.cursor) - .next(captor.capture())); - TimeoutContext timeoutContextForClose = captureTimeoutContext(captor -> verify(this.cursor) - .close(captor.capture())); - assertEquals(timeoutContextForNext.getTimeout(), timeoutContextForClose.getTimeout(), - "Timeout should not be refreshed on close after resume attempt"); - } - @Test @DisplayName("should perform resume attempt on next when resumable error is thrown") void shouldPerformResumeAttemptOnNextWhenResumableErrorIsThrown() { @@ -172,8 +102,6 @@ void shouldPerformResumeAttemptOnNextWhenResumableErrorIsThrown() { //then assertEquals(RESULT_FROM_NEW_CURSOR, next); - assertTimeoutWasRefreshedForOperation(operationContextCaptor -> - verify(newCursor).next(operationContextCaptor.capture())); verify(this.cursor, times(1)).next(any()); verify(this.cursor, atLeastOnce()).getPostBatchResumeToken(); verifyResumeAttemptCalled(); @@ -185,147 +113,6 @@ void shouldPerformResumeAttemptOnNextWhenResumableErrorIsThrown() { verifyNoMoreInteractions(changeStreamOperation); } - - @Test - @DisplayName("should resume only once on subsequent calls after timeout error") - void shouldResumeOnlyOnceOnSubsequentCallsAfterTimeoutError() { - when(cursor.next(any())).thenThrow(new MongoOperationTimeoutException("timeout")); - ChangeStreamBatchCursor cursor = createChangeStreamCursor(); - //when - assertThrows(MongoOperationTimeoutException.class, cursor::next); - - //then - assertTimeoutWasRefreshedForOperation(operationContextCaptor -> - verify(this.cursor).next(operationContextCaptor.capture())); - verify(this.cursor, times(1)).next(any()); - verify(this.cursor, atLeastOnce()).getPostBatchResumeToken(); - verifyNoMoreInteractions(this.cursor); - verifyNoResumeAttemptCalled(); - clearInvocations(this.cursor, newCursor, timeoutContext, changeStreamOperation, readBinding); - - //when seconds next is called. Resume is attempted. - sleep(TIMEOUT_CONSUMPTION_SLEEP_MS); - List next = cursor.next(); - - //then - assertEquals(Collections.emptyList(), next); - verify(this.cursor, times(1)).close(any()); - verifyNoMoreInteractions(this.cursor); - assertTimeoutWasRefreshedForOperation(operationContextCaptor -> - verify(newCursor).next(operationContextCaptor.capture())); - verify(changeStreamOperation).setChangeStreamOptionsForResume(resumeToken, maxWireVersion); - verify(changeStreamOperation, times(1)).getDecoder(); - verify(changeStreamOperation, times(1)).execute(any(ReadBinding.class), any()); - verifyNoMoreInteractions(changeStreamOperation); - verify(newCursor, times(1)).next(any()); - verify(newCursor, atLeastOnce()).getPostBatchResumeToken(); - clearInvocations(this.cursor, newCursor, timeoutContext, changeStreamOperation, readBinding); - - //when third next is called. No resume is attempted. - sleep(TIMEOUT_CONSUMPTION_SLEEP_MS); - List next2 = cursor.next(); - - //then - assertEquals(Collections.emptyList(), next2); - verifyNoInteractions(this.cursor); - assertTimeoutWasRefreshedForOperation(operationContextCaptor -> - verify(newCursor).next(operationContextCaptor.capture())); - verify(newCursor, times(1)).next(any()); - verify(newCursor, atLeastOnce()).getPostBatchResumeToken(); - verifyNoMoreInteractions(newCursor); - verify(changeStreamOperation, times(1)).getDecoder(); - verifyNoMoreInteractions(changeStreamOperation); - verifyNoInteractions(readBinding); - verifyNoMoreInteractions(changeStreamOperation); - } - - @Test - @DisplayName("should propagate any errors occurred in aggregate operation during creating new change stream when previous next timed out") - void shouldPropagateAnyErrorsOccurredInAggregateOperation() { - when(cursor.next(any())).thenThrow(new MongoOperationTimeoutException("timeout")); - MongoNotPrimaryException resumableError = new MongoNotPrimaryException(new BsonDocument(), new ServerAddress()); - when(changeStreamOperation.execute(any(ReadBinding.class), any())).thenThrow(resumableError); - - ChangeStreamBatchCursor cursor = createChangeStreamCursor(); - //when - assertThrows(MongoOperationTimeoutException.class, cursor::next); - clearInvocations(this.cursor, newCursor, timeoutContext, changeStreamOperation, readBinding); - assertThrows(MongoNotPrimaryException.class, cursor::next); - - //then - verifyResumeAttemptCalled(); - verifyNoMoreInteractions(changeStreamOperation); - verifyNoInteractions(newCursor); - } - - - @Test - @DisplayName("should perform a resume attempt in subsequent next call when previous resume attempt in next timed out") - void shouldResumeAfterTimeoutInAggregateOnNextCall() { - //given - ChangeStreamBatchCursor cursor = createChangeStreamCursor(); - - //first next operation times out on getMore - when(this.cursor.next(any())).thenThrow(new MongoOperationTimeoutException("timeout during next call")); - assertThrows(MongoOperationTimeoutException.class, cursor::next); - clearInvocations(this.cursor, newCursor, timeoutContext, changeStreamOperation, readBinding); - - //second next operation times out on resume attempt when creating change stream - when(changeStreamOperation.execute(any(ReadBinding.class), any())).thenThrow( - new MongoOperationTimeoutException("timeout during resumption")); - assertThrows(MongoOperationTimeoutException.class, cursor::next); - clearInvocations(this.cursor, newCursor, timeoutContext, changeStreamOperation, readBinding); - - doReturn(newChangeStreamCursor).when(changeStreamOperation).execute(any(ReadBinding.class), any()); - - //when third operation succeeds to resume and call next - sleep(TIMEOUT_CONSUMPTION_SLEEP_MS); - List next = cursor.next(); - - //then - assertEquals(RESULT_FROM_NEW_CURSOR, next); - verifyResumeAttemptCalled(); - verify(changeStreamOperation, times(1)).getDecoder(); - verifyNoMoreInteractions(changeStreamOperation); - - assertTimeoutWasRefreshedForOperation(operationContextCaptor -> - verify(newCursor).next(operationContextCaptor.capture())); - verify(newCursor, times(1)).next(any()); - verify(newCursor, atLeastOnce()).getPostBatchResumeToken(); - verifyNoMoreInteractions(newCursor); - } - - @Test - @DisplayName("should close change stream when resume operation fails due to non-timeout error") - void shouldCloseChangeStreamWhenResumeOperationFailsDueToNonTimeoutError() { - //given - ChangeStreamBatchCursor cursor = createChangeStreamCursor(); - - //first next operation times out on getMore - when(this.cursor.next(any())).thenThrow(new MongoOperationTimeoutException("timeout during next call")); - assertThrows(MongoOperationTimeoutException.class, cursor::next); - clearInvocations(this.cursor, newCursor, timeoutContext, changeStreamOperation, readBinding); - - //when second next operation errors on resume attempt when creating change stream - when(changeStreamOperation.execute(any(ReadBinding.class), any())).thenThrow( - new MongoNotPrimaryException(new BsonDocument(), new ServerAddress())); - assertThrows(MongoNotPrimaryException.class, cursor::next); - - //then - verifyResumeAttemptCalled(); - verifyNoMoreInteractions(changeStreamOperation); - verifyNoInteractions(newCursor); - clearInvocations(this.cursor, newCursor, timeoutContext, changeStreamOperation, readBinding); - - //when third next operation errors with cursor closed exception - doThrow(new IllegalStateException(MESSAGE_IF_CLOSED_AS_CURSOR)).when(this.cursor).next(any()); - MongoException mongoException = assertThrows(MongoException.class, cursor::next); - - //then - assertEquals(MESSAGE_IF_CLOSED_AS_CURSOR, mongoException.getMessage()); - verifyNoResumeAttemptCalled(); - } - private ChangeStreamBatchCursor createChangeStreamCursor() { ChangeStreamBatchCursor cursor = new ChangeStreamBatchCursor<>(changeStreamOperation, this.cursor, readBinding, operationContext, null, maxWireVersion); @@ -333,13 +120,6 @@ private ChangeStreamBatchCursor createChangeStreamCursor() { return cursor; } - private void verifyNoResumeAttemptCalled() { - verifyNoInteractions(changeStreamOperation); - verifyNoInteractions(newCursor); - verifyNoInteractions(readBinding); - } - - private void verifyResumeAttemptCalled() { verify(cursor, times(1)).close(any()); verify(changeStreamOperation).setChangeStreamOptionsForResume(resumeToken, maxWireVersion); @@ -359,9 +139,8 @@ void setUp() { when(serverDescription.getMaxWireVersion()).thenReturn(maxWireVersion); timeoutContext = spy(new TimeoutContext(new TimeoutSettings( - 10, 10, 10, TIMEOUT_MILLISECONDS, 0 + 10, 10, 10, 0 ))); - when(timeoutContext.hasTimeoutMS()).thenReturn(true); operationContext = spy(new OperationContext( IgnorableRequestContext.INSTANCE, @@ -404,34 +183,4 @@ void setUp() { return newChangeStreamCursor; }); } - - private void assertTimeoutWasRefreshedForOperation(final TimeoutContext timeoutContextUsedForOperation) { - assertNotNull(timeoutContextUsedForOperation.getTimeout(), "TimeoutMs was not set"); - timeoutContextUsedForOperation.getTimeout().run(TimeUnit.MILLISECONDS, () -> { - Assertions.fail("Non-infinite timeout was not expected to be refreshed to infinity"); - }, - (remainingMs) -> { - int allowedDifference = 20; - boolean originalAndRefreshedTimeoutDifference = TIMEOUT_MILLISECONDS - remainingMs < allowedDifference; - assertTrue(originalAndRefreshedTimeoutDifference, format("Timeout was expected to be refreshed " - + "to original timeout: %d, but remaining time was: %d. Allowed difference was: %d ", - TIMEOUT_MILLISECONDS, - remainingMs, - allowedDifference)); - }, - () -> { - Assertions.fail("Timeout was expected to be refreshed"); - }); - } - - private void assertTimeoutWasRefreshedForOperation(final Consumer> capturerConsumer) { - assertTimeoutWasRefreshedForOperation(captureTimeoutContext(capturerConsumer)); - } - - private static TimeoutContext captureTimeoutContext(final Consumer> capturerConsumer) { - ArgumentCaptor operationContextCaptor = ArgumentCaptor.forClass(OperationContext.class); - capturerConsumer.accept(operationContextCaptor); - TimeoutContext timeoutContextUsedForOperation = operationContextCaptor.getValue().getTimeoutContext(); - return timeoutContextUsedForOperation; - } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/CommandBatchCursorSpecification.groovy b/driver-core/src/test/unit/com/mongodb/internal/operation/CommandBatchCursorSpecification.groovy index d9375727bc3..ee648a2491b 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/CommandBatchCursorSpecification.groovy +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/CommandBatchCursorSpecification.groovy @@ -24,7 +24,6 @@ import com.mongodb.MongoSocketException import com.mongodb.MongoSocketOpenException import com.mongodb.ServerAddress import com.mongodb.ServerCursor -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.connection.ConnectionDescription import com.mongodb.connection.ServerConnectionState import com.mongodb.connection.ServerDescription @@ -46,8 +45,6 @@ import org.bson.Document import org.bson.codecs.DocumentCodec import spock.lang.Specification -import java.util.concurrent.TimeUnit - import static com.mongodb.ReadPreference.primary import static com.mongodb.internal.operation.CommandBatchCursorHelper.MESSAGE_IF_CLOSED_AS_CURSOR import static com.mongodb.internal.operation.CommandBatchCursorHelper.MESSAGE_IF_CONCURRENT_OPERATION @@ -74,7 +71,7 @@ class CommandBatchCursorSpecification extends Specification { when: def commandCoreCursor = new CommandCursor<>(firstBatch, batchSize, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new CommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, maxTimeMS, operationContext, commandCoreCursor) + def cursor = new CommandBatchCursor(maxTimeMS, operationContext, commandCoreCursor) then: 1 * timeoutContext.withMaxTimeOverride(*_) @@ -110,7 +107,7 @@ class CommandBatchCursorSpecification extends Specification { def connection = referenceCountedConnection(serverVersion) def connectionSource = getConnectionSource(connection) def commandCoreCursor = new CommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new CommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new CommandBatchCursor(0, operationContext, commandCoreCursor) when: cursor.close() @@ -138,7 +135,7 @@ class CommandBatchCursorSpecification extends Specification { when: def firstBatch = createCommandResult(FIRST_BATCH, 0) def commandCoreCursor = new CommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new CommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new CommandBatchCursor(0, operationContext, commandCoreCursor) then: cursor.next() == FIRST_BATCH @@ -162,7 +159,7 @@ class CommandBatchCursorSpecification extends Specification { when: def firstBatch = createCommandResult([], CURSOR_ID) def commandCoreCursor = new CommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new CommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new CommandBatchCursor(0, operationContext, commandCoreCursor) def batch = cursor.next() then: @@ -216,7 +213,7 @@ class CommandBatchCursorSpecification extends Specification { when: def commandCoreCursor = new CommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new CommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new CommandBatchCursor(0, operationContext, commandCoreCursor) List batch = cursor.next() then: @@ -269,7 +266,7 @@ class CommandBatchCursorSpecification extends Specification { when: def commandCoreCursor = new CommandCursor<>(createCommandResult(FIRST_BATCH, 42), 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new CommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new CommandBatchCursor(0, operationContext, commandCoreCursor) def batch = cursor.next() then: @@ -305,7 +302,7 @@ class CommandBatchCursorSpecification extends Specification { when: def commandCoreCursor = new CommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new CommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new CommandBatchCursor(0, operationContext, commandCoreCursor) def batch = cursor.next() then: @@ -344,7 +341,7 @@ class CommandBatchCursorSpecification extends Specification { def connectionSource = getConnectionSourceWithResult(ServerType.STANDALONE) { throw MONGO_EXCEPTION } def firstBatch = createCommandResult() def commandCoreCursor = new CommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new CommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new CommandBatchCursor(0, operationContext, commandCoreCursor) when: cursor.close() @@ -365,7 +362,7 @@ class CommandBatchCursorSpecification extends Specification { when: def firstBatch = createCommandResult() def commandCoreCursor = new CommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new CommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new CommandBatchCursor(0, operationContext, commandCoreCursor) then: cursor.next() @@ -392,7 +389,7 @@ class CommandBatchCursorSpecification extends Specification { when: def firstBatch = createCommandResult() def commandCoreCursor = new CommandCursor<>(firstBatch, 0, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new CommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 0, operationContext, commandCoreCursor) + def cursor = new CommandBatchCursor(0, operationContext, commandCoreCursor) then: connectionSource.getCount() == 1 @@ -451,7 +448,7 @@ class CommandBatchCursorSpecification extends Specification { def initialResults = createCommandResult([]) def commandCoreCursor = new CommandCursor<>(initialResults, 2, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new CommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 100, operationContext, commandCoreCursor) + def cursor = new CommandBatchCursor(100, operationContext, commandCoreCursor) when: cursor.close() @@ -477,7 +474,7 @@ class CommandBatchCursorSpecification extends Specification { def initialResults = createCommandResult([]) def commandCoreCursor = new CommandCursor<>(initialResults, 2, CODEC, null, connectionSource, initialConnection, false, null) - def cursor = new CommandBatchCursor(TimeoutMode.CURSOR_LIFETIME, 100, operationContext, commandCoreCursor) + def cursor = new CommandBatchCursor(100, operationContext, commandCoreCursor) when: cursor.close() @@ -605,7 +602,7 @@ class CommandBatchCursorSpecification extends Specification { OperationContext getOperationContext() { def timeoutContext = Spy(new TimeoutContext(TimeoutSettings.create( - MongoClientSettings.builder().timeout(3, TimeUnit.SECONDS).build()))) + MongoClientSettings.builder().build()))) Spy(new OperationContext( IgnorableRequestContext.INSTANCE, NoOpSessionContext.INSTANCE, diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/CommandBatchCursorTest.java b/driver-core/src/test/unit/com/mongodb/internal/operation/CommandBatchCursorTest.java index cdd0005d74d..14ac0bd533f 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/CommandBatchCursorTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/CommandBatchCursorTest.java @@ -17,7 +17,6 @@ package com.mongodb.internal.operation; import com.mongodb.MongoClientSettings; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.IgnorableRequestContext; import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.TimeoutSettings; @@ -32,7 +31,6 @@ import java.time.Duration; -import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; @@ -48,8 +46,9 @@ class CommandBatchCursorTest { @BeforeEach void setUp() { cursor = mock(Cursor.class); + MongoClientSettings.Builder builder = MongoClientSettings.builder(); timeoutContext = spy(new TimeoutContext(TimeoutSettings.create( - MongoClientSettings.builder().timeout(TIMEOUT.toMillis(), MILLISECONDS).build()))); + builder.build()))); operationContext = spy(new OperationContext( IgnorableRequestContext.INSTANCE, NoOpSessionContext.INSTANCE, @@ -59,7 +58,6 @@ void setUp() { private CommandBatchCursor createBatchCursor(final long maxTimeMS) { return new CommandBatchCursor<>( - TimeoutMode.CURSOR_LIFETIME, maxTimeMS, operationContext, cursor); diff --git a/driver-core/src/test/unit/com/mongodb/internal/operation/CommandCursorTest.java b/driver-core/src/test/unit/com/mongodb/internal/operation/CommandCursorTest.java index 2f75bba9821..9366ca19312 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/operation/CommandCursorTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/operation/CommandCursorTest.java @@ -18,7 +18,6 @@ import com.mongodb.MongoClientSettings; import com.mongodb.MongoNamespace; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoSocketException; import com.mongodb.ServerAddress; import com.mongodb.connection.ConnectionDescription; @@ -46,13 +45,10 @@ import java.time.Duration; import static com.mongodb.internal.operation.OperationUnitSpecification.getMaxWireVersionForServerVersion; -import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -89,8 +85,9 @@ void setUp() { when(mockConnection.retain()).thenReturn(mockConnection); connectionSource = mock(ConnectionSource.class); + MongoClientSettings.Builder builder = MongoClientSettings.builder(); timeoutContext = spy(new TimeoutContext(TimeoutSettings.create( - MongoClientSettings.builder().timeout(TIMEOUT.toMillis(), MILLISECONDS).build()))); + builder.build()))); operationContext = spy(new OperationContext( IgnorableRequestContext.INSTANCE, NoOpSessionContext.INSTANCE, @@ -119,52 +116,6 @@ void shouldSkipKillsCursorsCommandWhenNetworkErrorOccurs() { verify(mockConnection, times(1)).command(eq(NAMESPACE.getDatabaseName()), any(), any(), any(), any(), any()); } - @Test - void shouldNotSkipKillsCursorsCommandWhenTimeoutExceptionDoesNotHaveNetworkErrorCause() { - //given - when(mockConnection.command(eq(NAMESPACE.getDatabaseName()), any(), any(), any(), any(), any())).thenThrow( - new MongoOperationTimeoutException("test")); - when(serverDescription.getType()).thenReturn(ServerType.LOAD_BALANCER); - - Cursor cursor = createCoreCursor(); - - //when - assertThrows(MongoOperationTimeoutException.class, () -> cursor.next(operationContext)); - - cursor.close(operationContext); - - - //then - verify(mockConnection, times(2)).command(any(), - any(), any(), any(), any(), any()); - verify(mockConnection, times(1)).command(eq(NAMESPACE.getDatabaseName()), - argThat(bsonDocument -> bsonDocument.containsKey("getMore")), any(), any(), any(), any()); - verify(mockConnection, times(1)).command(eq(NAMESPACE.getDatabaseName()), - argThat(bsonDocument -> bsonDocument.containsKey("killCursors")), any(), any(), any(), any()); - } - - @Test - void shouldSkipKillsCursorsCommandWhenTimeoutExceptionHaveNetworkErrorCause() { - //given - when(mockConnection.command(eq(NAMESPACE.getDatabaseName()), any(), any(), any(), any(), any())).thenThrow( - new MongoOperationTimeoutException("test", new MongoSocketException("test", new ServerAddress()))); - when(serverDescription.getType()).thenReturn(ServerType.LOAD_BALANCER); - - Cursor cursor = createCoreCursor(); - - //when - assertThrows(MongoOperationTimeoutException.class, () -> cursor.next(operationContext)); - cursor.close(operationContext); - - //then - verify(mockConnection, times(1)).command(any(), - any(), any(), any(), any(), any()); - verify(mockConnection, times(1)).command(eq(NAMESPACE.getDatabaseName()), - argThat(bsonDocument -> bsonDocument.containsKey("getMore")), any(), any(), any(), any()); - verify(mockConnection, never()).command(eq(NAMESPACE.getDatabaseName()), - argThat(bsonDocument -> bsonDocument.containsKey("killCursors")), any(), any(), any(), any()); - } - private Cursor createCoreCursor() { return new CommandCursor<>( COMMAND_CURSOR_DOCUMENT, diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt index 439a0ccbb29..8e546c4690c 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncAggregateIterable.kt @@ -17,7 +17,6 @@ package com.mongodb.kotlin.client.coroutine.syncadapter import com.mongodb.ExplainVerbosity import com.mongodb.client.AggregateIterable as JAggregateIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.kotlin.client.coroutine.AggregateFlow import java.util.concurrent.TimeUnit @@ -59,10 +58,6 @@ data class SyncAggregateIterable(val wrapped: AggregateFlow) : override fun let(variables: Bson?): SyncAggregateIterable = apply { wrapped.let(variables) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncAggregateIterable = apply { - wrapped.timeoutMode(timeoutMode) - } - override fun explain(): Document = runBlocking { wrapped.explain() } override fun explain(verbosity: ExplainVerbosity): Document = runBlocking { wrapped.explain(verbosity) } diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncDistinctIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncDistinctIterable.kt index 1c5a382c8da..c4bae607cf3 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncDistinctIterable.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncDistinctIterable.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client.coroutine.syncadapter import com.mongodb.client.DistinctIterable as JDistinctIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.kotlin.client.coroutine.DistinctFlow import java.util.concurrent.TimeUnit @@ -35,7 +34,4 @@ data class SyncDistinctIterable(val wrapped: DistinctFlow) : override fun comment(comment: BsonValue?): SyncDistinctIterable = apply { wrapped.comment(comment) } override fun hint(hint: Bson?): SyncDistinctIterable = apply { wrapped.hint(hint) } override fun hintString(hint: String?): SyncDistinctIterable = apply { wrapped.hintString(hint) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncDistinctIterable = apply { - wrapped.timeoutMode(timeoutMode) - } } diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncFindIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncFindIterable.kt index 6c500a9cf90..b9e3a6665d6 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncFindIterable.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncFindIterable.kt @@ -18,7 +18,6 @@ package com.mongodb.kotlin.client.coroutine.syncadapter import com.mongodb.CursorType import com.mongodb.ExplainVerbosity import com.mongodb.client.FindIterable as JFindIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.kotlin.client.coroutine.FindFlow import java.util.concurrent.TimeUnit @@ -77,7 +76,6 @@ data class SyncFindIterable(val wrapped: FindFlow) : JFindIterable = apply { wrapped.returnKey(returnKey) } override fun showRecordId(showRecordId: Boolean): SyncFindIterable = apply { wrapped.showRecordId(showRecordId) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncFindIterable = apply { wrapped.timeoutMode(timeoutMode) } override fun explain(): Document = runBlocking { wrapped.explain() } diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListCollectionsIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListCollectionsIterable.kt index ab1853c756d..b16395db709 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListCollectionsIterable.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListCollectionsIterable.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client.coroutine.syncadapter import com.mongodb.client.ListCollectionsIterable as JListCollectionsIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.kotlin.client.coroutine.ListCollectionsFlow import java.util.concurrent.TimeUnit import org.bson.BsonValue @@ -33,7 +32,4 @@ data class SyncListCollectionsIterable(val wrapped: ListCollectionsFlow override fun filter(filter: Bson?): SyncListCollectionsIterable = apply { wrapped.filter(filter) } override fun comment(comment: String?): SyncListCollectionsIterable = apply { wrapped.comment(comment) } override fun comment(comment: BsonValue?): SyncListCollectionsIterable = apply { wrapped.comment(comment) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncListCollectionsIterable = apply { - wrapped.timeoutMode(timeoutMode) - } } diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListDatabasesIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListDatabasesIterable.kt index 4563dfe4a4f..3acd5581f1b 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListDatabasesIterable.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListDatabasesIterable.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client.coroutine.syncadapter import com.mongodb.client.ListDatabasesIterable as JListDatabasesIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.kotlin.client.coroutine.ListDatabasesFlow import java.util.concurrent.TimeUnit import org.bson.BsonValue @@ -42,7 +41,4 @@ data class SyncListDatabasesIterable(val wrapped: ListDatabasesFlow) override fun comment(comment: String?): SyncListDatabasesIterable = apply { wrapped.comment(comment) } override fun comment(comment: BsonValue?): SyncListDatabasesIterable = apply { wrapped.comment(comment) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncListDatabasesIterable = apply { - wrapped.timeoutMode(timeoutMode) - } } diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListIndexesIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListIndexesIterable.kt index 0e329c7bcdd..030b89bb1bf 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListIndexesIterable.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListIndexesIterable.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client.coroutine.syncadapter import com.mongodb.client.ListIndexesIterable as JListIndexesIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.kotlin.client.coroutine.ListIndexesFlow import java.util.concurrent.TimeUnit import org.bson.BsonValue @@ -29,7 +28,4 @@ data class SyncListIndexesIterable(val wrapped: ListIndexesFlow) : } override fun comment(comment: String?): SyncListIndexesIterable = apply { wrapped.comment(comment) } override fun comment(comment: BsonValue?): SyncListIndexesIterable = apply { wrapped.comment(comment) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncListIndexesIterable = apply { - wrapped.timeoutMode(timeoutMode) - } } diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListSearchIndexesIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListSearchIndexesIterable.kt index a7df87779df..62af2fe0c7c 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListSearchIndexesIterable.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncListSearchIndexesIterable.kt @@ -17,7 +17,6 @@ package com.mongodb.kotlin.client.coroutine.syncadapter import com.mongodb.ExplainVerbosity import com.mongodb.client.ListSearchIndexesIterable as JListSearchIndexesIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.kotlin.client.coroutine.ListSearchIndexesFlow import java.util.concurrent.TimeUnit @@ -46,9 +45,6 @@ internal class SyncListSearchIndexesIterable(val wrapped: ListSearchInd override fun comment(comment: String?): SyncListSearchIndexesIterable = apply { wrapped.comment(comment) } override fun comment(comment: BsonValue?): SyncListSearchIndexesIterable = apply { wrapped.comment(comment) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncListSearchIndexesIterable = apply { - wrapped.timeoutMode(timeoutMode) - } override fun explain(): Document = runBlocking { wrapped.explain() } override fun explain(verbosity: ExplainVerbosity): Document = runBlocking { wrapped.explain(verbosity) } diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMapReduceIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMapReduceIterable.kt index 8e5fc82455a..9aab6ed51a6 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMapReduceIterable.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMapReduceIterable.kt @@ -18,7 +18,6 @@ package com.mongodb.kotlin.client.coroutine.syncadapter import com.mongodb.client.MapReduceIterable as JMapReduceIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.client.model.MapReduceAction import com.mongodb.kotlin.client.coroutine.MapReduceFlow @@ -58,7 +57,4 @@ data class SyncMapReduceIterable(val wrapped: MapReduceFlow) : } override fun collation(collation: Collation?): SyncMapReduceIterable = apply { wrapped.collation(collation) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncMapReduceIterable = apply { - wrapped.timeoutMode(timeoutMode) - } } diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCluster.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCluster.kt index 01d0e27ff58..a0d98c523ec 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCluster.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCluster.kt @@ -29,7 +29,6 @@ import com.mongodb.client.model.bulk.ClientBulkWriteOptions import com.mongodb.client.model.bulk.ClientBulkWriteResult import com.mongodb.client.model.bulk.ClientNamespacedWriteModel import com.mongodb.kotlin.client.coroutine.MongoCluster -import java.util.concurrent.TimeUnit import kotlinx.coroutines.runBlocking import org.bson.Document import org.bson.codecs.configuration.CodecRegistry @@ -44,8 +43,6 @@ internal open class SyncMongoCluster(open val wrapped: MongoCluster) : JMongoClu override fun getReadConcern(): ReadConcern = wrapped.readConcern - override fun getTimeout(timeUnit: TimeUnit): Long? = wrapped.timeout(timeUnit) - override fun withCodecRegistry(codecRegistry: CodecRegistry): SyncMongoCluster = SyncMongoCluster(wrapped.withCodecRegistry(codecRegistry)) @@ -58,9 +55,6 @@ internal open class SyncMongoCluster(open val wrapped: MongoCluster) : JMongoClu override fun withWriteConcern(writeConcern: WriteConcern): SyncMongoCluster = SyncMongoCluster(wrapped.withWriteConcern(writeConcern)) - override fun withTimeout(timeout: Long, timeUnit: TimeUnit): SyncMongoCluster = - SyncMongoCluster(wrapped.withTimeout(timeout, timeUnit)) - override fun getDatabase(databaseName: String): MongoDatabase = SyncMongoDatabase(wrapped.getDatabase(databaseName)) override fun startSession(): ClientSession = SyncClientSession(runBlocking { wrapped.startSession() }, this) diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCollection.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCollection.kt index fa26fae86c1..756c884608a 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCollection.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoCollection.kt @@ -55,7 +55,6 @@ import com.mongodb.client.result.InsertManyResult import com.mongodb.client.result.InsertOneResult import com.mongodb.client.result.UpdateResult import com.mongodb.kotlin.client.coroutine.MongoCollection -import java.util.concurrent.TimeUnit import kotlinx.coroutines.flow.toCollection import kotlinx.coroutines.runBlocking import org.bson.Document @@ -75,7 +74,6 @@ data class SyncMongoCollection(val wrapped: MongoCollection) : JMong override fun getWriteConcern(): WriteConcern = wrapped.writeConcern override fun getReadConcern(): ReadConcern = wrapped.readConcern - override fun getTimeout(timeUnit: TimeUnit): Long? = wrapped.timeout(timeUnit) override fun withDocumentClass(clazz: Class): SyncMongoCollection = SyncMongoCollection(wrapped.withDocumentClass(clazz)) @@ -92,9 +90,6 @@ data class SyncMongoCollection(val wrapped: MongoCollection) : JMong override fun withReadConcern(readConcern: ReadConcern): SyncMongoCollection = SyncMongoCollection(wrapped.withReadConcern(readConcern)) - override fun withTimeout(timeout: Long, timeUnit: TimeUnit): com.mongodb.client.MongoCollection = - SyncMongoCollection(wrapped.withTimeout(timeout, timeUnit)) - override fun countDocuments(): Long = runBlocking { wrapped.countDocuments() } override fun countDocuments(filter: Bson): Long = runBlocking { wrapped.countDocuments(filter) } diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoDatabase.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoDatabase.kt index ae83a1443b7..ee4c4d23040 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoDatabase.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoDatabase.kt @@ -23,7 +23,6 @@ import com.mongodb.client.MongoDatabase as JMongoDatabase import com.mongodb.client.model.CreateCollectionOptions import com.mongodb.client.model.CreateViewOptions import com.mongodb.kotlin.client.coroutine.MongoDatabase -import java.util.concurrent.TimeUnit import kotlinx.coroutines.runBlocking import org.bson.Document import org.bson.codecs.configuration.CodecRegistry @@ -40,8 +39,6 @@ data class SyncMongoDatabase(val wrapped: MongoDatabase) : JMongoDatabase { override fun getReadConcern(): ReadConcern = wrapped.readConcern - override fun getTimeout(timeUnit: TimeUnit): Long? = wrapped.timeout(timeUnit) - override fun withCodecRegistry(codecRegistry: CodecRegistry): SyncMongoDatabase = SyncMongoDatabase(wrapped.withCodecRegistry(codecRegistry)) @@ -54,9 +51,6 @@ data class SyncMongoDatabase(val wrapped: MongoDatabase) : JMongoDatabase { override fun withReadConcern(readConcern: ReadConcern): SyncMongoDatabase = SyncMongoDatabase(wrapped.withReadConcern(readConcern)) - override fun withTimeout(timeout: Long, timeUnit: TimeUnit): SyncMongoDatabase = - SyncMongoDatabase(wrapped.withTimeout(timeout, timeUnit)) - override fun getCollection(collectionName: String): MongoCollection = SyncMongoCollection(wrapped.getCollection(collectionName, Document::class.java)) diff --git a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoIterable.kt b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoIterable.kt index 98ab0d93b75..e7a22506f0a 100644 --- a/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoIterable.kt +++ b/driver-kotlin-coroutine/src/integrationTest/kotlin/com/mongodb/kotlin/client/coroutine/syncadapter/SyncMongoIterable.kt @@ -18,7 +18,6 @@ package com.mongodb.kotlin.client.coroutine.syncadapter import com.mongodb.Function import com.mongodb.client.MongoCursor import com.mongodb.client.MongoIterable as JMongoIterable -import com.mongodb.client.cursor.TimeoutMode import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.map @@ -27,7 +26,6 @@ import kotlinx.coroutines.runBlocking open class SyncMongoIterable(private val delegate: Flow) : JMongoIterable { private var batchSize: Int? = null - private var timeoutMode: TimeoutMode? = null override fun iterator(): MongoCursor = cursor() diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt index a1debfd812f..73b763f1f2e 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlow.kt @@ -16,9 +16,6 @@ package com.mongodb.kotlin.client.coroutine import com.mongodb.ExplainVerbosity -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.reactivestreams.client.AggregatePublisher import java.util.concurrent.TimeUnit @@ -48,19 +45,6 @@ public class AggregateFlow(private val wrapped: AggregatePublisher) */ public fun batchSize(batchSize: Int): AggregateFlow = apply { wrapped.batchSize(batchSize) } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): AggregateFlow = apply { wrapped.timeoutMode(timeoutMode) } - /** * Aggregates documents according to the specified aggregation pipeline, which must end with an `$out` or `$merge` * stage. Calling this method is the preferred alternative to consuming this [AggregateFlow], because this method diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/DistinctFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/DistinctFlow.kt index 10eef030429..7894b478a6d 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/DistinctFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/DistinctFlow.kt @@ -15,9 +15,6 @@ */ package com.mongodb.kotlin.client.coroutine -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.lang.Nullable import com.mongodb.reactivestreams.client.DistinctPublisher @@ -45,19 +42,6 @@ public class DistinctFlow(private val wrapped: DistinctPublisher) : */ public fun batchSize(batchSize: Int): DistinctFlow = apply { wrapped.batchSize(batchSize) } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): DistinctFlow = apply { wrapped.timeoutMode(timeoutMode) } - /** * Sets the query filter to apply to the query. * diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/FindFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/FindFlow.kt index f0afb4e9937..5bd6d1a7a2f 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/FindFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/FindFlow.kt @@ -17,9 +17,6 @@ package com.mongodb.kotlin.client.coroutine import com.mongodb.CursorType import com.mongodb.ExplainVerbosity -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.reactivestreams.client.FindPublisher import java.util.concurrent.TimeUnit @@ -48,24 +45,6 @@ public class FindFlow(private val wrapped: FindPublisher) : Flow */ public fun batchSize(batchSize: Int): FindFlow = apply { wrapped.batchSize(batchSize) } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * If the `timeout` is set then: - * * For non-tailable cursors, the default value of timeoutMode is [TimeoutMode.CURSOR_LIFETIME] - * * For tailable cursors, the default value of timeoutMode is [TimeoutMode.ITERATION] and its an error to configure - * it as: [TimeoutMode.CURSOR_LIFETIME] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): FindFlow = apply { wrapped.timeoutMode(timeoutMode) } - /** * Sets the query filter to apply to the query. * diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListCollectionsFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListCollectionsFlow.kt index a6dfd770e08..cdfd901407a 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListCollectionsFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListCollectionsFlow.kt @@ -15,9 +15,6 @@ */ package com.mongodb.kotlin.client.coroutine -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.ListCollectionsPublisher import java.util.concurrent.TimeUnit import kotlinx.coroutines.flow.Flow @@ -44,21 +41,6 @@ public class ListCollectionsFlow(private val wrapped: ListCollectionsPu */ public fun batchSize(batchSize: Int): ListCollectionsFlow = apply { wrapped.batchSize(batchSize) } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): ListCollectionsFlow = apply { - wrapped.timeoutMode(timeoutMode) - } - /** * Sets the maximum execution time on the server for this operation. * diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListDatabasesFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListDatabasesFlow.kt index 473cde087b6..ac610ce22cf 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListDatabasesFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListDatabasesFlow.kt @@ -15,9 +15,6 @@ */ package com.mongodb.kotlin.client.coroutine -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.ListDatabasesPublisher import java.util.concurrent.TimeUnit import kotlinx.coroutines.flow.Flow @@ -43,19 +40,6 @@ public class ListDatabasesFlow(private val wrapped: ListDatabasesPublis */ public fun batchSize(batchSize: Int): ListDatabasesFlow = apply { wrapped.batchSize(batchSize) } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): ListDatabasesFlow = apply { wrapped.timeoutMode(timeoutMode) } - /** * Sets the maximum execution time on the server for this operation. * diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListIndexesFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListIndexesFlow.kt index b92453158a1..a09ae01ba09 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListIndexesFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListIndexesFlow.kt @@ -15,9 +15,6 @@ */ package com.mongodb.kotlin.client.coroutine -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.ListIndexesPublisher import java.util.concurrent.TimeUnit import kotlinx.coroutines.flow.Flow @@ -42,19 +39,6 @@ public class ListIndexesFlow(private val wrapped: ListIndexesPublisher< */ public fun batchSize(batchSize: Int): ListIndexesFlow = apply { wrapped.batchSize(batchSize) } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): ListIndexesFlow = apply { wrapped.timeoutMode(timeoutMode) } - /** * Sets the maximum execution time on the server for this operation. * diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListSearchIndexesFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListSearchIndexesFlow.kt index 1c7fe4ded5e..6d8d29a4d75 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListSearchIndexesFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/ListSearchIndexesFlow.kt @@ -16,9 +16,6 @@ package com.mongodb.kotlin.client.coroutine import com.mongodb.ExplainVerbosity -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.reactivestreams.client.ListSearchIndexesPublisher import java.util.concurrent.TimeUnit @@ -48,21 +45,6 @@ public class ListSearchIndexesFlow(private val wrapped: ListSearchIndex */ public fun batchSize(batchSize: Int): ListSearchIndexesFlow = apply { wrapped.batchSize(batchSize) } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): ListSearchIndexesFlow = apply { - wrapped.timeoutMode(timeoutMode) - } - /** * Sets an Atlas Search index name for this operation. * diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlow.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlow.kt index c43fe3842d5..538b8ec3ec2 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlow.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlow.kt @@ -17,9 +17,6 @@ package com.mongodb.kotlin.client.coroutine -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.client.model.MapReduceAction import com.mongodb.reactivestreams.client.MapReducePublisher @@ -53,19 +50,6 @@ public class MapReduceFlow(private val wrapped: MapReducePublisher) */ public fun batchSize(batchSize: Int): MapReduceFlow = apply { wrapped.batchSize(batchSize) } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): MapReduceFlow = apply { wrapped.timeoutMode(timeoutMode) } - /** * Aggregates documents to a collection according to the specified map-reduce function with the given options, which * must not emit results inline. Calling this method is the preferred alternative to consuming this [MapReduceFlow], diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoClient.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoClient.kt index 64832903b40..c100b542da6 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoClient.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoClient.kt @@ -15,7 +15,6 @@ */ package com.mongodb.kotlin.client.coroutine -import com.mongodb.ClientSessionOptions import com.mongodb.ConnectionString import com.mongodb.MongoClientSettings import com.mongodb.MongoDriverInformation @@ -24,7 +23,6 @@ import com.mongodb.lang.Nullable import com.mongodb.reactivestreams.client.MongoClient as JMongoClient import com.mongodb.reactivestreams.client.MongoClients as JMongoClients import java.io.Closeable -import java.util.concurrent.TimeUnit /** * A client-side representation of a MongoDB cluster. @@ -126,12 +124,3 @@ public class MongoClient(private val wrapped: JMongoClient) : MongoCluster(wrapp public fun appendMetadata(mongoDriverInformation: MongoDriverInformation): Unit = wrapped.appendMetadata(mongoDriverInformation) } - -/** - * ClientSessionOptions.Builder.defaultTimeout extension function - * - * @param defaultTimeout time in milliseconds - * @return the options - */ -public fun ClientSessionOptions.Builder.defaultTimeout(defaultTimeout: Long): ClientSessionOptions.Builder = - this.apply { defaultTimeout(defaultTimeout, TimeUnit.MILLISECONDS) } diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoCluster.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoCluster.kt index cf25ac5e8bf..b2c4aeb93a2 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoCluster.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoCluster.kt @@ -22,15 +22,12 @@ import com.mongodb.MongoException import com.mongodb.ReadConcern import com.mongodb.ReadPreference import com.mongodb.WriteConcern -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.client.model.bulk.ClientBulkWriteOptions import com.mongodb.client.model.bulk.ClientBulkWriteResult import com.mongodb.client.model.bulk.ClientNamespacedDeleteManyModel import com.mongodb.client.model.bulk.ClientNamespacedUpdateManyModel import com.mongodb.client.model.bulk.ClientNamespacedWriteModel import com.mongodb.reactivestreams.client.MongoCluster as JMongoCluster -import java.util.concurrent.TimeUnit import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitSingle @@ -65,27 +62,6 @@ public open class MongoCluster protected constructor(private val wrapped: JMongo public val writeConcern: WriteConcern get() = wrapped.writeConcern - /** - * The time limit for the full execution of an operation. - * - * If not null the following deprecated options will be ignored: `waitQueueTimeoutMS`, `socketTimeoutMS`, - * `wTimeoutMS`, `maxTimeMS` and `maxCommitTimeMS`. - * - `null` means that the timeout mechanism for operations will defer to using: - * - `waitQueueTimeoutMS`: The maximum wait time in milliseconds that a thread may wait for a connection to - * become available - * - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - * - `wTimeoutMS`: How long the server will wait for the write concern to be fulfilled before timing out. - * - `maxTimeMS`: The time limit for processing operations on a cursor. See: - * [cursor.maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS"). - * - `maxCommitTimeMS`: The maximum amount of time to allow a single `commitTransaction` command to execute. - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * @return the optional timeout duration - */ - @Alpha(Reason.CLIENT) - public fun timeout(timeUnit: TimeUnit = TimeUnit.MILLISECONDS): Long? = wrapped.getTimeout(timeUnit) - /** * Create a new MongoCluster instance with a different codec registry. * @@ -129,21 +105,6 @@ public open class MongoCluster protected constructor(private val wrapped: JMongo public fun withWriteConcern(newWriteConcern: WriteConcern): MongoCluster = MongoCluster(wrapped.withWriteConcern(newWriteConcern)) - /** - * Create a new MongoCluster instance with the set time limit for the full execution of an operation. - * - `0` means an infinite timeout - * - `> 0` The time limit to use for the full execution of an operation. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit, defaults to Milliseconds - * @return a new MongoCluster instance with the set time limit for operations - * @see [MongoDatabase.timeout] - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun withTimeout(timeout: Long, timeUnit: TimeUnit = TimeUnit.MILLISECONDS): MongoCluster = - MongoCluster(wrapped.withTimeout(timeout, timeUnit)) - /** * Gets a [MongoDatabase] instance for the given database name. * diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoCollection.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoCollection.kt index 5602b5ecd11..b1026c359f9 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoCollection.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoCollection.kt @@ -19,8 +19,6 @@ import com.mongodb.MongoNamespace import com.mongodb.ReadConcern import com.mongodb.ReadPreference import com.mongodb.WriteConcern -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.bulk.BulkWriteResult import com.mongodb.client.model.BulkWriteOptions import com.mongodb.client.model.CountOptions @@ -89,28 +87,6 @@ public class MongoCollection(private val wrapped: JMongoCollection) public val writeConcern: WriteConcern get() = wrapped.writeConcern - /** - * The time limit for the full execution of an operation. - * - * If not null the following deprecated options will be ignored: `waitQueueTimeoutMS`, `socketTimeoutMS`, - * `wTimeoutMS`, `maxTimeMS` and `maxCommitTimeMS`. - * - `null` means that the timeout mechanism for operations will defer to using: - * - `waitQueueTimeoutMS`: The maximum wait time in milliseconds that a thread may wait for a connection to - * become available - * - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - * - `wTimeoutMS`: How long the server will wait for the write concern to be fulfilled before timing out. - * - `maxTimeMS`: The time limit for processing operations on a cursor. See: - * [cursor.maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS"). - * - `maxCommitTimeMS`: The maximum amount of time to allow a single `commitTransaction` command to execute. - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * @return the optional timeout duration - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeout(timeUnit: TimeUnit = TimeUnit.MILLISECONDS): Long? = wrapped.getTimeout(timeUnit) - /** * Create a new collection instance with a different default class to cast any documents returned from the database * into. @@ -174,21 +150,6 @@ public class MongoCollection(private val wrapped: JMongoCollection) public fun withWriteConcern(newWriteConcern: WriteConcern): MongoCollection = MongoCollection(wrapped.withWriteConcern(newWriteConcern)) - /** - * Create a new MongoCollection instance with the set time limit for the full execution of an operation. - * - `0` means an infinite timeout - * - `> 0` The time limit to use for the full execution of an operation. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit, defaults to Milliseconds - * @return a new MongoCollection instance with the set time limit for operations - * @see [MongoCollection.timeout] - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun withTimeout(timeout: Long, timeUnit: TimeUnit = TimeUnit.MILLISECONDS): MongoCollection = - MongoCollection(wrapped.withTimeout(timeout, timeUnit)) - /** * Counts the number of documents in the collection. * diff --git a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoDatabase.kt b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoDatabase.kt index 007251bab31..bf40401a0a1 100644 --- a/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoDatabase.kt +++ b/driver-kotlin-coroutine/src/main/kotlin/com/mongodb/kotlin/client/coroutine/MongoDatabase.kt @@ -18,8 +18,6 @@ package com.mongodb.kotlin.client.coroutine import com.mongodb.ReadConcern import com.mongodb.ReadPreference import com.mongodb.WriteConcern -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.client.model.CreateCollectionOptions import com.mongodb.client.model.CreateViewOptions import com.mongodb.reactivestreams.client.MongoDatabase as JMongoDatabase @@ -57,28 +55,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { public val writeConcern: WriteConcern get() = wrapped.writeConcern - /** - * The time limit for the full execution of an operation. - * - * If not null the following deprecated options will be ignored: `waitQueueTimeoutMS`, `socketTimeoutMS`, - * `wTimeoutMS`, `maxTimeMS` and `maxCommitTimeMS`. - * - `null` means that the timeout mechanism for operations will defer to using: - * - `waitQueueTimeoutMS`: The maximum wait time in milliseconds that a thread may wait for a connection to - * become available - * - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - * - `wTimeoutMS`: How long the server will wait for the write concern to be fulfilled before timing out. - * - `maxTimeMS`: The time limit for processing operations on a cursor. See: - * [cursor.maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS"). - * - `maxCommitTimeMS`: The maximum amount of time to allow a single `commitTransaction` command to execute. - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * @return the optional timeout duration - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeout(timeUnit: TimeUnit = TimeUnit.MILLISECONDS): Long? = wrapped.getTimeout(timeUnit) - /** * Create a new MongoDatabase instance with a different codec registry. * @@ -122,21 +98,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { public fun withWriteConcern(newWriteConcern: WriteConcern): MongoDatabase = MongoDatabase(wrapped.withWriteConcern(newWriteConcern)) - /** - * Create a new MongoDatabase instance with the set time limit for the full execution of an operation. - * - `0` means an infinite timeout - * - `> 0` The time limit to use for the full execution of an operation. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit, defaults to Milliseconds - * @return a new MongoDatabase instance with the set time limit for operations - * @see [MongoDatabase.timeout] - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun withTimeout(timeout: Long, timeUnit: TimeUnit = TimeUnit.MILLISECONDS): MongoDatabase = - MongoDatabase(wrapped.withTimeout(timeout, timeUnit)) - /** * Gets a collection. * @@ -189,9 +150,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { /** * Executes the given command in the context of the current database with the given read preference. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and - * the `timeoutMS` setting has been set. - * * @param T the class to decode each document into * @param command the command to be run * @param readPreference the [ReadPreference] to be used when executing the command, defaults to @@ -208,9 +166,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { /** * Executes the given command in the context of the current database with the given read preference. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and - * the `timeoutMS` setting has been set. - * * @param T the class to decode each document into * @param clientSession the client session with which to associate this operation * @param command the command to be run @@ -229,9 +184,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { /** * Executes the given command in the context of the current database with the given read preference. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and - * the `timeoutMS` setting has been set. - * * @param T the class to decode each document into * @param command the command to be run * @param readPreference the [ReadPreference] to be used when executing the command, defaults to @@ -246,9 +198,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { /** * Executes the given command in the context of the current database with the given read preference. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and - * the `timeoutMS` setting has been set. - * * @param T the class to decode each document into * @param clientSession the client session with which to associate this operation * @param command the command to be run diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlowTest.kt index ab4b9694986..b42220e1d59 100644 --- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlowTest.kt +++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/AggregateFlowTest.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client.coroutine import com.mongodb.ExplainVerbosity -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.reactivestreams.client.AggregatePublisher import java.util.concurrent.TimeUnit @@ -27,12 +26,7 @@ import org.bson.BsonDocument import org.bson.BsonString import org.bson.Document import org.junit.jupiter.api.Test -import org.mockito.kotlin.doReturn -import org.mockito.kotlin.mock -import org.mockito.kotlin.times -import org.mockito.kotlin.verify -import org.mockito.kotlin.verifyNoMoreInteractions -import org.mockito.kotlin.whenever +import org.mockito.kotlin.* import reactor.core.publisher.Mono class AggregateFlowTest { @@ -73,7 +67,6 @@ class AggregateFlowTest { flow.maxAwaitTime(1, TimeUnit.SECONDS) flow.maxTime(1) flow.maxTime(1, TimeUnit.SECONDS) - flow.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).allowDiskUse(true) verify(wrapped).batchSize(batchSize) @@ -88,7 +81,6 @@ class AggregateFlowTest { verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) verify(wrapped).let(bson) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) whenever(wrapped.explain(Document::class.java)).doReturn(Mono.fromCallable { Document() }) whenever(wrapped.explain(Document::class.java, verbosity)).doReturn(Mono.fromCallable { Document() }) diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/DistinctFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/DistinctFlowTest.kt index 571c6f579bb..fa3b25f92dd 100644 --- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/DistinctFlowTest.kt +++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/DistinctFlowTest.kt @@ -15,7 +15,6 @@ */ package com.mongodb.kotlin.client.coroutine -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.reactivestreams.client.DistinctPublisher import java.util.concurrent.TimeUnit @@ -56,7 +55,6 @@ class DistinctFlowTest { flow.filter(filter) flow.maxTime(1) flow.maxTime(1, TimeUnit.SECONDS) - flow.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).batchSize(batchSize) verify(wrapped).collation(collation) @@ -65,7 +63,6 @@ class DistinctFlowTest { verify(wrapped).filter(filter) verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapped) } diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/FindFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/FindFlowTest.kt index 450059c8211..2216c044883 100644 --- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/FindFlowTest.kt +++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/FindFlowTest.kt @@ -17,7 +17,6 @@ package com.mongodb.kotlin.client.coroutine import com.mongodb.CursorType import com.mongodb.ExplainVerbosity -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.reactivestreams.client.FindPublisher import java.util.concurrent.TimeUnit @@ -79,7 +78,6 @@ class FindFlowTest { flow.showRecordId(true) flow.skip(1) flow.sort(bson) - flow.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).allowDiskUse(true) verify(wrapped).batchSize(batchSize) @@ -105,7 +103,6 @@ class FindFlowTest { verify(wrapped).showRecordId(true) verify(wrapped).skip(1) verify(wrapped).sort(bson) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) whenever(wrapped.explain(Document::class.java)).doReturn(Mono.fromCallable { Document() }) whenever(wrapped.explain(Document::class.java, verbosity)).doReturn(Mono.fromCallable { Document() }) diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ListCollectionsFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ListCollectionsFlowTest.kt index 59c6f896c86..98d16113ff9 100644 --- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ListCollectionsFlowTest.kt +++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ListCollectionsFlowTest.kt @@ -15,7 +15,6 @@ */ package com.mongodb.kotlin.client.coroutine -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.ListCollectionsPublisher import java.util.concurrent.TimeUnit import kotlin.reflect.full.declaredFunctions @@ -55,7 +54,6 @@ class ListCollectionsFlowTest { flow.filter(filter) flow.maxTime(1) flow.maxTime(1, TimeUnit.SECONDS) - flow.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).batchSize(batchSize) verify(wrapped).comment(bsonComment) @@ -63,7 +61,6 @@ class ListCollectionsFlowTest { verify(wrapped).filter(filter) verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapped) } diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ListDatabasesFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ListDatabasesFlowTest.kt index eac18960b3f..53e44f740f1 100644 --- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ListDatabasesFlowTest.kt +++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ListDatabasesFlowTest.kt @@ -15,7 +15,6 @@ */ package com.mongodb.kotlin.client.coroutine -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.ListDatabasesPublisher import java.util.concurrent.TimeUnit import kotlin.reflect.full.declaredFunctions @@ -56,7 +55,6 @@ class ListDatabasesFlowTest { flow.maxTime(1) flow.maxTime(1, TimeUnit.SECONDS) flow.nameOnly(true) - flow.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).authorizedDatabasesOnly(true) verify(wrapped).batchSize(batchSize) @@ -66,7 +64,6 @@ class ListDatabasesFlowTest { verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) verify(wrapped).nameOnly(true) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapped) } diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ListIndexesFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ListIndexesFlowTest.kt index d84765d428b..69287d1918d 100644 --- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ListIndexesFlowTest.kt +++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/ListIndexesFlowTest.kt @@ -15,7 +15,6 @@ */ package com.mongodb.kotlin.client.coroutine -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.ListIndexesPublisher import java.util.concurrent.TimeUnit import kotlin.reflect.full.declaredFunctions @@ -51,14 +50,12 @@ class ListIndexesFlowTest { flow.comment(comment) flow.maxTime(1) flow.maxTime(1, TimeUnit.SECONDS) - flow.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).batchSize(batchSize) verify(wrapped).comment(bsonComment) verify(wrapped).comment(comment) verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapped) } diff --git a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlowTest.kt b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlowTest.kt index 3a38b7e6460..4f9aa7d916d 100644 --- a/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlowTest.kt +++ b/driver-kotlin-coroutine/src/test/kotlin/com/mongodb/kotlin/client/coroutine/MapReduceFlowTest.kt @@ -17,7 +17,6 @@ package com.mongodb.kotlin.client.coroutine -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.client.model.MapReduceAction import com.mongodb.reactivestreams.client.MapReducePublisher @@ -28,11 +27,7 @@ import kotlinx.coroutines.runBlocking import org.bson.BsonDocument import org.bson.Document import org.junit.jupiter.api.Test -import org.mockito.kotlin.doReturn -import org.mockito.kotlin.mock -import org.mockito.kotlin.verify -import org.mockito.kotlin.verifyNoMoreInteractions -import org.mockito.kotlin.whenever +import org.mockito.kotlin.* import reactor.core.publisher.Mono class MapReduceFlowTest { @@ -73,7 +68,6 @@ class MapReduceFlowTest { flow.sort(bson) flow.verbose(true) flow.action(MapReduceAction.MERGE) - flow.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).batchSize(batchSize) verify(wrapped).bypassDocumentValidation(true) @@ -90,7 +84,6 @@ class MapReduceFlowTest { verify(wrapped).sort(bson) verify(wrapped).verbose(true) verify(wrapped).action(MapReduceAction.MERGE) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) whenever(wrapped.toCollection()).doReturn(Mono.empty()) runBlocking { flow.toCollection() } diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt index b563c67c368..2640e6250d7 100644 --- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt +++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncAggregateIterable.kt @@ -17,7 +17,6 @@ package com.mongodb.kotlin.client.syncadapter import com.mongodb.ExplainVerbosity import com.mongodb.client.AggregateIterable as JAggregateIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.kotlin.client.AggregateIterable import java.util.concurrent.TimeUnit @@ -28,9 +27,6 @@ import org.bson.conversions.Bson internal class SyncAggregateIterable(val wrapped: AggregateIterable) : JAggregateIterable, SyncMongoIterable(wrapped) { override fun batchSize(batchSize: Int): SyncAggregateIterable = apply { wrapped.batchSize(batchSize) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncAggregateIterable = apply { - wrapped.timeoutMode(timeoutMode) - } override fun toCollection() = wrapped.toCollection() diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncDistinctIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncDistinctIterable.kt index 92e52ce39da..1186dfdb774 100644 --- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncDistinctIterable.kt +++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncDistinctIterable.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client.syncadapter import com.mongodb.client.DistinctIterable as JDistinctIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.kotlin.client.DistinctIterable import java.util.concurrent.TimeUnit @@ -26,9 +25,6 @@ import org.bson.conversions.Bson internal class SyncDistinctIterable(val wrapped: DistinctIterable) : JDistinctIterable, SyncMongoIterable(wrapped) { override fun batchSize(batchSize: Int): SyncDistinctIterable = apply { wrapped.batchSize(batchSize) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncDistinctIterable = apply { - wrapped.timeoutMode(timeoutMode) - } override fun filter(filter: Bson?): SyncDistinctIterable = apply { wrapped.filter(filter) } override fun maxTime(maxTime: Long, timeUnit: TimeUnit): SyncDistinctIterable = apply { wrapped.maxTime(maxTime, timeUnit) diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncFindIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncFindIterable.kt index 81247aeb2a0..f179f4ff6bc 100644 --- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncFindIterable.kt +++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncFindIterable.kt @@ -18,7 +18,6 @@ package com.mongodb.kotlin.client.syncadapter import com.mongodb.CursorType import com.mongodb.ExplainVerbosity import com.mongodb.client.FindIterable as JFindIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.kotlin.client.FindIterable import java.util.concurrent.TimeUnit @@ -29,7 +28,6 @@ import org.bson.conversions.Bson internal class SyncFindIterable(val wrapped: FindIterable) : JFindIterable, SyncMongoIterable(wrapped) { override fun batchSize(batchSize: Int): SyncFindIterable = apply { wrapped.batchSize(batchSize) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncFindIterable = apply { wrapped.timeoutMode(timeoutMode) } override fun filter(filter: Bson?): SyncFindIterable = apply { wrapped.filter(filter) } override fun limit(limit: Int): SyncFindIterable = apply { wrapped.limit(limit) } diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListCollectionsIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListCollectionsIterable.kt index f38e7eed5e7..74579b15a20 100644 --- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListCollectionsIterable.kt +++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListCollectionsIterable.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client.syncadapter import com.mongodb.client.ListCollectionsIterable as JListCollectionsIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.kotlin.client.ListCollectionsIterable import java.util.concurrent.TimeUnit import org.bson.BsonValue @@ -26,9 +25,6 @@ internal class SyncListCollectionsIterable(val wrapped: ListCollections JListCollectionsIterable, SyncMongoIterable(wrapped) { override fun batchSize(batchSize: Int): SyncListCollectionsIterable = apply { wrapped.batchSize(batchSize) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncListCollectionsIterable = apply { - wrapped.timeoutMode(timeoutMode) - } override fun maxTime(maxTime: Long, timeUnit: TimeUnit): SyncListCollectionsIterable = apply { wrapped.maxTime(maxTime, timeUnit) diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListDatabasesIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListDatabasesIterable.kt index 34874827826..2e0e662a65d 100644 --- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListDatabasesIterable.kt +++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListDatabasesIterable.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client.syncadapter import com.mongodb.client.ListDatabasesIterable as JListDatabasesIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.kotlin.client.ListDatabasesIterable import java.util.concurrent.TimeUnit import org.bson.BsonValue @@ -26,9 +25,6 @@ internal class SyncListDatabasesIterable(val wrapped: ListDatabasesIter JListDatabasesIterable, SyncMongoIterable(wrapped) { override fun batchSize(batchSize: Int): SyncListDatabasesIterable = apply { wrapped.batchSize(batchSize) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncListDatabasesIterable = apply { - wrapped.timeoutMode(timeoutMode) - } override fun maxTime(maxTime: Long, timeUnit: TimeUnit): SyncListDatabasesIterable = apply { wrapped.maxTime(maxTime, timeUnit) diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListIndexesIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListIndexesIterable.kt index 56e5fec91cd..b9133970cb3 100644 --- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListIndexesIterable.kt +++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListIndexesIterable.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client.syncadapter import com.mongodb.client.ListIndexesIterable as JListIndexesIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.kotlin.client.ListIndexesIterable import java.util.concurrent.TimeUnit import org.bson.BsonValue @@ -24,9 +23,6 @@ import org.bson.BsonValue internal class SyncListIndexesIterable(val wrapped: ListIndexesIterable) : JListIndexesIterable, SyncMongoIterable(wrapped) { override fun batchSize(batchSize: Int): SyncListIndexesIterable = apply { wrapped.batchSize(batchSize) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncListIndexesIterable = apply { - wrapped.timeoutMode(timeoutMode) - } override fun maxTime(maxTime: Long, timeUnit: TimeUnit): SyncListIndexesIterable = apply { wrapped.maxTime(maxTime, timeUnit) } diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListSearchIndexesIterable.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListSearchIndexesIterable.kt index b0e6d522b7e..c63a249eeb0 100644 --- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListSearchIndexesIterable.kt +++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncListSearchIndexesIterable.kt @@ -17,7 +17,6 @@ package com.mongodb.kotlin.client.syncadapter import com.mongodb.ExplainVerbosity import com.mongodb.client.ListSearchIndexesIterable as JListSearchIndexesIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.kotlin.client.ListSearchIndexesIterable import java.util.concurrent.TimeUnit @@ -27,9 +26,6 @@ import org.bson.Document internal class SyncListSearchIndexesIterable(val wrapped: ListSearchIndexesIterable) : JListSearchIndexesIterable, SyncMongoIterable(wrapped) { override fun batchSize(batchSize: Int): SyncListSearchIndexesIterable = apply { wrapped.batchSize(batchSize) } - override fun timeoutMode(timeoutMode: TimeoutMode): SyncListSearchIndexesIterable = apply { - wrapped.timeoutMode(timeoutMode) - } override fun name(indexName: String): SyncListSearchIndexesIterable = apply { wrapped.name(indexName) } override fun allowDiskUse(allowDiskUse: Boolean?): com.mongodb.client.ListSearchIndexesIterable = apply { diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCluster.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCluster.kt index b86f2447a17..d954f63b131 100644 --- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCluster.kt +++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCluster.kt @@ -29,7 +29,6 @@ import com.mongodb.client.model.bulk.ClientBulkWriteOptions import com.mongodb.client.model.bulk.ClientBulkWriteResult import com.mongodb.client.model.bulk.ClientNamespacedWriteModel import com.mongodb.kotlin.client.MongoCluster -import java.util.concurrent.TimeUnit import org.bson.Document import org.bson.codecs.configuration.CodecRegistry import org.bson.conversions.Bson @@ -43,8 +42,6 @@ internal open class SyncMongoCluster(open val wrapped: MongoCluster) : JMongoClu override fun getReadConcern(): ReadConcern = wrapped.readConcern - override fun getTimeout(timeUnit: TimeUnit): Long? = wrapped.timeout(timeUnit) - override fun withCodecRegistry(codecRegistry: CodecRegistry): SyncMongoCluster = SyncMongoCluster(wrapped.withCodecRegistry(codecRegistry)) @@ -57,9 +54,6 @@ internal open class SyncMongoCluster(open val wrapped: MongoCluster) : JMongoClu override fun withWriteConcern(writeConcern: WriteConcern): SyncMongoCluster = SyncMongoCluster(wrapped.withWriteConcern(writeConcern)) - override fun withTimeout(timeout: Long, timeUnit: TimeUnit): SyncMongoCluster = - SyncMongoCluster(wrapped.withTimeout(timeout, timeUnit)) - override fun getDatabase(databaseName: String): MongoDatabase = SyncMongoDatabase(wrapped.getDatabase(databaseName)) override fun startSession(): ClientSession = SyncClientSession(wrapped.startSession(), this) diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCollection.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCollection.kt index 51c3a7db7e1..952b05d32e5 100644 --- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCollection.kt +++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoCollection.kt @@ -56,7 +56,6 @@ import com.mongodb.client.result.InsertOneResult import com.mongodb.client.result.UpdateResult import com.mongodb.kotlin.client.MongoCollection import java.lang.UnsupportedOperationException -import java.util.concurrent.TimeUnit import org.bson.Document import org.bson.codecs.configuration.CodecRegistry import org.bson.conversions.Bson @@ -74,7 +73,6 @@ internal class SyncMongoCollection(val wrapped: MongoCollection) : J override fun getWriteConcern(): WriteConcern = wrapped.writeConcern override fun getReadConcern(): ReadConcern = wrapped.readConcern - override fun getTimeout(timeUnit: TimeUnit): Long? = wrapped.timeout(timeUnit) override fun withDocumentClass(clazz: Class): SyncMongoCollection = SyncMongoCollection(wrapped.withDocumentClass(clazz)) @@ -91,9 +89,6 @@ internal class SyncMongoCollection(val wrapped: MongoCollection) : J override fun withReadConcern(readConcern: ReadConcern): SyncMongoCollection = SyncMongoCollection(wrapped.withReadConcern(readConcern)) - override fun withTimeout(timeout: Long, timeUnit: TimeUnit): com.mongodb.client.MongoCollection = - SyncMongoCollection(wrapped.withTimeout(timeout, timeUnit)) - override fun countDocuments(): Long = wrapped.countDocuments() override fun countDocuments(filter: Bson): Long = wrapped.countDocuments(filter) diff --git a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoDatabase.kt b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoDatabase.kt index 1111ee282ca..84a97bc2769 100644 --- a/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoDatabase.kt +++ b/driver-kotlin-sync/src/integrationTest/kotlin/com/mongodb/kotlin/client/syncadapter/SyncMongoDatabase.kt @@ -23,7 +23,6 @@ import com.mongodb.client.MongoDatabase as JMongoDatabase import com.mongodb.client.model.CreateCollectionOptions import com.mongodb.client.model.CreateViewOptions import com.mongodb.kotlin.client.MongoDatabase -import java.util.concurrent.TimeUnit import org.bson.Document import org.bson.codecs.configuration.CodecRegistry import org.bson.conversions.Bson @@ -39,8 +38,6 @@ internal class SyncMongoDatabase(val wrapped: MongoDatabase) : JMongoDatabase { override fun getReadConcern(): ReadConcern = wrapped.readConcern - override fun getTimeout(timeUnit: TimeUnit): Long? = wrapped.timeout(timeUnit) - override fun withCodecRegistry(codecRegistry: CodecRegistry): SyncMongoDatabase = SyncMongoDatabase(wrapped.withCodecRegistry(codecRegistry)) @@ -53,9 +50,6 @@ internal class SyncMongoDatabase(val wrapped: MongoDatabase) : JMongoDatabase { override fun withReadConcern(readConcern: ReadConcern): SyncMongoDatabase = SyncMongoDatabase(wrapped.withReadConcern(readConcern)) - override fun withTimeout(timeout: Long, timeUnit: TimeUnit): SyncMongoDatabase = - SyncMongoDatabase(wrapped.withTimeout(timeout, timeUnit)) - override fun getCollection(collectionName: String): MongoCollection = SyncMongoCollection(wrapped.getCollection(collectionName, Document::class.java)) diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt index 49130b82c60..4e395408f42 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/AggregateIterable.kt @@ -16,10 +16,7 @@ package com.mongodb.kotlin.client import com.mongodb.ExplainVerbosity -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.client.AggregateIterable as JAggregateIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import java.util.concurrent.TimeUnit import org.bson.BsonValue @@ -39,27 +36,6 @@ public class AggregateIterable(private val wrapped: JAggregateIterable< return this } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * If the `timeout` is set then: - * * For non-tailable cursors, the default value of timeoutMode is [TimeoutMode.CURSOR_LIFETIME] - * * For tailable cursors, the default value of timeoutMode is [TimeoutMode.ITERATION] and its an error to configure - * it as: [TimeoutMode.CURSOR_LIFETIME] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): AggregateIterable { - wrapped.timeoutMode(timeoutMode) - return this - } - /** * Aggregates documents according to the specified aggregation pipeline, which must end with an `$out` or `$merge` * stage. This method is the preferred alternative to [cursor], because this method does what is explicitly diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/DistinctIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/DistinctIterable.kt index 98cfd590104..fe3ad6a52f7 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/DistinctIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/DistinctIterable.kt @@ -15,10 +15,7 @@ */ package com.mongodb.kotlin.client -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.client.DistinctIterable as JDistinctIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import com.mongodb.lang.Nullable import java.util.concurrent.TimeUnit @@ -42,19 +39,6 @@ public class DistinctIterable(private val wrapped: JDistinctIterable = apply { wrapped.batchSize(batchSize) } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): DistinctIterable = apply { wrapped.timeoutMode(timeoutMode) } - /** * Sets the query filter to apply to the query. * diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/FindIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/FindIterable.kt index 81e1bb51864..d94b863b51b 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/FindIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/FindIterable.kt @@ -17,10 +17,7 @@ package com.mongodb.kotlin.client import com.mongodb.CursorType import com.mongodb.ExplainVerbosity -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.client.FindIterable as JFindIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import java.util.concurrent.TimeUnit import org.bson.BsonValue @@ -40,27 +37,6 @@ public class FindIterable(private val wrapped: JFindIterable) : Mong return this } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * If the `timeout` is set then: - * * For non-tailable cursors, the default value of timeoutMode is [TimeoutMode.CURSOR_LIFETIME] - * * For tailable cursors, the default value of timeoutMode is [TimeoutMode.ITERATION] and its an error to configure - * it as: [TimeoutMode.CURSOR_LIFETIME] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): FindIterable { - wrapped.timeoutMode(timeoutMode) - return this - } - /** * Sets the query filter to apply to the query. * diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListCollectionsIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListCollectionsIterable.kt index 43b2a9ba510..dd225f29305 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListCollectionsIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListCollectionsIterable.kt @@ -15,10 +15,7 @@ */ package com.mongodb.kotlin.client -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.client.ListCollectionsIterable as JListCollectionsIterable -import com.mongodb.client.cursor.TimeoutMode import java.util.concurrent.TimeUnit import org.bson.BsonValue import org.bson.conversions.Bson @@ -37,22 +34,6 @@ public class ListCollectionsIterable(private val wrapped: JListCollecti return this } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): ListCollectionsIterable { - wrapped.timeoutMode(timeoutMode) - return this - } - /** * Sets the maximum execution time on the server for this operation. * diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListDatabasesIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListDatabasesIterable.kt index dd9e1e0bcc8..525cb528fb1 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListDatabasesIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListDatabasesIterable.kt @@ -15,10 +15,7 @@ */ package com.mongodb.kotlin.client -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.client.ListDatabasesIterable as JListDatabasesIterable -import com.mongodb.client.cursor.TimeoutMode import java.util.concurrent.TimeUnit import org.bson.BsonValue import org.bson.conversions.Bson @@ -37,22 +34,6 @@ public class ListDatabasesIterable(private val wrapped: JListDatabasesI return this } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): ListDatabasesIterable { - wrapped.timeoutMode(timeoutMode) - return this - } - /** * Sets the maximum execution time on the server for this operation. * diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListIndexesIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListIndexesIterable.kt index cc4449384b8..5e8933b15d9 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListIndexesIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListIndexesIterable.kt @@ -15,10 +15,7 @@ */ package com.mongodb.kotlin.client -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.client.ListIndexesIterable as JListIndexesIterable -import com.mongodb.client.cursor.TimeoutMode import java.util.concurrent.TimeUnit import org.bson.BsonValue @@ -35,22 +32,6 @@ public class ListIndexesIterable(private val wrapped: JListIndexesItera return this } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): ListIndexesIterable { - wrapped.timeoutMode(timeoutMode) - return this - } - /** * Sets the maximum execution time on the server for this operation. * diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListSearchIndexesIterable.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListSearchIndexesIterable.kt index aa0dc1664bd..6790458a8d6 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListSearchIndexesIterable.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/ListSearchIndexesIterable.kt @@ -16,10 +16,7 @@ package com.mongodb.kotlin.client import com.mongodb.ExplainVerbosity -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.client.ListSearchIndexesIterable as JListSearchIndexesIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import java.util.concurrent.TimeUnit import org.bson.BsonValue @@ -39,22 +36,6 @@ public class ListSearchIndexesIterable(private val wrapped: JListSearch return this } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [com.mongodb.MongoClientSettings], via [MongoDatabase] or via - * [MongoCollection] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeoutMode(timeoutMode: TimeoutMode): ListSearchIndexesIterable { - wrapped.timeoutMode(timeoutMode) - return this - } - /** * Sets an Atlas Search index name for this operation. * diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoClient.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoClient.kt index c71e59520b6..36c92be7872 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoClient.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoClient.kt @@ -15,7 +15,6 @@ */ package com.mongodb.kotlin.client -import com.mongodb.ClientSessionOptions import com.mongodb.ConnectionString import com.mongodb.MongoClientSettings import com.mongodb.MongoDriverInformation @@ -23,7 +22,6 @@ import com.mongodb.client.MongoClient as JMongoClient import com.mongodb.client.MongoClients as JMongoClients import com.mongodb.connection.ClusterDescription import java.io.Closeable -import java.util.concurrent.TimeUnit /** * A client-side representation of a MongoDB cluster. @@ -125,12 +123,3 @@ public class MongoClient(private val wrapped: JMongoClient) : MongoCluster(wrapp public fun appendMetadata(mongoDriverInformation: MongoDriverInformation): Unit = wrapped.appendMetadata(mongoDriverInformation) } - -/** - * ClientSessionOptions.Builder.defaultTimeout extension function - * - * @param defaultTimeout time in milliseconds - * @return the options - */ -public fun ClientSessionOptions.Builder.defaultTimeout(defaultTimeout: Long): ClientSessionOptions.Builder = - this.apply { defaultTimeout(defaultTimeout, TimeUnit.MILLISECONDS) } diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoCluster.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoCluster.kt index aec3e83d72f..7e438fc7e86 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoCluster.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoCluster.kt @@ -22,15 +22,12 @@ import com.mongodb.MongoException import com.mongodb.ReadConcern import com.mongodb.ReadPreference import com.mongodb.WriteConcern -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.client.MongoCluster as JMongoCluster import com.mongodb.client.model.bulk.ClientBulkWriteOptions import com.mongodb.client.model.bulk.ClientBulkWriteResult import com.mongodb.client.model.bulk.ClientNamespacedDeleteManyModel import com.mongodb.client.model.bulk.ClientNamespacedUpdateManyModel import com.mongodb.client.model.bulk.ClientNamespacedWriteModel -import java.util.concurrent.TimeUnit import org.bson.Document import org.bson.codecs.configuration.CodecRegistry import org.bson.conversions.Bson @@ -62,31 +59,6 @@ public open class MongoCluster protected constructor(private val wrapped: JMongo public val writeConcern: WriteConcern get() = wrapped.writeConcern - /** - * The time limit for the full execution of an operation. - * - * If not null the following deprecated options will be ignored: `waitQueueTimeoutMS`, `socketTimeoutMS`, - * `wTimeoutMS`, `maxTimeMS` and `maxCommitTimeMS`. - * - `null` means that the timeout mechanism for operations will defer to using: - * - `waitQueueTimeoutMS`: The maximum wait time in milliseconds that a thread may wait for a connection to - * become available - * - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - * - `wTimeoutMS`: How long the server will wait for the write concern to be fulfilled before timing out. - * - `maxTimeMS`: The time limit for processing operations on a cursor. See: - * [cursor.maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS"). - * - `maxCommitTimeMS`: The maximum amount of time to allow a single `commitTransaction` command to execute. - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * Note: This timeout does not limit socket writes, therefore there is a possibility that the operation might not be - * timed out when expected. - * - * @return the optional timeout duration - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeout(timeUnit: TimeUnit = TimeUnit.MILLISECONDS): Long? = wrapped.getTimeout(timeUnit) - /** * Create a new MongoCluster instance with a different codec registry. * @@ -130,24 +102,6 @@ public open class MongoCluster protected constructor(private val wrapped: JMongo public fun withWriteConcern(newWriteConcern: WriteConcern): MongoCluster = MongoCluster(wrapped.withWriteConcern(newWriteConcern)) - /** - * Create a new MongoCluster instance with the set time limit for the full execution of an operation. - * - `0` means an infinite timeout - * - `> 0` The time limit to use for the full execution of an operation. - * - * Note: This timeout does not limit socket writes, therefore there is a possibility that the operation might not be - * timed out when expected. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit, defaults to Milliseconds - * @return a new MongoCluster instance with the set time limit for operations - * @see [MongoDatabase.timeout] - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun withTimeout(timeout: Long, timeUnit: TimeUnit = TimeUnit.MILLISECONDS): MongoCluster = - MongoCluster(wrapped.withTimeout(timeout, timeUnit)) - /** * Gets a [MongoDatabase] instance for the given database name. * diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoCollection.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoCollection.kt index 7a2f3449ad1..786140caf12 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoCollection.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoCollection.kt @@ -19,8 +19,6 @@ import com.mongodb.MongoNamespace import com.mongodb.ReadConcern import com.mongodb.ReadPreference import com.mongodb.WriteConcern -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.bulk.BulkWriteResult import com.mongodb.client.MongoCollection as JMongoCollection import com.mongodb.client.model.BulkWriteOptions @@ -86,31 +84,6 @@ public class MongoCollection(private val wrapped: JMongoCollection) public val writeConcern: WriteConcern get() = wrapped.writeConcern - /** - * The time limit for the full execution of an operation. - * - * If not null the following deprecated options will be ignored: `waitQueueTimeoutMS`, `socketTimeoutMS`, - * `wTimeoutMS`, `maxTimeMS` and `maxCommitTimeMS`. - * - `null` means that the timeout mechanism for operations will defer to using: - * - `waitQueueTimeoutMS`: The maximum wait time in milliseconds that a thread may wait for a connection to - * become available - * - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - * - `wTimeoutMS`: How long the server will wait for the write concern to be fulfilled before timing out. - * - `maxTimeMS`: The time limit for processing operations on a cursor. See: - * [cursor.maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS"). - * - `maxCommitTimeMS`: The maximum amount of time to allow a single `commitTransaction` command to execute. - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * Note: This timeout does not limit socket writes, therefore there is a possibility that the operation might not be - * timed out when expected. - * - * @return the optional timeout duration - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeout(timeUnit: TimeUnit = TimeUnit.MILLISECONDS): Long? = wrapped.getTimeout(timeUnit) - /** * Create a new collection instance with a different default class to cast any documents returned from the database * into. @@ -174,24 +147,6 @@ public class MongoCollection(private val wrapped: JMongoCollection) public fun withWriteConcern(newWriteConcern: WriteConcern): MongoCollection = MongoCollection(wrapped.withWriteConcern(newWriteConcern)) - /** - * Create a new MongoCollection instance with the set time limit for the full execution of an operation. - * - `0` means an infinite timeout - * - `> 0` The time limit to use for the full execution of an operation. - * - * Note: This timeout does not limit socket writes, therefore there is a possibility that the operation might not be - * timed out when expected. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit, defaults to Milliseconds - * @return a new MongoCollection instance with the set time limit for operations - * @see [MongoCollection.timeout] - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun withTimeout(timeout: Long, timeUnit: TimeUnit = TimeUnit.MILLISECONDS): MongoCollection = - MongoCollection(wrapped.withTimeout(timeout, timeUnit)) - /** * Counts the number of documents in the collection. * diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoCursor.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoCursor.kt index 714e82fa78e..b407195b079 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoCursor.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoCursor.kt @@ -76,14 +76,6 @@ public sealed interface MongoCursor : Iterator, Closeable { * } * ``` * - * A [com.mongodb.MongoOperationTimeoutException] does not invalidate the [MongoChangeStreamCursor], but is immediately - * propagated to the caller. Subsequent method calls will attempt to resume operation by establishing a new change - * stream on the server, without performing a `getMore` request first. - * - * If a [com.mongodb.MongoOperationTimeoutException] occurs before any events are received, it indicates that the server - * has timed out before it could finish processing the existing oplog. In such cases, it is recommended to close the - * current stream and recreate it with a higher timeout setting. - * * @param T The type of documents the cursor contains */ public sealed interface MongoChangeStreamCursor : MongoCursor { diff --git a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoDatabase.kt b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoDatabase.kt index 653079fe9e1..988db01485a 100644 --- a/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoDatabase.kt +++ b/driver-kotlin-sync/src/main/kotlin/com/mongodb/kotlin/client/MongoDatabase.kt @@ -18,8 +18,6 @@ package com.mongodb.kotlin.client import com.mongodb.ReadConcern import com.mongodb.ReadPreference import com.mongodb.WriteConcern -import com.mongodb.annotations.Alpha -import com.mongodb.annotations.Reason import com.mongodb.client.MongoDatabase as JMongoDatabase import com.mongodb.client.model.CreateCollectionOptions import com.mongodb.client.model.CreateViewOptions @@ -55,31 +53,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { public val writeConcern: WriteConcern get() = wrapped.writeConcern - /** - * The time limit for the full execution of an operation. - * - * If not null the following deprecated options will be ignored: `waitQueueTimeoutMS`, `socketTimeoutMS`, - * `wTimeoutMS`, `maxTimeMS` and `maxCommitTimeMS`. - * - `null` means that the timeout mechanism for operations will defer to using: - * - `waitQueueTimeoutMS`: The maximum wait time in milliseconds that a thread may wait for a connection to - * become available - * - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - * - `wTimeoutMS`: How long the server will wait for the write concern to be fulfilled before timing out. - * - `maxTimeMS`: The time limit for processing operations on a cursor. See: - * [cursor.maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS"). - * - `maxCommitTimeMS`: The maximum amount of time to allow a single `commitTransaction` command to execute. - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * Note: This timeout does not limit socket writes, therefore there is a possibility that the operation might not be - * timed out when expected. - * - * @return the optional timeout duration - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun timeout(timeUnit: TimeUnit = TimeUnit.MILLISECONDS): Long? = wrapped.getTimeout(timeUnit) - /** * Create a new MongoDatabase instance with a different codec registry. * @@ -123,24 +96,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { public fun withWriteConcern(newWriteConcern: WriteConcern): MongoDatabase = MongoDatabase(wrapped.withWriteConcern(newWriteConcern)) - /** - * Create a new MongoDatabase instance with the set time limit for the full execution of an operation. - * - `0` means an infinite timeout - * - `> 0` The time limit to use for the full execution of an operation. - * - * Note: This timeout does not limit socket writes, therefore there is a possibility that the operation might not be - * timed out when expected. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit, defaults to Milliseconds - * @return a new MongoDatabase instance with the set time limit for operations - * @see [MongoDatabase.timeout] - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - public fun withTimeout(timeout: Long, timeUnit: TimeUnit = TimeUnit.MILLISECONDS): MongoDatabase = - MongoDatabase(wrapped.withTimeout(timeout, timeUnit)) - /** * Gets a collection. * @@ -165,9 +120,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { /** * Executes the given command in the context of the current database with the given read preference. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and - * the `timeoutMS` setting has been set. - * * @param command the command to be run * @param readPreference the [ReadPreference] to be used when executing the command, defaults to * [MongoDatabase.readPreference] @@ -179,9 +131,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { /** * Executes the given command in the context of the current database with the given read preference. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and - * the `timeoutMS` setting has been set. - * * @param clientSession the client session with which to associate this operation * @param command the command to be run * @param readPreference the [ReadPreference] to be used when executing the command, defaults to @@ -197,9 +146,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { /** * Executes the given command in the context of the current database with the given read preference. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and - * the `timeoutMS` setting has been set. - * * @param T the class to decode each document into * @param command the command to be run * @param readPreference the [ReadPreference] to be used when executing the command, defaults to @@ -216,9 +162,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { /** * Executes the given command in the context of the current database with the given read preference. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and - * the `timeoutMS` setting has been set. - * * @param T the class to decode each document into * @param clientSession the client session with which to associate this operation * @param command the command to be run @@ -237,9 +180,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { /** * Executes the given command in the context of the current database with the given read preference. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and - * the `timeoutMS` setting has been set. - * * @param T the class to decode each document into * @param command the command to be run * @param readPreference the [ReadPreference] to be used when executing the command, defaults to @@ -254,9 +194,6 @@ public class MongoDatabase(private val wrapped: JMongoDatabase) { /** * Executes the given command in the context of the current database with the given read preference. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and - * the `timeoutMS` setting has been set. - * * @param T the class to decode each document into * @param clientSession the client session with which to associate this operation * @param command the command to be run diff --git a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/AggregateIterableTest.kt b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/AggregateIterableTest.kt index 83ca9bce0ad..87ba8f16ba3 100644 --- a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/AggregateIterableTest.kt +++ b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/AggregateIterableTest.kt @@ -17,7 +17,6 @@ package com.mongodb.kotlin.client import com.mongodb.ExplainVerbosity import com.mongodb.client.AggregateIterable as JAggregateIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import java.util.concurrent.TimeUnit import kotlin.reflect.full.declaredFunctions @@ -81,7 +80,6 @@ class AggregateIterableTest { iterable.maxAwaitTime(1, TimeUnit.SECONDS) iterable.maxTime(1) iterable.maxTime(1, TimeUnit.SECONDS) - iterable.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).allowDiskUse(true) verify(wrapped).batchSize(batchSize) @@ -99,7 +97,6 @@ class AggregateIterableTest { verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) verify(wrapped).let(bson) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) iterable.toCollection() verify(wrapped).toCollection() diff --git a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/DistinctIterableTest.kt b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/DistinctIterableTest.kt index 91f5e9b6f44..5c529a4a969 100644 --- a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/DistinctIterableTest.kt +++ b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/DistinctIterableTest.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client import com.mongodb.client.DistinctIterable as JDistinctIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import java.util.concurrent.TimeUnit import kotlin.reflect.full.declaredFunctions @@ -57,7 +56,6 @@ class DistinctIterableTest { iterable.filter(filter) iterable.maxTime(1) iterable.maxTime(1, TimeUnit.SECONDS) - iterable.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).batchSize(batchSize) verify(wrapped).collation(collation) @@ -66,7 +64,6 @@ class DistinctIterableTest { verify(wrapped).filter(filter) verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapped) } diff --git a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/FindIterableTest.kt b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/FindIterableTest.kt index 0f4b2725b2e..47e801b651f 100644 --- a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/FindIterableTest.kt +++ b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/FindIterableTest.kt @@ -18,7 +18,6 @@ package com.mongodb.kotlin.client import com.mongodb.CursorType import com.mongodb.ExplainVerbosity import com.mongodb.client.FindIterable as JFindIterable -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.Collation import java.util.concurrent.TimeUnit import kotlin.reflect.full.declaredFunctions @@ -87,7 +86,6 @@ class FindIterableTest { iterable.showRecordId(true) iterable.skip(1) iterable.sort(bson) - iterable.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).allowDiskUse(true) verify(wrapped).batchSize(batchSize) @@ -116,7 +114,6 @@ class FindIterableTest { verify(wrapped).showRecordId(true) verify(wrapped).skip(1) verify(wrapped).sort(bson) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapped) } diff --git a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ListCollectionsIterableTest.kt b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ListCollectionsIterableTest.kt index 26dd071768c..b0c23b331e4 100644 --- a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ListCollectionsIterableTest.kt +++ b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ListCollectionsIterableTest.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client import com.mongodb.client.ListCollectionsIterable as JListCollectionsIterable -import com.mongodb.client.cursor.TimeoutMode import java.util.concurrent.TimeUnit import kotlin.reflect.full.declaredFunctions import kotlin.test.assertEquals @@ -54,7 +53,6 @@ class ListCollectionsIterableTest { iterable.filter(filter) iterable.maxTime(1) iterable.maxTime(1, TimeUnit.SECONDS) - iterable.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).batchSize(batchSize) verify(wrapped).comment(bsonComment) @@ -62,7 +60,6 @@ class ListCollectionsIterableTest { verify(wrapped).filter(filter) verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapped) } diff --git a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ListDatabasesIterableTest.kt b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ListDatabasesIterableTest.kt index a1c95cad1a0..857365d5be0 100644 --- a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ListDatabasesIterableTest.kt +++ b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ListDatabasesIterableTest.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client import com.mongodb.client.ListDatabasesIterable as JListDatabasesIterable -import com.mongodb.client.cursor.TimeoutMode import java.util.concurrent.TimeUnit import kotlin.reflect.full.declaredFunctions import kotlin.test.assertEquals @@ -56,7 +55,6 @@ class ListDatabasesIterableTest { iterable.maxTime(1) iterable.maxTime(1, TimeUnit.SECONDS) iterable.nameOnly(true) - iterable.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).authorizedDatabasesOnly(true) verify(wrapped).batchSize(batchSize) @@ -66,7 +64,6 @@ class ListDatabasesIterableTest { verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) verify(wrapped).nameOnly(true) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapped) } diff --git a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ListIndexesIterableTest.kt b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ListIndexesIterableTest.kt index 08bd5b4e685..d328c1546c0 100644 --- a/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ListIndexesIterableTest.kt +++ b/driver-kotlin-sync/src/test/kotlin/com/mongodb/kotlin/client/ListIndexesIterableTest.kt @@ -16,7 +16,6 @@ package com.mongodb.kotlin.client import com.mongodb.client.ListIndexesIterable as JListIndexesIterable -import com.mongodb.client.cursor.TimeoutMode import java.util.concurrent.TimeUnit import kotlin.reflect.full.declaredFunctions import kotlin.test.assertEquals @@ -51,14 +50,12 @@ class ListIndexesIterableTest { iterable.comment(comment) iterable.maxTime(1) iterable.maxTime(1, TimeUnit.SECONDS) - iterable.timeoutMode(TimeoutMode.ITERATION) verify(wrapped).batchSize(batchSize) verify(wrapped).comment(bsonComment) verify(wrapped).comment(comment) verify(wrapped).maxTime(1, TimeUnit.MILLISECONDS) verify(wrapped).maxTime(1, TimeUnit.SECONDS) - verify(wrapped).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapped) } diff --git a/driver-legacy/src/main/com/mongodb/DB.java b/driver-legacy/src/main/com/mongodb/DB.java index 494970e2610..ca797fd252d 100644 --- a/driver-legacy/src/main/com/mongodb/DB.java +++ b/driver-legacy/src/main/com/mongodb/DB.java @@ -574,11 +574,6 @@ Codec getDefaultDBObjectCodec() { .withUuidRepresentation(getMongoClient().getMongoClientOptions().getUuidRepresentation()); } - @Nullable - Long getTimeoutMS() { - return mongo.getMongoClientOptions().getTimeout(); - } - private static final Set OBEDIENT_COMMANDS = new HashSet<>(); static { diff --git a/driver-legacy/src/main/com/mongodb/MongoClient.java b/driver-legacy/src/main/com/mongodb/MongoClient.java index fbbbab0f817..55cf04e2a9c 100644 --- a/driver-legacy/src/main/com/mongodb/MongoClient.java +++ b/driver-legacy/src/main/com/mongodb/MongoClient.java @@ -867,10 +867,9 @@ private void cleanCursors() { ReadWriteBinding binding = new SingleServerBinding(delegate.getCluster(), cur.serverCursor.getAddress()); try { - OperationContext serverSelectionOperationContext = operationContext.withOverride(TimeoutContext::withComputedServerSelectionTimeout); - ConnectionSource source = binding.getReadConnectionSource(serverSelectionOperationContext); + ConnectionSource source = binding.getReadConnectionSource(operationContext); try { - Connection connection = source.getConnection(serverSelectionOperationContext); + Connection connection = source.getConnection(operationContext); try { BsonDocument killCursorsCommand = new BsonDocument("killCursors", new BsonString(cur.namespace.getCollectionName())) .append("cursors", new BsonArray(singletonList(new BsonInt64(cur.serverCursor.getId())))); diff --git a/driver-legacy/src/main/com/mongodb/MongoClientOptions.java b/driver-legacy/src/main/com/mongodb/MongoClientOptions.java index efa3ae48ced..7aa0c3d92cf 100644 --- a/driver-legacy/src/main/com/mongodb/MongoClientOptions.java +++ b/driver-legacy/src/main/com/mongodb/MongoClientOptions.java @@ -16,7 +16,6 @@ package com.mongodb; -import com.mongodb.annotations.Alpha; import com.mongodb.annotations.Beta; import com.mongodb.annotations.Immutable; import com.mongodb.annotations.NotThreadSafe; @@ -621,41 +620,6 @@ public ServerApi getServerApi() { return wrapped.getServerApi(); } - /** - * The time limit for the full execution of an operation in Milliseconds. - * - *

    If set the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

    - * - *
      - *
    • {@code null} means that the timeout mechanism for operations will defer to using: - *
        - *
      • {@code waitQueueTimeoutMS}: The maximum wait time in milliseconds that a thread may wait for a connection to become - * available
      • - *
      • {@code socketTimeoutMS}: How long a send or receive on a socket can take before timing out.
      • - *
      • {@code wTimeoutMS}: How long the server will wait for the write concern to be fulfilled before timing out.
      • - *
      • {@code maxTimeMS}: The cumulative time limit for processing operations on a cursor. - * See: cursor.maxTimeMS.
      • - *
      • {@code maxCommitTimeMS}: The maximum amount of time to allow a single {@code commitTransaction} command to execute. - * See: {@link TransactionOptions#getMaxCommitTime}.
      • - *
      - *
    • - *
    • {@code 0} means infinite timeout.
    • - *
    • {@code > 0} The time limit to use for the full execution of an operation.
    • - *
    - * - *

    Note that this timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. - * - * @return the timeout in milliseconds - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - @Nullable - public Long getTimeout() { - return wrapped.getTimeout(MILLISECONDS); - } - /** * Gets the server selector. * @@ -1496,39 +1460,6 @@ public Builder srvHostValidator(final SrvHostValidator srvHostValidator) { wrapped.applyToClusterSettings(builder -> builder.srvHostValidator(srvHostValidator)); return this; } - /** - * Sets the time limit, in milliseconds for the full execution of an operation. - * - *

      - *
    • {@code null} means that the timeout mechanism for operations will defer to using: - *
        - *
      • {@code waitQueueTimeoutMS}: The maximum wait time in milliseconds that a thread may wait for a connection to become - * available
      • - *
      • {@code socketTimeoutMS}: How long a send or receive on a socket can take before timing out.
      • - *
      • {@code wTimeoutMS}: How long the server will wait for the write concern to be fulfilled before timing out.
      • - *
      • {@code maxTimeMS}: The cumulative time limit for processing operations on a cursor. - * See: cursor.maxTimeMS.
      • - *
      • {@code maxCommitTimeMS}: The maximum amount of time to allow a single {@code commitTransaction} command to execute. - * See: {@link TransactionOptions#getMaxCommitTime}.
      • - *
      - *
    • - *
    • {@code 0} means infinite timeout.
    • - *
    • {@code > 0} The time limit to use for the full execution of an operation.
    • - *
    - * - *

    Note that this timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. - * - * @param timeoutMS the timeout in milliseconds - * @return this - * @since 5.2 - * @see #getTimeout - */ - @Alpha(Reason.CLIENT) - public Builder timeout(final long timeoutMS) { - wrapped.timeout(timeoutMS, MILLISECONDS); - return this; - } /** * Build an instance of MongoClientOptions. diff --git a/driver-legacy/src/main/com/mongodb/MongoClientURI.java b/driver-legacy/src/main/com/mongodb/MongoClientURI.java index 7e8289648ac..26fe87ce373 100644 --- a/driver-legacy/src/main/com/mongodb/MongoClientURI.java +++ b/driver-legacy/src/main/com/mongodb/MongoClientURI.java @@ -100,8 +100,7 @@ * sslInvalidHostNameAllowed option *

  • {@code connectTimeoutMS=ms}: How long a connection can take to be opened before timing out.
  • *
  • {@code socketTimeoutMS=ms}: How long a receive on a socket can take before timing out. - * This option is the same as {@link MongoClientOptions#getSocketTimeout()}. - * Deprecated, use {@code timeoutMS} instead.
  • + * This option is the same as {@link MongoClientOptions#getSocketTimeout()}. *
  • {@code maxIdleTimeMS=ms}: Maximum idle time of a pooled connection. A connection that exceeds this limit will be closed
  • *
  • {@code maxLifeTimeMS=ms}: Maximum life time of a pooled connection. A connection that exceeds this limit will be closed
  • * @@ -125,7 +124,7 @@ *
  • {@code maxPoolSize=n}: The maximum number of connections in the connection pool.
  • *
  • {@code maxConnecting=n}: The maximum number of connections a pool may be establishing concurrently.
  • *
  • {@code waitQueueTimeoutMS=ms}: The maximum wait time in milliseconds that a thread may wait for a connection to - * become available. Deprecated, use {@code timeoutMS} instead.
  • + * become available. * * *

    Write concern configuration:

    @@ -150,7 +149,7 @@ * {@code "majority"} * * - *
  • {@code wtimeoutMS=ms}. Deprecated, use {@code timeoutMS} instead. + *
  • {@code wtimeoutMS=ms}. *
      *
    • The driver adds { wtimeout : ms } to all write commands. Implies {@code safe=true}.
    • *
    • Used in combination with {@code w}
    • @@ -484,10 +483,6 @@ public MongoClientOptions getOptions() { if (srvAllowedHostsSuffix != null) { builder.srvAllowedHostsSuffix(srvAllowedHostsSuffix); } - Long timeout = proxied.getTimeout(); - if (timeout != null) { - builder.timeout(timeout); - } return builder.build(); } diff --git a/driver-legacy/src/test/unit/com/mongodb/MongoClientOptionsSpecification.groovy b/driver-legacy/src/test/unit/com/mongodb/MongoClientOptionsSpecification.groovy index 16f1604838a..eb57b5b4edb 100644 --- a/driver-legacy/src/test/unit/com/mongodb/MongoClientOptionsSpecification.groovy +++ b/driver-legacy/src/test/unit/com/mongodb/MongoClientOptionsSpecification.groovy @@ -53,7 +53,6 @@ class MongoClientOptionsSpecification extends Specification { options.getMinConnectionsPerHost() == 0 options.getConnectionsPerHost() == 100 options.getMaxConnecting() == 2 - options.getTimeout() == null options.getConnectTimeout() == 10000 options.getReadPreference() == ReadPreference.primary() options.getServerSelector() == null @@ -140,7 +139,6 @@ class MongoClientOptionsSpecification extends Specification { .readConcern(ReadConcern.MAJORITY) .minConnectionsPerHost(30) .connectionsPerHost(500) - .timeout(10_000) .connectTimeout(100) .socketTimeout(700) .serverSelector(serverSelector) @@ -185,7 +183,6 @@ class MongoClientOptionsSpecification extends Specification { options.getMaxAdaptiveRetries() == 42 options.getEnableOverloadRetargeting() options.getServerSelectionTimeout() == 150 - options.getTimeout() == 10_000 options.getMaxWaitTime() == 200 options.getMaxConnectionIdleTime() == 300 options.getMaxConnectionLifeTime() == 400 @@ -237,7 +234,6 @@ class MongoClientOptionsSpecification extends Specification { settings.readConcern == ReadConcern.MAJORITY settings.uuidRepresentation == UuidRepresentation.C_SHARP_LEGACY settings.serverApi == serverApi - settings.getTimeout(TimeUnit.MILLISECONDS) == 10_000 when: def optionsFromSettings = MongoClientOptions.builder(settings).build() @@ -350,7 +346,6 @@ class MongoClientOptionsSpecification extends Specification { .writeConcern(WriteConcern.JOURNALED) .minConnectionsPerHost(30) .connectionsPerHost(500) - .timeout(10_000) .connectTimeout(100) .socketTimeout(700) .serverSelectionTimeout(150) @@ -652,7 +647,6 @@ class MongoClientOptionsSpecification extends Specification { .uuidRepresentation(UuidRepresentation.STANDARD) .minConnectionsPerHost(30) .connectionsPerHost(500) - .timeout(10_000) .connectTimeout(100) .socketTimeout(700) .serverSelectionTimeout(150) diff --git a/driver-legacy/src/test/unit/com/mongodb/MongoClientURISpecification.groovy b/driver-legacy/src/test/unit/com/mongodb/MongoClientURISpecification.groovy index 7e8fc5e31c2..a91f2f764c6 100644 --- a/driver-legacy/src/test/unit/com/mongodb/MongoClientURISpecification.groovy +++ b/driver-legacy/src/test/unit/com/mongodb/MongoClientURISpecification.groovy @@ -134,8 +134,7 @@ class MongoClientURISpecification extends Specification { + 'maxAdaptiveRetries=42&' + 'enableOverloadRetargeting=true&' + 'uuidRepresentation=csharpLegacy&' - + 'appName=app1&' - + 'timeoutMS=10000') + + 'appName=app1') when: def options = uri.getOptions() @@ -149,7 +148,6 @@ class MongoClientURISpecification extends Specification { options.getMaxConnectionIdleTime() == 200 options.getMaxConnectionLifeTime() == 300 options.getMaxConnecting() == 1 - options.getTimeout() == 10_000 options.getSocketTimeout() == 5500 options.getConnectTimeout() == 2500 options.getRequiredReplicaSetName() == 'test' @@ -173,7 +171,6 @@ class MongoClientURISpecification extends Specification { then: options.getConnectionsPerHost() == 100 options.getMaxConnecting() == 2 - options.getTimeout() == null options.getMaxWaitTime() == 120000 options.getConnectTimeout() == 10000 options.getSocketTimeout() == 0 @@ -199,7 +196,6 @@ class MongoClientURISpecification extends Specification { .writeConcern(WriteConcern.JOURNALED) .minConnectionsPerHost(30) .connectionsPerHost(500) - .timeout(10_000) .connectTimeout(100) .socketTimeout(700) .serverSelectionTimeout(150) @@ -230,7 +226,6 @@ class MongoClientURISpecification extends Specification { options.getRetryReads() options.getMaxAdaptiveRetries() == 42 options.getEnableOverloadRetargeting() - options.getTimeout() == 10_000 options.getServerSelectionTimeout() == 150 options.getMaxWaitTime() == 200 options.getMaxConnectionIdleTime() == 300 diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java index 4f18fe272bc..ebb177caf78 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/AggregatePublisher.java @@ -18,9 +18,6 @@ import com.mongodb.ExplainVerbosity; import com.mongodb.MongoNamespace; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Aggregates; import com.mongodb.client.model.Collation; import com.mongodb.client.model.MergeOptions; @@ -198,27 +195,6 @@ public interface AggregatePublisher extends Publisher { */ AggregatePublisher batchSize(int batchSize); - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - *

      - * If the {@code timeout} is set then: - *

        - *
      • For non-tailable cursors, the default value of timeoutMode is {@link TimeoutMode#CURSOR_LIFETIME}
      • - *
      • For tailable cursors, the default value of timeoutMode is {@link TimeoutMode#ITERATION} and its an error - * to configure it as: {@link TimeoutMode#CURSOR_LIFETIME}
      • - *
      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - AggregatePublisher timeoutMode(TimeoutMode timeoutMode); - /** * Helper to return a publisher limited to the first result. * diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/DistinctPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/DistinctPublisher.java index f91b2a50722..8dea51ec5ad 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/DistinctPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/DistinctPublisher.java @@ -16,9 +16,6 @@ package com.mongodb.reactivestreams.client; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.lang.Nullable; import org.bson.BsonValue; @@ -115,20 +112,6 @@ public interface DistinctPublisher extends Publisher { */ DistinctPublisher hintString(@Nullable String hint); - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - DistinctPublisher timeoutMode(TimeoutMode timeoutMode); - /** * Helper to return a publisher limited to the first result. * diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/FindPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/FindPublisher.java index 1128c87bd02..8a485facaf5 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/FindPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/FindPublisher.java @@ -18,9 +18,6 @@ import com.mongodb.CursorType; import com.mongodb.ExplainVerbosity; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.client.model.Projections; import com.mongodb.lang.Nullable; @@ -272,27 +269,6 @@ public interface FindPublisher extends Publisher { */ FindPublisher allowDiskUse(@Nullable Boolean allowDiskUse); - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - *

      - * If the {@code timeout} is set then: - *

        - *
      • For non-tailable cursors, the default value of timeoutMode is {@link TimeoutMode#CURSOR_LIFETIME}
      • - *
      • For tailable cursors, the default value of timeoutMode is {@link TimeoutMode#ITERATION} and its an error - * to configure it as: {@link TimeoutMode#CURSOR_LIFETIME}
      • - *
      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - FindPublisher timeoutMode(TimeoutMode timeoutMode); - /** * Explain the execution plan for this operation with the server's default verbosity level * diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionsPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionsPublisher.java index 50808928172..dadef9dfab9 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionsPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListCollectionsPublisher.java @@ -16,9 +16,6 @@ package com.mongodb.reactivestreams.client; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.lang.Nullable; import org.bson.BsonValue; import org.bson.conversions.Bson; @@ -87,20 +84,6 @@ public interface ListCollectionsPublisher extends Publisher { */ ListCollectionsPublisher comment(@Nullable BsonValue comment); - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - ListCollectionsPublisher timeoutMode(TimeoutMode timeoutMode); - /** * Helper to return a publisher limited to the first result. * diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListDatabasesPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListDatabasesPublisher.java index 0dea2b0e219..6f6f11e5296 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListDatabasesPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListDatabasesPublisher.java @@ -17,9 +17,6 @@ package com.mongodb.reactivestreams.client; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.lang.Nullable; import org.bson.BsonValue; import org.bson.conversions.Bson; @@ -110,20 +107,6 @@ public interface ListDatabasesPublisher extends Publisher { */ ListDatabasesPublisher comment(@Nullable BsonValue comment); - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - ListDatabasesPublisher timeoutMode(TimeoutMode timeoutMode); - /** * Helper to return a publisher limited to the first result. * diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListIndexesPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListIndexesPublisher.java index f2abb11a9bb..9ee05851576 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListIndexesPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListIndexesPublisher.java @@ -16,9 +16,6 @@ package com.mongodb.reactivestreams.client; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.lang.Nullable; import org.bson.BsonValue; import org.reactivestreams.Publisher; @@ -76,20 +73,6 @@ public interface ListIndexesPublisher extends Publisher { */ ListIndexesPublisher comment(@Nullable BsonValue comment); - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - ListIndexesPublisher timeoutMode(TimeoutMode timeoutMode); - /** * Helper to return a publisher limited to the first result. * diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListSearchIndexesPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListSearchIndexesPublisher.java index 0f4c7d798b3..941d6324c92 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListSearchIndexesPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/ListSearchIndexesPublisher.java @@ -17,10 +17,7 @@ package com.mongodb.reactivestreams.client; import com.mongodb.ExplainVerbosity; -import com.mongodb.annotations.Alpha; import com.mongodb.annotations.Evolving; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.lang.Nullable; import org.bson.BsonValue; @@ -101,20 +98,6 @@ public interface ListSearchIndexesPublisher extends Publisher */ ListSearchIndexesPublisher comment(@Nullable BsonValue comment); - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - ListSearchIndexesPublisher timeoutMode(TimeoutMode timeoutMode); - /** * Helper to return a publisher limited to the first result. * diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MapReducePublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MapReducePublisher.java index d104f77ee5f..08e2802b6f8 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MapReducePublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MapReducePublisher.java @@ -16,9 +16,6 @@ package com.mongodb.reactivestreams.client; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.lang.Nullable; import org.bson.conversions.Bson; @@ -204,27 +201,6 @@ public interface MapReducePublisher extends Publisher { */ MapReducePublisher batchSize(int batchSize); - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - *

      - * If the {@code timeout} is set then: - *

        - *
      • For non-tailable cursors, the default value of timeoutMode is {@link TimeoutMode#CURSOR_LIFETIME}
      • - *
      • For tailable cursors, the default value of timeoutMode is {@link TimeoutMode#ITERATION} and its an error - * to configure it as: {@link TimeoutMode#CURSOR_LIFETIME}
      • - *
      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - MapReducePublisher timeoutMode(TimeoutMode timeoutMode); - /** * Helper to return a publisher limited to the first result. * diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoCluster.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoCluster.java index 0e2a11d9926..3806442cca6 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoCluster.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoCluster.java @@ -24,22 +24,18 @@ import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; -import com.mongodb.annotations.Alpha; import com.mongodb.annotations.Immutable; -import com.mongodb.annotations.Reason; import com.mongodb.client.model.bulk.ClientBulkWriteOptions; import com.mongodb.client.model.bulk.ClientBulkWriteResult; import com.mongodb.client.model.bulk.ClientNamespacedDeleteManyModel; import com.mongodb.client.model.bulk.ClientNamespacedUpdateManyModel; import com.mongodb.client.model.bulk.ClientNamespacedWriteModel; -import com.mongodb.lang.Nullable; import org.bson.Document; import org.bson.codecs.configuration.CodecRegistry; import org.bson.conversions.Bson; import org.reactivestreams.Publisher; import java.util.List; -import java.util.concurrent.TimeUnit; /** * The client-side representation of a MongoDB cluster operations. @@ -88,37 +84,6 @@ public interface MongoCluster { */ ReadConcern getReadConcern(); - /** - * The time limit for the full execution of an operation. - * - *

      If not null the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

      - * - *
        - *
      • {@code null} means that the timeout mechanism for operations will defer to using: - *
          - *
        • {@code waitQueueTimeoutMS}: The maximum wait time in milliseconds that a thread may wait for a connection to become - * available
        • - *
        • {@code socketTimeoutMS}: How long a send or receive on a socket can take before timing out.
        • - *
        • {@code wTimeoutMS}: How long the server will wait for the write concern to be fulfilled before timing out.
        • - *
        • {@code maxTimeMS}: The cumulative time limit for processing operations on a cursor. - * See: cursor.maxTimeMS.
        • - *
        • {@code maxCommitTimeMS}: The maximum amount of time to allow a single {@code commitTransaction} command to execute. - * See: {@link com.mongodb.TransactionOptions#getMaxCommitTime}.
        • - *
        - *
      • - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - * @param timeUnit the time unit - * @return the timeout in the given time unit - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - @Nullable - Long getTimeout(TimeUnit timeUnit); - /** * Create a new MongoCluster instance with a different codec registry. * @@ -162,23 +127,6 @@ public interface MongoCluster { */ MongoCluster withReadConcern(ReadConcern readConcern); - /** - * Create a new MongoCluster instance with the set time limit for the full execution of an operation. - * - *
        - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit - * @return a new MongoCluster instance with the set time limit for the full execution of an operation. - * @since 5.2 - * @see #getTimeout - */ - @Alpha(Reason.CLIENT) - MongoCluster withTimeout(long timeout, TimeUnit timeUnit); - /** * Gets a {@link MongoDatabase} instance for the given database name. * diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoCollection.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoCollection.java index cc6da9dc554..0b6092033e1 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoCollection.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoCollection.java @@ -20,8 +20,6 @@ import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; import com.mongodb.annotations.ThreadSafe; import com.mongodb.bulk.BulkWriteResult; import com.mongodb.client.model.BulkWriteOptions; @@ -47,14 +45,12 @@ import com.mongodb.client.result.InsertManyResult; import com.mongodb.client.result.InsertOneResult; import com.mongodb.client.result.UpdateResult; -import com.mongodb.lang.Nullable; import org.bson.Document; import org.bson.codecs.configuration.CodecRegistry; import org.bson.conversions.Bson; import org.reactivestreams.Publisher; import java.util.List; -import java.util.concurrent.TimeUnit; /** * The MongoCollection interface. @@ -111,37 +107,6 @@ public interface MongoCollection { */ ReadConcern getReadConcern(); - /** - * The time limit for the full execution of an operation. - * - *

      If not null the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

      - * - *
        - *
      • {@code null} means that the timeout mechanism for operations will defer to using: - *
          - *
        • {@code waitQueueTimeoutMS}: The maximum wait time in milliseconds that a thread may wait for a connection to become - * available
        • - *
        • {@code socketTimeoutMS}: How long a send or receive on a socket can take before timing out.
        • - *
        • {@code wTimeoutMS}: How long the server will wait for the write concern to be fulfilled before timing out.
        • - *
        • {@code maxTimeMS}: The cumulative time limit for processing operations on a cursor. - * See: cursor.maxTimeMS.
        • - *
        • {@code maxCommitTimeMS}: The maximum amount of time to allow a single {@code commitTransaction} command to execute. - * See: {@link com.mongodb.TransactionOptions#getMaxCommitTime}.
        • - *
        - *
      • - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - * @param timeUnit the time unit - * @return the timeout in the given time unit - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - @Nullable - Long getTimeout(TimeUnit timeUnit); - /** * Create a new MongoCollection instance with a different default class to cast any documents returned from the database into.. * @@ -191,23 +156,6 @@ public interface MongoCollection { */ MongoCollection withReadConcern(ReadConcern readConcern); - /** - * Create a new MongoCollection instance with the set time limit for the full execution of an operation. - * - *
        - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit - * @return a new MongoCollection instance with the set time limit for the full execution of an operation - * @since 5.2 - * @see #getTimeout - */ - @Alpha(Reason.CLIENT) - MongoCollection withTimeout(long timeout, TimeUnit timeUnit); - /** * Gets an estimate of the count of documents in a collection using collection metadata. * diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoDatabase.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoDatabase.java index b479ece08c5..e17f2d05259 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoDatabase.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/MongoDatabase.java @@ -19,19 +19,15 @@ import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; import com.mongodb.annotations.ThreadSafe; import com.mongodb.client.model.CreateCollectionOptions; import com.mongodb.client.model.CreateViewOptions; -import com.mongodb.lang.Nullable; import org.bson.Document; import org.bson.codecs.configuration.CodecRegistry; import org.bson.conversions.Bson; import org.reactivestreams.Publisher; import java.util.List; -import java.util.concurrent.TimeUnit; /** * The MongoDatabase interface. @@ -78,37 +74,6 @@ public interface MongoDatabase { */ ReadConcern getReadConcern(); - /** - * The time limit for the full execution of an operation. - * - *

      If not null the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

      - * - *
        - *
      • {@code null} means that the timeout mechanism for operations will defer to using: - *
          - *
        • {@code waitQueueTimeoutMS}: The maximum wait time in milliseconds that a thread may wait for a connection to become - * available
        • - *
        • {@code socketTimeoutMS}: How long a send or receive on a socket can take before timing out.
        • - *
        • {@code wTimeoutMS}: How long the server will wait for the write concern to be fulfilled before timing out.
        • - *
        • {@code maxTimeMS}: The cumulative time limit for processing operations on a cursor. - * See: cursor.maxTimeMS.
        • - *
        • {@code maxCommitTimeMS}: The maximum amount of time to allow a single {@code commitTransaction} command to execute. - * See: {@link com.mongodb.TransactionOptions#getMaxCommitTime}.
        • - *
        - *
      • - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - * @param timeUnit the time unit - * @return the timeout in the given time unit - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - @Nullable - Long getTimeout(TimeUnit timeUnit); - /** * Create a new MongoDatabase instance with a different codec registry. * @@ -149,23 +114,6 @@ public interface MongoDatabase { */ MongoDatabase withReadConcern(ReadConcern readConcern); - /** - * Create a new MongoDatabase instance with the set time limit for the full execution of an operation. - * - *
        - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit - * @return a new MongoDatabase instance with the set time limit for the full execution of an operation. - * @since 5.2 - * @see #getTimeout - */ - @Alpha(Reason.CLIENT) - MongoDatabase withTimeout(long timeout, TimeUnit timeUnit); - /** * Gets a collection. * @@ -187,9 +135,6 @@ public interface MongoDatabase { /** * Executes command in the context of the current database. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param command the command to be run * @return a publisher containing the command result */ @@ -198,9 +143,6 @@ public interface MongoDatabase { /** * Executes command in the context of the current database. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param command the command to be run * @param readPreference the {@link com.mongodb.ReadPreference} to be used when executing the command * @return a publisher containing the command result @@ -210,9 +152,6 @@ public interface MongoDatabase { /** * Executes command in the context of the current database. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param command the command to be run * @param clazz the default class to cast any documents returned from the database into. * @param the type of the class to use instead of {@code Document}. @@ -223,9 +162,6 @@ public interface MongoDatabase { /** * Executes command in the context of the current database. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param command the command to be run * @param readPreference the {@link com.mongodb.ReadPreference} to be used when executing the command * @param clazz the default class to cast any documents returned from the database into. @@ -237,9 +173,6 @@ public interface MongoDatabase { /** * Executes command in the context of the current database. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param clientSession the client session with which to associate this operation * @param command the command to be run * @return a publisher containing the command result @@ -251,9 +184,6 @@ public interface MongoDatabase { /** * Executes command in the context of the current database. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param clientSession the client session with which to associate this operation * @param command the command to be run * @param readPreference the {@link com.mongodb.ReadPreference} to be used when executing the command @@ -266,9 +196,6 @@ public interface MongoDatabase { /** * Executes command in the context of the current database. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param clientSession the client session with which to associate this operation * @param command the command to be run * @param clazz the default class to cast any documents returned from the database into. @@ -282,9 +209,6 @@ public interface MongoDatabase { /** * Executes command in the context of the current database. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param clientSession the client session with which to associate this operation * @param command the command to be run * @param readPreference the {@link com.mongodb.ReadPreference} to be used when executing the command diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/gridfs/GridFSBucket.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/gridfs/GridFSBucket.java index 78a3f5357fc..e0df38798d4 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/gridfs/GridFSBucket.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/gridfs/GridFSBucket.java @@ -19,12 +19,9 @@ import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; import com.mongodb.annotations.ThreadSafe; import com.mongodb.client.gridfs.model.GridFSDownloadOptions; import com.mongodb.client.gridfs.model.GridFSUploadOptions; -import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.ClientSession; import org.bson.BsonValue; import org.bson.conversions.Bson; @@ -32,7 +29,6 @@ import org.reactivestreams.Publisher; import java.nio.ByteBuffer; -import java.util.concurrent.TimeUnit; /** * Represents a GridFS Bucket @@ -79,37 +75,6 @@ public interface GridFSBucket { */ ReadConcern getReadConcern(); - /** - * The time limit for the full execution of an operation. - * - *

      If not null the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

      - * - *
        - *
      • {@code null} means that the timeout mechanism for operations will defer to using: - *
          - *
        • {@code waitQueueTimeoutMS}: The maximum wait time in milliseconds that a thread may wait for a connection to become - * available
        • - *
        • {@code socketTimeoutMS}: How long a send or receive on a socket can take before timing out.
        • - *
        • {@code wTimeoutMS}: How long the server will wait for the write concern to be fulfilled before timing out.
        • - *
        • {@code maxTimeMS}: The cumulative time limit for processing operations on a cursor. - * See: cursor.maxTimeMS.
        • - *
        • {@code maxCommitTimeMS}: The maximum amount of time to allow a single {@code commitTransaction} command to execute. - * See: {@link com.mongodb.TransactionOptions#getMaxCommitTime}.
        • - *
        - *
      • - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - * @param timeUnit the time unit - * @return the timeout in the given time unit - * @since 4.x - */ - @Alpha(Reason.CLIENT) - @Nullable - Long getTimeout(TimeUnit timeUnit); - /** * Create a new GridFSBucket instance with a new chunk size in bytes. * @@ -144,23 +109,6 @@ public interface GridFSBucket { */ GridFSBucket withReadConcern(ReadConcern readConcern); - /** - * Create a new GridFSBucket instance with the set time limit for the full execution of an operation. - * - *
        - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit - * @return a new GridFSBucket instance with the set time limit for the full execution of an operation - * @since 4.x - * @see #getTimeout - */ - @Alpha(Reason.CLIENT) - GridFSBucket withTimeout(long timeout, TimeUnit timeUnit); - /** * Uploads the contents of the given {@code Publisher} to a GridFS bucket. *

      diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java index e37f536a4f7..0a4366fc2b8 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/AggregatePublisherImpl.java @@ -18,7 +18,6 @@ import com.mongodb.ExplainVerbosity; import com.mongodb.MongoNamespace; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.client.model.AggregationLevel; @@ -78,12 +77,6 @@ public AggregatePublisher batchSize(final int batchSize) { return this; } - @Override - public AggregatePublisher timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - @Override public AggregatePublisher maxTime(final long maxTime, final TimeUnit timeUnit) { notNull("timeUnit", timeUnit); @@ -203,12 +196,12 @@ Function, TimeoutSettings> getTimeoutSettings() { private ReadOperationExplainable asAggregateOperation(final int initialBatchSize) { return getOperations() - .aggregate(pipeline, getDocumentClass(), getTimeoutMode(), + .aggregate(pipeline, getDocumentClass(), initialBatchSize, collation, hint, hintString, comment, variables, allowDiskUse, aggregationLevel); } private ReadOperationSimple getAggregateToCollectionOperation() { - return getOperations().aggregateToCollection(pipeline, getTimeoutMode(), allowDiskUse, bypassDocumentValidation, + return getOperations().aggregateToCollection(pipeline, allowDiskUse, bypassDocumentValidation, collation, hint, hintString, comment, variables, aggregationLevel); } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java index 1d68eb0e56a..05693d74484 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/BatchCursorPublisher.java @@ -18,7 +18,6 @@ import com.mongodb.MongoNamespace; import com.mongodb.ReadPreference; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.VisibleForTesting; import com.mongodb.internal.async.AsyncBatchCursor; @@ -37,7 +36,6 @@ import java.util.function.Supplier; import static com.mongodb.assertions.Assertions.assertNotNull; -import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; @VisibleForTesting(otherwise = VisibleForTesting.AccessModifier.PROTECTED) @@ -45,7 +43,6 @@ public abstract class BatchCursorPublisher implements Publisher { private final ClientSession clientSession; private final MongoOperationPublisher mongoOperationPublisher; private Integer batchSize; - private TimeoutMode timeoutMode; BatchCursorPublisher(@Nullable final ClientSession clientSession, final MongoOperationPublisher mongoOperationPublisher) { this(clientSession, mongoOperationPublisher, null); @@ -109,19 +106,6 @@ public Publisher batchSize(final int batchSize) { return this; } - public Publisher timeoutMode(final TimeoutMode timeoutMode) { - if (mongoOperationPublisher.getTimeoutSettings().getTimeoutMS() == null) { - throw new IllegalArgumentException("TimeoutMode requires timeoutMS to be set."); - } - this.timeoutMode = timeoutMode; - return this; - } - - @Nullable - public TimeoutMode getTimeoutMode() { - return timeoutMode; - } - public Publisher first() { return batchCursor(this::asReadOperationFirst) .flatMap(batchCursor -> { @@ -152,12 +136,6 @@ Mono> batchCursor(final Supplier maxAwaitTimeMS); - - return maxAwaitTimeMS; + return TimeUnit.MILLISECONDS.convert(maxAwaitTime, timeUnit); } } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ClientSessionPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ClientSessionPublisherImpl.java index 0109b10b174..9311015d15b 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ClientSessionPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ClientSessionPublisherImpl.java @@ -29,7 +29,6 @@ import com.mongodb.internal.operation.AbortTransactionOperation; import com.mongodb.internal.operation.CommitTransactionOperation; import com.mongodb.internal.operation.ReadOperation; -import com.mongodb.internal.operation.WriteConcernHelper; import com.mongodb.internal.operation.WriteOperation; import com.mongodb.internal.session.BaseClientSessionImpl; import com.mongodb.internal.session.ServerSessionPool; @@ -132,7 +131,7 @@ public void startTransaction(final TransactionOptions transactionOptions) { this.transactionOptions = TransactionOptions.merge(transactionOptions, getOptions().getDefaultTransactionOptions()); TimeoutContext timeoutContext = createTimeoutContext(); - WriteConcern writeConcern = getWriteConcern(timeoutContext); + WriteConcern writeConcern = getWriteConcern(); if (writeConcern == null) { throw new MongoInternalException("Invariant violated. Transaction options write concern can not be null"); } @@ -148,12 +147,8 @@ public void startTransaction(final TransactionOptions transactionOptions) { } @Nullable - private WriteConcern getWriteConcern(@Nullable final TimeoutContext timeoutContext) { - WriteConcern writeConcern = transactionOptions.getWriteConcern(); - if (hasTimeoutMS(timeoutContext) && hasWTimeoutMS(writeConcern)) { - return WriteConcernHelper.cloneWithoutTimeout(writeConcern); - } - return writeConcern; + private WriteConcern getWriteConcern() { + return transactionOptions.getWriteConcern(); } @Override @@ -184,7 +179,7 @@ public Publisher commitTransaction() { commitInProgress = true; resetTimeout(); TimeoutContext timeoutContext = getTimeoutContext(); - WriteConcern writeConcern = assertNotNull(getWriteConcern(timeoutContext)); + WriteConcern writeConcern = assertNotNull(getWriteConcern()); return executor .execute( new CommitTransactionOperation(writeConcern, maxAdaptiveRetriesSetting, alreadyCommitted) @@ -235,7 +230,7 @@ public Publisher abortTransaction() { resetTimeout(); TimeoutContext timeoutContext = getTimeoutContext(); - WriteConcern writeConcern = assertNotNull(getWriteConcern(timeoutContext)); + WriteConcern writeConcern = assertNotNull(getWriteConcern()); return executor .execute(new AbortTransactionOperation(writeConcern, maxAdaptiveRetriesSetting) .recoveryToken(getRecoveryToken()), readConcern, this) diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/DistinctPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/DistinctPublisherImpl.java index e17b37bf959..6e8c57c637e 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/DistinctPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/DistinctPublisherImpl.java @@ -16,7 +16,6 @@ package com.mongodb.reactivestreams.client.internal; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.operation.Operations; @@ -101,12 +100,6 @@ public DistinctPublisher hintString(@Nullable final String hint) { return this; } - @Override - public DistinctPublisher timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - @Override ReadOperationCursor asReadOperation(final int initialBatchSize) { // initialBatchSize is ignored for distinct operations. diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java index e223b9daea9..5f6420f7595 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/FindPublisherImpl.java @@ -18,7 +18,6 @@ import com.mongodb.CursorType; import com.mongodb.ExplainVerbosity; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.client.model.FindOptions; @@ -185,13 +184,6 @@ public FindPublisher allowDiskUse(@Nullable final Boolean allowDiskUse) { return this; } - @Override - public FindPublisher timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - findOptions.timeoutMode(timeoutMode); - return this; - } - @Override public Publisher explain() { return publishExplain(Document.class, null); diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionsPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionsPublisherImpl.java index 1f1e5f9d00a..3c7e9f8c6be 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionsPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListCollectionsPublisherImpl.java @@ -17,7 +17,6 @@ package com.mongodb.reactivestreams.client.internal; import com.mongodb.ReadConcern; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.operation.Operations; import com.mongodb.internal.operation.ReadOperationCursor; @@ -79,14 +78,6 @@ public ListCollectionsPublisher comment(@Nullable final BsonValue comment) { return this; } - - @SuppressWarnings("ReactiveStreamsUnusedPublisher") - @Override - public ListCollectionsPublisher timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - /** * @see ListCollectionNamesPublisher#authorizedCollections(boolean) */ @@ -97,7 +88,7 @@ void authorizedCollections(final boolean authorizedCollections) { ReadOperationCursor asReadOperation(final int initialBatchSize) { return getOperations().listCollections(getNamespace().getDatabaseName(), getDocumentClass(), filter, collectionNamesOnly, - authorizedCollections, initialBatchSize, comment, getTimeoutMode()); + authorizedCollections, initialBatchSize, comment); } @Override diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListDatabasesPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListDatabasesPublisherImpl.java index 5c7b408ef3f..cd0ccc44908 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListDatabasesPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListDatabasesPublisherImpl.java @@ -16,7 +16,6 @@ package com.mongodb.reactivestreams.client.internal; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.operation.Operations; import com.mongodb.internal.operation.ReadOperationCursor; @@ -85,12 +84,6 @@ public ListDatabasesPublisher comment(@Nullable final BsonValue comment) { return this; } - @Override - public ListDatabasesPublisher timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - @Override Function, TimeoutSettings> getTimeoutSettings() { return (operations -> operations.createTimeoutSettings(maxTimeMS)); diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListIndexesPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListIndexesPublisherImpl.java index 851c56fcc54..c98b6a14486 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListIndexesPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListIndexesPublisherImpl.java @@ -16,7 +16,6 @@ package com.mongodb.reactivestreams.client.internal; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.operation.Operations; import com.mongodb.internal.operation.ReadOperationCursor; @@ -65,15 +64,8 @@ public ListIndexesPublisher comment(@Nullable final BsonValue comment) { return this; } - @SuppressWarnings("ReactiveStreamsUnusedPublisher") - @Override - public ListIndexesPublisher timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - ReadOperationCursor asReadOperation(final int initialBatchSize) { - return getOperations().listIndexes(getDocumentClass(), initialBatchSize, comment, getTimeoutMode()); + return getOperations().listIndexes(getDocumentClass(), initialBatchSize, comment); } @Override diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListSearchIndexesPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListSearchIndexesPublisherImpl.java index c4c703e9774..2c92d246f7a 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListSearchIndexesPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/ListSearchIndexesPublisherImpl.java @@ -17,7 +17,6 @@ package com.mongodb.reactivestreams.client.internal; import com.mongodb.ExplainVerbosity; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.operation.Operations; @@ -87,12 +86,6 @@ public ListSearchIndexesPublisher comment(@Nullable final String comment) { return this; } - @Override - public ListSearchIndexesPublisher timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - @Override public ListSearchIndexesPublisher comment(@Nullable final BsonValue comment) { this.comment = comment; diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java index 1e8e7fa223b..b5d5331432c 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MapReducePublisherImpl.java @@ -18,7 +18,6 @@ import com.mongodb.MongoNamespace; import com.mongodb.ReadPreference; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.async.AsyncBatchCursor; @@ -159,12 +158,6 @@ public com.mongodb.reactivestreams.client.MapReducePublisher bypassDocumentVa return this; } - @Override - public com.mongodb.reactivestreams.client.MapReducePublisher timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - @Override public Publisher toCollection() { if (inline) { diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoClientImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoClientImpl.java index 6b6eb7a6a03..db800a15910 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoClientImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoClientImpl.java @@ -55,7 +55,6 @@ import org.reactivestreams.Publisher; import java.util.List; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static com.mongodb.assertions.Assertions.notNull; @@ -302,12 +301,6 @@ public ReadConcern getReadConcern() { return delegate.getReadConcern(); } - @Override - @Nullable - public Long getTimeout(final TimeUnit timeUnit) { - return delegate.getTimeout(timeUnit); - } - @Override public MongoCluster withCodecRegistry(final CodecRegistry codecRegistry) { return delegate.withCodecRegistry(codecRegistry); @@ -328,11 +321,6 @@ public MongoCluster withReadConcern(final ReadConcern readConcern) { return delegate.withReadConcern(readConcern); } - @Override - public MongoCluster withTimeout(final long timeout, final TimeUnit timeUnit) { - return delegate.withTimeout(timeout, timeUnit); - } - @Override public MongoDatabase getDatabase(final String name) { return delegate.getDatabase(name); diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoClusterImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoClusterImpl.java index 3fdc128e5cd..4e482e17589 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoClusterImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoClusterImpl.java @@ -43,11 +43,9 @@ import java.util.Collections; import java.util.List; -import java.util.concurrent.TimeUnit; import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; -import static java.util.concurrent.TimeUnit.MILLISECONDS; final class MongoClusterImpl implements MongoCluster { @@ -90,14 +88,6 @@ public ReadConcern getReadConcern() { return mongoOperationPublisher.getReadConcern(); } - @Override - @Nullable - public Long getTimeout(final TimeUnit timeUnit) { - notNull("timeUnit", timeUnit); - Long timeoutMS = mongoOperationPublisher.getTimeoutMS(); - return timeoutMS == null ? null : timeUnit.convert(timeoutMS, MILLISECONDS); - } - @Override public MongoCluster withCodecRegistry(final CodecRegistry codecRegistry) { return new MongoClusterImpl(cluster, crypt, operationExecutor, serverSessionPool, clientSessionHelper, @@ -122,12 +112,6 @@ public MongoCluster withReadConcern(final ReadConcern readConcern) { mongoOperationPublisher.withReadConcern(readConcern)); } - @Override - public MongoCluster withTimeout(final long timeout, final TimeUnit timeUnit) { - return new MongoClusterImpl(cluster, crypt, operationExecutor, serverSessionPool, clientSessionHelper, - mongoOperationPublisher.withTimeout(timeout, timeUnit)); - } - public Cluster getCluster() { return cluster; } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoCollectionImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoCollectionImpl.java index 0ac3d6a2e39..d9fa18c6a54 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoCollectionImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoCollectionImpl.java @@ -62,7 +62,6 @@ import java.util.Collections; import java.util.List; -import java.util.concurrent.TimeUnit; import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.assertions.Assertions.notNull; @@ -106,12 +105,6 @@ public ReadConcern getReadConcern() { return mongoOperationPublisher.getReadConcern(); } - @Override - public Long getTimeout(final TimeUnit timeUnit) { - Long timeoutMS = mongoOperationPublisher.getTimeoutMS(); - return (timeoutMS != null) ? notNull("timeUnit", timeUnit).convert(timeoutMS, TimeUnit.MILLISECONDS) : null; - } - MongoOperationPublisher getPublisherHelper() { return mongoOperationPublisher; } @@ -141,11 +134,6 @@ public MongoCollection withReadConcern(final ReadConcern readConcern) { return new MongoCollectionImpl<>(mongoOperationPublisher.withReadConcern(readConcern)); } - @Override - public MongoCollection withTimeout(final long timeout, final TimeUnit timeUnit) { - return new MongoCollectionImpl<>(mongoOperationPublisher.withTimeout(timeout, timeUnit)); - } - @Override public Publisher estimatedDocumentCount() { return estimatedDocumentCount(new EstimatedDocumentCountOptions()); diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoDatabaseImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoDatabaseImpl.java index f8709f12ad8..268b9df8081 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoDatabaseImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoDatabaseImpl.java @@ -38,12 +38,10 @@ import java.util.Collections; import java.util.List; -import java.util.concurrent.TimeUnit; import static com.mongodb.MongoNamespace.checkDatabaseNameValidity; import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.assertions.Assertions.notNull; -import static java.util.concurrent.TimeUnit.MILLISECONDS; /** @@ -84,12 +82,6 @@ public ReadConcern getReadConcern() { return mongoOperationPublisher.getReadConcern(); } - @Override - public Long getTimeout(final TimeUnit timeUnit) { - Long timeoutMS = mongoOperationPublisher.getTimeoutSettings().getTimeoutMS(); - return timeoutMS == null ? null : notNull("timeUnit", timeUnit).convert(timeoutMS, MILLISECONDS); - } - MongoOperationPublisher getMongoOperationPublisher() { return mongoOperationPublisher; } @@ -114,11 +106,6 @@ public MongoDatabase withReadConcern(final ReadConcern readConcern) { return new MongoDatabaseImpl(mongoOperationPublisher.withReadConcern(readConcern)); } - @Override - public MongoDatabase withTimeout(final long timeout, final TimeUnit timeUnit) { - return new MongoDatabaseImpl(mongoOperationPublisher.withTimeout(timeout, timeUnit)); - } - @Override public MongoCollection getCollection(final String collectionName) { return getCollection(collectionName, Document.class); diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoOperationPublisher.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoOperationPublisher.java index 582453be5ea..dfeb2f4f0b6 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoOperationPublisher.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/MongoOperationPublisher.java @@ -78,8 +78,6 @@ import java.util.HashMap; import java.util.List; -import java.util.Objects; -import java.util.concurrent.TimeUnit; import java.util.function.Function; import java.util.function.Supplier; @@ -158,11 +156,6 @@ public boolean getRetryReads() { return operations.isRetryReads(); } - @Nullable - public Long getTimeoutMS() { - return getTimeoutSettings().getTimeoutMS(); - } - public TimeoutSettings getTimeoutSettings() { return operations.getTimeoutSettings(); } @@ -237,17 +230,6 @@ MongoOperationPublisher withReadConcern(final ReadConcern readConcern) { autoEncryptionSettings, getTimeoutSettings(), executor); } - MongoOperationPublisher withTimeout(final long timeout, final TimeUnit timeUnit) { - TimeoutSettings timeoutSettings = getTimeoutSettings().withTimeout(timeout, timeUnit); - if (Objects.equals(getTimeoutSettings(), timeoutSettings)) { - return this; - } - return new MongoOperationPublisher<>(getNamespace(), getDocumentClass(), - getCodecRegistry(), getReadPreference(), getReadConcern(), - getWriteConcern(), getRetryWrites(), getRetryReads(), maxAdaptiveRetriesSetting, uuidRepresentation, - autoEncryptionSettings, timeoutSettings, executor); - } - Publisher dropDatabase(@Nullable final ClientSession clientSession) { return createWriteOperationMono(operations::getTimeoutSettings, operations::dropDatabase, clientSession); } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/TimeoutHelper.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/TimeoutHelper.java deleted file mode 100644 index cd538202a2b..00000000000 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/TimeoutHelper.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.reactivestreams.client.internal; - -import com.mongodb.MongoOperationTimeoutException; -import com.mongodb.internal.TimeoutContext; -import com.mongodb.internal.time.Timeout; -import com.mongodb.lang.Nullable; -import com.mongodb.reactivestreams.client.MongoCollection; -import com.mongodb.reactivestreams.client.MongoDatabase; -import reactor.core.publisher.Mono; - -import static com.mongodb.internal.TimeoutContext.DEFAULT_TIMEOUT_MESSAGE; -import static java.util.concurrent.TimeUnit.MILLISECONDS; - -/** - *

      This class is not part of the public API and may be removed or changed at any time

      - */ -public final class TimeoutHelper { - private TimeoutHelper() { - //NOP - } - - public static MongoCollection collectionWithTimeout(final MongoCollection collection, - @Nullable final Timeout timeout) { - return collectionWithTimeout(collection, timeout, DEFAULT_TIMEOUT_MESSAGE); - } - - public static MongoCollection collectionWithTimeout(final MongoCollection collection, - @Nullable final Timeout timeout, - final String message) { - if (timeout != null) { - return timeout.call(MILLISECONDS, - () -> collection.withTimeout(0, MILLISECONDS), - ms -> collection.withTimeout(ms, MILLISECONDS), - () -> TimeoutContext.throwMongoTimeoutException(message)); - } - return collection; - } - - public static Mono> collectionWithTimeoutMono(final MongoCollection collection, - @Nullable final Timeout timeout) { - return collectionWithTimeoutMono(collection, timeout, DEFAULT_TIMEOUT_MESSAGE); - } - - public static Mono> collectionWithTimeoutMono(final MongoCollection collection, - @Nullable final Timeout timeout, - final String message) { - try { - return Mono.just(collectionWithTimeout(collection, timeout, message)); - } catch (MongoOperationTimeoutException e) { - return Mono.error(e); - } - } - - public static Mono> collectionWithTimeoutDeferred(final MongoCollection collection, - @Nullable final Timeout timeout) { - return collectionWithTimeoutDeferred(collection, timeout, DEFAULT_TIMEOUT_MESSAGE); - } - - public static Mono> collectionWithTimeoutDeferred(final MongoCollection collection, - @Nullable final Timeout timeout, - final String message) { - return Mono.defer(() -> collectionWithTimeoutMono(collection, timeout, message)); - } - - public static MongoDatabase databaseWithTimeout(final MongoDatabase database, - @Nullable final Timeout timeout) { - return databaseWithTimeout(database, DEFAULT_TIMEOUT_MESSAGE, timeout); - } - - public static MongoDatabase databaseWithTimeout(final MongoDatabase database, - final String message, - @Nullable final Timeout timeout) { - if (timeout != null) { - return timeout.call(MILLISECONDS, - () -> database.withTimeout(0, MILLISECONDS), - ms -> database.withTimeout(ms, MILLISECONDS), - () -> TimeoutContext.throwMongoTimeoutException(message)); - } - return database; - } - - private static Mono databaseWithTimeoutMono(final MongoDatabase database, - final String message, - @Nullable final Timeout timeout) { - try { - return Mono.just(databaseWithTimeout(database, message, timeout)); - } catch (MongoOperationTimeoutException e) { - return Mono.error(e); - } - } - - public static Mono databaseWithTimeoutDeferred(final MongoDatabase database, - @Nullable final Timeout timeout) { - return databaseWithTimeoutDeferred(database, DEFAULT_TIMEOUT_MESSAGE, timeout); - } - - public static Mono databaseWithTimeoutDeferred(final MongoDatabase database, - final String message, - @Nullable final Timeout timeout) { - return Mono.defer(() -> databaseWithTimeoutMono(database, message, timeout)); - } -} diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CollectionInfoRetriever.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CollectionInfoRetriever.java index 786055b1886..4327c7e1958 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CollectionInfoRetriever.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CollectionInfoRetriever.java @@ -16,14 +16,13 @@ package com.mongodb.reactivestreams.client.internal.crypt; -import com.mongodb.internal.time.Timeout; -import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.MongoClient; +import com.mongodb.reactivestreams.client.MongoDatabase; import org.bson.BsonDocument; import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.databaseWithTimeoutDeferred; class CollectionInfoRetriever { @@ -35,8 +34,10 @@ class CollectionInfoRetriever { this.client = notNull("client", client); } - public Flux filter(final String databaseName, final BsonDocument filter, @Nullable final Timeout operationTimeout) { - return databaseWithTimeoutDeferred(client.getDatabase(databaseName), TIMEOUT_ERROR_MESSAGE, operationTimeout) + public Flux filter(final String databaseName, final BsonDocument filter) { + final MongoDatabase database1 = client.getDatabase(databaseName); + + return Mono.defer(() -> Mono.just(database1)) .flatMapMany(database -> Flux.from(database.listCollections(BsonDocument.class).filter(filter))); } } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CommandMarker.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CommandMarker.java index 826b662a70e..23f06b494e8 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CommandMarker.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CommandMarker.java @@ -19,11 +19,9 @@ import com.mongodb.AutoEncryptionSettings; import com.mongodb.MongoClientException; import com.mongodb.MongoException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.internal.crypt.capi.MongoCrypt; -import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; @@ -39,7 +37,6 @@ import static com.mongodb.internal.capi.MongoCryptHelper.createProcessBuilder; import static com.mongodb.internal.capi.MongoCryptHelper.isMongocryptdSpawningDisabled; import static com.mongodb.internal.capi.MongoCryptHelper.startProcess; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.databaseWithTimeoutDeferred; @SuppressWarnings("UseOfProcessBuilder") class CommandMarker implements Closeable { @@ -84,14 +81,14 @@ class CommandMarker implements Closeable { } } - Mono mark(final String databaseName, final RawBsonDocument command, @Nullable final Timeout operationTimeout) { + Mono mark(final String databaseName, final RawBsonDocument command) { if (client != null) { - return runCommand(databaseName, command, operationTimeout) + return runCommand(databaseName, command) .onErrorResume(Exception.class, e -> { - if (processBuilder == null || e instanceof MongoOperationTimeoutException) { + if (processBuilder == null) { throw MongoException.fromThrowable(e); } - return Mono.fromRunnable(() -> startProcess(processBuilder)).then(runCommand(databaseName, command, operationTimeout)); + return Mono.fromRunnable(() -> startProcess(processBuilder)).then(runCommand(databaseName, command)); }) .onErrorMap(Exception.class, e -> new MongoClientException("Exception in encryption library: " + e.getMessage(), e)); } else { @@ -99,13 +96,13 @@ Mono mark(final String databaseName, final RawBsonDocument comm } } - private Mono runCommand(final String databaseName, final RawBsonDocument command, @Nullable final Timeout operationTimeout) { + private Mono runCommand(final String databaseName, final RawBsonDocument command) { assertNotNull(client); MongoDatabase mongoDatabase = client.getDatabase(databaseName) .withReadConcern(ReadConcern.DEFAULT) .withReadPreference(ReadPreference.primary()); - return databaseWithTimeoutDeferred(mongoDatabase, TIMEOUT_ERROR_MESSAGE, operationTimeout) + return Mono.defer(() -> Mono.just(mongoDatabase)) .flatMap(database -> Mono.from(database.runCommand(command, RawBsonDocument.class))); } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/Crypt.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/Crypt.java index 0138c5859e5..9d76c90e8b4 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/Crypt.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/Crypt.java @@ -31,7 +31,6 @@ import com.mongodb.internal.crypt.capi.MongoRewrapManyDataKeyOptions; import com.mongodb.internal.diagnostics.logging.Logger; import com.mongodb.internal.diagnostics.logging.Loggers; -import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.MongoClient; import org.bson.BsonBinary; @@ -129,14 +128,14 @@ public class Crypt implements Closeable { * @param databaseName the namespace * @param command the unencrypted command */ - public Mono encrypt(final String databaseName, final RawBsonDocument command, @Nullable final Timeout operationTimeout) { + public Mono encrypt(final String databaseName, final RawBsonDocument command) { notNull("databaseName", databaseName); notNull("command", command); if (bypassAutoEncryption) { return Mono.fromCallable(() -> command); } - return executeStateMachine(() -> mongoCrypt.createEncryptionContext(databaseName, command), databaseName, operationTimeout); + return executeStateMachine(() -> mongoCrypt.createEncryptionContext(databaseName, command), databaseName); } /** @@ -144,9 +143,9 @@ public Mono encrypt(final String databaseName, final RawBsonDoc * * @param commandResponse the encrypted command response */ - public Mono decrypt(final RawBsonDocument commandResponse, @Nullable final Timeout timeout) { + public Mono decrypt(final RawBsonDocument commandResponse) { notNull("commandResponse", commandResponse); - return executeStateMachine(() -> mongoCrypt.createDecryptionContext(commandResponse), timeout) + return executeStateMachine(() -> mongoCrypt.createDecryptionContext(commandResponse)) .onErrorMap(Exception.class, Crypt::wrapInClientException); } @@ -156,7 +155,7 @@ public Mono decrypt(final RawBsonDocument commandResponse, @Nul * @param kmsProvider the KMS provider to create the data key for * @param options the data key options */ - public Mono createDataKey(final String kmsProvider, final DataKeyOptions options, @Nullable final Timeout operationTimeout) { + public Mono createDataKey(final String kmsProvider, final DataKeyOptions options) { notNull("kmsProvider", kmsProvider); notNull("options", options); return executeStateMachine(() -> @@ -165,7 +164,7 @@ public Mono createDataKey(final String kmsProvider, final DataK .keyAltNames(options.getKeyAltNames()) .masterKey(options.getMasterKey()) .keyMaterial(options.getKeyMaterial()) - .build()), operationTimeout); + .build())); } /** @@ -174,10 +173,10 @@ public Mono createDataKey(final String kmsProvider, final DataK * @param value the value to encrypt * @param options the options */ - public Mono encryptExplicitly(final BsonValue value, final EncryptOptions options, @Nullable final Timeout operationTimeout) { + public Mono encryptExplicitly(final BsonValue value, final EncryptOptions options) { return executeStateMachine(() -> - mongoCrypt.createExplicitEncryptionContext(new BsonDocument("v", value), asMongoExplicitEncryptOptions(options)), - operationTimeout) + mongoCrypt.createExplicitEncryptionContext(new BsonDocument("v", value), asMongoExplicitEncryptOptions(options)) + ) .map(result -> result.getBinary("v")); } @@ -190,9 +189,9 @@ public Mono encryptExplicitly(final BsonValue value, final EncryptOp * @since 4.9 * @mongodb.server.release 6.2 */ - public Mono encryptExpression(final BsonDocument expression, final EncryptOptions options, @Nullable final Timeout operationTimeout) { + public Mono encryptExpression(final BsonDocument expression, final EncryptOptions options) { return executeStateMachine(() -> - mongoCrypt.createEncryptExpressionContext(new BsonDocument("v", expression), asMongoExplicitEncryptOptions(options)), operationTimeout + mongoCrypt.createEncryptExpressionContext(new BsonDocument("v", expression), asMongoExplicitEncryptOptions(options)) ).map(result -> result.getDocument("v")); } @@ -201,8 +200,8 @@ public Mono encryptExpression(final BsonDocument expression, final * * @param value the encrypted value */ - public Mono decryptExplicitly(final BsonBinary value, @Nullable final Timeout operationTimeout) { - return executeStateMachine(() -> mongoCrypt.createExplicitDecryptionContext(new BsonDocument("v", value)), operationTimeout) + public Mono decryptExplicitly(final BsonBinary value) { + return executeStateMachine(() -> mongoCrypt.createExplicitDecryptionContext(new BsonDocument("v", value))) .map(result -> result.get("v")); } @@ -212,14 +211,14 @@ public Mono decryptExplicitly(final BsonBinary value, @Nullable final * @param options the rewrap many data key options * @return the decrypted value */ - public Mono rewrapManyDataKey(final BsonDocument filter, final RewrapManyDataKeyOptions options, @Nullable final Timeout operationTimeout) { + public Mono rewrapManyDataKey(final BsonDocument filter, final RewrapManyDataKeyOptions options) { return executeStateMachine(() -> mongoCrypt.createRewrapManyDatakeyContext(filter, MongoRewrapManyDataKeyOptions .builder() .provider(options.getProvider()) .masterKey(options.getMasterKey()) - .build()), operationTimeout + .build()) ); } @@ -238,16 +237,15 @@ public void close() { } } - private Mono executeStateMachine(final Supplier cryptContextSupplier, - @Nullable final Timeout operationTimeout) { - return executeStateMachine(cryptContextSupplier, null, operationTimeout); + private Mono executeStateMachine(final Supplier cryptContextSupplier) { + return executeStateMachine(cryptContextSupplier, null); } private Mono executeStateMachine(final Supplier cryptContextSupplier, - @Nullable final String databaseName, @Nullable final Timeout operationTimeout) { + @Nullable final String databaseName) { try { MongoCryptContext cryptContext = cryptContextSupplier.get(); - return Mono.create(sink -> executeStateMachineWithSink(cryptContext, databaseName, sink, operationTimeout)) + return Mono.create(sink -> executeStateMachineWithSink(cryptContext, databaseName, sink)) .onErrorMap(Exception.class, Crypt::wrapInClientException) .doFinally(s -> cryptContext.close()); } catch (MongoCryptException e) { @@ -256,23 +254,23 @@ private Mono executeStateMachine(final Supplier sink, @Nullable final Timeout operationTimeout) { + final MonoSink sink) { State state = cryptContext.getState(); switch (state) { case NEED_MONGO_COLLINFO: - collInfo(cryptContext, databaseName, sink, operationTimeout); + collInfo(cryptContext, databaseName, sink); break; case NEED_MONGO_MARKINGS: - mark(cryptContext, databaseName, sink, operationTimeout); + mark(cryptContext, databaseName, sink); break; case NEED_KMS_CREDENTIALS: - fetchCredentials(cryptContext, databaseName, sink, operationTimeout); + fetchCredentials(cryptContext, databaseName, sink); break; case NEED_MONGO_KEYS: - fetchKeys(cryptContext, databaseName, sink, operationTimeout); + fetchKeys(cryptContext, databaseName, sink); break; case NEED_KMS: - decryptKeys(cryptContext, databaseName, sink, operationTimeout); + decryptKeys(cryptContext, databaseName, sink); break; case READY: sink.success(cryptContext.finish()); @@ -286,10 +284,10 @@ private void executeStateMachineWithSink(final MongoCryptContext cryptContext, @ } private void fetchCredentials(final MongoCryptContext cryptContext, @Nullable final String databaseName, - final MonoSink sink, @Nullable final Timeout operationTimeout) { + final MonoSink sink) { try { cryptContext.provideKmsProviderCredentials(MongoCryptHelper.fetchCredentials(kmsProviders, kmsProviderPropertySuppliers)); - executeStateMachineWithSink(cryptContext, databaseName, sink, operationTimeout); + executeStateMachineWithSink(cryptContext, databaseName, sink); } catch (Exception e) { sink.error(e); } @@ -297,18 +295,18 @@ private void fetchCredentials(final MongoCryptContext cryptContext, @Nullable fi private void collInfo(final MongoCryptContext cryptContext, @Nullable final String databaseName, - final MonoSink sink, @Nullable final Timeout operationTimeout) { + final MonoSink sink) { if (collectionInfoRetriever == null) { sink.error(new IllegalStateException("Missing collection Info retriever")); } else if (databaseName == null) { sink.error(new IllegalStateException("Missing database name")); } else { - collectionInfoRetriever.filter(databaseName, cryptContext.getMongoOperation(), operationTimeout) + collectionInfoRetriever.filter(databaseName, cryptContext.getMongoOperation()) .contextWrite(sink.contextView()) .doOnNext(result -> cryptContext.addMongoOperationResult(result)) .doOnComplete(() -> { cryptContext.completeMongoOperation(); - executeStateMachineWithSink(cryptContext, databaseName, sink, operationTimeout); + executeStateMachineWithSink(cryptContext, databaseName, sink); }) .doOnError(t -> sink.error(mapUnlessError(t, MongoException::fromThrowableNonNull))) .subscribe(); @@ -317,19 +315,18 @@ private void collInfo(final MongoCryptContext cryptContext, private void mark(final MongoCryptContext cryptContext, @Nullable final String databaseName, - final MonoSink sink, - @Nullable final Timeout operationTimeout) { + final MonoSink sink) { if (commandMarker == null) { sink.error(wrapInClientException(new MongoInternalException("Missing command marker"))); } else if (databaseName == null) { sink.error(wrapInClientException(new IllegalStateException("Missing database name"))); } else { - commandMarker.mark(databaseName, cryptContext.getMongoOperation(), operationTimeout) + commandMarker.mark(databaseName, cryptContext.getMongoOperation()) .contextWrite(sink.contextView()) .doOnSuccess(result -> { cryptContext.addMongoOperationResult(result); cryptContext.completeMongoOperation(); - executeStateMachineWithSink(cryptContext, databaseName, sink, operationTimeout); + executeStateMachineWithSink(cryptContext, databaseName, sink); }) .doOnError(t -> sink.error(mapUnlessError(t, Crypt::wrapInClientException))) .subscribe(); @@ -338,16 +335,15 @@ private void mark(final MongoCryptContext cryptContext, private void fetchKeys(final MongoCryptContext cryptContext, @Nullable final String databaseName, - final MonoSink sink, - @Nullable final Timeout operationTimeout) { - keyRetriever.find(cryptContext.getMongoOperation(), operationTimeout) + final MonoSink sink) { + keyRetriever.find(cryptContext.getMongoOperation()) .contextWrite(sink.contextView()) .doOnSuccess(results -> { for (BsonDocument result : results) { cryptContext.addMongoOperationResult(result); } cryptContext.completeMongoOperation(); - executeStateMachineWithSink(cryptContext, databaseName, sink, operationTimeout); + executeStateMachineWithSink(cryptContext, databaseName, sink); }) .doOnError(t -> sink.error(mapUnlessError(t, MongoException::fromThrowableNonNull))) .subscribe(); @@ -355,19 +351,18 @@ private void fetchKeys(final MongoCryptContext cryptContext, private void decryptKeys(final MongoCryptContext cryptContext, @Nullable final String databaseName, - final MonoSink sink, - @Nullable final Timeout operationTimeout) { + final MonoSink sink) { MongoKeyDecryptor keyDecryptor = cryptContext.nextKeyDecryptor(); if (keyDecryptor != null) { - keyManagementService.decryptKey(keyDecryptor, operationTimeout) + keyManagementService.decryptKey(keyDecryptor) .contextWrite(sink.contextView()) - .doOnSuccess(r -> decryptKeys(cryptContext, databaseName, sink, operationTimeout)) + .doOnSuccess(r -> decryptKeys(cryptContext, databaseName, sink)) .doOnError(t -> sink.error(mapUnlessError(t, Crypt::wrapInClientException))) .subscribe(); } else { Mono.fromRunnable(cryptContext::completeKeyDecryptors) .contextWrite(sink.contextView()) - .doOnSuccess(r -> executeStateMachineWithSink(cryptContext, databaseName, sink, operationTimeout)) + .doOnSuccess(r -> executeStateMachineWithSink(cryptContext, databaseName, sink)) .doOnError(t -> sink.error(mapUnlessError(t, Crypt::wrapInClientException))) .subscribe(); } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CryptConnection.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CryptConnection.java index f7febad164c..44270b15c18 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CryptConnection.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/CryptConnection.java @@ -121,14 +121,14 @@ public void commandAsync(final String database, final BsonDocument command, : new SplittablePayloadBsonWriter(bsonBinaryWriter, bsonOutput, createSplittablePayloadMessageSettings(), payload, MAX_SPLITTABLE_DOCUMENT_SIZE); - Timeout timeout = operationContext.getTimeoutContext().getTimeout(); + Timeout timeout = null; getEncoder(command).encode(writer, command, EncoderContext.builder().build()); - crypt.encrypt(database, new RawBsonDocument(bsonOutput.getInternalBuffer(), 0, bsonOutput.getSize()), timeout) + crypt.encrypt(database, new RawBsonDocument(bsonOutput.getInternalBuffer(), 0, bsonOutput.getSize())) .flatMap((Function>) encryptedCommand -> Mono.create(sink -> wrapped.commandAsync(database, encryptedCommand, commandFieldNameValidator, readPreference, new RawBsonDocumentCodec(), operationContext, responseExpected, EmptyMessageSequences.INSTANCE, sinkToCallback(sink)))) - .flatMap(rawBsonDocument -> crypt.decrypt(rawBsonDocument, timeout)) + .flatMap(rawBsonDocument -> crypt.decrypt(rawBsonDocument)) .map(decryptedResponse -> commandResultDecoder.decode(new BsonBinaryReader(decryptedResponse.getByteBuffer().asNIO()), DecoderContext.builder().build()) diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyManagementService.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyManagementService.java index 349b02f23b4..36d57e9a598 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyManagementService.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyManagementService.java @@ -17,7 +17,6 @@ package com.mongodb.reactivestreams.client.internal.crypt; import com.mongodb.MongoException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoSocketException; import com.mongodb.MongoSocketReadTimeoutException; import com.mongodb.MongoSocketWriteTimeoutException; @@ -25,7 +24,6 @@ import com.mongodb.connection.AsyncCompletionHandler; import com.mongodb.connection.SocketSettings; import com.mongodb.connection.SslSettings; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.connection.AsynchronousChannelStream; import com.mongodb.internal.connection.DefaultInetAddressResolver; @@ -37,7 +35,6 @@ import com.mongodb.internal.diagnostics.logging.Logger; import com.mongodb.internal.diagnostics.logging.Loggers; import com.mongodb.internal.thread.AsyncClientExecutor; -import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; import org.bson.ByteBuf; import org.bson.ByteBufNIO; @@ -74,7 +71,7 @@ public void close() { tlsChannelStreamFactoryFactory.close(); } - Mono decryptKey(final MongoKeyDecryptor keyDecryptor, @Nullable final Timeout operationTimeout) { + Mono decryptKey(final MongoKeyDecryptor keyDecryptor) { SocketSettings socketSettings = SocketSettings.builder() .connectTimeout(timeoutMillis, MILLISECONDS) .readTimeout(timeoutMillis, MILLISECONDS) @@ -88,7 +85,7 @@ Mono decryptKey(final MongoKeyDecryptor keyDecryptor, @Nullable final Time return Mono.create(sink -> { Stream stream = streamFactory.create(serverAddress); - OperationContext operationContext = createOperationContext(operationTimeout, socketSettings); + OperationContext operationContext = createOperationContext(socketSettings); stream.openAsync(operationContext, new AsyncCompletionHandler() { @Override public void completed(@Nullable final Void ignored) { @@ -98,7 +95,7 @@ public void completed(@Nullable final Void ignored) { @Override public void failed(final Throwable t) { stream.close(); - handleError(t, operationContext, sink); + handleError(t, sink); } }); }).onErrorMap(Exception.class, this::unWrapException); @@ -116,7 +113,7 @@ public void completed(@Nullable final Void aVoid) { @Override public void failed(final Throwable t) { stream.close(); - handleError(t, operationContext, sink); + handleError(t, sink); } }); } @@ -152,7 +149,7 @@ public void completed(final Integer integer, final Void aVoid) { public void failed(final Throwable t, final Void aVoid) { buffer.release(); stream.close(); - handleError(t, operationContext, sink); + handleError(t, sink); } }); } else { @@ -161,39 +158,21 @@ public void failed(final Throwable t, final Void aVoid) { } } - private static void handleError(final Throwable t, final OperationContext operationContext, final MonoSink sink) { - if (isTimeoutException(t) && operationContext.getTimeoutContext().hasTimeoutMS()) { - sink.error(TimeoutContext.createMongoTimeoutException(TIMEOUT_ERROR_MESSAGE, t)); - } else { - sink.error(t); - } + private static void handleError(final Throwable t, final MonoSink sink) { + sink.error(t); } - private OperationContext createOperationContext(@Nullable final Timeout operationTimeout, final SocketSettings socketSettings) { - TimeoutSettings timeoutSettings; - if (operationTimeout == null) { - timeoutSettings = createTimeoutSettings(socketSettings, null); - } else { - timeoutSettings = operationTimeout.call(MILLISECONDS, - () -> { - throw new AssertionError("operationTimeout cannot be infinite"); - }, - (ms) -> createTimeoutSettings(socketSettings, ms), - () -> { - throw new MongoOperationTimeoutException(TIMEOUT_ERROR_MESSAGE); - }); - } + private OperationContext createOperationContext(final SocketSettings socketSettings) { + TimeoutSettings timeoutSettings = createTimeoutSettings(socketSettings); return OperationContext.simpleOperationContext(timeoutSettings, null, AsyncClientExecutor.NO_OP); } @NonNull - private static TimeoutSettings createTimeoutSettings(final SocketSettings socketSettings, - @Nullable final Long ms) { + private static TimeoutSettings createTimeoutSettings(final SocketSettings socketSettings) { return new TimeoutSettings( 0, socketSettings.getConnectTimeout(MILLISECONDS), socketSettings.getReadTimeout(MILLISECONDS), - ms, 0); } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyRetriever.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyRetriever.java index 23e3a06eff0..044a54f71a5 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyRetriever.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/crypt/KeyRetriever.java @@ -18,8 +18,6 @@ import com.mongodb.MongoNamespace; import com.mongodb.ReadConcern; -import com.mongodb.internal.time.Timeout; -import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoCollection; import org.bson.BsonDocument; @@ -29,7 +27,6 @@ import java.util.List; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.collectionWithTimeout; class KeyRetriever { private static final String TIMEOUT_ERROR_MESSAGE = "Key retrieval exceeded the timeout limit."; @@ -41,12 +38,12 @@ class KeyRetriever { this.namespace = notNull("namespace", namespace); } - public Mono> find(final BsonDocument keyFilter, @Nullable final Timeout operationTimeout) { + public Mono> find(final BsonDocument keyFilter) { return Flux.defer(() -> { MongoCollection collection = client.getDatabase(namespace.getDatabaseName()) .getCollection(namespace.getCollectionName(), BsonDocument.class); - return collectionWithTimeout(collection, operationTimeout, TIMEOUT_ERROR_MESSAGE) + return collection .withReadConcern(ReadConcern.MAJORITY) .find(keyFilter); }).collectList(); diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSBucketImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSBucketImpl.java index c0e52015b5f..fd04cb54f6a 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSBucketImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSBucketImpl.java @@ -22,7 +22,6 @@ import com.mongodb.client.gridfs.model.GridFSDownloadOptions; import com.mongodb.client.gridfs.model.GridFSFile; import com.mongodb.client.gridfs.model.GridFSUploadOptions; -import com.mongodb.internal.time.Timeout; import com.mongodb.reactivestreams.client.ClientSession; import com.mongodb.reactivestreams.client.MongoClients; import com.mongodb.reactivestreams.client.MongoCollection; @@ -39,8 +38,7 @@ import org.reactivestreams.Publisher; import java.nio.ByteBuffer; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; +import java.util.function.Supplier; import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.reactivestreams.client.internal.gridfs.GridFSPublisherCreator.createDeletePublisher; @@ -49,7 +47,6 @@ import static com.mongodb.reactivestreams.client.internal.gridfs.GridFSPublisherCreator.createGridFSFindPublisher; import static com.mongodb.reactivestreams.client.internal.gridfs.GridFSPublisherCreator.createGridFSUploadPublisher; import static com.mongodb.reactivestreams.client.internal.gridfs.GridFSPublisherCreator.createRenamePublisher; -import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; @@ -118,12 +115,6 @@ public ReadConcern getReadConcern() { return filesCollection.getReadConcern(); } - @Override - public Long getTimeout(final TimeUnit timeUnit) { - Long timeoutMS = filesCollection.getTimeout(MILLISECONDS); - return timeoutMS == null ? null : notNull("timeUnit", timeUnit).convert(timeoutMS, MILLISECONDS); - } - @Override public GridFSBucket withChunkSizeBytes(final int chunkSizeBytes) { return new GridFSBucketImpl(bucketName, chunkSizeBytes, filesCollection, chunksCollection); @@ -150,12 +141,6 @@ public GridFSBucket withReadConcern(final ReadConcern readConcern) { chunksCollection.withReadConcern(readConcern)); } - @Override - public GridFSBucket withTimeout(final long timeout, final TimeUnit timeUnit) { - return new GridFSBucketImpl(bucketName, chunkSizeBytes, filesCollection.withTimeout(timeout, timeUnit), - chunksCollection.withTimeout(timeout, timeUnit)); - } - @Override public GridFSUploadPublisher uploadFromPublisher(final String filename, final Publisher source) { return uploadFromPublisher(filename, source, new GridFSUploadOptions()); @@ -218,8 +203,8 @@ public GridFSDownloadPublisher downloadToPublisher(final ObjectId id) { @Override public GridFSDownloadPublisher downloadToPublisher(final BsonValue id) { - Function findPublisherCreator = - operationTimeout -> createGridFSFindPublisher(filesCollection, null, GridFSFilters.eq("_id", id), operationTimeout); + Supplier findPublisherCreator = + () -> createGridFSFindPublisher(filesCollection, null, GridFSFilters.eq("_id", id)); return createGridFSDownloadPublisher(chunksCollection, null, findPublisherCreator); } @@ -230,8 +215,8 @@ public GridFSDownloadPublisher downloadToPublisher(final String filename) { @Override public GridFSDownloadPublisher downloadToPublisher(final String filename, final GridFSDownloadOptions options) { - Function findPublisherCreator = - timeout -> createGridFSFindPublisher(filesCollection, null, filename, options, timeout); + Supplier findPublisherCreator = + () -> createGridFSFindPublisher(filesCollection, null, filename, options); return createGridFSDownloadPublisher(chunksCollection, null, findPublisherCreator); } @@ -242,8 +227,8 @@ public GridFSDownloadPublisher downloadToPublisher(final ClientSession clientSes @Override public GridFSDownloadPublisher downloadToPublisher(final ClientSession clientSession, final BsonValue id) { - Function findPublisherCreator = - operationTimeout -> createGridFSFindPublisher(filesCollection, clientSession, GridFSFilters.eq("_id", id), operationTimeout); + Supplier findPublisherCreator = + () -> createGridFSFindPublisher(filesCollection, clientSession, GridFSFilters.eq("_id", id)); return createGridFSDownloadPublisher(chunksCollection, notNull("clientSession", clientSession), findPublisherCreator); } @@ -256,9 +241,9 @@ public GridFSDownloadPublisher downloadToPublisher(final ClientSession clientSes public GridFSDownloadPublisher downloadToPublisher(final ClientSession clientSession, final String filename, final GridFSDownloadOptions options) { - Function findPublisherCreator = - operationTimeout -> createGridFSFindPublisher(filesCollection, clientSession, filename, - options, operationTimeout); + Supplier findPublisherCreator = + () -> createGridFSFindPublisher(filesCollection, clientSession, filename, + options); return createGridFSDownloadPublisher(chunksCollection, notNull("clientSession", clientSession), findPublisherCreator); } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSDownloadPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSDownloadPublisherImpl.java index 77d7b5f980e..8188343677f 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSDownloadPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSDownloadPublisherImpl.java @@ -18,7 +18,6 @@ import com.mongodb.MongoGridFSException; import com.mongodb.client.gridfs.model.GridFSFile; -import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.ClientSession; import com.mongodb.reactivestreams.client.FindPublisher; @@ -36,34 +35,28 @@ import java.nio.ByteBuffer; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; +import java.util.function.Supplier; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.internal.TimeoutContext.startTimeout; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.collectionWithTimeout; import static java.lang.String.format; -import static java.util.concurrent.TimeUnit.MILLISECONDS; /** *

      This class is not part of the public API and may be removed or changed at any time

      */ public class GridFSDownloadPublisherImpl implements GridFSDownloadPublisher { - private static final String TIMEOUT_ERROR_MESSAGE = "Finding chunks exceeded the timeout limit."; private final ClientSession clientSession; - private final Function gridFSFileMono; + private final Supplier gridFSFileMono; private final MongoCollection chunksCollection; private Integer bufferSizeBytes; private volatile GridFSFile fileInfo; - @Nullable - private final Long timeoutMs; public GridFSDownloadPublisherImpl(@Nullable final ClientSession clientSession, - final Function gridFSFilePublisherCreator, + final Supplier gridFSFilePublisherCreator, final MongoCollection chunksCollection) { this.clientSession = clientSession; this.gridFSFileMono = notNull("gridFSFilePublisherCreator", gridFSFilePublisherCreator); this.chunksCollection = notNull("chunksCollection", chunksCollection); - this.timeoutMs = chunksCollection.getTimeout(MILLISECONDS); } @Override @@ -71,7 +64,7 @@ public Publisher getGridFSFile() { if (fileInfo != null) { return Mono.fromCallable(() -> fileInfo); } - return Mono.from(gridFSFileMono.apply(startTimeout(timeoutMs))) + return Mono.from(gridFSFileMono.get()) .doOnNext(gridFSFile -> fileInfo = gridFSFile); } @@ -83,25 +76,22 @@ public GridFSDownloadPublisher bufferSizeBytes(final int bufferSizeBytes) { @Override public void subscribe(final Subscriber subscriber) { - Flux.defer(()-> { - Timeout operationTimeout = startTimeout(timeoutMs); - return Mono.from(gridFSFileMono.apply(operationTimeout)) - .doOnSuccess(gridFSFile -> { - if (gridFSFile == null) { - throw new MongoGridFSException("File not found"); - } - fileInfo = gridFSFile; - }).flatMapMany((Function>) gridFSFile -> getChunkPublisher(gridFSFile, operationTimeout)); - }).subscribe(subscriber); + Flux.defer(() -> Mono.from(gridFSFileMono.get()) + .doOnSuccess(gridFSFile -> { + if (gridFSFile == null) { + throw new MongoGridFSException("File not found"); + } + fileInfo = gridFSFile; + }).flatMapMany((Function>) this::getChunkPublisher)).subscribe(subscriber); } - private Flux getChunkPublisher(final GridFSFile gridFSFile, @Nullable final Timeout timeout) { + private Flux getChunkPublisher(final GridFSFile gridFSFile) { BsonDocument filter = GridFSFilters.eq("files_id", gridFSFile.getId()); FindPublisher chunkPublisher; if (clientSession != null) { - chunkPublisher = collectionWithTimeout(chunksCollection, timeout, TIMEOUT_ERROR_MESSAGE).find(clientSession, filter); + chunkPublisher = chunksCollection.find(clientSession, filter); } else { - chunkPublisher = collectionWithTimeout(chunksCollection, timeout, TIMEOUT_ERROR_MESSAGE).find(filter); + chunkPublisher = chunksCollection.find(filter); } AtomicInteger chunkCounter = new AtomicInteger(0); diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSPublisherCreator.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSPublisherCreator.java index 161cd45c92a..3e81a028855 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSPublisherCreator.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSPublisherCreator.java @@ -17,13 +17,10 @@ package com.mongodb.reactivestreams.client.internal.gridfs; import com.mongodb.MongoGridFSException; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.gridfs.model.GridFSDownloadOptions; import com.mongodb.client.gridfs.model.GridFSFile; import com.mongodb.client.gridfs.model.GridFSUploadOptions; import com.mongodb.client.result.UpdateResult; -import com.mongodb.internal.TimeoutContext; -import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.ClientSession; import com.mongodb.reactivestreams.client.FindPublisher; @@ -38,14 +35,10 @@ import reactor.core.publisher.Mono; import java.nio.ByteBuffer; -import java.util.function.Function; +import java.util.function.Supplier; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.collectionWithTimeout; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.collectionWithTimeoutMono; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.collectionWithTimeoutDeferred; import static java.lang.String.format; -import static java.util.concurrent.TimeUnit.MILLISECONDS; /** *

      This class is not part of the public API and may be removed or changed at any time

      @@ -75,7 +68,7 @@ public static GridFSUploadPublisherImpl createGridFSUploadPublisher( public static GridFSDownloadPublisherImpl createGridFSDownloadPublisher( final MongoCollection chunksCollection, @Nullable final ClientSession clientSession, - final Function publisher) { + final Supplier publisher) { notNull("chunksCollection", chunksCollection); notNull("gridFSFileMono", publisher); return new GridFSDownloadPublisherImpl(clientSession, publisher, chunksCollection); @@ -89,21 +82,11 @@ public static GridFSFindPublisher createGridFSFindPublisher( return new GridFSFindPublisherImpl(createFindPublisher(filesCollection, clientSession, filter)); } - public static GridFSFindPublisher createGridFSFindPublisher( - final MongoCollection filesCollection, - @Nullable final ClientSession clientSession, - @Nullable final Bson filter, - @Nullable final Timeout timeout) { - notNull("filesCollection", filesCollection); - return new GridFSFindPublisherImpl(createFindPublisher(filesCollection, clientSession, filter, timeout)); - } - public static GridFSFindPublisher createGridFSFindPublisher( final MongoCollection filesCollection, @Nullable final ClientSession clientSession, final String filename, - final GridFSDownloadOptions options, - @Nullable final Timeout timeout) { + final GridFSDownloadOptions options) { notNull("filesCollection", filesCollection); notNull("filename", filename); notNull("options", options); @@ -119,33 +102,11 @@ public static GridFSFindPublisher createGridFSFindPublisher( sort = -1; } - return createGridFSFindPublisher(filesCollection, clientSession, new Document("filename", filename), timeout) + return createGridFSFindPublisher(filesCollection, clientSession, new Document("filename", filename)) .skip(skip) .sort(new Document("uploadDate", sort)); } - public static FindPublisher createFindPublisher( - final MongoCollection filesCollection, - @Nullable final ClientSession clientSession, - @Nullable final Bson filter, - @Nullable final Timeout timeout) { - notNull("filesCollection", filesCollection); - FindPublisher publisher; - if (clientSession == null) { - publisher = collectionWithTimeout(filesCollection, timeout).find(); - } else { - publisher = collectionWithTimeout(filesCollection, timeout).find(clientSession); - } - - if (filter != null) { - publisher = publisher.filter(filter); - } - if (timeout != null) { - publisher.timeoutMode(TimeoutMode.CURSOR_LIFETIME); - } - return publisher; - } - public static FindPublisher createFindPublisher( final MongoCollection filesCollection, @Nullable final ClientSession clientSession, @@ -160,9 +121,6 @@ public static FindPublisher createFindPublisher( if (filter != null) { publisher = publisher.filter(filter); } - if (filesCollection.getTimeout(MILLISECONDS) != null) { - publisher.timeoutMode(TimeoutMode.CURSOR_LIFETIME); - } return publisher; } @@ -176,28 +134,25 @@ public static Publisher createDeletePublisher(final MongoCollection { - Timeout timeout = startTimeout(filesCollection.getTimeout(MILLISECONDS)); - return collectionWithTimeoutMono(filesCollection, timeout) - .flatMap(wrappedCollection -> { - if (clientSession == null) { - return Mono.from(wrappedCollection.deleteOne(filter)); - } else { - return Mono.from(wrappedCollection.deleteOne(clientSession, filter)); - } - }).flatMap(deleteResult -> { - if (deleteResult.wasAcknowledged() && deleteResult.getDeletedCount() == 0) { - return Mono.error(new MongoGridFSException(format("No file found with the ObjectId: %s", id))); - } - return collectionWithTimeoutMono(chunksCollection, timeout); - }).flatMap(wrappedCollection -> { - if (clientSession == null) { - return Mono.from(wrappedCollection.deleteMany(chunksFilter)); - } else { - return Mono.from(wrappedCollection.deleteMany(clientSession, chunksFilter)); - } - }).then(); - }); + return Mono.defer(()-> Mono.just(filesCollection) + .flatMap(wrappedCollection -> { + if (clientSession == null) { + return Mono.from(wrappedCollection.deleteOne(filter)); + } else { + return Mono.from(wrappedCollection.deleteOne(clientSession, filter)); + } + }).flatMap(deleteResult -> { + if (deleteResult.wasAcknowledged() && deleteResult.getDeletedCount() == 0) { + return Mono.error(new MongoGridFSException(format("No file found with the ObjectId: %s", id))); + } + return Mono.just(chunksCollection); + }).flatMap(wrappedCollection -> { + if (clientSession == null) { + return Mono.from(wrappedCollection.deleteMany(chunksFilter)); + } else { + return Mono.from(wrappedCollection.deleteMany(clientSession, chunksFilter)); + } + }).then()); } public static Publisher createRenamePublisher(final MongoCollection filesCollection, @@ -229,29 +184,21 @@ public static Publisher createDropPublisher(final MongoCollection chunksCollection, @Nullable final ClientSession clientSession) { - return Mono.defer(() -> { - Timeout timeout = startTimeout(filesCollection.getTimeout(MILLISECONDS)); - return collectionWithTimeoutMono(filesCollection, timeout) - .flatMap(wrappedCollection -> { - if (clientSession == null) { - return Mono.from(wrappedCollection.drop()); - } else { - return Mono.from(wrappedCollection.drop(clientSession)); - } - }).then(collectionWithTimeoutDeferred(chunksCollection, timeout)) - .flatMap(wrappedCollection -> { - if (clientSession == null) { - return Mono.from(wrappedCollection.drop()); - } else { - return Mono.from(wrappedCollection.drop(clientSession)); - } - - }); - }); - } + return Mono.defer(() -> Mono.just(filesCollection) + .flatMap(wrappedCollection -> { + if (clientSession == null) { + return Mono.from(wrappedCollection.drop()); + } else { + return Mono.from(wrappedCollection.drop(clientSession)); + } + }).then(Mono.defer(() -> Mono.just(chunksCollection))) + .flatMap(wrappedCollection -> { + if (clientSession == null) { + return Mono.from(wrappedCollection.drop()); + } else { + return Mono.from(wrappedCollection.drop(clientSession)); + } - @Nullable - private static Timeout startTimeout(@Nullable final Long timeoutMs) { - return timeoutMs == null ? null : TimeoutContext.startTimeout(timeoutMs); + })); } } diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSUploadPublisherImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSUploadPublisherImpl.java index 6f7700629cb..ac2e1a4eb83 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSUploadPublisherImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/gridfs/GridFSUploadPublisherImpl.java @@ -17,12 +17,9 @@ package com.mongodb.reactivestreams.client.internal.gridfs; import com.mongodb.MongoGridFSException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.client.gridfs.model.GridFSFile; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.InsertOneResult; -import com.mongodb.internal.TimeoutContext; -import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.ClientSession; import com.mongodb.reactivestreams.client.MongoCollection; @@ -44,10 +41,6 @@ import static com.mongodb.ReadPreference.primary; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.collectionWithTimeout; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.collectionWithTimeoutDeferred; -import static java.time.Duration.ofMillis; -import static java.util.concurrent.TimeUnit.MILLISECONDS; /** @@ -55,8 +48,6 @@ */ public final class GridFSUploadPublisherImpl implements GridFSUploadPublisher { - private static final String TIMEOUT_ERROR_MESSAGE_CHUNKS_SAVING = "Saving chunks exceeded the timeout limit."; - private static final String TIMEOUT_ERROR_MESSAGE_UPLOAD_CANCELLATION = "Upload cancellation exceeded the timeout limit."; private static final Document PROJECTION = new Document("_id", 1); private static final Document FILES_INDEX = new Document("filename", 1).append("uploadDate", 1); private static final Document CHUNKS_INDEX = new Document("files_id", 1).append("n", 1); @@ -68,8 +59,6 @@ public final class GridFSUploadPublisherImpl implements GridFSUploadPublisher source; - @Nullable - private final Long timeoutMs; public GridFSUploadPublisherImpl(@Nullable final ClientSession clientSession, final MongoCollection filesCollection, @@ -87,7 +76,6 @@ public GridFSUploadPublisherImpl(@Nullable final ClientSession clientSession, this.chunkSizeBytes = chunkSizeBytes; this.metadata = metadata; this.source = source; - this.timeoutMs = filesCollection.getTimeout(MILLISECONDS); } @Override @@ -107,19 +95,18 @@ public BsonValue getId() { public void subscribe(final Subscriber s) { Mono.deferContextual(ctx -> { AtomicBoolean terminated = new AtomicBoolean(false); - Timeout timeout = TimeoutContext.startTimeout(timeoutMs); - return createCheckAndCreateIndexesMono(timeout) - .then(createSaveChunksMono(terminated, timeout)) - .flatMap(lengthInBytes -> createSaveFileDataMono(terminated, lengthInBytes, timeout)) + return createCheckAndCreateIndexesMono() + .then(createSaveChunksMono(terminated)) + .flatMap(lengthInBytes -> createSaveFileDataMono(terminated, lengthInBytes)) .onErrorResume(originalError -> - createCancellationMono(terminated, timeout) + createCancellationMono(terminated) .onErrorMap(cancellationError -> { // Timeout exception might occur during cancellation. It gets suppressed. originalError.addSuppressed(cancellationError); return originalError; }) .then(Mono.error(originalError))) - .doOnCancel(() -> createCancellationMono(terminated, timeout).contextWrite(ctx).subscribe()) + .doOnCancel(() -> createCancellationMono(terminated).contextWrite(ctx).subscribe()) .then(); }).subscribe(s); } @@ -147,20 +134,21 @@ public void subscribe(final Subscriber subscriber) { }; } - private Mono createCheckAndCreateIndexesMono(@Nullable final Timeout timeout) { - return collectionWithTimeoutDeferred(filesCollection.withDocumentClass(Document.class).withReadPreference(primary()), timeout) + private Mono createCheckAndCreateIndexesMono() { + final MongoCollection collection1 = filesCollection.withDocumentClass(Document.class).withReadPreference(primary()); + return Mono.defer(() -> Mono.just(collection1)) .map(collection -> clientSession != null ? collection.find(clientSession) : collection.find()) .flatMap(findPublisher -> Mono.from(findPublisher.projection(PROJECTION).first())) .switchIfEmpty(Mono.defer(() -> - checkAndCreateIndex(filesCollection.withReadPreference(primary()), FILES_INDEX, timeout) - .then(checkAndCreateIndex(chunksCollection.withReadPreference(primary()), CHUNKS_INDEX, timeout)) + checkAndCreateIndex(filesCollection.withReadPreference(primary()), FILES_INDEX) + .then(checkAndCreateIndex(chunksCollection.withReadPreference(primary()), CHUNKS_INDEX)) .then(Mono.empty()) )) .then(); } - private Mono hasIndex(final MongoCollection collection, final Document index, @Nullable final Timeout timeout) { - return collectionWithTimeoutDeferred(collection, timeout) + private Mono hasIndex(final MongoCollection collection, final Document index) { + return Mono.defer(() -> Mono.just(collection)) .map(wrappedCollection -> { if (clientSession != null) { return wrappedCollection.listIndexes(clientSession); @@ -187,25 +175,24 @@ private Mono hasIndex(final MongoCollection collection, final Do }); } - private Mono checkAndCreateIndex(final MongoCollection collection, final Document index, @Nullable final Timeout timeout) { - return hasIndex(collection, index, timeout).flatMap(hasIndex -> { + private Mono checkAndCreateIndex(final MongoCollection collection, final Document index) { + return hasIndex(collection, index).flatMap(hasIndex -> { if (!hasIndex) { - return createIndexMono(collection, index, timeout).flatMap(s -> Mono.empty()); + return createIndexMono(collection, index).flatMap(s -> Mono.empty()); } else { return Mono.empty(); } }); } - private Mono createIndexMono(final MongoCollection collection, final Document index, @Nullable final Timeout timeout) { - return collectionWithTimeoutDeferred(collection, timeout).flatMap(wrappedCollection -> + private Mono createIndexMono(final MongoCollection collection, final Document index) { + return Mono.defer(() -> Mono.just(collection)).flatMap(wrappedCollection -> Mono.from(clientSession == null ? wrappedCollection.createIndex(index) : wrappedCollection.createIndex(clientSession, index)) ); } - private Mono createSaveChunksMono(final AtomicBoolean terminated, @Nullable final Timeout timeout) { + private Mono createSaveChunksMono(final AtomicBoolean terminated) { return new ResizingByteBufferFlux(source, chunkSizeBytes) - .takeUntilOther(createMonoTimer(timeout)) .index() .flatMap(indexAndBuffer -> { if (terminated.get()) { @@ -227,38 +214,23 @@ private Mono createSaveChunksMono(final AtomicBoolean terminated, @Nullabl .append("n", index.intValue()) .append("data", data); - Publisher insertOnePublisher = clientSession == null - ? collectionWithTimeout(chunksCollection, timeout, TIMEOUT_ERROR_MESSAGE_CHUNKS_SAVING).insertOne(chunkDocument) - : collectionWithTimeout(chunksCollection, timeout, TIMEOUT_ERROR_MESSAGE_CHUNKS_SAVING) - .insertOne(clientSession, chunkDocument); + Publisher insertOnePublisher; + if (clientSession == null) { + insertOnePublisher = chunksCollection.insertOne(chunkDocument); + } else { + insertOnePublisher = chunksCollection + .insertOne(clientSession, chunkDocument); + } return Mono.from(insertOnePublisher).thenReturn(data.length()); }) .reduce(0L, Long::sum); } - /** - * Creates a Mono that emits a {@link MongoOperationTimeoutException} after the specified timeout. - * - * @param timeout - remaining timeout. - * @return Mono that emits a {@link MongoOperationTimeoutException}. - */ - private static Mono createMonoTimer(final @Nullable Timeout timeout) { - return Timeout.nullAsInfinite(timeout).call(MILLISECONDS, - () -> Mono.never(), - (ms) -> Mono.delay(ofMillis(ms)).then(createTimeoutMonoError()), - () -> createTimeoutMonoError()); - } - - private static Mono createTimeoutMonoError() { - return Mono.error(TimeoutContext.createMongoTimeoutException( - "GridFS waiting for data from the source Publisher exceeded the timeout limit.")); - } private Mono createSaveFileDataMono(final AtomicBoolean terminated, - final long lengthInBytes, - @Nullable final Timeout timeout) { - Mono> filesCollectionMono = collectionWithTimeoutDeferred(filesCollection, timeout); + final long lengthInBytes) { + Mono> filesCollectionMono = Mono.defer(() -> Mono.just(filesCollection)); if (terminated.compareAndSet(false, true)) { GridFSFile gridFSFile = new GridFSFile(fileId, filename, lengthInBytes, chunkSizeBytes, new Date(), metadata); if (clientSession != null) { @@ -271,9 +243,8 @@ private Mono createSaveFileDataMono(final AtomicBoolean termina } } - private Mono createCancellationMono(final AtomicBoolean terminated, @Nullable final Timeout timeout) { - Mono> chunksCollectionMono = collectionWithTimeoutDeferred(chunksCollection, timeout, - TIMEOUT_ERROR_MESSAGE_UPLOAD_CANCELLATION); + private Mono createCancellationMono(final AtomicBoolean terminated) { + Mono> chunksCollectionMono = Mono.defer(() -> Mono.just(chunksCollection)); if (terminated.compareAndSet(false, true)) { BsonDocument chunksFilter = GridFSFilters.eq("files_id", fileId); if (clientSession != null) { diff --git a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/vault/ClientEncryptionImpl.java b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/vault/ClientEncryptionImpl.java index 9942bae926c..5814c21f35d 100644 --- a/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/vault/ClientEncryptionImpl.java +++ b/driver-reactive-streams/src/main/com/mongodb/reactivestreams/client/internal/vault/ClientEncryptionImpl.java @@ -32,10 +32,8 @@ import com.mongodb.client.model.vault.RewrapManyDataKeyOptions; import com.mongodb.client.model.vault.RewrapManyDataKeyResult; import com.mongodb.client.result.DeleteResult; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.VisibleForTesting; import com.mongodb.internal.time.Timeout; -import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.FindPublisher; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; @@ -65,22 +63,15 @@ import static com.mongodb.internal.ExceptionUtils.mapUnlessError; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; import static com.mongodb.internal.capi.MongoCryptHelper.validateRewrapManyDataKeyOptions; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.collectionWithTimeout; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.databaseWithTimeout; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.databaseWithTimeoutDeferred; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; -import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.bson.internal.BsonUtil.mutableDeepCopy; /** *

      This class is not part of the public API and may be removed or changed at any time

      */ public class ClientEncryptionImpl implements ClientEncryption { - private static final String TIMEOUT_ERROR_MESSAGE_CREATE_DATA_KEY = "Creating data key exceeded the timeout limit."; - private static final String TIMEOUT_ERROR_MESSAGE_REWRAP_DATA_KEY = "Rewrapping data key exceeded the timeout limit."; - private static final String TIMEOUT_ERROR_MESSAGE_CREATE_COLLECTION = "Encryption collection creation exceeded the timeout limit."; private final Crypt crypt; private final ClientEncryptionSettings options; private final MongoClient keyVaultClient; @@ -102,16 +93,10 @@ public ClientEncryptionImpl(final MongoClient keyVaultClient, final ClientEncryp private static MongoCollection getVaultCollection(final MongoClient keyVaultClient, final ClientEncryptionSettings options, final MongoNamespace namespace) { - MongoCollection vaultCollection = keyVaultClient.getDatabase(namespace.getDatabaseName()) + return keyVaultClient.getDatabase(namespace.getDatabaseName()) .getCollection(namespace.getCollectionName(), BsonDocument.class) .withWriteConcern(WriteConcern.MAJORITY) .withReadConcern(ReadConcern.MAJORITY); - - Long timeoutMs = options.getTimeout(MILLISECONDS); - if (timeoutMs != null){ - vaultCollection = vaultCollection.withTimeout(timeoutMs, MILLISECONDS); - } - return vaultCollection; } @Override @@ -120,15 +105,8 @@ public Publisher createDataKey(final String kmsProvider) { } @Override - public Publisher createDataKey(final String kmsProvider, final DataKeyOptions dataKeyOptions) { - return Mono.defer(() -> { - Timeout operationTimeout = startTimeout(); - return createDataKey(kmsProvider, dataKeyOptions, operationTimeout); - }); - } - - public Mono createDataKey(final String kmsProvider, final DataKeyOptions dataKeyOptions, @Nullable final Timeout operationTimeout) { - return crypt.createDataKey(kmsProvider, dataKeyOptions, operationTimeout) + public Mono createDataKey(final String kmsProvider, final DataKeyOptions dataKeyOptions) { + return Mono.defer(() -> crypt.createDataKey(kmsProvider, dataKeyOptions)) .flatMap(dataKeyDocument -> { MongoNamespace namespace = new MongoNamespace(options.getKeyVaultNamespace()); @@ -136,7 +114,7 @@ public Mono createDataKey(final String kmsProvider, final DataKeyOpt .getDatabase(namespace.getDatabaseName()) .getCollection(namespace.getCollectionName(), BsonDocument.class) .withWriteConcern(WriteConcern.MAJORITY); - return Mono.from(collectionWithTimeout(vaultCollection, operationTimeout, TIMEOUT_ERROR_MESSAGE_CREATE_DATA_KEY) + return Mono.from(vaultCollection .insertOne(dataKeyDocument)) .map(i -> dataKeyDocument.getBinary("_id")); }); @@ -147,21 +125,21 @@ public Publisher encrypt(final BsonValue value, final EncryptOptions notNull("value", value); notNull("options", options); - return Mono.defer(() -> crypt.encryptExplicitly(value, options, startTimeout())); + return Mono.defer(() -> crypt.encryptExplicitly(value, options)); } @Override public Publisher encryptExpression(final Bson expression, final EncryptOptions options) { return Mono.defer(() -> crypt.encryptExpression( expression.toBsonDocument(BsonDocument.class, collection.getCodecRegistry()), - options, - startTimeout())); + options + )); } @Override public Publisher decrypt(final BsonBinary value) { notNull("value", value); - return Mono.defer(() -> crypt.decryptExplicitly(value, startTimeout())); + return Mono.defer(() -> crypt.decryptExplicitly(value)); } @Override @@ -222,8 +200,8 @@ public Publisher rewrapManyDataKey(final Bson filter) { public Publisher rewrapManyDataKey(final Bson filter, final RewrapManyDataKeyOptions options) { return Mono.fromRunnable(() -> validateRewrapManyDataKeyOptions(options)) .then(Mono.defer(()-> { - Timeout operationTimeout = startTimeout(); - return crypt.rewrapManyDataKey(filter.toBsonDocument(BsonDocument.class, collection.getCodecRegistry()), options, operationTimeout) + Timeout operationTimeout = null; + return crypt.rewrapManyDataKey(filter.toBsonDocument(BsonDocument.class, collection.getCodecRegistry()), options) .flatMap(results -> { if (results.isEmpty()) { return Mono.fromCallable(RewrapManyDataKeyResult::new); @@ -237,7 +215,7 @@ public Publisher rewrapManyDataKey(final Bson filter, f Updates.currentDate("updateDate")) ); }).collect(Collectors.toList()); - return Mono.from(collectionWithTimeout(collection, operationTimeout, TIMEOUT_ERROR_MESSAGE_REWRAP_DATA_KEY) + return Mono.from(collection .bulkWrite(updateModels)).map(RewrapManyDataKeyResult::new); }); })); @@ -266,7 +244,7 @@ public Publisher createEncryptedCollection(final MongoDatabase dat } String keyIdBsonKey = "keyId"; return Mono.defer(() -> { - Timeout operationTimeout = startTimeout(); + Timeout operationTimeout = null; // `Mono.defer` results in `maybeUpdatedEncryptedFields` and `dataKeyMightBeCreated` (mutable state) // being created once per `Subscriber`, which allows the produced `Mono` to support multiple `Subscribers`. BsonDocument maybeUpdatedEncryptedFields = mutableDeepCopy(encryptedFields); @@ -278,7 +256,7 @@ public Publisher createEncryptedCollection(final MongoDatabase dat .filter(field -> field.containsKey(keyIdBsonKey)) .filter(field -> Objects.equals(field.get(keyIdBsonKey), BsonNull.VALUE)) // here we rely on the `createDataKey` publisher being cold, i.e., doing nothing until it is subscribed to - .map(field -> Mono.fromDirect(createDataKey(kmsProvider, dataKeyOptions, operationTimeout)) + .map(field -> Mono.fromDirect(createDataKey(kmsProvider, dataKeyOptions)) // This is the closest we can do with reactive streams to setting the `dataKeyMightBeCreated` flag // immediately before calling `createDataKey`. .doOnSubscribe(subscription -> dataKeyMightBeCreated.set(true)) @@ -300,8 +278,7 @@ public Publisher createEncryptedCollection(final MongoDatabase dat // // Similarly, the `Subscriber` of the returned `Publisher` is guaranteed to observe all those write actions // via the `maybeUpdatedEncryptedFields` reference, which is emitted as a result of `thenReturn`. - .thenEmpty(Mono.defer(() -> Mono.fromDirect(databaseWithTimeout(database, - TIMEOUT_ERROR_MESSAGE_CREATE_COLLECTION, operationTimeout) + .thenEmpty(Mono.defer(() -> Mono.fromDirect(database .createCollection(collectionName, new CreateCollectionOptions(createCollectionOptions) .encryptedFields(maybeUpdatedEncryptedFields)))) ) @@ -312,7 +289,8 @@ public Publisher createEncryptedCollection(final MongoDatabase dat .thenReturn(maybeUpdatedEncryptedFields); }); } else { - return databaseWithTimeoutDeferred(database, startTimeout()) + + return Mono.defer(() -> Mono.just(database)) .flatMap(wrappedDatabase -> Mono.fromDirect(wrappedDatabase .createCollection(collectionName, createCollectionOptions))) .thenReturn(encryptedFields); @@ -325,8 +303,4 @@ public void close() { crypt.close(); } - @Nullable - private Timeout startTimeout() { - return TimeoutContext.startTimeout(options.getTimeout(MILLISECONDS)); - } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideOperationTimeoutProseTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideOperationTimeoutProseTest.java deleted file mode 100644 index 87f7d0a8a2c..00000000000 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/ClientSideOperationTimeoutProseTest.java +++ /dev/null @@ -1,605 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.reactivestreams.client; - -import com.mongodb.MongoClientSettings; -import com.mongodb.MongoCommandException; -import com.mongodb.MongoNamespace; -import com.mongodb.MongoOperationTimeoutException; -import com.mongodb.ReadPreference; -import com.mongodb.WriteConcern; -import com.mongodb.client.AbstractClientSideOperationsTimeoutProseTest; -import com.mongodb.client.model.changestream.FullDocument; -import com.mongodb.event.CommandFailedEvent; -import com.mongodb.event.CommandStartedEvent; -import com.mongodb.internal.InternalMongoClientSettings; -import com.mongodb.reactivestreams.client.gridfs.GridFSBucket; -import com.mongodb.reactivestreams.client.gridfs.GridFSBuckets; -import com.mongodb.reactivestreams.client.syncadapter.SyncGridFSBucket; -import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient; -import com.mongodb.test.FlakyTest; -import org.bson.BsonDocument; -import org.bson.BsonTimestamp; -import org.bson.Document; -import org.bson.types.ObjectId; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; -import reactor.core.publisher.Flux; -import reactor.core.publisher.Hooks; -import reactor.core.publisher.Mono; -import reactor.test.StepVerifier; - -import java.nio.ByteBuffer; -import java.time.Duration; -import java.time.Instant; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.stream.Collectors; - -import static com.mongodb.ClusterFixture.TIMEOUT_DURATION; -import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; -import static com.mongodb.ClusterFixture.isStandalone; -import static com.mongodb.ClusterFixture.serverVersionAtLeast; -import static com.mongodb.ClusterFixture.sleep; -import static com.mongodb.assertions.Assertions.assertTrue; -import static java.util.Collections.singletonList; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assumptions.assumeFalse; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - - -/** - * See https://github.com/mongodb/specifications/blob/master/source/client-side-operations-timeout/tests/README.md#prose-tests - */ -public final class ClientSideOperationTimeoutProseTest extends AbstractClientSideOperationsTimeoutProseTest { - private MongoClient wrapped; - - @Override - protected com.mongodb.client.MongoClient createMongoClient(final MongoClientSettings mongoClientSettings) { - SyncMongoClient client = new SyncMongoClient(mongoClientSettings); - wrapped = client.getWrapped(); - return client; - } - - @Override - protected com.mongodb.client.MongoClient createMongoClientWithInternalSettings(final MongoClientSettings mongoClientSettings, - final InternalMongoClientSettings internalSettings) { - SyncMongoClient client = new SyncMongoClient(mongoClientSettings, null, internalSettings); - wrapped = client.getWrapped(); - return client; - } - - private static MongoClient createReactiveClient(final MongoClientSettings.Builder builder) { - return MongoClients.create(builder.build()); - } - - @Override - protected com.mongodb.client.gridfs.GridFSBucket createGridFsBucket(final com.mongodb.client.MongoDatabase mongoDatabase, - final String bucketName) { - return new SyncGridFSBucket(GridFSBuckets.create(wrapped.getDatabase(mongoDatabase.getName()), bucketName)); - } - - private GridFSBucket createReaciveGridFsBucket(final MongoDatabase mongoDatabase, final String bucketName) { - return GridFSBuckets.create(mongoDatabase, bucketName); - } - - @Override - protected boolean isAsync() { - return true; - } - - @DisplayName("6. GridFS Upload - uploads via openUploadStream can be timed out") - @Test - @Override - public void testGridFSUploadViaOpenUploadStreamTimeout() { - assumeTrue(serverVersionAtLeast(4, 4)); - - //given - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"" + FAIL_COMMAND_NAME + "\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"insert\"]," - + " blockConnection: true," - + " blockTimeMS: " + 600 - + " }" - + "}"); - - try (MongoClient client = createReactiveClient(getMongoClientSettingsBuilder() - .timeout(600, TimeUnit.MILLISECONDS))) { - MongoDatabase database = client.getDatabase(gridFsFileNamespace.getDatabaseName()); - GridFSBucket gridFsBucket = createReaciveGridFsBucket(database, GRID_FS_BUCKET_NAME); - - - TestEventPublisher eventPublisher = new TestEventPublisher<>(); - TestSubscriber testSubscriber = new TestSubscriber<>(); - - gridFsBucket.uploadFromPublisher("filename", eventPublisher.getEventStream()) - .subscribe(testSubscriber); - - //when - eventPublisher.sendEvent(ByteBuffer.wrap(new byte[]{0x12})); - testSubscriber.requestMore(1); - /* - By prose spec definition we have to close GridFSUploadStream when we don't have more data to submit and want to flux internal buffers. - However, in Reactive streams that would be equivalent to calling propagating complete signal from the source publisher. - */ - eventPublisher.complete(); - - //then - testSubscriber.assertTerminalEvent(); - - List onErrorEvents = testSubscriber.getOnErrorEvents(); - assertEquals(1, onErrorEvents.size()); - - Throwable commandError = onErrorEvents.get(0); - assertInstanceOf(MongoOperationTimeoutException.class, commandError); - - CommandFailedEvent chunkInsertFailedEvent = commandListener.getCommandFailedEvent("insert"); - assertNotNull(chunkInsertFailedEvent); - assertEquals(commandError, commandListener.getCommandFailedEvent("insert").getThrowable()); - } - } - - @DisplayName("6. GridFS Upload - Aborting an upload stream can be timed out") - @Test - @Override - public void testAbortingGridFsUploadStreamTimeout() throws ExecutionException, InterruptedException, TimeoutException { - assumeTrue(serverVersionAtLeast(4, 4)); - - //given - CompletableFuture droppedErrorFuture = new CompletableFuture<>(); - Hooks.onErrorDropped(droppedErrorFuture::complete); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"" + FAIL_COMMAND_NAME + "\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"delete\"]," - + " blockConnection: true," - + " blockTimeMS: " + 405 - + " }" - + "}"); - - try (MongoClient client = createReactiveClient(getMongoClientSettingsBuilder() - .timeout(400, TimeUnit.MILLISECONDS))) { - MongoDatabase database = client.getDatabase(gridFsFileNamespace.getDatabaseName()); - GridFSBucket gridFsBucket = createReaciveGridFsBucket(database, GRID_FS_BUCKET_NAME); - - - TestEventPublisher eventPublisher = new TestEventPublisher<>(); - TestSubscriber testSubscriber = new TestSubscriber<>(); - - gridFsBucket.uploadFromPublisher("filename", eventPublisher.getEventStream()) - .subscribe(testSubscriber); - - //when - eventPublisher.sendEvent(ByteBuffer.wrap(new byte[]{0x01, 0x02, 0x03, 0x04})); - testSubscriber.requestMore(1); - /* - By prose spec definition we have to abort GridFSUploadStream. - However, in Reactive streams that would be equivalent to calling subscription to propagate cancellation signal. - */ - testSubscriber.cancelSubscription(); - - //then - Throwable droppedError = droppedErrorFuture.get(TIMEOUT_DURATION.toMillis(), TimeUnit.MILLISECONDS); - Throwable commandError = droppedError.getCause(); - - CommandFailedEvent deleteFailedEvent = commandListener.getCommandFailedEvent("delete"); - assertNotNull(deleteFailedEvent); - - CommandStartedEvent deleteStartedEvent = commandListener.getCommandStartedEvent("delete"); - assertTrue(deleteStartedEvent.getCommand().containsKey("maxTimeMS"), "Expected delete command to have maxTimeMS"); - long deleteMaxTimeMS = deleteStartedEvent - .getCommand() - .get("maxTimeMS") - .asNumber() - .longValue(); - - assertTrue(deleteMaxTimeMS <= 420 - // some leeway for timing variations, when compression is used it is often less then 300. - // Without it, it is more than 300. - && deleteMaxTimeMS >= 150, - "Expected maxTimeMS for delete command to be between 150s and 420ms, " + "but was: " + deleteMaxTimeMS + "ms"); - assertEquals(commandError, deleteFailedEvent.getThrowable()); - - // When subscription is cancelled, we should not receive any more events. - testSubscriber.assertNoTerminalEvent(); - } - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @DisplayName("TimeoutMS applies to full resume attempt in a next call") - @Test - public void testTimeoutMSAppliesToFullResumeAttemptInNextCall() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeTrue(isDiscoverableReplicaSet()); - - //given - try (MongoClient client = createReactiveClient(getMongoClientSettingsBuilder() - .timeout(500, TimeUnit.MILLISECONDS))) { - - MongoNamespace namespace = generateNamespace(); - MongoCollection collection = client.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()).withReadPreference(ReadPreference.primary()); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1}," - + " data: {" - + " failCommands: [\"getMore\" ]," - + " errorCode: 7," - + " errorLabels: [\"ResumableChangeStreamError\" ]" - + " }" - + "}"); - - //when - ChangeStreamPublisher documentChangeStreamPublisher = collection.watch( - singletonList(Document.parse("{ '$match': {'operationType': 'insert'}}"))); - - Assertions.assertThrows(MongoOperationTimeoutException.class, - () -> Flux.from(documentChangeStreamPublisher).blockFirst(TIMEOUT_DURATION)); - //then - sleep(200); //let publisher invalidate the cursor after the error. - List commandStartedEvents = commandListener.getCommandStartedEvents(); - - List expectedCommandNames = Arrays.asList("aggregate", "getMore", "killCursors", "aggregate", "getMore", "killCursors"); - assertCommandStartedEventsInOder(expectedCommandNames, commandStartedEvents); - - List commandFailedEvents = commandListener.getCommandFailedEvents(); - assertEquals(2, commandFailedEvents.size()); - - CommandFailedEvent firstGetMoreFailedEvent = commandFailedEvents.get(0); - assertEquals("getMore", firstGetMoreFailedEvent.getCommandName()); - assertInstanceOf(MongoCommandException.class, firstGetMoreFailedEvent.getThrowable()); - - CommandFailedEvent secondGetMoreFailedEvent = commandFailedEvents.get(1); - assertEquals("getMore", secondGetMoreFailedEvent.getCommandName()); - assertInstanceOf(MongoOperationTimeoutException.class, secondGetMoreFailedEvent.getThrowable()); - } - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @DisplayName("TimeoutMS applied to initial aggregate") - @Test - public void testTimeoutMSAppliedToInitialAggregate() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeTrue(isDiscoverableReplicaSet()); - - //given - try (MongoClient client = createReactiveClient(getMongoClientSettingsBuilder() - .timeout(200, TimeUnit.MILLISECONDS))) { - - MongoNamespace namespace = generateNamespace(); - MongoCollection collection = client.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()).withReadPreference(ReadPreference.primary()); - ChangeStreamPublisher documentChangeStreamPublisher = collection.watch( - singletonList(Document.parse("{ '$match': {'operationType': 'insert'}}"))) - .fullDocument(FullDocument.UPDATE_LOOKUP); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1}," - + " data: {" - + " failCommands: [\"aggregate\" ]," - + " blockConnection: true," - + " blockTimeMS: " + 201 - + " }" - + "}"); - - //when - Assertions.assertThrows(MongoOperationTimeoutException.class, - () -> Flux.from(documentChangeStreamPublisher).blockFirst(TIMEOUT_DURATION)); - - //We do not expect cursor to have been created. However, publisher closes cursor asynchronously, thus we give it some time - // to make sure that cursor has not been closed (which would indicate that it was created). - sleep(200); - - //then - List commandStartedEvents = commandListener.getCommandStartedEvents(); - assertEquals(1, commandStartedEvents.size()); - assertEquals("aggregate", commandStartedEvents.get(0).getCommandName()); - assertOnlyOneCommandTimeoutFailure("aggregate"); - } - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @DisplayName("TimeoutMS is refreshed for getMore if maxAwaitTimeMS is not set") - @Test - public void testTimeoutMsRefreshedForGetMoreWhenMaxAwaitTimeMsNotSet() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeTrue(isDiscoverableReplicaSet()); - - //given - BsonTimestamp startTime = new BsonTimestamp((int) Instant.now().getEpochSecond(), 0); - sleep(2000); - - try (MongoClient client = createReactiveClient(getMongoClientSettingsBuilder() - .timeout(500, TimeUnit.MILLISECONDS))) { - - MongoCollection collection = client.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()).withReadPreference(ReadPreference.primary()); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 3}," - + " data: {" - + " failCommands: [\"getMore\", \"aggregate\"]," - + " blockConnection: true," - + " blockTimeMS: " + 200 - + " }" - + "}"); - - collectionHelper.insertDocuments(WriteConcern.MAJORITY, - BsonDocument.parse("{x: 1}"), - BsonDocument.parse("{x: 2}"), - - BsonDocument.parse("{x: 3}"), - BsonDocument.parse("{x: 4}"), - - BsonDocument.parse("{x: 5}"), - BsonDocument.parse("{x: 6}")); - - //when - ChangeStreamPublisher documentChangeStreamPublisher = collection.watch() - .startAtOperationTime(startTime); - StepVerifier.create(documentChangeStreamPublisher, 2) - //then - .expectNextCount(2) - .thenAwait(Duration.ofMillis(300)) - .thenRequest(2) - .expectNextCount(2) - .thenAwait(Duration.ofMillis(300)) - .thenRequest(2) - .expectNextCount(2) - .thenAwait(Duration.ofMillis(300)) - .thenRequest(2) - .expectError(MongoOperationTimeoutException.class) - .verify(); - - sleep(500); //let publisher invalidate the cursor after the error. - - List commandStartedEvents = commandListener.getCommandStartedEvents(); - List expectedCommandNames = Arrays.asList("aggregate", "getMore", "getMore", "getMore", "killCursors"); - assertCommandStartedEventsInOder(expectedCommandNames, commandStartedEvents); - assertOnlyOneCommandTimeoutFailure("getMore"); - } - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @DisplayName("TimeoutMS is refreshed for getMore if maxAwaitTimeMS is set") - @Test - public void testTimeoutMsRefreshedForGetMoreWhenMaxAwaitTimeMsSet() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeTrue(isDiscoverableReplicaSet()); - - //given - BsonTimestamp startTime = new BsonTimestamp((int) Instant.now().getEpochSecond(), 0); - sleep(2000); - - try (MongoClient client = createReactiveClient(getMongoClientSettingsBuilder() - .timeout(500, TimeUnit.MILLISECONDS))) { - - MongoCollection collection = client.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()) - .withReadPreference(ReadPreference.primary()); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 2}," - + " data: {" - + " failCommands: [\"aggregate\", \"getMore\"]," - + " blockConnection: true," - + " blockTimeMS: " + 200 - + " }" - + "}"); - - - collectionHelper.insertDocuments(WriteConcern.MAJORITY, - BsonDocument.parse("{x: 1}"), - BsonDocument.parse("{x: 2}"), - - BsonDocument.parse("{x: 3}"), - BsonDocument.parse("{x: 4}")); - - //when - ChangeStreamPublisher documentChangeStreamPublisher = collection.watch() - .maxAwaitTime(1, TimeUnit.MILLISECONDS) - .startAtOperationTime(startTime); - StepVerifier.create(documentChangeStreamPublisher, 2) - //then - .expectNextCount(2) - .thenAwait(Duration.ofMillis(600)) - .thenRequest(2) - .expectNextCount(2) - .thenCancel() - .verify(); - - sleep(500); //let publisher invalidate the cursor after the error. - - List commandStartedEvents = commandListener.getCommandStartedEvents(); - List expectedCommandNames = Arrays.asList("aggregate", "getMore", "killCursors"); - assertCommandStartedEventsInOder(expectedCommandNames, commandStartedEvents); - } - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @DisplayName("TimeoutMS is honored for next operation when several getMore executed internally") - // TODO-JAVA-6341: this test intermittently timesout in CI - @FlakyTest(maxAttempts = 3) - public void testTimeoutMsISHonoredForNnextOperationWhenSeveralGetMoreExecutedInternally() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeTrue(isDiscoverableReplicaSet()); - - //given - try (MongoClient client = createReactiveClient(getMongoClientSettingsBuilder() - .timeout(2500, TimeUnit.MILLISECONDS))) { - - MongoCollection collection = client.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()).withReadPreference(ReadPreference.primary()); - - //when - ChangeStreamPublisher documentChangeStreamPublisher = collection.watch().maxAwaitTime(1000, TimeUnit.MILLISECONDS); - StepVerifier.create(documentChangeStreamPublisher, 2) - //then - .expectError(MongoOperationTimeoutException.class) - .verify(); - - sleep(200); //let publisher invalidate the cursor after the error. - - List commandStartedEvents = commandListener.getCommandStartedEvents(); - assertCommandStartedEventsInOder(Arrays.asList("aggregate", "getMore", "getMore", "getMore", "killCursors"), - commandStartedEvents); - - } - } - - @DisplayName("9. End Session. The timeout specified via the MongoClient timeoutMS option") - @Test - @Override - public void test9EndSessionClientTimeout() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeFalse(isStandalone()); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"abortTransaction\"]," - + " blockConnection: true," - + " blockTimeMS: " + 400 - + " }" - + "}"); - - try (MongoClient mongoClient = createReactiveClient(getMongoClientSettingsBuilder().retryWrites(false) - .timeout(300, TimeUnit.MILLISECONDS))) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - try (ClientSession session = Mono.from(mongoClient.startSession()).block()) { - session.startTransaction(); - Mono.from(collection.insertOne(session, new Document("x", 1))).block(); - } - - sleep(postSessionCloseSleep()); - CommandFailedEvent abortTransactionEvent = assertDoesNotThrow(() -> commandListener.getCommandFailedEvent("abortTransaction")); - long elapsedTime = abortTransactionEvent.getElapsedTime(TimeUnit.MILLISECONDS); - assertInstanceOf(MongoOperationTimeoutException.class, abortTransactionEvent.getThrowable()); - assertTrue(elapsedTime <= 400, "Took too long to time out, elapsedMS: " + elapsedTime); - } - } - - @Test - @DisplayName("9. End Session. The timeout specified via the ClientSession defaultTimeoutMS option") - @Override - public void test9EndSessionSessionTimeout() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeFalse(isStandalone()); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"abortTransaction\"]," - + " blockConnection: true," - + " blockTimeMS: " + 400 - + " }" - + "}"); - - try (MongoClient mongoClient = createReactiveClient(getMongoClientSettingsBuilder())) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - try (ClientSession session = Mono.from(mongoClient.startSession(com.mongodb.ClientSessionOptions.builder() - .defaultTimeout(300, TimeUnit.MILLISECONDS).build())).block()) { - - session.startTransaction(); - Mono.from(collection.insertOne(session, new Document("x", 1))).block(); - } - - sleep(postSessionCloseSleep()); - CommandFailedEvent abortTransactionEvent = assertDoesNotThrow(() -> commandListener.getCommandFailedEvent("abortTransaction")); - long elapsedTime = abortTransactionEvent.getElapsedTime(TimeUnit.MILLISECONDS); - assertInstanceOf(MongoOperationTimeoutException.class, abortTransactionEvent.getThrowable()); - assertTrue(elapsedTime <= 400, "Took too long to time out, elapsedMS: " + elapsedTime); - } - } - - private static void assertCommandStartedEventsInOder(final List expectedCommandNames, - final List commandStartedEvents) { - assertEquals(expectedCommandNames.size(), commandStartedEvents.size(), "Expected: " + expectedCommandNames + ". Actual: " - + commandStartedEvents.stream() - .map(CommandStartedEvent::getCommand) - .map(BsonDocument::toJson) - .collect(Collectors.toList())); - - for (int i = 0; i < expectedCommandNames.size(); i++) { - CommandStartedEvent commandStartedEvent = commandStartedEvents.get(i); - - assertEquals(expectedCommandNames.get(i), commandStartedEvent.getCommandName()); - } - } - - private void assertOnlyOneCommandTimeoutFailure(final String command) { - List commandFailedEvents = commandListener.getCommandFailedEvents(); - assertEquals(1, commandFailedEvents.size()); - - CommandFailedEvent failedAggregateCommandEvent = commandFailedEvents.get(0); - assertEquals(command, commandFailedEvents.get(0).getCommandName()); - assertInstanceOf(MongoOperationTimeoutException.class, failedAggregateCommandEvent.getThrowable()); - } - - @Override - @BeforeEach - public void setUp() { - super.setUp(); - SyncMongoClient.enableSleepAfterSessionClose(postSessionCloseSleep()); - } - - @Override - @AfterEach - public void tearDown() throws InterruptedException { - super.tearDown(); - SyncMongoClient.disableSleep(); - } - - @Override - protected int postSessionCloseSleep() { - return 1000; - } -} diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/csot/ClientSideOperationsEncryptionTimeoutProseTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/csot/ClientSideOperationsEncryptionTimeoutProseTest.java deleted file mode 100644 index 877f3774015..00000000000 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/csot/ClientSideOperationsEncryptionTimeoutProseTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.reactivestreams.client.csot; - - -import com.mongodb.ClientEncryptionSettings; -import com.mongodb.MongoClientSettings; -import com.mongodb.client.MongoClient; -import com.mongodb.client.csot.AbstractClientSideOperationsEncryptionTimeoutProseTest; -import com.mongodb.client.vault.ClientEncryption; -import com.mongodb.reactivestreams.client.syncadapter.SyncClientEncryption; -import com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient; -import com.mongodb.reactivestreams.client.vault.ClientEncryptions; - -public class ClientSideOperationsEncryptionTimeoutProseTest extends AbstractClientSideOperationsEncryptionTimeoutProseTest { - public ClientEncryption createClientEncryption(final ClientEncryptionSettings.Builder builder) { - return new SyncClientEncryption(ClientEncryptions.create(builder.build())); - } - - @Override - protected MongoClient createMongoClient(final MongoClientSettings.Builder builder) { - return new SyncMongoClient(builder); - } -} diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncAggregateIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncAggregateIterable.java index 6b81b1f42af..21c0921225a 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncAggregateIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncAggregateIterable.java @@ -17,7 +17,6 @@ import com.mongodb.ExplainVerbosity; import com.mongodb.client.AggregateIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.AggregatePublisher; @@ -112,12 +111,6 @@ public AggregateIterable let(final Bson variables) { return this; } - @Override - public AggregateIterable timeoutMode(final TimeoutMode timeoutMode) { - wrapped.timeoutMode(timeoutMode); - return this; - } - @Override public Document explain() { return requireNonNull(Mono.from(wrapped.explain()).contextWrite(CONTEXT).block(TIMEOUT_DURATION)); diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncDistinctIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncDistinctIterable.java index 5b3e3c71fe1..2b75c370616 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncDistinctIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncDistinctIterable.java @@ -17,7 +17,6 @@ package com.mongodb.reactivestreams.client.syncadapter; import com.mongodb.client.DistinctIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.DistinctPublisher; @@ -82,10 +81,4 @@ public DistinctIterable hintString(@Nullable final String hint) { wrapped.hintString(hint); return this; } - - @Override - public DistinctIterable timeoutMode(final TimeoutMode timeoutMode) { - wrapped.timeoutMode(timeoutMode); - return this; - } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncFindIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncFindIterable.java index 3cf93b9ffb0..0cc68b0042e 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncFindIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncFindIterable.java @@ -19,7 +19,6 @@ import com.mongodb.CursorType; import com.mongodb.ExplainVerbosity; import com.mongodb.client.FindIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.FindPublisher; @@ -175,12 +174,6 @@ public FindIterable allowDiskUse(@Nullable final java.lang.Boolean allowDiskU return this; } - @Override - public FindIterable timeoutMode(final TimeoutMode timeoutMode) { - wrapped.timeoutMode(timeoutMode); - return this; - } - @Override public Document explain() { return requireNonNull(Mono.from(wrapped.explain()).contextWrite(CONTEXT).block(TIMEOUT_DURATION)); diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncGridFSBucket.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncGridFSBucket.java index 48b28e5540a..562c7ae80fe 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncGridFSBucket.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncGridFSBucket.java @@ -42,7 +42,6 @@ import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static com.mongodb.ClusterFixture.TIMEOUT_DURATION; import static com.mongodb.reactivestreams.client.syncadapter.ContextHelper.CONTEXT; @@ -80,11 +79,6 @@ public ReadConcern getReadConcern() { return wrapped.getReadConcern(); } - @Override - public Long getTimeout(final TimeUnit timeUnit) { - return wrapped.getTimeout(timeUnit); - } - @Override public GridFSBucket withChunkSizeBytes(final int chunkSizeBytes) { return new SyncGridFSBucket(wrapped.withChunkSizeBytes(chunkSizeBytes)); @@ -105,11 +99,6 @@ public GridFSBucket withReadConcern(final ReadConcern readConcern) { return new SyncGridFSBucket(wrapped.withReadConcern(readConcern)); } - @Override - public GridFSBucket withTimeout(final long timeout, final TimeUnit timeUnit) { - return new SyncGridFSBucket(wrapped.withTimeout(timeout, timeUnit)); - } - @Override public GridFSUploadStream openUploadStream(final String filename) { return openUploadStream(filename, new GridFSUploadOptions()); diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListCollectionsIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListCollectionsIterable.java index 48d88963077..5dfa3fe76d6 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListCollectionsIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListCollectionsIterable.java @@ -17,7 +17,6 @@ package com.mongodb.reactivestreams.client.syncadapter; import com.mongodb.client.ListCollectionsIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.ListCollectionsPublisher; import org.bson.BsonValue; @@ -63,10 +62,4 @@ public ListCollectionsIterable comment(final BsonValue comment) { wrapped.comment(comment); return this; } - - @Override - public ListCollectionsIterable timeoutMode(final TimeoutMode timeoutMode) { - wrapped.timeoutMode(timeoutMode); - return this; - } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListDatabasesIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListDatabasesIterable.java index 4248e59c361..53f901e538b 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListDatabasesIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListDatabasesIterable.java @@ -17,7 +17,6 @@ package com.mongodb.reactivestreams.client.syncadapter; import com.mongodb.client.ListDatabasesIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.lang.Nullable; import com.mongodb.reactivestreams.client.ListDatabasesPublisher; import org.bson.BsonValue; @@ -75,10 +74,4 @@ public ListDatabasesIterable comment(final BsonValue comment) { wrapped.comment(comment); return this; } - - @Override - public ListDatabasesIterable timeoutMode(final TimeoutMode timeoutMode) { - wrapped.timeoutMode(timeoutMode); - return this; - } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListIndexesIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListIndexesIterable.java index 947cb8f0d0f..3cec57e3ce0 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListIndexesIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListIndexesIterable.java @@ -17,7 +17,6 @@ package com.mongodb.reactivestreams.client.syncadapter; import com.mongodb.client.ListIndexesIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.reactivestreams.client.ListIndexesPublisher; import org.bson.BsonValue; @@ -55,10 +54,4 @@ public ListIndexesIterable comment(final BsonValue comment) { wrapped.comment(comment); return this; } - - @Override - public ListIndexesIterable timeoutMode(final TimeoutMode timeoutMode) { - wrapped.timeoutMode(timeoutMode); - return this; - } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListSearchIndexesIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListSearchIndexesIterable.java index f119c645916..7efbde8d9fa 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListSearchIndexesIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncListSearchIndexesIterable.java @@ -18,7 +18,6 @@ import com.mongodb.ExplainVerbosity; import com.mongodb.client.ListSearchIndexesIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.reactivestreams.client.ListSearchIndexesPublisher; import org.bson.BsonValue; @@ -81,12 +80,6 @@ public ListSearchIndexesIterable comment(final BsonValue comment) { return this; } - @Override - public ListSearchIndexesIterable timeoutMode(final TimeoutMode timeoutMode) { - wrapped.timeoutMode(timeoutMode); - return this; - } - @Override public Document explain() { return requireNonNull(Mono.from(wrapped.explain()).contextWrite(CONTEXT).block(TIMEOUT_DURATION)); diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMapReduceIterable.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMapReduceIterable.java index efc70b690fa..623ad2310d8 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMapReduceIterable.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMapReduceIterable.java @@ -16,7 +16,6 @@ package com.mongodb.reactivestreams.client.syncadapter; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.lang.Nullable; import org.bson.conversions.Bson; @@ -126,10 +125,4 @@ public com.mongodb.client.MapReduceIterable collation(@Nullable final Collati wrapped.collation(collation); return this; } - - @Override - public com.mongodb.client.MapReduceIterable timeoutMode(final TimeoutMode timeoutMode) { - wrapped.timeoutMode(timeoutMode); - return this; - } } diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoClient.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoClient.java index 23764d49180..532e5b788ae 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoClient.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoClient.java @@ -47,7 +47,6 @@ import org.bson.conversions.Bson; import java.util.List; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static com.mongodb.ClusterFixture.sleep; @@ -193,11 +192,6 @@ public ReadConcern getReadConcern() { return delegate.getReadConcern(); } - @Override - public Long getTimeout(final TimeUnit timeUnit) { - return delegate.getTimeout(timeUnit); - } - @Override public MongoCluster withCodecRegistry(final CodecRegistry codecRegistry) { return delegate.withCodecRegistry(codecRegistry); @@ -218,11 +212,6 @@ public MongoCluster withReadConcern(final ReadConcern readConcern) { return delegate.withReadConcern(readConcern); } - @Override - public MongoCluster withTimeout(final long timeout, final TimeUnit timeUnit) { - return delegate.withTimeout(timeout, timeUnit); - } - @Override public MongoDatabase getDatabase(final String databaseName) { return delegate.getDatabase(databaseName); diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCluster.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCluster.java index fc3cad4b6a7..0567a28575a 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCluster.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCluster.java @@ -37,7 +37,6 @@ import reactor.core.publisher.Mono; import java.util.List; -import java.util.concurrent.TimeUnit; import static com.mongodb.ClusterFixture.TIMEOUT_DURATION; import static com.mongodb.reactivestreams.client.syncadapter.ContextHelper.CONTEXT; @@ -166,11 +165,6 @@ public ReadConcern getReadConcern() { return wrapped.getReadConcern(); } - @Override - public Long getTimeout(final TimeUnit timeUnit) { - return wrapped.getTimeout(timeUnit); - } - @Override public MongoCluster withCodecRegistry(final CodecRegistry codecRegistry) { return new SyncMongoCluster(wrapped.withCodecRegistry(codecRegistry)); @@ -191,11 +185,6 @@ public MongoCluster withReadConcern(final ReadConcern readConcern) { return new SyncMongoCluster(wrapped.withReadConcern(readConcern)); } - @Override - public MongoCluster withTimeout(final long timeout, final TimeUnit timeUnit) { - return new SyncMongoCluster(wrapped.withTimeout(timeout, timeUnit)); - } - @Override public MongoDatabase getDatabase(final String databaseName) { return new SyncMongoDatabase(wrapped.getDatabase(databaseName)); diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCollection.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCollection.java index 922e07cc2d5..64d94984b2e 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCollection.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoCollection.java @@ -59,7 +59,6 @@ import reactor.core.publisher.Mono; import java.util.List; -import java.util.concurrent.TimeUnit; import static com.mongodb.ClusterFixture.TIMEOUT_DURATION; import static com.mongodb.reactivestreams.client.syncadapter.ContextHelper.CONTEXT; @@ -103,11 +102,6 @@ public ReadConcern getReadConcern() { return wrapped.getReadConcern(); } - @Override - public Long getTimeout(final TimeUnit timeUnit) { - return wrapped.getTimeout(timeUnit); - } - @Override public MongoCollection withDocumentClass(final Class clazz) { return new SyncMongoCollection<>(wrapped.withDocumentClass(clazz)); @@ -133,11 +127,6 @@ public MongoCollection withReadConcern(final ReadConcern readConcern) { return new SyncMongoCollection<>(wrapped.withReadConcern(readConcern)); } - @Override - public MongoCollection withTimeout(final long timeout, final TimeUnit timeUnit) { - return new SyncMongoCollection<>(wrapped.withTimeout(timeout, timeUnit)); - } - @Override public long countDocuments() { return requireNonNull(Mono.from(wrapped.countDocuments()).contextWrite(CONTEXT).block(TIMEOUT_DURATION)); diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoDatabase.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoDatabase.java index 40b15632366..f1e6d125842 100644 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoDatabase.java +++ b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/syncadapter/SyncMongoDatabase.java @@ -34,7 +34,6 @@ import reactor.core.publisher.Mono; import java.util.List; -import java.util.concurrent.TimeUnit; import static com.mongodb.ClusterFixture.TIMEOUT_DURATION; import static com.mongodb.reactivestreams.client.syncadapter.ContextHelper.CONTEXT; @@ -76,11 +75,6 @@ public ReadConcern getReadConcern() { return wrapped.getReadConcern(); } - @Override - public Long getTimeout(final TimeUnit timeUnit) { - return wrapped.getTimeout(timeUnit); - } - @Override public MongoDatabase withCodecRegistry(final CodecRegistry codecRegistry) { return new SyncMongoDatabase(wrapped.withCodecRegistry(codecRegistry)); @@ -101,11 +95,6 @@ public MongoDatabase withReadConcern(final ReadConcern readConcern) { return new SyncMongoDatabase(wrapped.withReadConcern(readConcern)); } - @Override - public MongoDatabase withTimeout(final long timeout, final TimeUnit timeUnit) { - return new SyncMongoDatabase(wrapped.withTimeout(timeout, timeUnit)); - } - @Override public MongoCollection getCollection(final String collectionName) { return new SyncMongoCollection<>(wrapped.getCollection(collectionName)); diff --git a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ClientSideOperationTimeoutTest.java b/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ClientSideOperationTimeoutTest.java deleted file mode 100644 index b00b8c365cb..00000000000 --- a/driver-reactive-streams/src/test/functional/com/mongodb/reactivestreams/client/unified/ClientSideOperationTimeoutTest.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.reactivestreams.client.unified; - -import com.mongodb.lang.Nullable; -import org.bson.BsonArray; -import org.bson.BsonDocument; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; -import reactor.core.publisher.Hooks; - -import java.util.Collection; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - -import static com.mongodb.client.ClientSideOperationTimeoutTest.skipOperationTimeoutTests; -import static com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient.disableSleep; -import static com.mongodb.reactivestreams.client.syncadapter.SyncMongoClient.enableSleepAfterCursorError; -import static java.lang.String.format; -import static java.util.Arrays.asList; -import static org.junit.jupiter.api.Assumptions.assumeFalse; - - -// See https://github.com/mongodb/specifications/tree/master/source/client-side-operation-timeout/tests -public class ClientSideOperationTimeoutTest extends UnifiedReactiveStreamsTest { - - private final AtomicReference atomicReferenceThrowable = new AtomicReference<>(); - - private static Collection data() { - return getTestData("client-side-operations-timeout"); - } - - @Override - protected void skips(final String fileDescription, final String testDescription) { - skipOperationTimeoutTests(fileDescription, testDescription); - - assumeFalse(testDescription.equals("timeoutMS is refreshed for getMore if maxAwaitTimeMS is not set"), - "No iterateOnce support. There is alternative prose test for it."); - assumeFalse(testDescription.equals("timeoutMS is refreshed for getMore if maxAwaitTimeMS is set"), - "No iterateOnce support. There is alternative prose test for it."); - /* - The Reactive Streams specification prevents us from allowing a subsequent next call (event in reactive terms) after a timeout error, - conflicting with the CSOT spec requirement not to invalidate the change stream and to try resuming and establishing a new change - stream on the server. We immediately let users know about a timeout error, which then closes the stream/publisher. - */ - assumeFalse(testDescription.equals("change stream can be iterated again if previous iteration times out"), - "It is not possible due to a conflict with the Reactive Streams specification ."); - assumeFalse(testDescription.equals("timeoutMS applies to full resume attempt in a next call"), - "Flaky and racy due to asynchronous behaviour. There is alternative prose test for it."); - assumeFalse(testDescription.equals("timeoutMS applied to initial aggregate"), - "No way to catch an error on BarchCursor creation. There is alternative prose test for it."); - - assumeFalse(testDescription.endsWith("createChangeStream on client")); - assumeFalse(testDescription.endsWith("createChangeStream on database")); - assumeFalse(testDescription.endsWith("createChangeStream on collection")); - - // No withTransaction support - assumeFalse(fileDescription.contains("withTransaction") || testDescription.contains("withTransaction")); - - assumeFalse(fileDescription.equals("operations ignore deprecated timeout options if timeoutMS is set") - && (testDescription.startsWith("abortTransaction ignores") || testDescription.startsWith("commitTransaction ignores")), - "No operation session based overrides"); - - if (testDescription.equals("timeoutMS is refreshed for close")) { - enableSleepAfterCursorError(256); - } - - /* - * The test is occasionally racy. The "killCursors" command may appear as an additional event. This is unexpected in unified tests, - * but anticipated in reactive streams because an operation timeout error triggers the closure of the stream/publisher. - */ - ignoreExtraCommandEvents(testDescription.contains("timeoutMS is refreshed for getMore - failure")); - - Hooks.onOperatorDebug(); - Hooks.onErrorDropped(atomicReferenceThrowable::set); - } - - @ParameterizedTest(name = "{0}: {1}") - @MethodSource("data") - @Override - public void shouldPassAllOutcomes( - final String testName, - @Nullable final String fileDescription, - @Nullable final String testDescription, - @Nullable final String directoryName, - final int attemptNumber, - final int totalAttempts, - final String schemaVersion, - @Nullable final BsonArray runOnRequirements, - final BsonArray entitiesArray, - final BsonArray initialData, - final BsonDocument definition) { - try { - super.shouldPassAllOutcomes( - testName, - fileDescription, - testDescription, - directoryName, - attemptNumber, - totalAttempts, - schemaVersion, - runOnRequirements, - entitiesArray, - initialData, - definition); - - } catch (AssertionError e) { - assertNoDroppedError(format("%s failed due to %s.\n" - + "The test also caused a dropped error; `onError` called with no handler.", - testDescription, e.getMessage())); - if (racyTestAssertion(testDescription, e)) { - // Ignore failure - racy test often no time to do the getMore - return; - } - throw e; - } - assertNoDroppedError(format("%s passed but there was a dropped error; `onError` called with no handler.", testDescription)); - } - - @AfterEach - public void cleanUp() { - super.cleanUp(); - disableSleep(); - Hooks.resetOnOperatorDebug(); - Hooks.resetOnErrorDropped(); - } - - public static boolean racyTestAssertion(final String testDescription, final AssertionError e) { - return RACY_GET_MORE_TESTS.contains(testDescription) && e.getMessage().startsWith("Number of events must be the same"); - } - - private static final List RACY_GET_MORE_TESTS = asList( - "remaining timeoutMS applied to getMore if timeoutMode is cursor_lifetime", - "remaining timeoutMS applied to getMore if timeoutMode is unset"); - - private void assertNoDroppedError(final String message) { - Throwable droppedError = atomicReferenceThrowable.get(); - if (droppedError != null) { - throw new AssertionError(message, droppedError); - } - } -} diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoClusterImplTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoClusterImplTest.java index b79d3a645d9..38e641fa65e 100644 --- a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoClusterImplTest.java +++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoClusterImplTest.java @@ -38,7 +38,6 @@ import reactor.core.publisher.Mono; import java.util.List; -import java.util.concurrent.TimeUnit; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; @@ -76,11 +75,6 @@ public void withReadPreference() { .getReadPreference()); } - @Test - public void withTimeout() { - assertEquals(1000, mongoCluster.withTimeout(1000, TimeUnit.MILLISECONDS).getTimeout(TimeUnit.MILLISECONDS)); - } - @Test public void withWriteConcern() { assertEquals(WriteConcern.MAJORITY, mongoCluster.withWriteConcern(WriteConcern.MAJORITY).getWriteConcern()); diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoCollectionImplTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoCollectionImplTest.java index 97b7bbf0d78..63274c8f916 100644 --- a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoCollectionImplTest.java +++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoCollectionImplTest.java @@ -112,11 +112,6 @@ public void withReadPreference() { .getReadPreference()); } - @Test - public void withTimeout() { - assertEquals(1000, collection.withTimeout(1000, TimeUnit.MILLISECONDS).getTimeout(TimeUnit.MILLISECONDS)); - } - @Test public void withWriteConcern() { assertEquals(WriteConcern.MAJORITY, collection.withWriteConcern(WriteConcern.MAJORITY).getWriteConcern()); diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoDatabaseImplTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoDatabaseImplTest.java index f50e44a7db6..a69dc8b8157 100644 --- a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoDatabaseImplTest.java +++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoDatabaseImplTest.java @@ -40,7 +40,6 @@ import org.reactivestreams.Publisher; import java.util.List; -import java.util.concurrent.TimeUnit; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; @@ -76,11 +75,6 @@ public void withReadPreference() { .getReadPreference()); } - @Test - public void withTimeout() { - assertEquals(1000, database.withTimeout(1000, TimeUnit.MILLISECONDS).getTimeout(TimeUnit.MILLISECONDS)); - } - @Test public void withWriteConcern() { assertEquals(WriteConcern.MAJORITY, database.withWriteConcern(WriteConcern.MAJORITY).getWriteConcern()); diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoOperationPublisherTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoOperationPublisherTest.java index b0d1bdbc4ea..4fb2c6e0235 100644 --- a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoOperationPublisherTest.java +++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/MongoOperationPublisherTest.java @@ -29,12 +29,8 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import java.util.concurrent.TimeUnit; - -import static com.mongodb.ClusterFixture.TIMEOUT; -import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS_WITH_TIMEOUT; +import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; @@ -55,7 +51,7 @@ public class MongoOperationPublisherTest { private static final MongoOperationPublisher DEFAULT_MOP = new MongoOperationPublisher<>( MONGO_NAMESPACE, Document.class, MongoClientSettings.getDefaultCodecRegistry(), ReadPreference.primary(), ReadConcern.DEFAULT, WriteConcern.ACKNOWLEDGED, true, true, null, UuidRepresentation.STANDARD, - null, TIMEOUT_SETTINGS_WITH_TIMEOUT, OPERATION_EXECUTOR); + null, TIMEOUT_SETTINGS, OPERATION_EXECUTOR); @Test public void withCodecRegistry() { @@ -112,13 +108,6 @@ public void withReadPreference() { .getReadPreference()); } - @Test - public void withTimeout() { - assertEquals(DEFAULT_MOP, DEFAULT_MOP.withTimeout(TIMEOUT, TimeUnit.SECONDS)); - assertEquals(1000, DEFAULT_MOP.withTimeout(1000, TimeUnit.MILLISECONDS).getTimeoutMS()); - assertThrows(IllegalArgumentException.class, () -> DEFAULT_MOP.withTimeout(500, TimeUnit.NANOSECONDS)); - } - @Test public void withWriteConcern() { assertEquals(DEFAULT_MOP, DEFAULT_MOP.withWriteConcern(WriteConcern.ACKNOWLEDGED)); diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/TimeoutHelperTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/TimeoutHelperTest.java index 01924c61f0e..d102fb6dc19 100644 --- a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/TimeoutHelperTest.java +++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/TimeoutHelperTest.java @@ -16,47 +16,27 @@ package com.mongodb.reactivestreams.client.internal; -import com.mongodb.MongoOperationTimeoutException; -import com.mongodb.internal.time.Timeout; import com.mongodb.reactivestreams.client.MongoCollection; import com.mongodb.reactivestreams.client.MongoDatabase; import org.bson.Document; import org.junit.jupiter.api.Test; - -import java.util.concurrent.TimeUnit; +import reactor.core.publisher.Mono; import static com.mongodb.internal.mockito.MongoMockito.mock; -import static com.mongodb.internal.time.Timeout.ZeroSemantics.ZERO_DURATION_MEANS_EXPIRED; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.collectionWithTimeout; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.collectionWithTimeoutDeferred; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.collectionWithTimeoutMono; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.databaseWithTimeout; -import static com.mongodb.reactivestreams.client.internal.TimeoutHelper.databaseWithTimeoutDeferred; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.longThat; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; @SuppressWarnings("unchecked") class TimeoutHelperTest { - private static final String TIMEOUT_ERROR_MESSAGE = "message"; - private static final String DEFAULT_TIMEOUT_ERROR_MESSAGE = "Operation exceeded the timeout limit."; - @Test void shouldNotSetRemainingTimeoutOnCollectionWhenTimeoutIsNull() { //given MongoCollection collection = mock(MongoCollection.class); //when - MongoCollection result = collectionWithTimeout(collection, null); - MongoCollection monoResult = collectionWithTimeoutMono(collection, null).block(); - MongoCollection monoResultDeferred = collectionWithTimeoutDeferred(collection, null).block(); + MongoCollection result = collection; + MongoCollection monoResult = Mono.just(collection).block(); + MongoCollection monoResultDeferred = Mono.defer(() -> Mono.just(collection)).block(); //then assertEquals(collection, result); @@ -70,164 +50,13 @@ void shouldNotSetRemainingTimeoutDatabaseWhenTimeoutIsNull() { MongoDatabase database = mock(MongoDatabase.class); //when - MongoDatabase result = databaseWithTimeout(database, TIMEOUT_ERROR_MESSAGE, null); - MongoDatabase monoResultDeferred = databaseWithTimeoutDeferred(database, TIMEOUT_ERROR_MESSAGE, null).block(); + MongoDatabase result = database; + + MongoDatabase monoResultDeferred = Mono.defer(() -> Mono.just(database)).block(); //then assertEquals(database, result); assertEquals(database, monoResultDeferred); } - @Test - void shouldNotSetRemainingTimeoutOnCollectionWhenTimeoutIsInfinite() { - //given - MongoCollection collectionWithTimeout = mock(MongoCollection.class); - MongoCollection collection = mock(MongoCollection.class, mongoCollection -> { - when(mongoCollection.withTimeout(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(collectionWithTimeout); - }); - - //when - MongoCollection result = collectionWithTimeout(collection, Timeout.infinite()); - MongoCollection monoResult = collectionWithTimeoutMono(collection, Timeout.infinite()).block(); - MongoCollection monoResultDeferred = collectionWithTimeoutDeferred(collection, Timeout.infinite()).block(); - - //then - assertEquals(collectionWithTimeout, result); - assertEquals(collectionWithTimeout, monoResult); - assertEquals(collectionWithTimeout, monoResultDeferred); - verify(collection, times(3)) - .withTimeout(0L, TimeUnit.MILLISECONDS); - } - - @Test - void shouldNotSetRemainingTimeoutOnDatabaseWhenTimeoutIsInfinite() { - //given - MongoDatabase databaseWithTimeout = mock(MongoDatabase.class); - MongoDatabase database = mock(MongoDatabase.class, mongoDatabase -> { - when(mongoDatabase.withTimeout(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(databaseWithTimeout); - }); - - //when - MongoDatabase result = databaseWithTimeout(database, TIMEOUT_ERROR_MESSAGE, Timeout.infinite()); - MongoDatabase monoResultDeferred = databaseWithTimeoutDeferred(database, TIMEOUT_ERROR_MESSAGE, Timeout.infinite()).block(); - - //then - assertEquals(databaseWithTimeout, result); - assertEquals(databaseWithTimeout, monoResultDeferred); - verify(database, times(2)) - .withTimeout(0L, TimeUnit.MILLISECONDS); - } - - @Test - void shouldSetRemainingTimeoutOnCollectionWhenTimeout() { - //given - MongoCollection collectionWithTimeout = mock(MongoCollection.class); - MongoCollection collection = mock(MongoCollection.class, mongoCollection -> { - when(mongoCollection.withTimeout(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(collectionWithTimeout); - }); - Timeout timeout = Timeout.expiresIn(1, TimeUnit.DAYS, ZERO_DURATION_MEANS_EXPIRED); - - //when - MongoCollection result = collectionWithTimeout(collection, timeout); - MongoCollection monoResult = collectionWithTimeoutMono(collection, timeout).block(); - MongoCollection monoResultDeferred = collectionWithTimeoutDeferred(collection, timeout).block(); - - //then - verify(collection, times(3)) - .withTimeout(longThat(remaining -> remaining > 0), eq(TimeUnit.MILLISECONDS)); - assertEquals(collectionWithTimeout, result); - assertEquals(collectionWithTimeout, monoResult); - assertEquals(collectionWithTimeout, monoResultDeferred); - } - - @Test - void shouldSetRemainingTimeoutOnDatabaseWhenTimeout() { - //given - MongoDatabase databaseWithTimeout = mock(MongoDatabase.class); - MongoDatabase database = mock(MongoDatabase.class, mongoDatabase -> { - when(mongoDatabase.withTimeout(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(databaseWithTimeout); - }); - Timeout timeout = Timeout.expiresIn(1, TimeUnit.DAYS, ZERO_DURATION_MEANS_EXPIRED); - - //when - MongoDatabase result = databaseWithTimeout(database, TIMEOUT_ERROR_MESSAGE, timeout); - MongoDatabase monoResultDeferred = databaseWithTimeoutDeferred(database, TIMEOUT_ERROR_MESSAGE, timeout).block(); - - //then - verify(database, times(2)) - .withTimeout(longThat(remaining -> remaining > 0), eq(TimeUnit.MILLISECONDS)); - assertEquals(databaseWithTimeout, result); - assertEquals(databaseWithTimeout, monoResultDeferred); - } - - @Test - void shouldThrowErrorWhenTimeoutHasExpiredOnCollection() { - //given - MongoCollection collection = mock(MongoCollection.class); - Timeout timeout = Timeout.expiresIn(1, TimeUnit.MICROSECONDS, ZERO_DURATION_MEANS_EXPIRED); - - //when - MongoOperationTimeoutException mongoExecutionTimeoutException = - assertThrows(MongoOperationTimeoutException.class, () -> collectionWithTimeout(collection, timeout)); - MongoOperationTimeoutException mongoExecutionTimeoutExceptionMono = - assertThrows(MongoOperationTimeoutException.class, () -> collectionWithTimeoutMono(collection, timeout).block()); - MongoOperationTimeoutException mongoExecutionTimeoutExceptionDeferred = - assertThrows(MongoOperationTimeoutException.class, () -> collectionWithTimeoutDeferred(collection, timeout).block()); - - //then - assertEquals(DEFAULT_TIMEOUT_ERROR_MESSAGE, mongoExecutionTimeoutExceptionMono.getMessage()); - assertEquals(DEFAULT_TIMEOUT_ERROR_MESSAGE, mongoExecutionTimeoutException.getMessage()); - assertEquals(DEFAULT_TIMEOUT_ERROR_MESSAGE, mongoExecutionTimeoutExceptionDeferred.getMessage()); - verifyNoInteractions(collection); - } - - @Test - void shouldThrowErrorWhenTimeoutHasExpiredOnDatabase() { - //given - MongoDatabase database = mock(MongoDatabase.class); - Timeout timeout = Timeout.expiresIn(1, TimeUnit.MICROSECONDS, ZERO_DURATION_MEANS_EXPIRED); - - //when - MongoOperationTimeoutException mongoExecutionTimeoutException = - assertThrows(MongoOperationTimeoutException.class, () -> databaseWithTimeout(database, TIMEOUT_ERROR_MESSAGE, timeout)); - MongoOperationTimeoutException mongoExecutionTimeoutExceptionDeferred = - assertThrows(MongoOperationTimeoutException.class, - () -> databaseWithTimeoutDeferred(database, TIMEOUT_ERROR_MESSAGE, timeout) - .block()); - - //then - assertEquals(TIMEOUT_ERROR_MESSAGE, mongoExecutionTimeoutException.getMessage()); - assertEquals(TIMEOUT_ERROR_MESSAGE, mongoExecutionTimeoutExceptionDeferred.getMessage()); - verifyNoInteractions(database); - } - - @Test - void shouldThrowErrorWhenTimeoutHasExpiredWithZeroRemainingOnCollection() { - //given - MongoCollection collection = mock(MongoCollection.class); - Timeout timeout = Timeout.expiresIn(0, TimeUnit.NANOSECONDS, ZERO_DURATION_MEANS_EXPIRED); - - //when - assertThrows(MongoOperationTimeoutException.class, () -> collectionWithTimeout(collection, timeout)); - assertThrows(MongoOperationTimeoutException.class, () -> collectionWithTimeoutMono(collection, timeout).block()); - assertThrows(MongoOperationTimeoutException.class, () -> collectionWithTimeoutDeferred(collection, timeout).block()); - - //then - - } - - @Test - void shouldThrowErrorWhenTimeoutHasExpiredWithZeroRemainingOnDatabase() { - //given - MongoDatabase database = mock(MongoDatabase.class); - Timeout timeout = Timeout.expiresIn(0, TimeUnit.NANOSECONDS, ZERO_DURATION_MEANS_EXPIRED); - - //when - assertThrows(MongoOperationTimeoutException.class, () -> databaseWithTimeout(database, TIMEOUT_ERROR_MESSAGE, timeout)); - assertThrows(MongoOperationTimeoutException.class, - () -> databaseWithTimeoutDeferred(database, TIMEOUT_ERROR_MESSAGE, timeout).block()); - - //then - verifyNoInteractions(database); - } } diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/gridfs/GridFSQueryFilterTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/gridfs/GridFSQueryFilterTest.java index 89a111a478f..58993be7d51 100644 --- a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/gridfs/GridFSQueryFilterTest.java +++ b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/gridfs/GridFSQueryFilterTest.java @@ -39,7 +39,6 @@ import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -69,9 +68,6 @@ private static Stream ids() { void deleteUsesEqualityFilters(final BsonValue id) { MongoCollection filesCollection = mock(MongoCollection.class); MongoCollection chunksCollection = mock(MongoCollection.class); - // Mockito answers 0L rather than null for the Long-returning getTimeout, which would make the publisher apply a 0ms timeout. - when(filesCollection.getTimeout(any(TimeUnit.class))).thenReturn(null); - when(chunksCollection.getTimeout(any(TimeUnit.class))).thenReturn(null); when(filesCollection.deleteOne(any(Bson.class))).thenReturn(Mono.just(DeleteResult.acknowledged(1))); when(chunksCollection.deleteMany(any(Bson.class))).thenReturn(Mono.just(DeleteResult.acknowledged(1))); @@ -91,7 +87,6 @@ void deleteUsesEqualityFilters(final BsonValue id) { @SuppressWarnings("unchecked") void renameUsesEqualityFilter(final BsonValue id) { MongoCollection filesCollection = mock(MongoCollection.class); - when(filesCollection.getTimeout(any(TimeUnit.class))).thenReturn(null); when(filesCollection.updateOne(any(Bson.class), any(Bson.class))) .thenReturn(Mono.just(UpdateResult.acknowledged(1, 1L, null))); @@ -120,8 +115,6 @@ void downloadToPublisherUsesEqualityFilter(final BsonValue id) { when(rawFilesCollection.withCodecRegistry(any())).thenReturn(filesCollection); when(database.getCollection("fs.chunks")).thenReturn(rawChunksCollection); when(rawChunksCollection.withCodecRegistry(any())).thenReturn(chunksCollection); - when(filesCollection.getTimeout(any(TimeUnit.class))).thenReturn(null); - when(chunksCollection.getTimeout(any(TimeUnit.class))).thenReturn(null); when(filesCollection.find()).thenReturn(findPublisher); when(findPublisher.filter(any(Bson.class))).thenReturn(findPublisher); @@ -152,15 +145,12 @@ void uploadCancellationUsesEqualityFilter(final BsonValue id) { MongoCollection chunksCollection = mock(MongoCollection.class); FindPublisher findPublisher = mock(FindPublisher.class); - when(filesCollection.getTimeout(any(TimeUnit.class))).thenReturn(null); when(filesCollection.withDocumentClass(Document.class)).thenReturn(filesAsDocuments); when(filesAsDocuments.withReadPreference(any())).thenReturn(filesAsDocuments); - when(filesAsDocuments.getTimeout(any(TimeUnit.class))).thenReturn(null); when(filesAsDocuments.find()).thenReturn(findPublisher); when(findPublisher.projection(any())).thenReturn(findPublisher); // A non-empty files collection, so the index checks are skipped. when(findPublisher.first()).thenReturn(Mono.just(new Document())); - when(chunksCollection.getTimeout(any(TimeUnit.class))).thenReturn(null); when(chunksCollection.deleteMany(any(Bson.class))).thenReturn(Mono.just(DeleteResult.acknowledged(0))); GridFSUploadPublisherImpl uploadPublisher = new GridFSUploadPublisherImpl(null, filesCollection, chunksCollection, id, diff --git a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/gridfs/GridFSUploadPublisherImplTest.java b/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/gridfs/GridFSUploadPublisherImplTest.java deleted file mode 100644 index 38d19647fd7..00000000000 --- a/driver-reactive-streams/src/test/unit/com/mongodb/reactivestreams/client/internal/gridfs/GridFSUploadPublisherImplTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.reactivestreams.client.internal.gridfs; - -import com.mongodb.ClusterFixture; -import com.mongodb.MongoClientSettings; -import com.mongodb.MongoOperationTimeoutException; -import com.mongodb.ReadConcern; -import com.mongodb.ReadPreference; -import com.mongodb.WriteConcern; -import com.mongodb.client.Fixture; -import com.mongodb.client.test.CollectionHelper; -import com.mongodb.event.CommandEvent; -import com.mongodb.internal.connection.TestCommandListener; -import com.mongodb.reactivestreams.client.TestEventPublisher; -import com.mongodb.reactivestreams.client.MongoClient; -import com.mongodb.reactivestreams.client.MongoClients; -import com.mongodb.reactivestreams.client.MongoDatabase; -import com.mongodb.reactivestreams.client.TestSubscriber; -import com.mongodb.reactivestreams.client.gridfs.GridFSBucket; -import com.mongodb.reactivestreams.client.gridfs.GridFSBuckets; -import org.bson.types.ObjectId; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.reactivestreams.Subscription; -import reactor.core.publisher.Flux; - -import java.nio.ByteBuffer; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.TimeUnit; - -import static com.mongodb.ClusterFixture.TIMEOUT_DURATION; -import static com.mongodb.ClusterFixture.serverVersionAtLeast; -import static com.mongodb.client.Fixture.getDefaultDatabaseName; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - - -class GridFSUploadPublisherTest { - private static final String GRID_FS_BUCKET_NAME = "db.fs"; - private TestCommandListener commandListener; - - protected MongoClientSettings.Builder getMongoClientSettingsBuilder() { - commandListener.reset(); - return Fixture.getMongoClientSettingsBuilder() - .readConcern(ReadConcern.MAJORITY) - .writeConcern(WriteConcern.MAJORITY) - .readPreference(ReadPreference.primary()) - .addCommandListener(commandListener); - } - - @Test - void shouldTimeoutWhenSourcePublisherCompletionExceedsOverallOperationTimeout() { - assumeTrue(serverVersionAtLeast(4, 4)); - long rtt = ClusterFixture.getPrimaryRTT(); - - //given - try (MongoClient client = MongoClients.create(getMongoClientSettingsBuilder() - .timeout(rtt + 800, TimeUnit.MILLISECONDS).build())) { - MongoDatabase database = client.getDatabase(getDefaultDatabaseName()); - GridFSBucket gridFsBucket = GridFSBuckets.create(database, GRID_FS_BUCKET_NAME); - - TestEventPublisher eventPublisher = new TestEventPublisher<>(); - TestSubscriber testSubscriber = new TestSubscriber<>(); - - //when - gridFsBucket.uploadFromPublisher("filename", eventPublisher.getEventStream()) - .subscribe(testSubscriber); - testSubscriber.requestMore(1); - - //then - testSubscriber.assertTerminalEvent(); - - List onErrorEvents = testSubscriber.getOnErrorEvents(); - assertEquals(1, onErrorEvents.size()); - - Throwable throwable = onErrorEvents.get(0); - assertEquals(MongoOperationTimeoutException.class, throwable.getClass()); - assertEquals("GridFS waiting for data from the source Publisher exceeded the timeout limit.", throwable.getMessage()); - - //assert no chunk has been inserted as we have not sent any data from source publisher. - for (CommandEvent event : commandListener.getEvents()) { - assertNotEquals("insert", event.getCommandName()); - } - } - } - - @Test - void shouldCancelSubscriptionToSourceWhenOperationTimeoutOccurs() throws Exception { - assumeTrue(serverVersionAtLeast(4, 4)); - long rtt = ClusterFixture.getPrimaryRTT(); - - //given - try (MongoClient client = MongoClients.create(getMongoClientSettingsBuilder() - .timeout(rtt + 1000, TimeUnit.MILLISECONDS).build())) { - MongoDatabase database = client.getDatabase(getDefaultDatabaseName()); - GridFSBucket gridFsBucket = GridFSBuckets.create(database, GRID_FS_BUCKET_NAME); - - TestEventPublisher testEventPublisher = new TestEventPublisher<>(); - CompletableFuture subscriptionSignal = new CompletableFuture<>(); - Flux eventStream = testEventPublisher.getEventStream().doOnSubscribe(subscriptionSignal::complete); - TestSubscriber testSubscriber = new TestSubscriber<>(); - - //when - gridFsBucket.uploadFromPublisher("filename", eventStream) - .subscribe(testSubscriber); - testSubscriber.requestMore(1); - - //then - subscriptionSignal.get(TIMEOUT_DURATION.toMillis(), TimeUnit.MILLISECONDS); - assertEquals(1, testEventPublisher.currentSubscriberCount()); - //We wait for timeout to occur here - testSubscriber.assertTerminalEvent(); - assertEquals(0, testEventPublisher.currentSubscriberCount()); - } - } - - @BeforeEach - public void setUp() { - commandListener = new TestCommandListener(); - } - - @AfterEach - public void tearDown() { - CollectionHelper.dropDatabase(getDefaultDatabaseName()); - } -} diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala index 74f5a909811..37160562ace 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncAggregateIterable.scala @@ -21,7 +21,7 @@ import com.mongodb.client.model.Collation import org.bson.conversions.Bson import org.bson.{ BsonValue, Document } import org.mongodb.scala.bson.DefaultHelper.DefaultsTo -import org.mongodb.scala.{ documentToUntypedDocument, AggregateObservable, SingleObservableFuture, TimeoutMode } +import org.mongodb.scala.{ documentToUntypedDocument, AggregateObservable, SingleObservableFuture } import java.util.concurrent.TimeUnit import scala.concurrent.duration.Duration @@ -42,11 +42,6 @@ case class SyncAggregateIterable[T](wrapped: AggregateObservable[T]) this } - override def timeoutMode(timeoutMode: TimeoutMode): AggregateIterable[T] = { - wrapped.timeoutMode(timeoutMode) - this - } - override def maxTime(maxTime: Long, timeUnit: TimeUnit): AggregateIterable[T] = { wrapped.maxTime(Duration(maxTime, timeUnit)) this diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncDistinctIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncDistinctIterable.scala index 7f7fa4de4be..c64e30295ad 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncDistinctIterable.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncDistinctIterable.scala @@ -43,11 +43,6 @@ case class SyncDistinctIterable[T](wrapped: DistinctObservable[T]) this } - override def timeoutMode(timeoutMode: TimeoutMode): DistinctIterable[T] = { - wrapped.timeoutMode(timeoutMode) - this - } - override def collation(collation: Collation): DistinctIterable[T] = { wrapped.collation(collation) this diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncFindIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncFindIterable.scala index 57d73068c6a..7a11cb364f4 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncFindIterable.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncFindIterable.scala @@ -85,11 +85,6 @@ case class SyncFindIterable[T](wrapped: FindObservable[T]) extends SyncMongoIter this } - override def timeoutMode(timeoutMode: TimeoutMode): FindIterable[T] = { - wrapped.timeoutMode(timeoutMode) - this - } - override def collation(collation: Collation): FindIterable[T] = { wrapped.collation(collation) this diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListCollectionsIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListCollectionsIterable.scala index 291fe8f29b1..281c502cc25 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListCollectionsIterable.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListCollectionsIterable.scala @@ -18,7 +18,7 @@ package org.mongodb.scala.syncadapter import com.mongodb.client.ListCollectionsIterable import org.bson.conversions.Bson import org.mongodb.scala.bson.BsonValue -import org.mongodb.scala.{ ListCollectionsObservable, TimeoutMode } +import org.mongodb.scala.ListCollectionsObservable import java.util.concurrent.TimeUnit import scala.concurrent.duration.Duration @@ -41,11 +41,6 @@ case class SyncListCollectionsIterable[T](wrapped: ListCollectionsObservable[T]) this } - override def timeoutMode(timeoutMode: TimeoutMode): ListCollectionsIterable[T] = { - wrapped.timeoutMode(timeoutMode) - this - } - override def comment(comment: String): ListCollectionsIterable[T] = { wrapped.comment(comment) this diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListDatabasesIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListDatabasesIterable.scala index 5501dee8d81..af1f544a7d3 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListDatabasesIterable.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListDatabasesIterable.scala @@ -3,7 +3,7 @@ package org.mongodb.scala.syncadapter import com.mongodb.client.ListDatabasesIterable import org.bson.conversions.Bson import org.mongodb.scala.bson.BsonValue -import org.mongodb.scala.{ ListDatabasesObservable, TimeoutMode } +import org.mongodb.scala.ListDatabasesObservable import java.util.concurrent.TimeUnit import scala.concurrent.duration.Duration @@ -21,11 +21,6 @@ case class SyncListDatabasesIterable[T](wrapped: ListDatabasesObservable[T]) this } - override def timeoutMode(timeoutMode: TimeoutMode): ListDatabasesIterable[T] = { - wrapped.timeoutMode(timeoutMode) - this - } - override def filter(filter: Bson): ListDatabasesIterable[T] = { wrapped.filter(filter) this diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListIndexesIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListIndexesIterable.scala index 3142d94a0bd..74c25c2a0eb 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListIndexesIterable.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListIndexesIterable.scala @@ -18,7 +18,7 @@ package org.mongodb.scala.syncadapter import com.mongodb.client.ListIndexesIterable import org.mongodb.scala.bson.BsonValue -import org.mongodb.scala.{ ListIndexesObservable, TimeoutMode } +import org.mongodb.scala.ListIndexesObservable import java.util.concurrent.TimeUnit import scala.concurrent.duration.Duration @@ -36,11 +36,6 @@ case class SyncListIndexesIterable[T](wrapped: ListIndexesObservable[T]) this } - override def timeoutMode(timeoutMode: TimeoutMode): ListIndexesIterable[T] = { - wrapped.timeoutMode(timeoutMode) - this - } - override def comment(comment: String): ListIndexesIterable[T] = { wrapped.comment(comment) this diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListSearchIndexesIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListSearchIndexesIterable.scala index 65e8741fdb4..88f1536518b 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListSearchIndexesIterable.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncListSearchIndexesIterable.scala @@ -21,7 +21,7 @@ import com.mongodb.client.ListSearchIndexesIterable import com.mongodb.client.model.Collation import org.bson.{ BsonValue, Document } import org.mongodb.scala.bson.DefaultHelper.DefaultsTo -import org.mongodb.scala.{ ListSearchIndexesObservable, SingleObservableFuture, TimeoutMode } +import org.mongodb.scala.{ ListSearchIndexesObservable, SingleObservableFuture } import java.util.concurrent.TimeUnit import scala.concurrent.duration.Duration @@ -46,11 +46,6 @@ case class SyncListSearchIndexesIterable[T](wrapped: ListSearchIndexesObservable this } - override def timeoutMode(timeoutMode: TimeoutMode): ListSearchIndexesIterable[T] = { - wrapped.timeoutMode(timeoutMode) - this - } - override def maxTime(maxTime: Long, timeUnit: TimeUnit): ListSearchIndexesIterable[T] = { wrapped.maxTime(Duration(maxTime, timeUnit)) this diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMapReduceIterable.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMapReduceIterable.scala index 87d01258841..cac1370c580 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMapReduceIterable.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMapReduceIterable.scala @@ -19,7 +19,7 @@ package org.mongodb.scala.syncadapter import com.mongodb.client.MapReduceIterable import com.mongodb.client.model.{ Collation, MapReduceAction } import org.bson.conversions.Bson -import org.mongodb.scala.{ MapReduceObservable, SingleObservableFuture, TimeoutMode } +import org.mongodb.scala.{ MapReduceObservable, SingleObservableFuture } import java.util.concurrent.TimeUnit import scala.concurrent.duration.Duration @@ -89,11 +89,6 @@ case class SyncMapReduceIterable[T](wrapped: MapReduceObservable[T]) this } - override def timeoutMode(timeoutMode: TimeoutMode): MapReduceIterable[T] = { - wrapped.timeoutMode(timeoutMode) - this - } - override def bypassDocumentValidation(bypassDocumentValidation: java.lang.Boolean): MapReduceIterable[T] = { wrapped.bypassDocumentValidation(bypassDocumentValidation) this diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCluster.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCluster.scala index 54900de5a26..281a308e656 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCluster.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCluster.scala @@ -6,14 +6,12 @@ import com.mongodb.{ ClientSessionOptions, ReadConcern, ReadPreference, WriteCon import org.bson.Document import org.bson.codecs.configuration.CodecRegistry import org.bson.conversions.Bson -import org.mongodb.scala.{ MongoCluster, SingleObservableFuture } import org.mongodb.scala.bson.DefaultHelper.DefaultsTo +import org.mongodb.scala.{ MongoCluster, SingleObservableFuture } import java.util -import java.util.concurrent.TimeUnit import scala.collection.JavaConverters._ import scala.concurrent.Await -import scala.concurrent.duration.Duration import scala.reflect.ClassTag object SyncMongoCluster { @@ -31,11 +29,6 @@ class SyncMongoCluster(wrapped: MongoCluster) extends JMongoCluster { override def getReadConcern: ReadConcern = wrapped.readConcern - override def getTimeout(timeUnit: TimeUnit): java.lang.Long = { - val timeout = wrapped.timeout.map(d => timeUnit.convert(d.toMillis, TimeUnit.MILLISECONDS)) - if (timeout.isDefined) timeout.get else null - } - override def withCodecRegistry(codecRegistry: CodecRegistry): JMongoCluster = SyncMongoCluster(wrapped.withCodecRegistry(codecRegistry)) @@ -48,9 +41,6 @@ class SyncMongoCluster(wrapped: MongoCluster) extends JMongoCluster { override def withReadConcern(readConcern: ReadConcern): JMongoCluster = SyncMongoCluster(wrapped.withReadConcern(readConcern)) - override def withTimeout(timeout: Long, timeUnit: TimeUnit): JMongoCluster = - SyncMongoCluster(wrapped.withTimeout(Duration(timeout, timeUnit))) - override def getDatabase(databaseName: String): JMongoDatabase = SyncMongoDatabase(wrapped.getDatabase(databaseName)) diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCollection.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCollection.scala index 9d9ed6fdf8d..dfebfe26b12 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCollection.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoCollection.scala @@ -33,9 +33,7 @@ import org.mongodb.scala.{ MongoCollection, ObservableFuture, SingleObservableFu import org.mongodb.scala.bson.DefaultHelper.DefaultsTo import org.mongodb.scala.result.{ InsertManyResult, InsertOneResult } -import java.util.concurrent.TimeUnit import scala.collection.JavaConverters._ -import scala.concurrent.duration.{ Duration, MILLISECONDS } import scala.reflect.ClassTag case class SyncMongoCollection[T](wrapped: MongoCollection[T]) extends JMongoCollection[T] { @@ -54,13 +52,6 @@ case class SyncMongoCollection[T](wrapped: MongoCollection[T]) extends JMongoCol override def getReadConcern: ReadConcern = wrapped.readConcern - override def getTimeout(timeUnit: TimeUnit): java.lang.Long = { - wrapped.timeout match { - case Some(value) => timeUnit.convert(value.toMillis, MILLISECONDS) - case None => null - } - } - override def withDocumentClass[NewTDocument](clazz: Class[NewTDocument]): JMongoCollection[NewTDocument] = SyncMongoCollection[NewTDocument]( wrapped.withDocumentClass[NewTDocument]()( @@ -81,9 +72,6 @@ case class SyncMongoCollection[T](wrapped: MongoCollection[T]) extends JMongoCol override def withReadConcern(readConcern: ReadConcern): JMongoCollection[T] = SyncMongoCollection[T](wrapped.withReadConcern(readConcern)) - override def withTimeout(timeout: Long, timeUnit: TimeUnit): JMongoCollection[T] = - SyncMongoCollection[T](wrapped.withTimeout(Duration(timeout, timeUnit))) - override def countDocuments: Long = wrapped.countDocuments().toFuture().get() override def countDocuments(filter: Bson): Long = wrapped.countDocuments(filter).toFuture().get() diff --git a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoDatabase.scala b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoDatabase.scala index f77c45259fd..fb003222d26 100644 --- a/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoDatabase.scala +++ b/driver-scala/src/integrationTest/scala/org/mongodb/scala/syncadapter/SyncMongoDatabase.scala @@ -24,9 +24,7 @@ import org.bson.conversions.Bson import org.mongodb.scala.bson.DefaultHelper.DefaultsTo import org.mongodb.scala.{ documentToUntypedDocument, MongoDatabase, SingleObservableFuture } -import java.util.concurrent.TimeUnit import scala.collection.JavaConverters._ -import scala.concurrent.duration.{ Duration, MILLISECONDS } import scala.reflect.ClassTag case class SyncMongoDatabase(wrapped: MongoDatabase) extends JMongoDatabase { @@ -41,13 +39,6 @@ case class SyncMongoDatabase(wrapped: MongoDatabase) extends JMongoDatabase { override def getReadConcern: ReadConcern = wrapped.readConcern - override def getTimeout(timeUnit: TimeUnit): java.lang.Long = { - wrapped.timeout match { - case Some(value) => timeUnit.convert(value.toMillis, MILLISECONDS) - case None => null - } - } - override def withCodecRegistry(codecRegistry: CodecRegistry) = SyncMongoDatabase(wrapped.withCodecRegistry(codecRegistry)) @@ -58,9 +49,6 @@ case class SyncMongoDatabase(wrapped: MongoDatabase) extends JMongoDatabase { override def withReadConcern(readConcern: ReadConcern) = SyncMongoDatabase(wrapped.withReadConcern(readConcern)) - override def withTimeout(timeout: Long, timeUnit: TimeUnit) = - SyncMongoDatabase(wrapped.withTimeout(Duration(timeout, timeUnit))) - override def getCollection(collectionName: String) = SyncMongoCollection[Document](wrapped.getCollection(collectionName)) diff --git a/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala index a363ee21662..9f19e50a679 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/AggregateObservable.scala @@ -17,7 +17,6 @@ package org.mongodb.scala import com.mongodb.ExplainVerbosity -import com.mongodb.annotations.{ Alpha, Reason } import java.util.concurrent.TimeUnit import com.mongodb.reactivestreams.client.AggregatePublisher @@ -205,28 +204,6 @@ case class AggregateObservable[TResult](private val wrapped: AggregatePublisher[ */ def toCollection(): SingleObservable[Unit] = wrapped.toCollection() - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [[MongoClientSettings]], - * via [[MongoDatabase]] or via [[MongoCollection]] - * - * If the `timeout` is set then: - * - * - For non-tailable cursors, the default value of timeoutMode is `TimeoutMode.CURSOR_LIFETIME` - * - For tailable cursors, the default value of timeoutMode is `TimeoutMode.ITERATION` and its an error - * to configure it as: `TimeoutMode.CURSOR_LIFETIME` - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - def timeoutMode(timeoutMode: TimeoutMode): AggregateObservable[TResult] = { - wrapped.timeoutMode(timeoutMode) - this - } - /** * Helper to return a single observable limited to the first result. * diff --git a/driver-scala/src/main/scala/org/mongodb/scala/DistinctObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/DistinctObservable.scala index 84e0905cdf9..53a5dbd194a 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/DistinctObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/DistinctObservable.scala @@ -16,8 +16,6 @@ package org.mongodb.scala -import com.mongodb.annotations.{ Alpha, Reason } - import java.util.concurrent.TimeUnit import com.mongodb.reactivestreams.client.DistinctPublisher import org.mongodb.scala.bson.BsonValue @@ -136,22 +134,6 @@ case class DistinctObservable[TResult](private val wrapped: DistinctPublisher[TR this } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [[MongoClientSettings]], - * via [[MongoDatabase]] or via [[MongoCollection]] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - def timeoutMode(timeoutMode: TimeoutMode): DistinctObservable[TResult] = { - wrapped.timeoutMode(timeoutMode) - this - } - /** * Helper to return a single observable limited to the first result. * diff --git a/driver-scala/src/main/scala/org/mongodb/scala/FindObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/FindObservable.scala index 57a964b8315..575ca66e8c8 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/FindObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/FindObservable.scala @@ -16,7 +16,6 @@ package org.mongodb.scala -import com.mongodb.annotations.{ Alpha, Reason } import com.mongodb.reactivestreams.client.FindPublisher import com.mongodb.{ CursorType, ExplainVerbosity } import org.mongodb.scala.bson.BsonValue @@ -333,28 +332,6 @@ case class FindObservable[TResult](private val wrapped: FindPublisher[TResult]) this } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [[MongoClientSettings]], - * via [[MongoDatabase]] or via [[MongoCollection]] - * - * If the `timeout` is set then: - * - * - For non-tailable cursors, the default value of timeoutMode is `TimeoutMode.CURSOR_LIFETIME` - * - For tailable cursors, the default value of timeoutMode is `TimeoutMode.ITERATION` and its an error - * to configure it as: `TimeoutMode.CURSOR_LIFETIME` - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - def timeoutMode(timeoutMode: TimeoutMode): FindObservable[TResult] = { - wrapped.timeoutMode(timeoutMode) - this - } - /** * Explain the execution plan for this operation with the server's default verbosity level * diff --git a/driver-scala/src/main/scala/org/mongodb/scala/ListCollectionsObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/ListCollectionsObservable.scala index 3e34de87dfe..65b5b61a5d4 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/ListCollectionsObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/ListCollectionsObservable.scala @@ -16,8 +16,6 @@ package org.mongodb.scala -import com.mongodb.annotations.{ Alpha, Reason } - import java.util.concurrent.TimeUnit import com.mongodb.reactivestreams.client.ListCollectionsPublisher import org.mongodb.scala.bson.BsonValue @@ -96,22 +94,6 @@ case class ListCollectionsObservable[TResult](wrapped: ListCollectionsPublisher[ this } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [[MongoClientSettings]], - * via [[MongoDatabase]] or via [[MongoCollection]] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - def timeoutMode(timeoutMode: TimeoutMode): ListCollectionsObservable[TResult] = { - wrapped.timeoutMode(timeoutMode) - this - } - /** * Helper to return a single observable limited to the first result. * diff --git a/driver-scala/src/main/scala/org/mongodb/scala/ListDatabasesObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/ListDatabasesObservable.scala index 8fd7f41843c..1d389eb476e 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/ListDatabasesObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/ListDatabasesObservable.scala @@ -16,8 +16,6 @@ package org.mongodb.scala -import com.mongodb.annotations.{ Alpha, Reason } - import java.util.concurrent.TimeUnit import com.mongodb.reactivestreams.client.ListDatabasesPublisher import org.mongodb.scala.bson.BsonValue @@ -125,22 +123,6 @@ case class ListDatabasesObservable[TResult](wrapped: ListDatabasesPublisher[TRes this } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [[MongoClientSettings]], - * via [[MongoDatabase]] or via [[MongoCollection]] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - def timeoutMode(timeoutMode: TimeoutMode): ListDatabasesObservable[TResult] = { - wrapped.timeoutMode(timeoutMode) - this - } - /** * Helper to return a single observable limited to the first result. * diff --git a/driver-scala/src/main/scala/org/mongodb/scala/ListIndexesObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/ListIndexesObservable.scala index f6ab4c53c10..8de986edde0 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/ListIndexesObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/ListIndexesObservable.scala @@ -16,8 +16,6 @@ package org.mongodb.scala -import com.mongodb.annotations.{ Alpha, Reason } - import java.util.concurrent.TimeUnit import com.mongodb.reactivestreams.client.ListIndexesPublisher import org.mongodb.scala.bson.BsonValue @@ -83,22 +81,6 @@ case class ListIndexesObservable[TResult](wrapped: ListIndexesPublisher[TResult] this } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [[MongoClientSettings]], - * via [[MongoDatabase]] or via [[MongoCollection]] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - def timeoutMode(timeoutMode: TimeoutMode): ListIndexesObservable[TResult] = { - wrapped.timeoutMode(timeoutMode) - this - } - /** * Helper to return a single observable limited to the first result. * diff --git a/driver-scala/src/main/scala/org/mongodb/scala/ListSearchIndexesObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/ListSearchIndexesObservable.scala index db7b687c498..e4665cfec38 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/ListSearchIndexesObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/ListSearchIndexesObservable.scala @@ -17,7 +17,6 @@ package org.mongodb.scala import com.mongodb.ExplainVerbosity -import com.mongodb.annotations.{ Alpha, Reason } import com.mongodb.reactivestreams.client.ListSearchIndexesPublisher import org.mongodb.scala.bson.BsonValue import org.mongodb.scala.bson.DefaultHelper.DefaultsTo @@ -123,28 +122,6 @@ case class ListSearchIndexesObservable[TResult](wrapped: ListSearchIndexesPublis this } - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [[MongoClientSettings]], - * via [[MongoDatabase]] or via [[MongoCollection]] - * - * If the `timeout` is set then: - * - * - For non-tailable cursors, the default value of timeoutMode is `TimeoutMode.CURSOR_LIFETIME` - * - For tailable cursors, the default value of timeoutMode is `TimeoutMode.ITERATION` and its an error - * to configure it as: `TimeoutMode.CURSOR_LIFETIME` - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - def timeoutMode(timeoutMode: TimeoutMode): ListSearchIndexesObservable[TResult] = { - wrapped.timeoutMode(timeoutMode) - this - } - /** * Helper to return a single observable limited to the first result. * diff --git a/driver-scala/src/main/scala/org/mongodb/scala/MapReduceObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/MapReduceObservable.scala index a7f08258cd7..bb8fefcc6fc 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/MapReduceObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/MapReduceObservable.scala @@ -16,8 +16,6 @@ package org.mongodb.scala -import com.mongodb.annotations.{ Alpha, Reason } - import java.util.concurrent.TimeUnit import com.mongodb.client.model.MapReduceAction import com.mongodb.reactivestreams.client.MapReducePublisher @@ -231,22 +229,6 @@ case class MapReduceObservable[TResult](wrapped: MapReducePublisher[TResult]) ex */ def toCollection(): SingleObservable[Unit] = wrapped.toCollection() - /** - * Sets the timeoutMode for the cursor. - * - * Requires the `timeout` to be set, either in the [[MongoClientSettings]], - * via [[MongoDatabase]] or via [[MongoCollection]] - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - def timeoutMode(timeoutMode: TimeoutMode): MapReduceObservable[TResult] = { - wrapped.timeoutMode(timeoutMode) - this - } - /** * Helper to return a single observable limited to the first result. * diff --git a/driver-scala/src/main/scala/org/mongodb/scala/MongoCluster.scala b/driver-scala/src/main/scala/org/mongodb/scala/MongoCluster.scala index 9e5a75e2d7b..dd47d1a9d0c 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/MongoCluster.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/MongoCluster.scala @@ -16,7 +16,6 @@ package org.mongodb.scala -import com.mongodb.annotations.{ Alpha, Reason } import com.mongodb.{ ReadConcern, ReadPreference, WriteConcern } import com.mongodb.reactivestreams.client.{ MongoCluster => JMongoCluster } import org.bson.codecs.configuration.CodecRegistry @@ -25,7 +24,6 @@ import org.mongodb.scala.bson.conversions.Bson import org.mongodb.scala.model.bulk.{ ClientBulkWriteOptions, ClientBulkWriteResult, ClientNamespacedWriteModel } import scala.collection.JavaConverters._ -import scala.concurrent.duration.{ Duration, MILLISECONDS } import scala.reflect.ClassTag /** @@ -83,28 +81,6 @@ class MongoCluster(private val wrapped: JMongoCluster) { */ lazy val readConcern: ReadConcern = wrapped.getReadConcern - /** - * The time limit for the full execution of an operation. - * - * If not null the following deprecated options will be ignored: `waitQueueTimeoutMS`, `socketTimeoutMS`, - * `wTimeoutMS`, `maxTimeMS` and `maxCommitTimeMS`. - * - * - `null` means that the timeout mechanism for operations will defer to using: - * - `waitQueueTimeoutMS`: The maximum wait time in milliseconds that a thread may wait for a connection to become available - * - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - * - `wTimeoutMS`: How long the server will wait for the write concern to be fulfilled before timing out. - * - `maxTimeMS`: The time limit for processing operations on a cursor. - * See: [cursor.maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS"). - * - `maxCommitTimeMS`: The maximum amount of time to allow a single `commitTransaction` command to execute. - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * @return the optional timeout duration - */ - @Alpha(Array(Reason.CLIENT)) - lazy val timeout: Option[Duration] = - Option.apply(wrapped.getTimeout(MILLISECONDS)).map(t => Duration(t, MILLISECONDS)) - /** * Create a new MongoCluster instance with a different codec registry. * @@ -149,20 +125,6 @@ class MongoCluster(private val wrapped: JMongoCluster) { def withReadConcern(readConcern: ReadConcern): MongoCluster = MongoCluster(wrapped.withReadConcern(readConcern)) - /** - * Create a new MongoCluster instance with the set time limit for the full execution of an operation. - * - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @return a new MongoCluster instance with the set time limit for operations - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - def withTimeout(timeout: Duration): MongoCluster = - MongoCluster(wrapped.withTimeout(timeout.toMillis, MILLISECONDS)) - /** * Creates a client session. * diff --git a/driver-scala/src/main/scala/org/mongodb/scala/MongoCollection.scala b/driver-scala/src/main/scala/org/mongodb/scala/MongoCollection.scala index 48e09aa7921..454fd4463fa 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/MongoCollection.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/MongoCollection.scala @@ -16,7 +16,6 @@ package org.mongodb.scala -import com.mongodb.annotations.{ Alpha, Reason } import com.mongodb.client.model.DropCollectionOptions import java.util @@ -28,7 +27,6 @@ import org.mongodb.scala.model._ import org.mongodb.scala.result._ import scala.collection.JavaConverters._ -import scala.concurrent.duration.{ Duration, MILLISECONDS, TimeUnit } import scala.reflect.ClassTag // scalastyle:off number.of.methods file.size.limit @@ -85,29 +83,6 @@ case class MongoCollection[TResult](private val wrapped: JMongoCollection[TResul */ lazy val readConcern: ReadConcern = wrapped.getReadConcern - /** - * The time limit for the full execution of an operation. - * - * If not null the following deprecated options will be ignored: `waitQueueTimeoutMS`, `socketTimeoutMS`, - * `wTimeoutMS`, `maxTimeMS` and `maxCommitTimeMS`. - * - * - `null` means that the timeout mechanism for operations will defer to using: - * - `waitQueueTimeoutMS`: The maximum wait time in milliseconds that a thread may wait for a connection to become available - * - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - * - `wTimeoutMS`: How long the server will wait for the write concern to be fulfilled before timing out. - * - `maxTimeMS`: The time limit for processing operations on a cursor. - * See: [cursor.maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS"). - * - `maxCommitTimeMS`: The maximum amount of time to allow a single `commitTransaction` command to execute. - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * @return the optional timeout duration - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - lazy val timeout: Option[Duration] = - Option.apply(wrapped.getTimeout(MILLISECONDS)).map(t => Duration(t, MILLISECONDS)) - /** * Create a new MongoCollection instance with a different default class to cast any documents returned from the database into.. * @@ -161,20 +136,6 @@ case class MongoCollection[TResult](private val wrapped: JMongoCollection[TResul def withReadConcern(readConcern: ReadConcern): MongoCollection[TResult] = MongoCollection(wrapped.withReadConcern(readConcern)) - /** - * Sets the time limit for the full execution of an operation. - * - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @return a new MongoCollection instance with the set time limit for operations - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - def withTimeout(timeout: Duration): MongoCollection[TResult] = - MongoCollection(wrapped.withTimeout(timeout.toMillis, MILLISECONDS)) - /** * Gets an estimate of the count of documents in a collection using collection metadata. * diff --git a/driver-scala/src/main/scala/org/mongodb/scala/MongoDatabase.scala b/driver-scala/src/main/scala/org/mongodb/scala/MongoDatabase.scala index 54c48574c72..33ad891373c 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/MongoDatabase.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/MongoDatabase.scala @@ -16,7 +16,6 @@ package org.mongodb.scala -import com.mongodb.annotations.{ Alpha, Reason } import com.mongodb.client.model.{ CreateCollectionOptions, CreateViewOptions } import com.mongodb.reactivestreams.client.{ MongoDatabase => JMongoDatabase } import org.bson.codecs.configuration.CodecRegistry @@ -24,7 +23,6 @@ import org.mongodb.scala.bson.DefaultHelper.DefaultsTo import org.mongodb.scala.bson.conversions.Bson import scala.collection.JavaConverters._ -import scala.concurrent.duration.{ Duration, MILLISECONDS } import scala.reflect.ClassTag /** @@ -71,29 +69,6 @@ case class MongoDatabase(private[scala] val wrapped: JMongoDatabase) { */ lazy val readConcern: ReadConcern = wrapped.getReadConcern - /** - * The time limit for the full execution of an operation. - * - * If not null the following deprecated options will be ignored: `waitQueueTimeoutMS`, `socketTimeoutMS`, - * `wTimeoutMS`, `maxTimeMS` and `maxCommitTimeMS`. - * - * - `null` means that the timeout mechanism for operations will defer to using: - * - `waitQueueTimeoutMS`: The maximum wait time in milliseconds that a thread may wait for a connection to become available - * - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - * - `wTimeoutMS`: How long the server will wait for the write concern to be fulfilled before timing out. - * - `maxTimeMS`: The time limit for processing operations on a cursor. - * See: [cursor.maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS"). - * - `maxCommitTimeMS`: The maximum amount of time to allow a single `commitTransaction` command to execute. - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * @return the optional timeout duration - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - lazy val timeout: Option[Duration] = - Option.apply(wrapped.getTimeout(MILLISECONDS)).map(t => Duration(t, MILLISECONDS)) - /** * Create a new MongoDatabase instance with a different codec registry. * @@ -138,20 +113,6 @@ case class MongoDatabase(private[scala] val wrapped: JMongoDatabase) { def withReadConcern(readConcern: ReadConcern): MongoDatabase = MongoDatabase(wrapped.withReadConcern(readConcern)) - /** - * Sets the time limit for the full execution of an operation. - * - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @return a new MongoDatabase instance with the set time limit for operations - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - def withTimeout(timeout: Duration): MongoDatabase = - MongoDatabase(wrapped.withTimeout(timeout.toMillis, MILLISECONDS)) - /** * Gets a collection, with a specific default document class. * @@ -167,9 +128,6 @@ case class MongoDatabase(private[scala] val wrapped: JMongoDatabase) { /** * Executes command in the context of the current database using the primary server. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and the - * `timeoutMS` setting has been set. - * * @param command the command to be run * @tparam TResult the type of the class to use instead of [[Document]]. * @return a Observable containing the command result @@ -182,9 +140,6 @@ case class MongoDatabase(private[scala] val wrapped: JMongoDatabase) { /** * Executes command in the context of the current database. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and the - * `timeoutMS` setting has been set. - * * @param command the command to be run * @param readPreference the [[ReadPreference]] to be used when executing the command * @tparam TResult the type of the class to use instead of [[Document]]. @@ -199,9 +154,6 @@ case class MongoDatabase(private[scala] val wrapped: JMongoDatabase) { /** * Executes command in the context of the current database using the primary server. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and the - * `timeoutMS` setting has been set. - * * @param clientSession the client session with which to associate this operation * @param command the command to be run * @tparam TResult the type of the class to use instead of [[Document]]. @@ -218,9 +170,6 @@ case class MongoDatabase(private[scala] val wrapped: JMongoDatabase) { /** * Executes command in the context of the current database. * - * Note: The behavior of `runCommand` is undefined if the provided command document includes a `maxTimeMS` field and the - * `timeoutMS` setting has been set. - * * @param command the command to be run * @param readPreference the [[ReadPreference]] to be used when executing the command * @tparam TResult the type of the class to use instead of [[Document]]. diff --git a/driver-scala/src/main/scala/org/mongodb/scala/gridfs/GridFSBucket.scala b/driver-scala/src/main/scala/org/mongodb/scala/gridfs/GridFSBucket.scala index 15849798fe3..a4963d371cb 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/gridfs/GridFSBucket.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/gridfs/GridFSBucket.scala @@ -16,7 +16,6 @@ package org.mongodb.scala.gridfs -import com.mongodb.annotations.{ Alpha, Reason } import java.nio.ByteBuffer import com.mongodb.reactivestreams.client.gridfs.{ GridFSBucket => JGridFSBucket, GridFSBuckets } import org.mongodb.scala.bson.conversions.Bson @@ -31,8 +30,6 @@ import org.mongodb.scala.{ WriteConcern } -import scala.concurrent.duration.{ Duration, MILLISECONDS } - /** * A factory for GridFSBucket instances. * @@ -104,29 +101,6 @@ case class GridFSBucket(private val wrapped: JGridFSBucket) { */ lazy val readConcern: ReadConcern = wrapped.getReadConcern - /** - * The time limit for the full execution of an operation. - * - * If not null the following deprecated options will be ignored: `waitQueueTimeoutMS`, `socketTimeoutMS`, - * `wTimeoutMS`, `maxTimeMS` and `maxCommitTimeMS`. - * - * - `null` means that the timeout mechanism for operations will defer to using: - * - `waitQueueTimeoutMS`: The maximum wait time in milliseconds that a thread may wait for a connection to become available - * - `socketTimeoutMS`: How long a send or receive on a socket can take before timing out. - * - `wTimeoutMS`: How long the server will wait for the write concern to be fulfilled before timing out. - * - `maxTimeMS`: The time limit for processing operations on a cursor. - * See: [cursor.maxTimeMS](https://docs.mongodb.com/manual/reference/method/cursor.maxTimeMS"). - * - `maxCommitTimeMS`: The maximum amount of time to allow a single `commitTransaction` command to execute. - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * @return the optional timeout duration - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - lazy val timeout: Option[Duration] = - Option.apply(wrapped.getTimeout(MILLISECONDS)).map(t => Duration(t, MILLISECONDS)) - /** * Create a new GridFSBucket instance with a new chunk size in bytes. * @@ -162,30 +136,12 @@ case class GridFSBucket(private val wrapped: JGridFSBucket) { */ def withReadConcern(readConcern: ReadConcern): GridFSBucket = GridFSBucket(wrapped.withReadConcern(readConcern)) - /** - * Sets the time limit for the full execution of an operation. - * - * - `0` means infinite timeout. - * - `> 0` The time limit to use for the full execution of an operation. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @return a new GridFSBucket instance with the set time limit for operations - * @since 5.2 - */ - @Alpha(Array(Reason.CLIENT)) - def withTimeout(timeout: Duration): GridFSBucket = - GridFSBucket(wrapped.withTimeout(timeout.toMillis, MILLISECONDS)) - /** * Uploads the contents of the given `Observable` to a GridFS bucket. * * Reads the contents of the user file from the `source` and uploads it as chunks in the chunks collection. After all the * chunks have been uploaded, it creates a files collection document for `filename` in the files collection. * - * Note: When this [[GridFSBucket]] is set with a operation timeout (via timeout inherited from [[MongoDatabase]] - * settings or [[withTimeout]]), timeout breaches may occur due to the [[Observable]] - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit. - * * @param filename the filename for the stream * @param source the Publisher providing the file data * @return an Observable with a single element, the ObjectId of the uploaded file. @@ -200,10 +156,6 @@ case class GridFSBucket(private val wrapped: JGridFSBucket) { * Reads the contents of the user file from the `source` and uploads it as chunks in the chunks collection. After all the * chunks have been uploaded, it creates a files collection document for `filename` in the files collection. * - * Note: When this [[GridFSBucket]] is set with a operation timeout (via timeout inherited from [[MongoDatabase]] - * settings or [[withTimeout]]), timeout breaches may occur due to the [[Observable]] - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit. - * * @param filename the filename for the stream * @param source the Publisher providing the file data * @param options the GridFSUploadOptions @@ -223,10 +175,6 @@ case class GridFSBucket(private val wrapped: JGridFSBucket) { * Reads the contents of the user file from the `source` and uploads it as chunks in the chunks collection. After all the * chunks have been uploaded, it creates a files collection document for `filename` in the files collection. * - * Note: When this [[GridFSBucket]] is set with a operation timeout (via timeout inherited from [[MongoDatabase]] - * settings or [[withTimeout]]), timeout breaches may occur due to the [[Observable]] - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit. - * * @param id the custom id value of the file * @param filename the filename for the stream * @param source the Publisher providing the file data @@ -246,10 +194,6 @@ case class GridFSBucket(private val wrapped: JGridFSBucket) { * Reads the contents of the user file from the `source` and uploads it as chunks in the chunks collection. After all the * chunks have been uploaded, it creates a files collection document for `filename` in the files collection. * - * Note: When this [[GridFSBucket]] is set with a operation timeout (via timeout inherited from [[MongoDatabase]] - * settings or [[withTimeout]]), timeout breaches may occur due to the [[Observable]] - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit. - * * @param id the custom id value of the file * @param filename the filename for the stream * @param source the Publisher providing the file data @@ -271,10 +215,6 @@ case class GridFSBucket(private val wrapped: JGridFSBucket) { * Reads the contents of the user file from the `source` and uploads it as chunks in the chunks collection. After all the * chunks have been uploaded, it creates a files collection document for `filename` in the files collection. * - * Note: When this [[GridFSBucket]] is set with a operation timeout (via timeout inherited from [[MongoDatabase]] - * settings or [[withTimeout]]), timeout breaches may occur due to the [[Observable]] - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit. - * * @param clientSession the client session with which to associate this operation * @param filename the filename for the stream * @param source the Publisher providing the file data @@ -295,10 +235,6 @@ case class GridFSBucket(private val wrapped: JGridFSBucket) { * Reads the contents of the user file from the `source` and uploads it as chunks in the chunks collection. After all the * chunks have been uploaded, it creates a files collection document for `filename` in the files collection. * - * Note: When this [[GridFSBucket]] is set with a operation timeout (via timeout inherited from [[MongoDatabase]] - * settings or [[withTimeout]]), timeout breaches may occur due to the [[Observable]] - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit. - * * @param clientSession the client session with which to associate this operation * @param filename the filename for the stream * @param source the Publisher providing the file data @@ -321,10 +257,6 @@ case class GridFSBucket(private val wrapped: JGridFSBucket) { * Reads the contents of the user file from the `source` and uploads it as chunks in the chunks collection. After all the * chunks have been uploaded, it creates a files collection document for `filename` in the files collection. * - * Note: When this [[GridFSBucket]] is set with a operation timeout (via timeout inherited from [[MongoDatabase]] - * settings or [[withTimeout]]), timeout breaches may occur due to the [[Observable]] - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit. - * * @param clientSession the client session with which to associate this operation * @param id the custom id value of the file * @param filename the filename for the stream @@ -347,10 +279,6 @@ case class GridFSBucket(private val wrapped: JGridFSBucket) { * Reads the contents of the user file from the `source` and uploads it as chunks in the chunks collection. After all the * chunks have been uploaded, it creates a files collection document for `filename` in the files collection. * - * Note: When this [[GridFSBucket]] is set with a operation timeout (via timeout inherited from [[MongoDatabase]] - * settings or [[withTimeout]]), timeout breaches may occur due to the [[Observable]] - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit. - * * @param clientSession the client session with which to associate this operation * @param id the custom id value of the file * @param filename the filename for the stream diff --git a/driver-scala/src/main/scala/org/mongodb/scala/gridfs/GridFSFindObservable.scala b/driver-scala/src/main/scala/org/mongodb/scala/gridfs/GridFSFindObservable.scala index fdbea9add70..64f9bf3baa4 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/gridfs/GridFSFindObservable.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/gridfs/GridFSFindObservable.scala @@ -19,7 +19,7 @@ package org.mongodb.scala.gridfs import java.util.concurrent.TimeUnit import com.mongodb.reactivestreams.client.gridfs.GridFSFindPublisher import org.mongodb.scala.bson.conversions.Bson -import org.mongodb.scala.{ Observable, Observer, SingleObservable, TimeoutMode } +import org.mongodb.scala.{ Observable, Observer, SingleObservable } import scala.concurrent.duration.Duration diff --git a/driver-scala/src/main/scala/org/mongodb/scala/package.scala b/driver-scala/src/main/scala/org/mongodb/scala/package.scala index ae57fea182b..4c42d984ab0 100644 --- a/driver-scala/src/main/scala/org/mongodb/scala/package.scala +++ b/driver-scala/src/main/scala/org/mongodb/scala/package.scala @@ -108,16 +108,6 @@ package object scala extends ClientSessionImplicits with ObservableImplicits wit */ type TagSet = com.mongodb.TagSet - /** - * The timeout mode for a cursor - * - * For operations that create cursors, `timeoutMS` can either cap the lifetime of the cursor or be applied separately to the - * original operation and all next calls. - * - * @since 5.2 - */ - type TimeoutMode = com.mongodb.client.cursor.TimeoutMode - /** * Controls the acknowledgment of write operations with various options. */ @@ -402,19 +392,6 @@ package object scala extends ClientSessionImplicits with ObservableImplicits wit */ type MongoTimeoutException = com.mongodb.MongoTimeoutException - /** - * Exception thrown to indicate that a MongoDB operation has exceeded the specified timeout for - * the full execution of operation. - * - *

      The [[MongoOperationTimeoutException]] might provide information about the underlying - * cause of the timeout, if available. For example, if retries are attempted due to transient failures, - * and a timeout occurs in any of the attempts, the exception from one of the retries may be appended - * as the cause to this [[MongoOperationTimeoutException]]. - - @since 5.0 - */ - type MongoOperationTimeoutException = com.mongodb.MongoOperationTimeoutException - /** * An exception indicating that the convenient transactions API (`withTransaction`) exceeded its overall timeout * while retrying the user-supplied callback or the commit loop. diff --git a/driver-scala/src/test/scala/org/mongodb/scala/AggregateObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/AggregateObservableSpec.scala index bd30396ac28..79521cac1f9 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/AggregateObservableSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/AggregateObservableSpec.scala @@ -17,7 +17,6 @@ package org.mongodb.scala import com.mongodb.ExplainVerbosity -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.AggregatePublisher import org.mockito.Mockito.{ verify, verifyNoMoreInteractions } import org.mongodb.scala.model.Collation @@ -59,7 +58,6 @@ class AggregateObservableSpec extends BaseSpec with MockitoSugar { observable.batchSize(batchSize) observable.explain[Document]() observable.explain[Document](verbosity) - observable.timeoutMode(TimeoutMode.ITERATION) verify(wrapper).allowDiskUse(true) verify(wrapper).maxTime(duration.toMillis, TimeUnit.MILLISECONDS) @@ -71,7 +69,6 @@ class AggregateObservableSpec extends BaseSpec with MockitoSugar { verify(wrapper).batchSize(batchSize) verify(wrapper).explain(ct) verify(wrapper).explain(ct, verbosity) - verify(wrapper).timeoutMode(TimeoutMode.ITERATION) observable.toCollection() verify(wrapper).toCollection diff --git a/driver-scala/src/test/scala/org/mongodb/scala/ChangeStreamObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/ChangeStreamObservableSpec.scala index bcc4bfea815..8cbeab6528a 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/ChangeStreamObservableSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/ChangeStreamObservableSpec.scala @@ -16,7 +16,6 @@ package org.mongodb.scala -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.ChangeStreamPublisher import org.mockito.Mockito.{ verify, verifyNoMoreInteractions } import org.mongodb.scala.bson.BsonTimestamp diff --git a/driver-scala/src/test/scala/org/mongodb/scala/DistinctObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/DistinctObservableSpec.scala index 562873d13c3..3e36a4317aa 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/DistinctObservableSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/DistinctObservableSpec.scala @@ -16,7 +16,6 @@ package org.mongodb.scala -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.DistinctPublisher import org.mockito.Mockito.{ verify, verifyNoMoreInteractions } import org.mongodb.scala.model.Collation @@ -52,13 +51,11 @@ class DistinctObservableSpec extends BaseSpec with MockitoSugar { observable.maxTime(duration) observable.collation(collation) observable.batchSize(batchSize) - observable.timeoutMode(TimeoutMode.ITERATION) verify(wrapper).filter(filter) verify(wrapper).maxTime(duration.toMillis, TimeUnit.MILLISECONDS) verify(wrapper).collation(collation) verify(wrapper).batchSize(batchSize) - verify(wrapper).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapper) } diff --git a/driver-scala/src/test/scala/org/mongodb/scala/FindObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/FindObservableSpec.scala index 570978012ae..c4e8b8d72d5 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/FindObservableSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/FindObservableSpec.scala @@ -16,7 +16,6 @@ package org.mongodb.scala -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.FindPublisher import com.mongodb.{ CursorType, ExplainVerbosity } import org.mockito.Mockito.{ verify, verifyNoMoreInteractions } @@ -76,7 +75,6 @@ class FindObservableSpec extends BaseSpec with MockitoSugar { observable.allowDiskUse(true) observable.explain[Document]() observable.explain[Document](verbosity) - observable.timeoutMode(TimeoutMode.ITERATION) verify(wrapper).collation(collation) verify(wrapper).cursorType(CursorType.NonTailable) @@ -95,7 +93,6 @@ class FindObservableSpec extends BaseSpec with MockitoSugar { verify(wrapper).allowDiskUse(true) verify(wrapper).explain(ct) verify(wrapper).explain(ct, verbosity) - verify(wrapper).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapper) } diff --git a/driver-scala/src/test/scala/org/mongodb/scala/ListCollectionsObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/ListCollectionsObservableSpec.scala index 141dd62013a..0c6d3798333 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/ListCollectionsObservableSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/ListCollectionsObservableSpec.scala @@ -16,7 +16,6 @@ package org.mongodb.scala -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.ListCollectionsPublisher import org.mockito.Mockito.{ verify, verifyNoMoreInteractions } import org.reactivestreams.Publisher @@ -49,12 +48,10 @@ class ListCollectionsObservableSpec extends BaseSpec with MockitoSugar { observable.filter(filter) observable.maxTime(duration) observable.batchSize(batchSize) - observable.timeoutMode(TimeoutMode.ITERATION) verify(wrapper).filter(filter) verify(wrapper).maxTime(duration.toMillis, TimeUnit.MILLISECONDS) verify(wrapper).batchSize(batchSize) - verify(wrapper).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapper) } diff --git a/driver-scala/src/test/scala/org/mongodb/scala/ListDatabasesObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/ListDatabasesObservableSpec.scala index 385bbf4e306..6ce75b5f6d1 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/ListDatabasesObservableSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/ListDatabasesObservableSpec.scala @@ -15,7 +15,6 @@ */ package org.mongodb.scala -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.ListDatabasesPublisher import org.mockito.Mockito.{ verify, verifyNoMoreInteractions } import org.reactivestreams.Publisher @@ -48,13 +47,11 @@ class ListDatabasesObservableSpec extends BaseSpec with MockitoSugar { observable.filter(filter) observable.nameOnly(true) observable.batchSize(batchSize) - observable.timeoutMode(TimeoutMode.ITERATION) verify(wrapper).maxTime(duration.toMillis, TimeUnit.MILLISECONDS) verify(wrapper).filter(filter) verify(wrapper).nameOnly(true) verify(wrapper).batchSize(batchSize) - verify(wrapper).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapper) } diff --git a/driver-scala/src/test/scala/org/mongodb/scala/ListIndexesObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/ListIndexesObservableSpec.scala index 6d8a60a1e92..ca7c5396c09 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/ListIndexesObservableSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/ListIndexesObservableSpec.scala @@ -15,7 +15,6 @@ */ package org.mongodb.scala -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.reactivestreams.client.ListIndexesPublisher import org.mockito.Mockito.{ verify, verifyNoMoreInteractions } import org.reactivestreams.Publisher @@ -45,11 +44,9 @@ class ListIndexesObservableSpec extends BaseSpec with MockitoSugar { observable.maxTime(duration) observable.batchSize(batchSize) - observable.timeoutMode(TimeoutMode.ITERATION) verify(wrapper).maxTime(duration.toMillis, TimeUnit.MILLISECONDS) verify(wrapper).batchSize(batchSize) - verify(wrapper).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapper) } diff --git a/driver-scala/src/test/scala/org/mongodb/scala/MapReduceObservableSpec.scala b/driver-scala/src/test/scala/org/mongodb/scala/MapReduceObservableSpec.scala index 7c99804d329..5b3163f86c8 100644 --- a/driver-scala/src/test/scala/org/mongodb/scala/MapReduceObservableSpec.scala +++ b/driver-scala/src/test/scala/org/mongodb/scala/MapReduceObservableSpec.scala @@ -16,7 +16,6 @@ package org.mongodb.scala -import com.mongodb.client.cursor.TimeoutMode import com.mongodb.client.model.MapReduceAction import com.mongodb.reactivestreams.client.MapReducePublisher import org.mockito.Mockito.{ verify, verifyNoMoreInteractions } @@ -63,7 +62,6 @@ class MapReduceObservableSpec extends BaseSpec with MockitoSugar { observable.bypassDocumentValidation(true) observable.collation(collation) observable.batchSize(batchSize) - observable.timeoutMode(TimeoutMode.ITERATION) verify(wrapper).filter(filter) verify(wrapper).scope(scope) @@ -79,7 +77,6 @@ class MapReduceObservableSpec extends BaseSpec with MockitoSugar { verify(wrapper).bypassDocumentValidation(true) verify(wrapper).collation(collation) verify(wrapper).batchSize(batchSize) - verify(wrapper).timeoutMode(TimeoutMode.ITERATION) verifyNoMoreInteractions(wrapper) observable.toCollection() diff --git a/driver-sync/src/main/com/mongodb/client/AggregateIterable.java b/driver-sync/src/main/com/mongodb/client/AggregateIterable.java index 032e1860244..25537f7b08c 100644 --- a/driver-sync/src/main/com/mongodb/client/AggregateIterable.java +++ b/driver-sync/src/main/com/mongodb/client/AggregateIterable.java @@ -18,9 +18,6 @@ import com.mongodb.ExplainVerbosity; import com.mongodb.MongoNamespace; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Aggregates; import com.mongodb.client.model.Collation; import com.mongodb.client.model.MergeOptions; @@ -101,31 +98,6 @@ public interface AggregateIterable extends MongoIterable { */ AggregateIterable batchSize(int batchSize); - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - *

      - * If the {@code timeout} is set then: - *

        - *
      • For non-tailable cursors, the default value of timeoutMode is {@link TimeoutMode#CURSOR_LIFETIME}
      • - *
      • For tailable cursors, the default value of timeoutMode is {@link TimeoutMode#ITERATION} and its an error - * to configure it as: {@link TimeoutMode#CURSOR_LIFETIME}
      • - *
      - *

      - * Will error if the timeoutMode is set to {@link TimeoutMode#ITERATION} and the pipeline contains either - * an {@code $out} or a {@code $merge} stage. - *

      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - AggregateIterable timeoutMode(TimeoutMode timeoutMode); - /** * Sets the maximum execution time on the server for this operation. * diff --git a/driver-sync/src/main/com/mongodb/client/DistinctIterable.java b/driver-sync/src/main/com/mongodb/client/DistinctIterable.java index 9488c7fb49e..8f6538cbe3c 100644 --- a/driver-sync/src/main/com/mongodb/client/DistinctIterable.java +++ b/driver-sync/src/main/com/mongodb/client/DistinctIterable.java @@ -16,9 +16,6 @@ package com.mongodb.client; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.lang.Nullable; import org.bson.BsonValue; @@ -111,19 +108,4 @@ public interface DistinctIterable extends MongoIterable { * @since 5.3 */ DistinctIterable hintString(@Nullable String hint); - - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - DistinctIterable timeoutMode(TimeoutMode timeoutMode); } diff --git a/driver-sync/src/main/com/mongodb/client/FindIterable.java b/driver-sync/src/main/com/mongodb/client/FindIterable.java index d610ed73ffa..4cd3c7b7f43 100644 --- a/driver-sync/src/main/com/mongodb/client/FindIterable.java +++ b/driver-sync/src/main/com/mongodb/client/FindIterable.java @@ -18,9 +18,6 @@ import com.mongodb.CursorType; import com.mongodb.ExplainVerbosity; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.client.model.Projections; import com.mongodb.lang.Nullable; @@ -264,28 +261,6 @@ public interface FindIterable extends MongoIterable { */ FindIterable allowDiskUse(@Nullable Boolean allowDiskUse); - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - *

      - * If the {@code timeout} is set then: - *

        - *
      • For non-tailable cursors, the default value of timeoutMode is {@link TimeoutMode#CURSOR_LIFETIME}
      • - *
      • For tailable cursors, the default value of timeoutMode is {@link TimeoutMode#ITERATION} and its an error - * to configure it as: {@link TimeoutMode#CURSOR_LIFETIME}
      • - *
      - * - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - FindIterable timeoutMode(TimeoutMode timeoutMode); - /** * Explain the execution plan for this operation with the server's default verbosity level * diff --git a/driver-sync/src/main/com/mongodb/client/ListCollectionsIterable.java b/driver-sync/src/main/com/mongodb/client/ListCollectionsIterable.java index 421fbcaa674..52480103d07 100644 --- a/driver-sync/src/main/com/mongodb/client/ListCollectionsIterable.java +++ b/driver-sync/src/main/com/mongodb/client/ListCollectionsIterable.java @@ -16,9 +16,6 @@ package com.mongodb.client; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.lang.Nullable; import org.bson.BsonValue; import org.bson.conversions.Bson; @@ -82,18 +79,4 @@ public interface ListCollectionsIterable extends MongoIterable * @mongodb.server.release 4.4 */ ListCollectionsIterable comment(@Nullable BsonValue comment); - - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - ListCollectionsIterable timeoutMode(TimeoutMode timeoutMode); } diff --git a/driver-sync/src/main/com/mongodb/client/ListDatabasesIterable.java b/driver-sync/src/main/com/mongodb/client/ListDatabasesIterable.java index 75625e487a0..9b344a6ae89 100644 --- a/driver-sync/src/main/com/mongodb/client/ListDatabasesIterable.java +++ b/driver-sync/src/main/com/mongodb/client/ListDatabasesIterable.java @@ -16,9 +16,6 @@ package com.mongodb.client; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.lang.Nullable; import org.bson.BsonValue; import org.bson.conversions.Bson; @@ -104,18 +101,4 @@ public interface ListDatabasesIterable extends MongoIterable { * @mongodb.server.release 4.4 */ ListDatabasesIterable comment(@Nullable BsonValue comment); - - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - ListDatabasesIterable timeoutMode(TimeoutMode timeoutMode); } diff --git a/driver-sync/src/main/com/mongodb/client/ListIndexesIterable.java b/driver-sync/src/main/com/mongodb/client/ListIndexesIterable.java index 160cb59ebd9..2b3de183d64 100644 --- a/driver-sync/src/main/com/mongodb/client/ListIndexesIterable.java +++ b/driver-sync/src/main/com/mongodb/client/ListIndexesIterable.java @@ -16,9 +16,6 @@ package com.mongodb.client; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.lang.Nullable; import org.bson.BsonValue; @@ -71,18 +68,4 @@ public interface ListIndexesIterable extends MongoIterable { * @mongodb.server.release 4.4 */ ListIndexesIterable comment(@Nullable BsonValue comment); - - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - ListIndexesIterable timeoutMode(TimeoutMode timeoutMode); } diff --git a/driver-sync/src/main/com/mongodb/client/ListSearchIndexesIterable.java b/driver-sync/src/main/com/mongodb/client/ListSearchIndexesIterable.java index a5579bacfd5..bc3921c2ce8 100644 --- a/driver-sync/src/main/com/mongodb/client/ListSearchIndexesIterable.java +++ b/driver-sync/src/main/com/mongodb/client/ListSearchIndexesIterable.java @@ -17,10 +17,7 @@ package com.mongodb.client; import com.mongodb.ExplainVerbosity; -import com.mongodb.annotations.Alpha; import com.mongodb.annotations.Evolving; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.lang.Nullable; import org.bson.BsonValue; @@ -101,20 +98,6 @@ public interface ListSearchIndexesIterable extends MongoIterable comment(@Nullable BsonValue comment); - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - ListSearchIndexesIterable timeoutMode(TimeoutMode timeoutMode); - /** * Explain the execution plan for this operation with the server's default verbosity level. * diff --git a/driver-sync/src/main/com/mongodb/client/MapReduceIterable.java b/driver-sync/src/main/com/mongodb/client/MapReduceIterable.java index 13d029155f9..e4afc612b17 100644 --- a/driver-sync/src/main/com/mongodb/client/MapReduceIterable.java +++ b/driver-sync/src/main/com/mongodb/client/MapReduceIterable.java @@ -16,9 +16,6 @@ package com.mongodb.client; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.lang.Nullable; import org.bson.conversions.Bson; @@ -210,18 +207,4 @@ public interface MapReduceIterable extends MongoIterable { * @mongodb.server.release 3.4 */ MapReduceIterable collation(@Nullable Collation collation); - - /** - * Sets the timeoutMode for the cursor. - * - *

      - * Requires the {@code timeout} to be set, either in the {@link com.mongodb.MongoClientSettings}, - * via {@link MongoDatabase} or via {@link MongoCollection} - *

      - * @param timeoutMode the timeout mode - * @return this - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - MapReduceIterable timeoutMode(TimeoutMode timeoutMode); } diff --git a/driver-sync/src/main/com/mongodb/client/MongoChangeStreamCursor.java b/driver-sync/src/main/com/mongodb/client/MongoChangeStreamCursor.java index ed58412496d..38e33c8ae8e 100644 --- a/driver-sync/src/main/com/mongodb/client/MongoChangeStreamCursor.java +++ b/driver-sync/src/main/com/mongodb/client/MongoChangeStreamCursor.java @@ -33,16 +33,6 @@ * } * } * - * - *

      - * A {@link com.mongodb.MongoOperationTimeoutException} does not invalidate the {@link MongoChangeStreamCursor}, but is immediately - * propagated to the caller. Subsequent method call will attempt to resume operation by establishing a new change stream on the server, - * without doing {@code getMore} request first.

      - *

      - * If a {@link com.mongodb.MongoOperationTimeoutException} occurs before any events are received, it indicates that the server - * has timed out before it could finish processing the existing oplog. In such cases, it is recommended to close the current stream - * and recreate it with a higher timeout setting. - * * @since 3.11 * @param The type of documents the cursor contains */ diff --git a/driver-sync/src/main/com/mongodb/client/MongoCluster.java b/driver-sync/src/main/com/mongodb/client/MongoCluster.java index 198b0a66280..032176a365a 100644 --- a/driver-sync/src/main/com/mongodb/client/MongoCluster.java +++ b/driver-sync/src/main/com/mongodb/client/MongoCluster.java @@ -24,21 +24,17 @@ import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; -import com.mongodb.annotations.Alpha; import com.mongodb.annotations.Immutable; -import com.mongodb.annotations.Reason; import com.mongodb.client.model.bulk.ClientBulkWriteOptions; import com.mongodb.client.model.bulk.ClientBulkWriteResult; import com.mongodb.client.model.bulk.ClientNamespacedDeleteManyModel; import com.mongodb.client.model.bulk.ClientNamespacedUpdateManyModel; import com.mongodb.client.model.bulk.ClientNamespacedWriteModel; -import com.mongodb.lang.Nullable; import org.bson.Document; import org.bson.codecs.configuration.CodecRegistry; import org.bson.conversions.Bson; import java.util.List; -import java.util.concurrent.TimeUnit; /** * The client-side representation of a MongoDB cluster operations. @@ -87,40 +83,6 @@ public interface MongoCluster { */ ReadConcern getReadConcern(); - /** - * The time limit for the full execution of an operation. - * - *

      If not null the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

      - * - *
        - *
      • {@code null} means that the timeout mechanism for operations will defer to using: - *
          - *
        • {@code waitQueueTimeoutMS}: The maximum wait time in milliseconds that a thread may wait for a connection to become - * available
        • - *
        • {@code socketTimeoutMS}: How long a send or receive on a socket can take before timing out.
        • - *
        • {@code wTimeoutMS}: How long the server will wait for the write concern to be fulfilled before timing out.
        • - *
        • {@code maxTimeMS}: The cumulative time limit for processing operations on a cursor. - * See: cursor.maxTimeMS.
        • - *
        • {@code maxCommitTimeMS}: The maximum amount of time to allow a single {@code commitTransaction} command to execute. - * See: {@link com.mongodb.TransactionOptions#getMaxCommitTime}.
        • - *
        - *
      • - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - *

      Note: This timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. - * - * @param timeUnit the time unit - * @return the timeout in the given time unit - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - @Nullable - Long getTimeout(TimeUnit timeUnit); - /** * Create a new MongoCluster instance with a different codec registry. * @@ -164,26 +126,6 @@ public interface MongoCluster { */ MongoCluster withReadConcern(ReadConcern readConcern); - /** - * Create a new MongoCluster instance with the set time limit for the full execution of an operation. - * - *

        - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - *

      Note: This timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit - * @return a new MongoCluster instance with the set time limit for the full execution of an operation. - * @since 5.2 - * @see #getTimeout - */ - @Alpha(Reason.CLIENT) - MongoCluster withTimeout(long timeout, TimeUnit timeUnit); - /** * Gets a {@link MongoDatabase} instance for the given database name. * diff --git a/driver-sync/src/main/com/mongodb/client/MongoCollection.java b/driver-sync/src/main/com/mongodb/client/MongoCollection.java index a63b0f2ffcc..ecf5e7d1e4f 100644 --- a/driver-sync/src/main/com/mongodb/client/MongoCollection.java +++ b/driver-sync/src/main/com/mongodb/client/MongoCollection.java @@ -20,8 +20,6 @@ import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; import com.mongodb.annotations.ThreadSafe; import com.mongodb.bulk.BulkWriteResult; import com.mongodb.client.model.BulkWriteOptions; @@ -53,7 +51,6 @@ import org.bson.conversions.Bson; import java.util.List; -import java.util.concurrent.TimeUnit; /** * The MongoCollection interface. @@ -115,40 +112,6 @@ public interface MongoCollection { */ ReadConcern getReadConcern(); - /** - * The time limit for the full execution of an operation. - * - *

      If not null the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

      - * - *
        - *
      • {@code null} means that the timeout mechanism for operations will defer to using: - *
          - *
        • {@code waitQueueTimeoutMS}: The maximum wait time in milliseconds that a thread may wait for a connection to become - * available
        • - *
        • {@code socketTimeoutMS}: How long a send or receive on a socket can take before timing out.
        • - *
        • {@code wTimeoutMS}: How long the server will wait for the write concern to be fulfilled before timing out.
        • - *
        • {@code maxTimeMS}: The cumulative time limit for processing operations on a cursor. - * See: cursor.maxTimeMS.
        • - *
        • {@code maxCommitTimeMS}: The maximum amount of time to allow a single {@code commitTransaction} command to execute. - * See: {@link com.mongodb.TransactionOptions#getMaxCommitTime}.
        • - *
        - *
      • - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - *

      Note: This timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. - * - * @param timeUnit the time unit - * @return the timeout in the given time unit - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - @Nullable - Long getTimeout(TimeUnit timeUnit); - /** * Create a new MongoCollection instance with a different default class to cast any documents returned from the database into.. * @@ -199,26 +162,6 @@ public interface MongoCollection { */ MongoCollection withReadConcern(ReadConcern readConcern); - /** - * Create a new MongoCollection instance with the set time limit for the full execution of an operation. - * - *

        - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - *

      Note: This timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit - * @return a new MongoCollection instance with the set time limit for the full execution of an operation - * @since 5.2 - * @see #getTimeout - */ - @Alpha(Reason.CLIENT) - MongoCollection withTimeout(long timeout, TimeUnit timeUnit); - /** * Counts the number of documents in the collection. * diff --git a/driver-sync/src/main/com/mongodb/client/MongoDatabase.java b/driver-sync/src/main/com/mongodb/client/MongoDatabase.java index f21aedd597f..364f7377d4a 100644 --- a/driver-sync/src/main/com/mongodb/client/MongoDatabase.java +++ b/driver-sync/src/main/com/mongodb/client/MongoDatabase.java @@ -19,18 +19,14 @@ import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; import com.mongodb.annotations.ThreadSafe; import com.mongodb.client.model.CreateCollectionOptions; import com.mongodb.client.model.CreateViewOptions; -import com.mongodb.lang.Nullable; import org.bson.Document; import org.bson.codecs.configuration.CodecRegistry; import org.bson.conversions.Bson; import java.util.List; -import java.util.concurrent.TimeUnit; /** * The MongoDatabase interface. @@ -80,40 +76,6 @@ public interface MongoDatabase { */ ReadConcern getReadConcern(); - /** - * The time limit for the full execution of an operation. - * - *

      If not null the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

      - * - *
        - *
      • {@code null} means that the timeout mechanism for operations will defer to using: - *
          - *
        • {@code waitQueueTimeoutMS}: The maximum wait time in milliseconds that a thread may wait for a connection to become - * available
        • - *
        • {@code socketTimeoutMS}: How long a send or receive on a socket can take before timing out.
        • - *
        • {@code wTimeoutMS}: How long the server will wait for the write concern to be fulfilled before timing out.
        • - *
        • {@code maxTimeMS}: The cumulative time limit for processing operations on a cursor. - * See: cursor.maxTimeMS.
        • - *
        • {@code maxCommitTimeMS}: The maximum amount of time to allow a single {@code commitTransaction} command to execute. - * See: {@link com.mongodb.TransactionOptions#getMaxCommitTime}.
        • - *
        - *
      • - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - *

      Note: This timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. - * - * @param timeUnit the time unit - * @return the timeout in the given time unit - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - @Nullable - Long getTimeout(TimeUnit timeUnit); - /** * Create a new MongoDatabase instance with a different codec registry. * @@ -155,26 +117,6 @@ public interface MongoDatabase { */ MongoDatabase withReadConcern(ReadConcern readConcern); - /** - * Create a new MongoDatabase instance with the set time limit for the full execution of an operation. - * - *

        - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - *

      Note: This timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit - * @return a new MongoDatabase instance with the set time limit for the full execution of an operation. - * @since 5.2 - * @see #getTimeout - */ - @Alpha(Reason.CLIENT) - MongoDatabase withTimeout(long timeout, TimeUnit timeUnit); - /** * Gets a collection. * @@ -198,9 +140,6 @@ public interface MongoDatabase { /** * Executes the given command in the context of the current database with a read preference of {@link ReadPreference#primary()}. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param command the command to be run * @return the command result */ @@ -209,9 +148,6 @@ public interface MongoDatabase { /** * Executes the given command in the context of the current database with the given read preference. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param command the command to be run * @param readPreference the {@link ReadPreference} to be used when executing the command * @return the command result @@ -221,9 +157,6 @@ public interface MongoDatabase { /** * Executes the given command in the context of the current database with a read preference of {@link ReadPreference#primary()}. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param command the command to be run * @param resultClass the class to decode each document into * @param the type of the class to use instead of {@code Document}. @@ -234,9 +167,6 @@ public interface MongoDatabase { /** * Executes the given command in the context of the current database with the given read preference. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param command the command to be run * @param readPreference the {@link ReadPreference} to be used when executing the command * @param resultClass the class to decode each document into @@ -248,9 +178,6 @@ public interface MongoDatabase { /** * Executes the given command in the context of the current database with a read preference of {@link ReadPreference#primary()}. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param clientSession the client session with which to associate this operation * @param command the command to be run * @return the command result @@ -262,9 +189,6 @@ public interface MongoDatabase { /** * Executes the given command in the context of the current database with the given read preference. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param clientSession the client session with which to associate this operation * @param command the command to be run * @param readPreference the {@link ReadPreference} to be used when executing the command @@ -277,9 +201,6 @@ public interface MongoDatabase { /** * Executes the given command in the context of the current database with a read preference of {@link ReadPreference#primary()}. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param clientSession the client session with which to associate this operation * @param command the command to be run * @param resultClass the class to decode each document into @@ -293,9 +214,6 @@ public interface MongoDatabase { /** * Executes the given command in the context of the current database with the given read preference. * - *

      Note: The behavior of {@code runCommand} is undefined if the provided command document includes a {@code maxTimeMS} field and the - * {@code timeoutMS} setting has been set.

      - * * @param clientSession the client session with which to associate this operation * @param command the command to be run * @param readPreference the {@link ReadPreference} to be used when executing the command diff --git a/driver-sync/src/main/com/mongodb/client/gridfs/GridFSBucket.java b/driver-sync/src/main/com/mongodb/client/gridfs/GridFSBucket.java index 14756ef9286..c32f114844c 100644 --- a/driver-sync/src/main/com/mongodb/client/gridfs/GridFSBucket.java +++ b/driver-sync/src/main/com/mongodb/client/gridfs/GridFSBucket.java @@ -19,21 +19,16 @@ import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; -import com.mongodb.annotations.Alpha; -import com.mongodb.annotations.Reason; import com.mongodb.annotations.ThreadSafe; import com.mongodb.client.ClientSession; -import com.mongodb.client.MongoDatabase; import com.mongodb.client.gridfs.model.GridFSDownloadOptions; import com.mongodb.client.gridfs.model.GridFSUploadOptions; -import com.mongodb.lang.Nullable; import org.bson.BsonValue; import org.bson.conversions.Bson; import org.bson.types.ObjectId; import java.io.InputStream; import java.io.OutputStream; -import java.util.concurrent.TimeUnit; /** * Represents a GridFS Bucket @@ -81,40 +76,6 @@ public interface GridFSBucket { */ ReadConcern getReadConcern(); - /** - * The time limit for the full execution of an operation. - * - *

      If not null the following deprecated options will be ignored: - * {@code waitQueueTimeoutMS}, {@code socketTimeoutMS}, {@code wTimeoutMS}, {@code maxTimeMS} and {@code maxCommitTimeMS}

      - * - *
        - *
      • {@code null} means that the timeout mechanism for operations will defer to using: - *
          - *
        • {@code waitQueueTimeoutMS}: The maximum wait time in milliseconds that a thread may wait for a connection to become - * available
        • - *
        • {@code socketTimeoutMS}: How long a send or receive on a socket can take before timing out.
        • - *
        • {@code wTimeoutMS}: How long the server will wait for the write concern to be fulfilled before timing out.
        • - *
        • {@code maxTimeMS}: The cumulative time limit for processing operations on a cursor. - * See: cursor.maxTimeMS.
        • - *
        • {@code maxCommitTimeMS}: The maximum amount of time to allow a single {@code commitTransaction} command to execute. - * See: {@link com.mongodb.TransactionOptions#getMaxCommitTime}.
        • - *
        - *
      • - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - *

      Note: This timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. - * - * @param timeUnit the time unit - * @return the timeout in the given time unit - * @since 5.2 - */ - @Alpha(Reason.CLIENT) - @Nullable - Long getTimeout(TimeUnit timeUnit); - /** * Create a new GridFSBucket instance with a new chunk size in bytes. * @@ -150,26 +111,6 @@ public interface GridFSBucket { */ GridFSBucket withReadConcern(ReadConcern readConcern); - /** - * Create a new GridFSBucket instance with the set time limit for the full execution of an operation. - * - *

        - *
      • {@code 0} means infinite timeout.
      • - *
      • {@code > 0} The time limit to use for the full execution of an operation.
      • - *
      - * - *

      Note: This timeout does not limit socket writes, therefore there is a possibility that the - * operation might not be timed out when expected. - * - * @param timeout the timeout, which must be greater than or equal to 0 - * @param timeUnit the time unit - * @return a new GridFSBucket instance with the set time limit for the full execution of an operation - * @since 5.2 - * @see #getTimeout - */ - @Alpha(Reason.CLIENT) - GridFSBucket withTimeout(long timeout, TimeUnit timeUnit); - /** * Opens a Stream that the application can write the contents of the file to. *

      @@ -355,10 +296,6 @@ public interface GridFSBucket { * chunks have been uploaded, it creates a files collection document for {@code filename} in the files collection. *

      * -

      Note: When this {@link GridFSBucket} is set with a operation timeout (via timeout inherited from {@link MongoDatabase} - * settings or {@link #withTimeout(long, TimeUnit)}), timeout breaches may occur due to the {@link InputStream} - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit.

      - * * @param id the custom id value of the file * @param filename the filename for the stream * @param source the Stream providing the file data @@ -373,10 +310,6 @@ public interface GridFSBucket { * chunks have been uploaded, it creates a files collection document for {@code filename} in the files collection. *

      * -

      Note: When this {@link GridFSBucket} is set with a operation timeout (via timeout inherited from {@link MongoDatabase} - * settings or {@link #withTimeout(long, TimeUnit)}), timeout breaches may occur due to the {@link InputStream} - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit.

      - * * @param id the custom id value of the file * @param filename the filename for the stream * @param source the Stream providing the file data @@ -392,10 +325,6 @@ public interface GridFSBucket { * chunks have been uploaded, it creates a files collection document for {@code filename} in the files collection. *

      * -

      Note: When this {@link GridFSBucket} is set with a operation timeout (via timeout inherited from {@link MongoDatabase} - * settings or {@link #withTimeout(long, TimeUnit)}), timeout breaches may occur due to the {@link InputStream} - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit.

      - * * @param clientSession the client session with which to associate this operation * @param filename the filename for the stream * @param source the Stream providing the file data @@ -412,10 +341,6 @@ public interface GridFSBucket { * chunks have been uploaded, it creates a files collection document for {@code filename} in the files collection. *

      * -

      Note: When this {@link GridFSBucket} is set with a operation timeout (via timeout inherited from {@link MongoDatabase} - * settings or {@link #withTimeout(long, TimeUnit)}), timeout breaches may occur due to the {@link InputStream} - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit.

      - * * @param clientSession the client session with which to associate this operation * @param filename the filename for the stream * @param source the Stream providing the file data @@ -433,10 +358,6 @@ public interface GridFSBucket { * chunks have been uploaded, it creates a files collection document for {@code filename} in the files collection. *

      * -

      Note: When this {@link GridFSBucket} is set with a operation timeout (via timeout inherited from {@link MongoDatabase} - * settings or {@link #withTimeout(long, TimeUnit)}), timeout breaches may occur due to the {@link InputStream} - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit.

      - * * @param clientSession the client session with which to associate this operation * @param id the custom id value of the file * @param filename the filename for the stream @@ -453,10 +374,6 @@ public interface GridFSBucket { * chunks have been uploaded, it creates a files collection document for {@code filename} in the files collection. *

      * -

      Note: When this {@link GridFSBucket} is set with a operation timeout (via timeout inherited from {@link MongoDatabase} - * settings or {@link #withTimeout(long, TimeUnit)}), timeout breaches may occur due to the {@link InputStream} - * lacking inherent read timeout support, which might extend the operation beyond the specified timeout limit.

      - * * @param clientSession the client session with which to associate this operation * @param id the custom id value of the file * @param filename the filename for the stream diff --git a/driver-sync/src/main/com/mongodb/client/gridfs/GridFSBucketImpl.java b/driver-sync/src/main/com/mongodb/client/gridfs/GridFSBucketImpl.java index cd9432e6fe0..4fc6ea56a0a 100644 --- a/driver-sync/src/main/com/mongodb/client/gridfs/GridFSBucketImpl.java +++ b/driver-sync/src/main/com/mongodb/client/gridfs/GridFSBucketImpl.java @@ -18,7 +18,6 @@ import com.mongodb.MongoClientSettings; import com.mongodb.MongoGridFSException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; @@ -27,17 +26,13 @@ import com.mongodb.client.ListIndexesIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.gridfs.model.GridFSDownloadOptions; import com.mongodb.client.gridfs.model.GridFSFile; import com.mongodb.client.gridfs.model.GridFSUploadOptions; -import com.mongodb.client.internal.TimeoutHelper; import com.mongodb.client.model.IndexOptions; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.VisibleForTesting; -import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; import org.bson.BsonDocument; import org.bson.BsonObjectId; @@ -52,17 +47,14 @@ import java.io.OutputStream; import java.util.ArrayList; import java.util.Map; -import java.util.concurrent.TimeUnit; import static com.mongodb.ReadPreference.primary; import static com.mongodb.assertions.Assertions.notNull; import static java.lang.String.format; -import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.bson.codecs.configuration.CodecRegistries.fromRegistries; final class GridFSBucketImpl implements GridFSBucket { private static final int DEFAULT_CHUNKSIZE_BYTES = 255 * 1024; - private static final String TIMEOUT_MESSAGE = "GridFS operation exceeded the timeout limit."; private final String bucketName; private final int chunkSizeBytes; private final MongoCollection filesCollection; @@ -113,11 +105,6 @@ public ReadConcern getReadConcern() { return filesCollection.getReadConcern(); } - @Override - public Long getTimeout(final TimeUnit timeUnit) { - return filesCollection.getTimeout(timeUnit); - } - @Override public GridFSBucket withChunkSizeBytes(final int chunkSizeBytes) { return new GridFSBucketImpl(bucketName, chunkSizeBytes, filesCollection, chunksCollection); @@ -141,12 +128,6 @@ public GridFSBucket withReadConcern(final ReadConcern readConcern) { chunksCollection.withReadConcern(readConcern)); } - @Override - public GridFSBucket withTimeout(final long timeout, final TimeUnit timeUnit) { - return new GridFSBucketImpl(bucketName, chunkSizeBytes, filesCollection.withTimeout(timeout, timeUnit), - chunksCollection.withTimeout(timeout, timeUnit)); - } - @Override public GridFSUploadStream openUploadStream(final String filename) { return openUploadStream(new BsonObjectId(), filename); @@ -197,14 +178,13 @@ public GridFSUploadStream openUploadStream(final ClientSession clientSession, fi private GridFSUploadStream createGridFSUploadStream(@Nullable final ClientSession clientSession, final BsonValue id, final String filename, final GridFSUploadOptions options) { - Timeout operationTimeout = startTimeout(); notNull("options", options); Integer chunkSizeBytes = options.getChunkSizeBytes(); int chunkSize = chunkSizeBytes == null ? this.chunkSizeBytes : chunkSizeBytes; - checkCreateIndex(clientSession, operationTimeout); + checkCreateIndex(clientSession); return new GridFSUploadStreamImpl(clientSession, filesCollection, chunksCollection, id, filename, chunkSize, - options.getMetadata(), operationTimeout); + options.getMetadata()); } @Override @@ -280,10 +260,8 @@ public GridFSDownloadStream openDownloadStream(final ObjectId id) { @Override public GridFSDownloadStream openDownloadStream(final BsonValue id) { - Timeout operationTimeout = startTimeout(); - - GridFSFile fileInfo = getFileInfoById(null, id, operationTimeout); - return createGridFSDownloadStream(null, fileInfo, operationTimeout); + GridFSFile fileInfo = getFileInfoById(null, id); + return createGridFSDownloadStream(null, fileInfo); } @Override @@ -293,9 +271,8 @@ public GridFSDownloadStream openDownloadStream(final String filename) { @Override public GridFSDownloadStream openDownloadStream(final String filename, final GridFSDownloadOptions options) { - Timeout operationTimeout = startTimeout(); - GridFSFile file = getFileByName(null, filename, options, operationTimeout); - return createGridFSDownloadStream(null, file, operationTimeout); + GridFSFile file = getFileByName(null, filename, options); + return createGridFSDownloadStream(null, file); } @Override @@ -306,9 +283,8 @@ public GridFSDownloadStream openDownloadStream(final ClientSession clientSession @Override public GridFSDownloadStream openDownloadStream(final ClientSession clientSession, final BsonValue id) { notNull("clientSession", clientSession); - Timeout operationTimeout = startTimeout(); - GridFSFile fileInfoById = getFileInfoById(clientSession, id, operationTimeout); - return createGridFSDownloadStream(clientSession, fileInfoById, operationTimeout); + GridFSFile fileInfoById = getFileInfoById(clientSession, id); + return createGridFSDownloadStream(clientSession, fileInfoById); } @Override @@ -320,14 +296,12 @@ public GridFSDownloadStream openDownloadStream(final ClientSession clientSession public GridFSDownloadStream openDownloadStream(final ClientSession clientSession, final String filename, final GridFSDownloadOptions options) { notNull("clientSession", clientSession); - Timeout operationTimeout = startTimeout(); - GridFSFile file = getFileByName(clientSession, filename, options, operationTimeout); - return createGridFSDownloadStream(clientSession, file, operationTimeout); + GridFSFile file = getFileByName(clientSession, filename, options); + return createGridFSDownloadStream(clientSession, file); } - private GridFSDownloadStream createGridFSDownloadStream(@Nullable final ClientSession clientSession, final GridFSFile gridFSFile, - @Nullable final Timeout operationTimeout) { - return new GridFSDownloadStreamImpl(clientSession, gridFSFile, chunksCollection, operationTimeout); + private GridFSDownloadStream createGridFSDownloadStream(@Nullable final ClientSession clientSession, final GridFSFile gridFSFile) { + return new GridFSDownloadStreamImpl(clientSession, gridFSFile, chunksCollection); } @Override @@ -398,12 +372,7 @@ public GridFSFindIterable find(final ClientSession clientSession, final Bson fil } private GridFSFindIterable createGridFSFindIterable(@Nullable final ClientSession clientSession, @Nullable final Bson filter) { - return new GridFSFindIterableImpl(createFindIterable(clientSession, filter, startTimeout())); - } - - private GridFSFindIterable createGridFSFindIterable(@Nullable final ClientSession clientSession, @Nullable final Bson filter, - @Nullable final Timeout operationTimeout) { - return new GridFSFindIterableImpl(createFindIterable(clientSession, filter, operationTimeout)); + return new GridFSFindIterableImpl(createFindIterable(clientSession, filter)); } @Override @@ -428,19 +397,18 @@ public void delete(final ClientSession clientSession, final BsonValue id) { } private void executeDelete(@Nullable final ClientSession clientSession, final BsonValue id) { - Timeout operationTimeout = startTimeout(); BsonDocument filesFilter = GridFSFilters.eq("_id", id); BsonDocument chunksFilter = GridFSFilters.eq("files_id", id); DeleteResult result; if (clientSession != null) { - result = withNullableTimeout(filesCollection, operationTimeout) + result = filesCollection .deleteOne(clientSession, filesFilter); - withNullableTimeout(chunksCollection, operationTimeout) + chunksCollection .deleteMany(clientSession, chunksFilter); } else { - result = withNullableTimeout(filesCollection, operationTimeout) + result = filesCollection .deleteOne(filesFilter); - withNullableTimeout(chunksCollection, operationTimeout) + chunksCollection .deleteMany(chunksFilter); } @@ -471,14 +439,13 @@ public void rename(final ClientSession clientSession, final BsonValue id, final } private void executeRename(@Nullable final ClientSession clientSession, final BsonValue id, final String newFilename) { - Timeout operationTimeout = startTimeout(); BsonDocument filesFilter = GridFSFilters.eq("_id", id); UpdateResult updateResult; if (clientSession != null) { - updateResult = withNullableTimeout(filesCollection, operationTimeout).updateOne(clientSession, filesFilter, + updateResult = filesCollection.updateOne(clientSession, filesFilter, new BsonDocument("$set", new BsonDocument("filename", new BsonString(newFilename)))); } else { - updateResult = withNullableTimeout(filesCollection, operationTimeout).updateOne(filesFilter, + updateResult = filesCollection.updateOne(filesFilter, new BsonDocument("$set", new BsonDocument("filename", new BsonString(newFilename)))); } @@ -489,17 +456,15 @@ private void executeRename(@Nullable final ClientSession clientSession, final Bs @Override public void drop() { - Timeout operationTimeout = startTimeout(); - withNullableTimeout(filesCollection, operationTimeout).drop(); - withNullableTimeout(chunksCollection, operationTimeout).drop(); + filesCollection.drop(); + chunksCollection.drop(); } @Override public void drop(final ClientSession clientSession) { - Timeout operationTimeout = startTimeout(); notNull("clientSession", clientSession); - withNullableTimeout(filesCollection, operationTimeout).drop(clientSession); - withNullableTimeout(chunksCollection, operationTimeout).drop(clientSession); + filesCollection.drop(clientSession); + chunksCollection.drop(clientSession); } private static MongoCollection getFilesCollection(final MongoDatabase database, final String bucketName) { @@ -512,19 +477,19 @@ private static MongoCollection getChunksCollection(final MongoData return database.getCollection(bucketName + ".chunks", BsonDocument.class).withCodecRegistry(MongoClientSettings.getDefaultCodecRegistry()); } - private void checkCreateIndex(@Nullable final ClientSession clientSession, @Nullable final Timeout operationTimeout) { + private void checkCreateIndex(@Nullable final ClientSession clientSession) { if (!checkedIndexes) { if (collectionIsEmpty(clientSession, - filesCollection.withDocumentClass(Document.class).withReadPreference(primary()), - operationTimeout)) { + filesCollection.withDocumentClass(Document.class).withReadPreference(primary()) + )) { Document filesIndex = new Document("filename", 1).append("uploadDate", 1); - if (!hasIndex(clientSession, filesCollection.withReadPreference(primary()), filesIndex, operationTimeout)) { - createIndex(clientSession, filesCollection, filesIndex, new IndexOptions(), operationTimeout); + if (!hasIndex(clientSession, filesCollection.withReadPreference(primary()), filesIndex)) { + createIndex(clientSession, filesCollection, filesIndex, new IndexOptions()); } Document chunksIndex = new Document("files_id", 1).append("n", 1); - if (!hasIndex(clientSession, chunksCollection.withReadPreference(primary()), chunksIndex, operationTimeout)) { - createIndex(clientSession, chunksCollection, chunksIndex, new IndexOptions().unique(true), operationTimeout); + if (!hasIndex(clientSession, chunksCollection.withReadPreference(primary()), chunksIndex)) { + createIndex(clientSession, chunksCollection, chunksIndex, new IndexOptions().unique(true)); } } checkedIndexes = true; @@ -532,25 +497,24 @@ private void checkCreateIndex(@Nullable final ClientSession clientSession, @Null } private boolean collectionIsEmpty(@Nullable final ClientSession clientSession, - final MongoCollection collection, - @Nullable final Timeout operationTimeout) { + final MongoCollection collection) { if (clientSession != null) { - return withNullableTimeout(collection, operationTimeout) + return collection .find(clientSession).projection(new Document("_id", 1)).first() == null; } else { - return withNullableTimeout(collection, operationTimeout) + return collection .find().projection(new Document("_id", 1)).first() == null; } } private boolean hasIndex(@Nullable final ClientSession clientSession, final MongoCollection collection, - final Document index, @Nullable final Timeout operationTimeout) { + final Document index) { boolean hasIndex = false; ListIndexesIterable listIndexesIterable; if (clientSession != null) { - listIndexesIterable = withNullableTimeout(collection, operationTimeout).listIndexes(clientSession); + listIndexesIterable = collection.listIndexes(clientSession); } else { - listIndexesIterable = withNullableTimeout(collection, operationTimeout).listIndexes(); + listIndexesIterable = collection.listIndexes(); } ArrayList indexes = listIndexesIterable.into(new ArrayList<>()); @@ -570,16 +534,16 @@ private boolean hasIndex(@Nullable final ClientSession clientSession, final } private void createIndex(@Nullable final ClientSession clientSession, final MongoCollection collection, final Document index, - final IndexOptions indexOptions, final @Nullable Timeout operationTimeout) { + final IndexOptions indexOptions) { if (clientSession != null) { - withNullableTimeout(collection, operationTimeout).createIndex(clientSession, index, indexOptions); + collection.createIndex(clientSession, index, indexOptions); } else { - withNullableTimeout(collection, operationTimeout).createIndex(index, indexOptions); + collection.createIndex(index, indexOptions); } } private GridFSFile getFileByName(@Nullable final ClientSession clientSession, final String filename, - final GridFSDownloadOptions options, @Nullable final Timeout operationTimeout) { + final GridFSDownloadOptions options) { int revision = options.getRevision(); int skip; int sort; @@ -591,7 +555,7 @@ private GridFSFile getFileByName(@Nullable final ClientSession clientSession, fi sort = -1; } - GridFSFile fileInfo = createGridFSFindIterable(clientSession, new Document("filename", filename), operationTimeout).skip(skip) + GridFSFile fileInfo = createGridFSFindIterable(clientSession, new Document("filename", filename)).skip(skip) .sort(new Document("uploadDate", sort)).first(); if (fileInfo == null) { throw new MongoGridFSException(format("No file found with the filename: %s and revision: %s", filename, revision)); @@ -599,30 +563,25 @@ private GridFSFile getFileByName(@Nullable final ClientSession clientSession, fi return fileInfo; } - private GridFSFile getFileInfoById(@Nullable final ClientSession clientSession, final BsonValue id, - @Nullable final Timeout operationTImeout) { + private GridFSFile getFileInfoById(@Nullable final ClientSession clientSession, final BsonValue id) { notNull("id", id); - GridFSFile fileInfo = createFindIterable(clientSession, GridFSFilters.eq("_id", id), operationTImeout).first(); + GridFSFile fileInfo = createFindIterable(clientSession, GridFSFilters.eq("_id", id)).first(); if (fileInfo == null) { throw new MongoGridFSException(format("No file found with the id: %s", id)); } return fileInfo; } - private FindIterable createFindIterable(@Nullable final ClientSession clientSession, @Nullable final Bson filter, - @Nullable final Timeout operationTImeout) { + private FindIterable createFindIterable(@Nullable final ClientSession clientSession, @Nullable final Bson filter) { FindIterable findIterable; if (clientSession != null) { - findIterable = withNullableTimeout(filesCollection, operationTImeout).find(clientSession); + findIterable = filesCollection.find(clientSession); } else { - findIterable = withNullableTimeout(filesCollection, operationTImeout).find(); + findIterable = filesCollection.find(); } if (filter != null) { findIterable = findIterable.filter(filter); } - if (filesCollection.getTimeout(MILLISECONDS) != null) { - findIterable.timeoutMode(TimeoutMode.CURSOR_LIFETIME); - } return findIterable; } @@ -634,8 +593,6 @@ private void downloadToStream(final GridFSDownloadStream downloadStream, final O while ((len = downloadStream.read(buffer)) != -1) { destination.write(buffer, 0, len); } - } catch (MongoOperationTimeoutException e){ - throw e; } catch (IOException e) { savedThrowable = new MongoGridFSException("IOException when reading from the OutputStream", e); } catch (Exception e) { @@ -651,14 +608,4 @@ private void downloadToStream(final GridFSDownloadStream downloadStream, final O } } } - - private static MongoCollection withNullableTimeout(final MongoCollection chunksCollection, - @Nullable final Timeout timeout) { - return TimeoutHelper.collectionWithTimeout(chunksCollection, TIMEOUT_MESSAGE, timeout); - } - - @Nullable - private Timeout startTimeout() { - return TimeoutContext.startTimeout(filesCollection.getTimeout(MILLISECONDS)); - } } diff --git a/driver-sync/src/main/com/mongodb/client/gridfs/GridFSDownloadStreamImpl.java b/driver-sync/src/main/com/mongodb/client/gridfs/GridFSDownloadStreamImpl.java index 61849f679ed..0130fdf897d 100644 --- a/driver-sync/src/main/com/mongodb/client/gridfs/GridFSDownloadStreamImpl.java +++ b/driver-sync/src/main/com/mongodb/client/gridfs/GridFSDownloadStreamImpl.java @@ -21,10 +21,7 @@ import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.gridfs.model.GridFSFile; -import com.mongodb.client.internal.TimeoutHelper; -import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; import org.bson.BsonBinary; import org.bson.BsonDocument; @@ -36,7 +33,6 @@ import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.internal.Locks.withInterruptibleLock; -import static com.mongodb.internal.TimeoutContext.createMongoTimeoutException; import static java.lang.String.format; class GridFSDownloadStreamImpl extends GridFSDownloadStream { @@ -61,14 +57,12 @@ class GridFSDownloadStreamImpl extends GridFSDownloadStream { private long currentPosition; private byte[] buffer = null; private long markPosition; - @Nullable - private final Timeout timeout; private final ReentrantLock closeLock = new ReentrantLock(); private final ReentrantLock cursorLock = new ReentrantLock(); private boolean closed = false; GridFSDownloadStreamImpl(@Nullable final ClientSession clientSession, final GridFSFile fileInfo, - final MongoCollection chunksCollection, @Nullable final Timeout timeout) { + final MongoCollection chunksCollection) { this.clientSession = clientSession; this.fileInfo = notNull("file information", fileInfo); this.chunksCollection = notNull("chunks collection", chunksCollection); @@ -77,7 +71,6 @@ class GridFSDownloadStreamImpl extends GridFSDownloadStream { length = fileInfo.getLength(); chunkSizeInBytes = fileInfo.getChunkSize(); numberOfChunks = (int) Math.ceil((double) length / chunkSizeInBytes); - this.timeout = timeout; } @Override @@ -111,7 +104,6 @@ public int read(final byte[] b) { @Override public int read(final byte[] b, final int off, final int len) { checkClosed(); - checkTimeout(); if (currentPosition == length) { return -1; @@ -133,7 +125,7 @@ public int read(final byte[] b, final int off, final int len) { @Override public long skip(final long bytesToSkip) { checkClosed(); - checkTimeout(); + if (bytesToSkip <= 0) { return 0; } @@ -162,7 +154,7 @@ public long skip(final long bytesToSkip) { @Override public int available() { checkClosed(); - checkTimeout(); + if (buffer == null) { return 0; } else { @@ -183,7 +175,7 @@ public void mark(final int readlimit) { @Override public void reset() { checkClosed(); - checkTimeout(); + if (currentPosition == markPosition) { return; } @@ -213,11 +205,6 @@ public void close() { }); } - private void checkTimeout() { - Timeout.onExistsAndExpired(timeout, () -> { - throw createMongoTimeoutException(TIMEOUT_MESSAGE); - }); - } private void checkClosed() { withInterruptibleLock(closeLock, () -> { if (closed) { @@ -260,12 +247,9 @@ private MongoCursor getCursor(final int startChunkIndex) { BsonDocument filter = GridFSFilters.eq("files_id", fileId) .append("n", new BsonDocument("$gte", new BsonInt32(startChunkIndex))); if (clientSession != null) { - findIterable = withNullableTimeout(chunksCollection, timeout).find(clientSession, filter); + findIterable = chunksCollection.find(clientSession, filter); } else { - findIterable = withNullableTimeout(chunksCollection, timeout).find(filter); - } - if (timeout != null){ - findIterable.timeoutMode(TimeoutMode.CURSOR_LIFETIME); + findIterable = chunksCollection.find(filter); } return findIterable.batchSize(batchSize) .sort(new BsonDocument("n", new BsonInt32(1))).iterator(); @@ -308,8 +292,4 @@ private byte[] getBuffer(final int chunkIndexToFetch) { return getBufferFromChunk(getChunk(chunkIndexToFetch), chunkIndexToFetch); } - private MongoCollection withNullableTimeout(final MongoCollection chunksCollection, - @Nullable final Timeout timeout) { - return TimeoutHelper.collectionWithTimeout(chunksCollection, TIMEOUT_MESSAGE, timeout); - } } diff --git a/driver-sync/src/main/com/mongodb/client/gridfs/GridFSUploadStreamImpl.java b/driver-sync/src/main/com/mongodb/client/gridfs/GridFSUploadStreamImpl.java index bd1c73b742f..96b07d7645d 100644 --- a/driver-sync/src/main/com/mongodb/client/gridfs/GridFSUploadStreamImpl.java +++ b/driver-sync/src/main/com/mongodb/client/gridfs/GridFSUploadStreamImpl.java @@ -20,9 +20,6 @@ import com.mongodb.client.ClientSession; import com.mongodb.client.MongoCollection; import com.mongodb.client.gridfs.model.GridFSFile; -import com.mongodb.client.internal.TimeoutHelper; -import com.mongodb.internal.TimeoutContext; -import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; import org.bson.BsonBinary; import org.bson.BsonDocument; @@ -38,7 +35,6 @@ import static com.mongodb.internal.Locks.withInterruptibleLock; final class GridFSUploadStreamImpl extends GridFSUploadStream { - public static final String TIMEOUT_MESSAGE = "The GridFS upload stream exceeded the timeout limit."; private final ClientSession clientSession; private final MongoCollection filesCollection; private final MongoCollection chunksCollection; @@ -50,14 +46,12 @@ final class GridFSUploadStreamImpl extends GridFSUploadStream { private long lengthInBytes; private int bufferOffset; private int chunkIndex; - @Nullable - private final Timeout timeout; private final ReentrantLock closeLock = new ReentrantLock(); private boolean closed = false; GridFSUploadStreamImpl(@Nullable final ClientSession clientSession, final MongoCollection filesCollection, final MongoCollection chunksCollection, final BsonValue fileId, final String filename, - final int chunkSizeBytes, @Nullable final Document metadata, @Nullable final Timeout timeout) { + final int chunkSizeBytes, @Nullable final Document metadata) { this.clientSession = clientSession; this.filesCollection = notNull("files collection", filesCollection); this.chunksCollection = notNull("chunks collection", chunksCollection); @@ -68,7 +62,6 @@ final class GridFSUploadStreamImpl extends GridFSUploadStream { chunkIndex = 0; bufferOffset = 0; buffer = new byte[chunkSizeBytes]; - this.timeout = timeout; } @Override @@ -93,10 +86,10 @@ public void abort() { BsonDocument chunksFilter = GridFSFilters.eq("files_id", fileId); if (clientSession != null) { - withNullableTimeout(chunksCollection, timeout) + chunksCollection .deleteMany(clientSession, chunksFilter); } else { - withNullableTimeout(chunksCollection, timeout) + chunksCollection .deleteMany(chunksFilter); } } @@ -116,7 +109,6 @@ public void write(final byte[] b) { @Override public void write(final byte[] b, final int off, final int len) { checkClosed(); - checkTimeout(); notNull("b", b); if ((off < 0) || (off > b.length) || (len < 0) @@ -148,10 +140,6 @@ public void write(final byte[] b, final int off, final int len) { } } - private void checkTimeout() { - Timeout.onExistsAndExpired(timeout, () -> TimeoutContext.throwMongoTimeoutException(TIMEOUT_MESSAGE)); - } - @Override public void close() { boolean alreadyClosed = withInterruptibleLock(closeLock, () -> { @@ -166,9 +154,9 @@ public void close() { GridFSFile gridFSFile = new GridFSFile(fileId, filename, lengthInBytes, chunkSizeBytes, new Date(), metadata); if (clientSession != null) { - withNullableTimeout(filesCollection, timeout).insertOne(clientSession, gridFSFile); + filesCollection.insertOne(clientSession, gridFSFile); } else { - withNullableTimeout(filesCollection, timeout).insertOne(gridFSFile); + filesCollection.insertOne(gridFSFile); } buffer = null; } @@ -176,12 +164,12 @@ public void close() { private void writeChunk() { if (bufferOffset > 0) { if (clientSession != null) { - withNullableTimeout(chunksCollection, timeout) + chunksCollection .insertOne(clientSession, new BsonDocument("files_id", fileId) .append("n", new BsonInt32(chunkIndex)) .append("data", getData())); } else { - withNullableTimeout(chunksCollection, timeout) + chunksCollection .insertOne(new BsonDocument("files_id", fileId) .append("n", new BsonInt32(chunkIndex)) .append("data", getData())); @@ -208,8 +196,4 @@ private void checkClosed() { }); } - private static MongoCollection withNullableTimeout(final MongoCollection collection, - @Nullable final Timeout timeout) { - return TimeoutHelper.collectionWithTimeout(collection, TIMEOUT_MESSAGE, timeout); - } } diff --git a/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java index 841d2532312..52598d9e425 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/AggregateIterableImpl.java @@ -23,7 +23,6 @@ import com.mongodb.WriteConcern; import com.mongodb.client.AggregateIterable; import com.mongodb.client.ClientSession; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.client.model.AggregationLevel; @@ -101,7 +100,7 @@ public void toCollection() { } getExecutor().execute( - operations.aggregateToCollection(pipeline, getTimeoutMode(), allowDiskUse, + operations.aggregateToCollection(pipeline, allowDiskUse, bypassDocumentValidation, collation, hint, hintString, comment, variables, aggregationLevel), getReadPreference(), getReadConcern(), getClientSession()); } @@ -118,12 +117,6 @@ public AggregateIterable batchSize(final int batchSize) { return this; } - @Override - public AggregateIterable timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - @Override public AggregateIterable maxTime(final long maxTime, final TimeUnit timeUnit) { notNull("timeUnit", timeUnit); @@ -210,9 +203,8 @@ private E executeExplain(final Class explainResultClass, @Nullable final public ReadOperationCursor asReadOperation() { MongoNamespace outNamespace = getOutNamespace(); if (outNamespace != null) { - validateTimeoutMode(); getExecutor().execute( - operations.aggregateToCollection(pipeline, getTimeoutMode(), allowDiskUse, + operations.aggregateToCollection(pipeline, allowDiskUse, bypassDocumentValidation, collation, hint, hintString, comment, variables, aggregationLevel), getReadPreference(), getReadConcern(), getClientSession()); @@ -232,7 +224,7 @@ protected OperationExecutor getExecutor() { } private ReadOperationExplainable asAggregateOperation() { - return operations.aggregate(pipeline, resultClass, getTimeoutMode(), getBatchSize(), collation, hint, hintString, comment, + return operations.aggregate(pipeline, resultClass, getBatchSize(), collation, hint, hintString, comment, variables, allowDiskUse, aggregationLevel); } @@ -284,11 +276,4 @@ private MongoNamespace getOutNamespace() { return null; } - - private void validateTimeoutMode() { - if (getTimeoutMode() == TimeoutMode.ITERATION) { - throw new IllegalArgumentException("Aggregations that output to a collection do not support the ITERATION value for the " - + "timeoutMode option."); - } - } } diff --git a/driver-sync/src/main/com/mongodb/client/internal/ClientEncryptionImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ClientEncryptionImpl.java index 3edef6b937d..1f1f468a8db 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ClientEncryptionImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ClientEncryptionImpl.java @@ -39,10 +39,8 @@ import com.mongodb.client.model.vault.RewrapManyDataKeyResult; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.vault.ClientEncryption; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.VisibleForTesting; import com.mongodb.internal.time.Timeout; -import com.mongodb.lang.Nullable; import org.bson.BsonArray; import org.bson.BsonBinary; import org.bson.BsonDocument; @@ -58,14 +56,11 @@ import java.util.stream.Collectors; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.client.internal.TimeoutHelper.collectionWithTimeout; -import static com.mongodb.client.internal.TimeoutHelper.databaseWithTimeout; import static com.mongodb.internal.VisibleForTesting.AccessModifier.PRIVATE; import static com.mongodb.internal.capi.MongoCryptHelper.validateRewrapManyDataKeyOptions; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; -import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.bson.internal.BsonUtil.mutableDeepCopy; /** @@ -98,10 +93,6 @@ private static MongoCollection getVaultCollection(final MongoClien .withWriteConcern(WriteConcern.MAJORITY) .withReadConcern(ReadConcern.MAJORITY); - Long timeoutMs = options.getTimeout(MILLISECONDS); - if (timeoutMs != null){ - vaultCollection = vaultCollection.withTimeout(timeoutMs, MILLISECONDS); - } return vaultCollection; } @@ -112,48 +103,43 @@ public BsonBinary createDataKey(final String kmsProvider) { @Override public BsonBinary createDataKey(final String kmsProvider, final DataKeyOptions dataKeyOptions) { - Timeout operationTimeout = startTimeout(); - return createDataKey(kmsProvider, dataKeyOptions, operationTimeout); - } - - public BsonBinary createDataKey(final String kmsProvider, final DataKeyOptions dataKeyOptions, @Nullable final Timeout operationTimeout) { - BsonDocument dataKeyDocument = crypt.createDataKey(kmsProvider, dataKeyOptions, operationTimeout); - collectionWithTimeout(collection, "Data key insertion exceeded the timeout limit.", operationTimeout).insertOne(dataKeyDocument); + BsonDocument dataKeyDocument = crypt.createDataKey(kmsProvider, dataKeyOptions); + collection.insertOne(dataKeyDocument); return dataKeyDocument.getBinary("_id"); } @Override public BsonBinary encrypt(final BsonValue value, final EncryptOptions options) { - Timeout operationTimeout = startTimeout(); + Timeout operationTimeout = null; return crypt.encryptExplicitly(value, options, operationTimeout); } @Override public BsonDocument encryptExpression(final Bson expression, final EncryptOptions options) { - Timeout operationTimeout = startTimeout(); + Timeout operationTimeout = null; return crypt.encryptExpression(expression.toBsonDocument(BsonDocument.class, collection.getCodecRegistry()), options, operationTimeout); } @Override public BsonValue decrypt(final BsonBinary value) { - Timeout operationTimeout = startTimeout(); + Timeout operationTimeout = null; return crypt.decryptExplicitly(value, operationTimeout); } @Override public DeleteResult deleteKey(final BsonBinary id) { - return collectionWithTimeout(collection, startTimeout()).deleteOne(Filters.eq("_id", id)); + return collection.deleteOne(Filters.eq("_id", id)); } @Override public BsonDocument getKey(final BsonBinary id) { - return collectionWithTimeout(collection, startTimeout()).find(Filters.eq("_id", id)).first(); + return collection.find(Filters.eq("_id", id)).first(); } @Override public FindIterable getKeys() { - return collectionWithTimeout(collection, startTimeout()).find(); + return collection.find(); } @Override @@ -198,7 +184,7 @@ public RewrapManyDataKeyResult rewrapManyDataKey(final Bson filter) { @Override public RewrapManyDataKeyResult rewrapManyDataKey(final Bson filter, final RewrapManyDataKeyOptions options) { validateRewrapManyDataKeyOptions(options); - Timeout operationTimeout = startTimeout(); + Timeout operationTimeout = null; BsonDocument results = crypt.rewrapManyDataKey(filter.toBsonDocument(BsonDocument.class, collection.getCodecRegistry()), options, operationTimeout); if (results.isEmpty()) { @@ -213,7 +199,7 @@ public RewrapManyDataKeyResult rewrapManyDataKey(final Bson filter, final Rewrap Updates.currentDate("updateDate")) ); }).collect(Collectors.toList()); - BulkWriteResult bulkWriteResult = collectionWithTimeout(collection, operationTimeout).bulkWrite(updateModels); + BulkWriteResult bulkWriteResult = collection.bulkWrite(updateModels); return new RewrapManyDataKeyResult(bulkWriteResult); } @@ -223,7 +209,7 @@ public BsonDocument createEncryptedCollection(final MongoDatabase database, fina notNull("collectionName", collectionName); notNull("createCollectionOptions", createCollectionOptions); notNull("createEncryptedCollectionParams", createEncryptedCollectionParams); - Timeout operationTimeout = startTimeout(); + Timeout operationTimeout = null; MongoNamespace namespace = new MongoNamespace(database.getName(), collectionName); Bson rawEncryptedFields = createCollectionOptions.getEncryptedFields(); if (rawEncryptedFields == null) { @@ -254,10 +240,10 @@ public BsonDocument createEncryptedCollection(final MongoDatabase database, fina // It is crucial to set the `dataKeyMightBeCreated` flag either immediately before calling `createDataKey`, // or after that in a `finally` block. dataKeyMightBeCreated.set(true); - BsonBinary dataKeyId = createDataKey(kmsProvider, dataKeyOptions, operationTimeout); + BsonBinary dataKeyId = createDataKey(kmsProvider, dataKeyOptions); field.put(keyIdBsonKey, dataKeyId); }); - databaseWithTimeout(database, operationTimeout).createCollection(collectionName, + database.createCollection(collectionName, new CreateCollectionOptions(createCollectionOptions).encryptedFields(maybeUpdatedEncryptedFields)); return maybeUpdatedEncryptedFields; } catch (Exception e) { @@ -268,7 +254,7 @@ public BsonDocument createEncryptedCollection(final MongoDatabase database, fina } } } else { - databaseWithTimeout(database, operationTimeout).createCollection(collectionName, createCollectionOptions); + database.createCollection(collectionName, createCollectionOptions); return encryptedFields; } } @@ -278,9 +264,4 @@ public void close() { crypt.close(); keyVaultClient.close(); } - - @Nullable - private Timeout startTimeout() { - return TimeoutContext.startTimeout(options.getTimeout(MILLISECONDS)); - } } diff --git a/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java index d2d6720edd9..dd1aa40a042 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java @@ -35,7 +35,6 @@ import com.mongodb.internal.operation.CommitTransactionOperation; import com.mongodb.internal.operation.OperationHelper; import com.mongodb.internal.operation.ReadOperation; -import com.mongodb.internal.operation.WriteConcernHelper; import com.mongodb.internal.operation.WriteOperation; import com.mongodb.internal.session.BaseClientSessionImpl; import com.mongodb.internal.session.ServerSessionPool; @@ -54,8 +53,8 @@ import static com.mongodb.assertions.Assertions.isTrue; import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.internal.TimeoutContext.DEFAULT_TIMEOUT_MESSAGE; -import static com.mongodb.internal.TimeoutContext.createMongoTimeoutException; import static com.mongodb.internal.thread.InterruptionUtil.interruptAndCreateMongoInterruptedException; +import static com.mongodb.internal.time.Timeout.ZeroSemantics.ZERO_DURATION_MEANS_INFINITE; final class ClientSessionImpl extends BaseClientSessionImpl implements ClientSession { @@ -152,8 +151,7 @@ public void abortTransaction() { throw new MongoInternalException("Invariant violated. Transaction options read concern can not be null"); } resetTimeout(); - TimeoutContext timeoutContext = getTimeoutContext(); - WriteConcern writeConcern = assertNotNull(getWriteConcern(timeoutContext)); + WriteConcern writeConcern = assertNotNull(getWriteConcern()); operationExecutor .execute(new AbortTransactionOperation(writeConcern, maxAdaptiveRetriesSetting) .recoveryToken(getRecoveryToken()), readConcern, this); @@ -191,7 +189,7 @@ private void startTransaction(final TransactionOptions transactionOptions, final } getServerSession().advanceTransactionNumber(); this.transactionOptions = TransactionOptions.merge(transactionOptions, getOptions().getDefaultTransactionOptions()); - WriteConcern writeConcern = getWriteConcern(timeoutContext); + WriteConcern writeConcern = getWriteConcern(); if (writeConcern == null) { throw new MongoInternalException("Invariant violated. Transaction options write concern can not be null"); } @@ -208,12 +206,8 @@ private void startTransaction(final TransactionOptions transactionOptions, final } @Nullable - private WriteConcern getWriteConcern(@Nullable final TimeoutContext timeoutContext) { - WriteConcern writeConcern = transactionOptions.getWriteConcern(); - if (hasTimeoutMS(timeoutContext) && hasWTimeoutMS(writeConcern)) { - return WriteConcernHelper.cloneWithoutTimeout(writeConcern); - } - return writeConcern; + private WriteConcern getWriteConcern() { + return transactionOptions.getWriteConcern(); } private void commitTransaction(final boolean resetTimeout) { @@ -238,8 +232,7 @@ private void commitTransaction(final boolean resetTimeout) { if (resetTimeout) { resetTimeout(); } - TimeoutContext timeoutContext = getTimeoutContext(); - WriteConcern writeConcern = assertNotNull(getWriteConcern(timeoutContext)); + WriteConcern writeConcern = assertNotNull(getWriteConcern()); operationExecutor .execute(new CommitTransactionOperation(writeConcern, maxAdaptiveRetriesSetting, alreadyCommitted) .recoveryToken(getRecoveryToken()), readConcern, this); @@ -277,10 +270,7 @@ public T withTransaction(final TransactionBody transactionBody) { public T withTransaction(final TransactionBody transactionBody, final TransactionOptions options) { notNull("transactionBody", transactionBody); TimeoutContext withTransactionTimeoutContext = createTimeoutContext(options); - boolean timeoutMsConfigured = withTransactionTimeoutContext.hasTimeoutMS(); - Timeout withTransactionTimeout = assertNotNull(timeoutMsConfigured - ? withTransactionTimeoutContext.getTimeout() - : TimeoutContext.startTimeout(MAX_RETRY_TIME_LIMIT_MS)); + Timeout withTransactionTimeout = Timeout.expiresIn(MAX_RETRY_TIME_LIMIT_MS, TimeUnit.MILLISECONDS, ZERO_DURATION_MEANS_INFINITE); BooleanSupplier withTransactionTimeoutExpired = () -> withTransactionTimeout.call(TimeUnit.MILLISECONDS, () -> false, ms -> false, () -> true); int transactionAttempt = 0; @@ -290,7 +280,7 @@ public T withTransaction(final TransactionBody transactionBody, final Tra transactionAttempts: while (true) { if (transactionAttempt > 0) { - backoff(transactionAttempt, withTransactionTimeout, assertNotNull(lastError), timeoutMsConfigured); + backoff(transactionAttempt, withTransactionTimeout, assertNotNull(lastError)); } try { startTransaction(options, withTransactionTimeoutContext); @@ -329,7 +319,7 @@ public T withTransaction(final TransactionBody transactionBody, final Tra if (mongoException.hasErrorLabel(UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL) && !(mongoException instanceof MongoExecutionTimeoutException)) { if (withTransactionTimeoutExpired.getAsBoolean()) { - throw wrapInMongoTimeoutException(mongoException, timeoutMsConfigured); + throw wrapInMongoTimeoutException(mongoException); } continue; } else if (mongoException.hasErrorLabel(TRANSIENT_TRANSACTION_ERROR_LABEL)) { @@ -384,10 +374,10 @@ private TimeoutContext createTimeoutContext(final TransactionOptions transaction } private static void backoff(final int transactionAttempt, - final Timeout withTransactionTimeout, final MongoException lastError, final boolean timeoutMsConfigured) { + final Timeout withTransactionTimeout, final MongoException lastError) { long backoffMs = ExponentialBackoff.calculateTransactionBackoffMs(transactionAttempt); withTransactionTimeout.shortenBy(backoffMs, TimeUnit.MILLISECONDS).onExpired(() -> { - throw wrapInMongoTimeoutException(lastError, timeoutMsConfigured); + throw wrapInMongoTimeoutException(lastError); }); try { if (backoffMs > 0) { @@ -398,10 +388,8 @@ private static void backoff(final int transactionAttempt, } } - private static MongoClientException wrapInMongoTimeoutException(final MongoException cause, final boolean timeoutMsConfigured) { - MongoClientException timeoutException = timeoutMsConfigured - ? createMongoTimeoutException(cause) - : wrapInNonTimeoutMsMongoTimeoutException(cause); + private static MongoClientException wrapInMongoTimeoutException(final MongoException cause) { + MongoClientException timeoutException = wrapInNonTimeoutMsMongoTimeoutException(cause); //TODO-JAVA-6154 constructor should be used. if (timeoutException != cause) { cause.getErrorLabels().forEach(timeoutException::addLabel); diff --git a/driver-sync/src/main/com/mongodb/client/internal/CollectionInfoRetriever.java b/driver-sync/src/main/com/mongodb/client/internal/CollectionInfoRetriever.java index 9ce34fd18a9..f27cb14f836 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/CollectionInfoRetriever.java +++ b/driver-sync/src/main/com/mongodb/client/internal/CollectionInfoRetriever.java @@ -17,15 +17,12 @@ package com.mongodb.client.internal; import com.mongodb.client.MongoClient; -import com.mongodb.internal.time.Timeout; -import com.mongodb.lang.Nullable; import org.bson.BsonDocument; import java.util.ArrayList; import java.util.List; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.client.internal.TimeoutHelper.databaseWithTimeout; class CollectionInfoRetriever { @@ -36,8 +33,8 @@ class CollectionInfoRetriever { this.client = notNull("client", client); } - public List filter(final String databaseName, final BsonDocument filter, @Nullable final Timeout timeout) { - return databaseWithTimeout(client.getDatabase(databaseName), TIMEOUT_ERROR_MESSAGE, timeout) + public List filter(final String databaseName, final BsonDocument filter) { + return client.getDatabase(databaseName) .listCollections(BsonDocument.class) .filter(filter) .into(new ArrayList<>()); diff --git a/driver-sync/src/main/com/mongodb/client/internal/CommandMarker.java b/driver-sync/src/main/com/mongodb/client/internal/CommandMarker.java index 365b1fc49e1..6abb5b44b03 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/CommandMarker.java +++ b/driver-sync/src/main/com/mongodb/client/internal/CommandMarker.java @@ -19,7 +19,6 @@ import com.mongodb.AutoEncryptionSettings; import com.mongodb.MongoClientException; import com.mongodb.MongoException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoTimeoutException; import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; @@ -27,7 +26,6 @@ import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import com.mongodb.internal.crypt.capi.MongoCrypt; -import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; import org.bson.RawBsonDocument; @@ -35,7 +33,6 @@ import java.util.Map; import static com.mongodb.assertions.Assertions.assertNotNull; -import static com.mongodb.client.internal.TimeoutHelper.databaseWithTimeout; import static com.mongodb.internal.capi.MongoCryptHelper.createMongocryptdClientSettings; import static com.mongodb.internal.capi.MongoCryptHelper.createProcessBuilder; import static com.mongodb.internal.capi.MongoCryptHelper.isMongocryptdSpawningDisabled; @@ -84,19 +81,17 @@ class CommandMarker implements Closeable { } } - RawBsonDocument mark(final String databaseName, final RawBsonDocument command, @Nullable final Timeout timeout) { + RawBsonDocument mark(final String databaseName, final RawBsonDocument command) { if (client != null) { try { try { - return executeCommand(databaseName, command, timeout); - } catch (MongoOperationTimeoutException e){ - throw e; + return executeCommand(databaseName, command); } catch (MongoTimeoutException e) { if (processBuilder == null) { // mongocryptdBypassSpawn=true throw e; } startProcess(processBuilder); - return executeCommand(databaseName, command, timeout); + return executeCommand(databaseName, command); } } catch (MongoException e) { throw new MongoClientException("Exception in encryption library: " + e.getMessage(), e); @@ -115,15 +110,14 @@ public void close() { private RawBsonDocument executeCommand( final String databaseName, - final RawBsonDocument markableCommand, - @Nullable final Timeout timeout) { + final RawBsonDocument markableCommand) { assertNotNull(client); MongoDatabase mongoDatabase = client.getDatabase(databaseName) .withReadConcern(ReadConcern.DEFAULT) .withReadPreference(ReadPreference.primary()); - return databaseWithTimeout(mongoDatabase, TIMEOUT_ERROR_MESSAGE, timeout) + return mongoDatabase .runCommand(markableCommand, RawBsonDocument.class); } } diff --git a/driver-sync/src/main/com/mongodb/client/internal/Crypt.java b/driver-sync/src/main/com/mongodb/client/internal/Crypt.java index a6fe46eecc3..5db15010b25 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/Crypt.java +++ b/driver-sync/src/main/com/mongodb/client/internal/Crypt.java @@ -134,8 +134,7 @@ public class Crypt implements Closeable { */ RawBsonDocument encrypt( final String databaseName, - final RawBsonDocument command, - @Nullable final Timeout timeout) { + final RawBsonDocument command) { notNull("databaseName", databaseName); notNull("command", command); @@ -144,7 +143,7 @@ RawBsonDocument encrypt( } try (MongoCryptContext encryptionContext = mongoCrypt.createEncryptionContext(databaseName, command)) { - return executeStateMachine(encryptionContext, databaseName, timeout); + return executeStateMachine(encryptionContext, databaseName); } catch (MongoCryptException e) { throw wrapInClientException(e); } @@ -156,10 +155,10 @@ RawBsonDocument encrypt( * @param commandResponse the encrypted command response * @return the decrypted command response */ - RawBsonDocument decrypt(final RawBsonDocument commandResponse, @Nullable final Timeout timeoutOperation) { + RawBsonDocument decrypt(final RawBsonDocument commandResponse) { notNull("commandResponse", commandResponse); try (MongoCryptContext decryptionContext = mongoCrypt.createDecryptionContext(commandResponse)) { - return executeStateMachine(decryptionContext, null, timeoutOperation); + return executeStateMachine(decryptionContext, null); } catch (MongoCryptException e) { throw wrapInClientException(e); } @@ -172,7 +171,7 @@ RawBsonDocument decrypt(final RawBsonDocument commandResponse, @Nullable final * @param options the data key options * @return the document representing the data key to be added to the key vault */ - BsonDocument createDataKey(final String kmsProvider, final DataKeyOptions options, @Nullable final Timeout operationTimeout) { + BsonDocument createDataKey(final String kmsProvider, final DataKeyOptions options) { notNull("kmsProvider", kmsProvider); notNull("options", options); @@ -182,7 +181,7 @@ BsonDocument createDataKey(final String kmsProvider, final DataKeyOptions option .masterKey(options.getMasterKey()) .keyMaterial(options.getKeyMaterial()) .build())) { - return executeStateMachine(dataKeyCreationContext, null, operationTimeout); + return executeStateMachine(dataKeyCreationContext, null); } catch (MongoCryptException e) { throw wrapInClientException(e); } @@ -201,7 +200,7 @@ BsonBinary encryptExplicitly(final BsonValue value, final EncryptOptions options try (MongoCryptContext encryptionContext = mongoCrypt.createExplicitEncryptionContext( new BsonDocument("v", value), asMongoExplicitEncryptOptions(options))) { - return executeStateMachine(encryptionContext, null, timeoutOperation).getBinary("v"); + return executeStateMachine(encryptionContext, null).getBinary("v"); } catch (MongoCryptException e) { throw wrapInClientException(e); } @@ -220,7 +219,7 @@ BsonDocument encryptExpression(final BsonDocument expression, final EncryptOptio try (MongoCryptContext encryptionContext = mongoCrypt.createEncryptExpressionContext( new BsonDocument("v", expression), asMongoExplicitEncryptOptions(options))) { - return executeStateMachine(encryptionContext, null, timeoutOperation).getDocument("v"); + return executeStateMachine(encryptionContext, null).getDocument("v"); } catch (MongoCryptException e) { throw wrapInClientException(e); } @@ -235,7 +234,7 @@ BsonDocument encryptExpression(final BsonDocument expression, final EncryptOptio BsonValue decryptExplicitly(final BsonBinary value, @Nullable final Timeout timeoutOperation) { notNull("value", value); try (MongoCryptContext decryptionContext = mongoCrypt.createExplicitDecryptionContext(new BsonDocument("v", value))) { - return assertNotNull(executeStateMachine(decryptionContext, null, timeoutOperation).get("v")); + return assertNotNull(executeStateMachine(decryptionContext, null).get("v")); } catch (MongoCryptException e) { throw wrapInClientException(e); } @@ -257,7 +256,7 @@ BsonDocument rewrapManyDataKey(final BsonDocument filter, final RewrapManyDataKe .provider(options.getProvider()) .masterKey(options.getMasterKey()) .build())) { - return executeStateMachine(rewrapManyDatakeyContext, null, operationTimeout); + return executeStateMachine(rewrapManyDatakeyContext, null); } } catch (MongoCryptException e) { throw wrapInClientException(e); @@ -279,25 +278,24 @@ public void close() { private RawBsonDocument executeStateMachine( final MongoCryptContext cryptContext, - @Nullable final String databaseName, - @Nullable final Timeout timeout) { + @Nullable final String databaseName) { while (true) { State state = cryptContext.getState(); switch (state) { case NEED_MONGO_COLLINFO: - collInfo(cryptContext, notNull("databaseName", databaseName), timeout); + collInfo(cryptContext, notNull("databaseName", databaseName)); break; case NEED_MONGO_MARKINGS: - mark(cryptContext, notNull("databaseName", databaseName), timeout); + mark(cryptContext, notNull("databaseName", databaseName)); break; case NEED_KMS_CREDENTIALS: fetchCredentials(cryptContext); break; case NEED_MONGO_KEYS: - fetchKeys(cryptContext, timeout); + fetchKeys(cryptContext); break; case NEED_KMS: - decryptKeys(cryptContext, timeout); + decryptKeys(cryptContext); break; case READY: return cryptContext.finish(); @@ -313,10 +311,10 @@ private void fetchCredentials(final MongoCryptContext cryptContext) { cryptContext.provideKmsProviderCredentials(MongoCryptHelper.fetchCredentials(kmsProviders, kmsProviderPropertySuppliers)); } - private void collInfo(final MongoCryptContext cryptContext, final String databaseName, @Nullable final Timeout operationTimeout) { + private void collInfo(final MongoCryptContext cryptContext, final String databaseName) { try { List results = assertNotNull(collectionInfoRetriever) - .filter(databaseName, cryptContext.getMongoOperation(), operationTimeout); + .filter(databaseName, cryptContext.getMongoOperation()); for (BsonDocument result : results) { cryptContext.addMongoOperationResult(result); } @@ -326,9 +324,9 @@ private void collInfo(final MongoCryptContext cryptContext, final String databas } } - private void mark(final MongoCryptContext cryptContext, final String databaseName, @Nullable final Timeout timeout) { + private void mark(final MongoCryptContext cryptContext, final String databaseName) { try { - RawBsonDocument markedCommand = assertNotNull(commandMarker).mark(databaseName, cryptContext.getMongoOperation(), timeout); + RawBsonDocument markedCommand = assertNotNull(commandMarker).mark(databaseName, cryptContext.getMongoOperation()); cryptContext.addMongoOperationResult(markedCommand); cryptContext.completeMongoOperation(); } catch (Exception e) { @@ -336,9 +334,9 @@ private void mark(final MongoCryptContext cryptContext, final String databaseNam } } - private void fetchKeys(final MongoCryptContext keyBroker, @Nullable final Timeout operationTimeout) { + private void fetchKeys(final MongoCryptContext keyBroker) { try { - for (BsonDocument bsonDocument : keyRetriever.find(keyBroker.getMongoOperation(), operationTimeout)) { + for (BsonDocument bsonDocument : keyRetriever.find(keyBroker.getMongoOperation())) { keyBroker.addMongoOperationResult(bsonDocument); } keyBroker.completeMongoOperation(); @@ -347,11 +345,11 @@ private void fetchKeys(final MongoCryptContext keyBroker, @Nullable final Timeou } } - private void decryptKeys(final MongoCryptContext cryptContext, @Nullable final Timeout operationTimeout) { + private void decryptKeys(final MongoCryptContext cryptContext) { try { MongoKeyDecryptor keyDecryptor = cryptContext.nextKeyDecryptor(); while (keyDecryptor != null) { - decryptKey(keyDecryptor, operationTimeout); + decryptKey(keyDecryptor); keyDecryptor = cryptContext.nextKeyDecryptor(); } cryptContext.completeKeyDecryptors(); @@ -361,9 +359,9 @@ private void decryptKeys(final MongoCryptContext cryptContext, @Nullable final T } } - private void decryptKey(final MongoKeyDecryptor keyDecryptor, @Nullable final Timeout operationTimeout) throws IOException { + private void decryptKey(final MongoKeyDecryptor keyDecryptor) throws IOException { try (InputStream inputStream = keyManagementService.stream(keyDecryptor.getKmsProvider(), keyDecryptor.getHostName(), - keyDecryptor.getMessage(), operationTimeout)) { + keyDecryptor.getMessage())) { int bytesNeeded = keyDecryptor.bytesNeeded(); while (bytesNeeded > 0) { diff --git a/driver-sync/src/main/com/mongodb/client/internal/CryptConnection.java b/driver-sync/src/main/com/mongodb/client/internal/CryptConnection.java index b5c814edb04..cd16f8e6018 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/CryptConnection.java +++ b/driver-sync/src/main/com/mongodb/client/internal/CryptConnection.java @@ -112,11 +112,11 @@ public T command(final String database, final BsonDocument command, final Fi getEncoder(command).encode(writer, command, EncoderContext.builder().build()); - Timeout timeout = operationContext.getTimeoutContext().getTimeout(); + Timeout timeout = null; RawBsonDocument encryptedCommand = crypt.encrypt( database, - new RawBsonDocument(bsonOutput.getInternalBuffer(), 0, bsonOutput.getSize()), - timeout); + new RawBsonDocument(bsonOutput.getInternalBuffer(), 0, bsonOutput.getSize()) + ); RawBsonDocument encryptedResponse = wrapped.command(database, encryptedCommand, commandFieldNameValidator, readPreference, new RawBsonDocumentCodec(), operationContext, responseExpected, EmptyMessageSequences.INSTANCE); @@ -125,7 +125,7 @@ public T command(final String database, final BsonDocument command, final Fi return null; } - RawBsonDocument decryptedResponse = crypt.decrypt(encryptedResponse, timeout); + RawBsonDocument decryptedResponse = crypt.decrypt(encryptedResponse); BsonBinaryReader reader = new BsonBinaryReader(decryptedResponse.getByteBuffer().asNIO()); diff --git a/driver-sync/src/main/com/mongodb/client/internal/DistinctIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/DistinctIterableImpl.java index 5108d1849e4..039ed761ac9 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/DistinctIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/DistinctIterableImpl.java @@ -21,7 +21,6 @@ import com.mongodb.ReadPreference; import com.mongodb.client.ClientSession; import com.mongodb.client.DistinctIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.operation.Operations; @@ -79,12 +78,6 @@ public DistinctIterable batchSize(final int batchSize) { return this; } - @Override - public DistinctIterable timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - @Override public DistinctIterable collation(@Nullable final Collation collation) { this.collation = collation; diff --git a/driver-sync/src/main/com/mongodb/client/internal/FindIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/FindIterableImpl.java index 5524ca8c145..59a1becfef9 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/FindIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/FindIterableImpl.java @@ -23,7 +23,6 @@ import com.mongodb.ReadPreference; import com.mongodb.client.ClientSession; import com.mongodb.client.FindIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.client.model.FindOptions; @@ -105,13 +104,6 @@ public FindIterable batchSize(final int batchSize) { return this; } - @Override - public FindIterable timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - findOptions.timeoutMode(timeoutMode); - return this; - } - @Override public FindIterable collation(@Nullable final Collation collation) { findOptions.collation(collation); diff --git a/driver-sync/src/main/com/mongodb/client/internal/KeyManagementService.java b/driver-sync/src/main/com/mongodb/client/internal/KeyManagementService.java index 0e423cae9fb..0ed9dc40537 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/KeyManagementService.java +++ b/driver-sync/src/main/com/mongodb/client/internal/KeyManagementService.java @@ -18,12 +18,9 @@ import com.mongodb.KmsConnectCallback; import com.mongodb.ServerAddress; -import com.mongodb.internal.TimeoutContext; import com.mongodb.internal.diagnostics.logging.Logger; import com.mongodb.internal.diagnostics.logging.Loggers; -import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; -import com.mongodb.lang.NonNull; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; @@ -31,14 +28,10 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; -import java.net.SocketException; import java.nio.ByteBuffer; import java.util.Map; -import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.assertions.Assertions.notNull; -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static java.util.concurrent.TimeUnit.NANOSECONDS; class KeyManagementService { private static final Logger LOGGER = Loggers.getLogger("client"); @@ -54,21 +47,15 @@ class KeyManagementService { this.timeoutMillis = timeoutMillis; } - public InputStream stream(final String kmsProvider, final String host, final ByteBuffer message, @Nullable final Timeout operationTimeout) throws IOException { + public InputStream stream(final String kmsProvider, final String host, final ByteBuffer message) throws IOException { ServerAddress serverAddress = new ServerAddress(host); LOGGER.info("Connecting to KMS server at " + serverAddress); SSLContext sslContext = kmsProviderSslContextMap.get(kmsProvider); SSLSocket socket = KmsSocketConnector.connect(sslContext, kmsConnectCallback, serverAddress, - timeoutMillis, remainingMillis(operationTimeout)); + timeoutMillis, remainingMillis()); - // A KmsConnectCallback performs blocking I/O and may overrun the deadline it was given, which cannot be - // preempted. Re-check before issuing a request whose time budget is already spent. - Timeout.nullAsInfinite(operationTimeout).onExpired(() -> { - closeSocket(socket); - TimeoutContext.throwMongoTimeoutException("Connecting to KMS server exceeded the timeout limit."); - }); try { OutputStream outputStream = socket.getOutputStream(); @@ -83,7 +70,7 @@ public InputStream stream(final String kmsProvider, final String host, final Byt } try { - return OperationTimeoutAwareInputStream.wrapIfNeeded(operationTimeout, socket); + return socket.getInputStream(); } catch (IOException e) { closeSocket(socket); throw e; @@ -99,11 +86,8 @@ public InputStream stream(final String kmsProvider, final String host, final Byt * @return the remaining time available for connecting to the KMS server, in milliseconds, never larger than the * configured connect timeout. */ - long remainingMillis(@Nullable final Timeout operationTimeout) { - return Timeout.nullAsInfinite(operationTimeout).call(MILLISECONDS, - () -> (long) timeoutMillis, - (ms) -> Math.min(ms, timeoutMillis), - () -> TimeoutContext.throwMongoTimeoutException("Connecting to KMS server exceeded the timeout limit.")); + long remainingMillis() { + return timeoutMillis; } private void closeSocket(final Socket socket) { @@ -113,85 +97,4 @@ private void closeSocket(final Socket socket) { // ignore } } - - private static final class OperationTimeoutAwareInputStream extends InputStream { - private final Socket socket; - private final Timeout operationTimeout; - private final InputStream wrapped; - - /** - * @param socket - socket to set timeout on. - * @param operationTimeout - non-infinite timeout. - */ - private OperationTimeoutAwareInputStream(final Socket socket, final Timeout operationTimeout) throws IOException { - this.socket = socket; - this.operationTimeout = operationTimeout; - this.wrapped = socket.getInputStream(); - } - - public static InputStream wrapIfNeeded(@Nullable final Timeout operationTimeout, final SSLSocket socket) throws IOException { - return Timeout.nullAsInfinite(operationTimeout).checkedCall(NANOSECONDS, - () -> socket.getInputStream(), - (ns) -> new OperationTimeoutAwareInputStream(socket, assertNotNull(operationTimeout)), - () -> new OperationTimeoutAwareInputStream(socket, assertNotNull(operationTimeout))); - } - - private void setSocketSoTimeoutToOperationTimeout() throws SocketException { - operationTimeout.checkedRun(MILLISECONDS, - () -> { - throw new AssertionError("operationTimeout cannot be infinite"); - }, - (ms) -> socket.setSoTimeout(Math.toIntExact(ms)), - () -> TimeoutContext.throwMongoTimeoutException("Reading from KMS server exceeded the timeout limit.")); - } - - @Override - public int read() throws IOException { - setSocketSoTimeoutToOperationTimeout(); - return wrapped.read(); - } - - @Override - public int read(@NonNull final byte[] b) throws IOException { - setSocketSoTimeoutToOperationTimeout(); - return wrapped.read(b); - } - - @Override - public int read(@NonNull final byte[] b, final int off, final int len) throws IOException { - setSocketSoTimeoutToOperationTimeout(); - return wrapped.read(b, off, len); - } - - @Override - public void close() throws IOException { - wrapped.close(); - } - - @Override - public long skip(final long n) throws IOException { - setSocketSoTimeoutToOperationTimeout(); - return wrapped.skip(n); - } - - @Override - public int available() throws IOException { - return wrapped.available(); - } - - @Override - public synchronized void mark(final int readlimit) { - wrapped.mark(readlimit); - } - - @Override - public synchronized void reset() throws IOException { - wrapped.reset(); - } - - @Override - public boolean markSupported() { - return wrapped.markSupported(); - } - } } diff --git a/driver-sync/src/main/com/mongodb/client/internal/KeyRetriever.java b/driver-sync/src/main/com/mongodb/client/internal/KeyRetriever.java index 59544eefc45..9175ab497ea 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/KeyRetriever.java +++ b/driver-sync/src/main/com/mongodb/client/internal/KeyRetriever.java @@ -20,15 +20,12 @@ import com.mongodb.ReadConcern; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoCollection; -import com.mongodb.internal.time.Timeout; -import com.mongodb.lang.Nullable; import org.bson.BsonDocument; import java.util.ArrayList; import java.util.List; import static com.mongodb.assertions.Assertions.notNull; -import static com.mongodb.client.internal.TimeoutHelper.collectionWithTimeout; class KeyRetriever { private static final String TIMEOUT_ERROR_MESSAGE = "Key retrieval exceeded the timeout limit."; @@ -40,11 +37,11 @@ class KeyRetriever { this.namespace = notNull("namespace", namespace); } - public List find(final BsonDocument keyFilter, @Nullable final Timeout operationTimeout) { + public List find(final BsonDocument keyFilter) { MongoCollection collection = client.getDatabase(namespace.getDatabaseName()) .getCollection(namespace.getCollectionName(), BsonDocument.class); - return collectionWithTimeout(collection, TIMEOUT_ERROR_MESSAGE, operationTimeout) + return collection .withReadConcern(ReadConcern.MAJORITY) .find(keyFilter).into(new ArrayList<>()); } diff --git a/driver-sync/src/main/com/mongodb/client/internal/ListCollectionsIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ListCollectionsIterableImpl.java index 8e9a7b9e04d..8ddc4961b7a 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ListCollectionsIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ListCollectionsIterableImpl.java @@ -21,7 +21,6 @@ import com.mongodb.client.ClientSession; import com.mongodb.client.ListCollectionNamesIterable; import com.mongodb.client.ListCollectionsIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.operation.Operations; import com.mongodb.internal.operation.ReadOperationCursor; @@ -78,12 +77,6 @@ public ListCollectionsIterable batchSize(final int batchSize) { return this; } - @Override - public ListCollectionsIterable timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - @Override public ListCollectionsIterable comment(@Nullable final String comment) { this.comment = comment != null ? new BsonString(comment) : null; @@ -107,7 +100,7 @@ ListCollectionsIterableImpl authorizedCollections(final boolean authori @Override public ReadOperationCursor asReadOperation() { return operations.listCollections(databaseName, resultClass, filter, collectionNamesOnly, authorizedCollections, - getBatchSize(), comment, getTimeoutMode()); + getBatchSize(), comment); } diff --git a/driver-sync/src/main/com/mongodb/client/internal/ListDatabasesIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ListDatabasesIterableImpl.java index 8b57e02ed0a..9ac8c9f58f7 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ListDatabasesIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ListDatabasesIterableImpl.java @@ -19,7 +19,6 @@ import com.mongodb.ReadPreference; import com.mongodb.client.ClientSession; import com.mongodb.client.ListDatabasesIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.operation.Operations; import com.mongodb.internal.operation.ReadOperationCursor; @@ -71,12 +70,6 @@ public ListDatabasesIterable batchSize(final int batchSize) { return this; } - @Override - public ListDatabasesIterable timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - @Override public ListDatabasesIterable filter(@Nullable final Bson filter) { this.filter = filter; diff --git a/driver-sync/src/main/com/mongodb/client/internal/ListIndexesIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ListIndexesIterableImpl.java index ae69b1c9fe6..54054a0e896 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ListIndexesIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ListIndexesIterableImpl.java @@ -21,7 +21,6 @@ import com.mongodb.ReadPreference; import com.mongodb.client.ClientSession; import com.mongodb.client.ListIndexesIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.operation.Operations; import com.mongodb.internal.operation.ReadOperationCursor; @@ -63,12 +62,6 @@ public ListIndexesIterable batchSize(final int batchSize) { return this; } - @Override - public ListIndexesIterable timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - @Override public ListIndexesIterable comment(@Nullable final String comment) { this.comment = comment != null ? new BsonString(comment) : null; @@ -83,7 +76,7 @@ public ListIndexesIterable comment(@Nullable final BsonValue comment) { @Override public ReadOperationCursor asReadOperation() { - return operations.listIndexes(resultClass, getBatchSize(), comment, getTimeoutMode()); + return operations.listIndexes(resultClass, getBatchSize(), comment); } protected OperationExecutor getExecutor() { diff --git a/driver-sync/src/main/com/mongodb/client/internal/ListSearchIndexesIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ListSearchIndexesIterableImpl.java index 13fd7e71ba8..cc9c478f8dc 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ListSearchIndexesIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ListSearchIndexesIterableImpl.java @@ -21,7 +21,6 @@ import com.mongodb.ReadConcern; import com.mongodb.ReadPreference; import com.mongodb.client.ListSearchIndexesIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.operation.Operations; @@ -79,11 +78,6 @@ public ListSearchIndexesIterable batchSize(final int batchSize) { return this; } - @Override - public ListSearchIndexesIterable timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } @Override public ListSearchIndexesIterable maxTime(final long maxTime, final TimeUnit timeUnit) { diff --git a/driver-sync/src/main/com/mongodb/client/internal/MapReduceIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MapReduceIterableImpl.java index 66a712b0054..f6c4c8710dc 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MapReduceIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MapReduceIterableImpl.java @@ -21,7 +21,6 @@ import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; import com.mongodb.client.ClientSession; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.Collation; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.async.AsyncBatchCursor; @@ -166,12 +165,6 @@ public com.mongodb.client.MapReduceIterable batchSize(final int batchSi return this; } - @Override - public com.mongodb.client.MapReduceIterable timeoutMode(final TimeoutMode timeoutMode) { - super.timeoutMode(timeoutMode); - return this; - } - @Override public com.mongodb.client.MapReduceIterable bypassDocumentValidation(@Nullable final Boolean bypassDocumentValidation) { this.bypassDocumentValidation = bypassDocumentValidation; diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java index 21a70391a15..7067a4774e3 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoClientImpl.java @@ -53,7 +53,6 @@ import org.bson.conversions.Bson; import java.util.List; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import static com.mongodb.assertions.Assertions.notNull; @@ -172,12 +171,6 @@ public ReadConcern getReadConcern() { return delegate.getReadConcern(); } - @Override - @Nullable - public Long getTimeout(final TimeUnit timeUnit) { - return delegate.getTimeout(timeUnit); - } - @Override public MongoCluster withCodecRegistry(final CodecRegistry codecRegistry) { return delegate.withCodecRegistry(codecRegistry); @@ -198,11 +191,6 @@ public MongoCluster withReadConcern(final ReadConcern readConcern) { return delegate.withReadConcern(readConcern); } - @Override - public MongoCluster withTimeout(final long timeout, final TimeUnit timeUnit) { - return delegate.withTimeout(timeout, timeUnit); - } - @Override public MongoDatabase getDatabase(final String databaseName) { return delegate.getDatabase(databaseName); diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java index 11579f86e40..17163d2f4b2 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java @@ -70,7 +70,6 @@ import java.util.Collections; import java.util.List; import java.util.Objects; -import java.util.concurrent.TimeUnit; import static com.mongodb.MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL; import static com.mongodb.MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL; @@ -79,7 +78,6 @@ import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.internal.TimeoutContext.createTimeoutContext; -import static java.util.concurrent.TimeUnit.MILLISECONDS; final class MongoClusterImpl implements MongoCluster { @Nullable @@ -171,14 +169,6 @@ public ReadConcern getReadConcern() { return readConcern; } - @Override - @Nullable - public Long getTimeout(final TimeUnit timeUnit) { - notNull("timeUnit", timeUnit); - Long timeoutMS = timeoutSettings.getTimeoutMS(); - return timeoutMS == null ? null : timeUnit.convert(timeoutMS, MILLISECONDS); - } - @Override public MongoCluster withCodecRegistry(final CodecRegistry codecRegistry) { return new MongoClusterImpl(autoEncryptionSettings, cluster, codecRegistry, contextProvider, crypt, originator, @@ -207,14 +197,6 @@ public MongoCluster withReadConcern(final ReadConcern readConcern) { serverApi, serverSessionPool, timeoutSettings, uuidRepresentation, writeConcern, clientExecutor, tracingManager); } - @Override - public MongoCluster withTimeout(final long timeout, final TimeUnit timeUnit) { - return new MongoClusterImpl(autoEncryptionSettings, cluster, codecRegistry, contextProvider, crypt, originator, - operationExecutor, readConcern, readPreference, retryReads, retryWrites, maxAdaptiveRetriesSetting, enableOverloadRetargeting, - serverApi, serverSessionPool, timeoutSettings.withTimeout(timeout, timeUnit), uuidRepresentation, writeConcern, clientExecutor, - tracingManager); - } - @Override public MongoDatabase getDatabase(final String databaseName) { return new MongoDatabaseImpl(databaseName, codecRegistry, readPreference, writeConcern, retryWrites, retryReads, maxAdaptiveRetriesSetting, diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java index 2641616a2d6..e4cc044728d 100755 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java @@ -77,7 +77,6 @@ import java.util.Collections; import java.util.HashMap; import java.util.List; -import java.util.concurrent.TimeUnit; import static com.mongodb.assertions.Assertions.notNull; import static com.mongodb.assertions.Assertions.notNullElements; @@ -86,7 +85,6 @@ import static com.mongodb.internal.bulk.WriteRequest.Type.REPLACE; import static com.mongodb.internal.bulk.WriteRequest.Type.UPDATE; import static java.util.Collections.singletonList; -import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.bson.codecs.configuration.CodecRegistries.withUuidRepresentation; class MongoCollectionImpl implements MongoCollection { @@ -160,13 +158,6 @@ public ReadConcern getReadConcern() { return readConcern; } - @Override - @Nullable - public Long getTimeout(final TimeUnit timeUnit) { - Long timeoutMS = timeoutSettings.getTimeoutMS(); - return timeoutMS == null ? null : notNull("timeUnit", timeUnit).convert(timeoutMS, MILLISECONDS); - } - @Override public MongoCollection withDocumentClass(final Class clazz) { return new MongoCollectionImpl<>(namespace, clazz, codecRegistry, readPreference, writeConcern, @@ -203,13 +194,6 @@ public MongoCollection withReadConcern(final ReadConcern readConcern) readConcern, uuidRepresentation, autoEncryptionSettings, timeoutSettings, executor); } - @Override - public MongoCollection withTimeout(final long timeout, final TimeUnit timeUnit) { - return new MongoCollectionImpl<>(namespace, documentClass, codecRegistry, readPreference, writeConcern, - retryWrites, retryReads, maxAdaptiveRetriesSetting, - readConcern, uuidRepresentation, autoEncryptionSettings, timeoutSettings.withTimeout(timeout, timeUnit), executor); - } - @Override public long countDocuments() { return countDocuments(new BsonDocument()); diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoDatabaseImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoDatabaseImpl.java index 1f8a2cdedb1..44be9acf30f 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoDatabaseImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoDatabaseImpl.java @@ -44,11 +44,9 @@ import java.util.Collections; import java.util.List; -import java.util.concurrent.TimeUnit; import static com.mongodb.MongoNamespace.checkDatabaseNameValidity; import static com.mongodb.assertions.Assertions.notNull; -import static java.util.concurrent.TimeUnit.MILLISECONDS; import static org.bson.codecs.configuration.CodecRegistries.withUuidRepresentation; /** @@ -120,13 +118,6 @@ public ReadConcern getReadConcern() { return readConcern; } - @Override - @Nullable - public Long getTimeout(final TimeUnit timeUnit) { - Long timeoutMS = timeoutSettings.getTimeoutMS(); - return timeoutMS == null ? null : notNull("timeUnit", timeUnit).convert(timeoutMS, MILLISECONDS); - } - @Override public MongoDatabase withCodecRegistry(final CodecRegistry codecRegistry) { return new MongoDatabaseImpl(name, withUuidRepresentation(codecRegistry, uuidRepresentation), readPreference, writeConcern, retryWrites, @@ -151,12 +142,6 @@ public MongoDatabase withReadConcern(final ReadConcern readConcern) { maxAdaptiveRetriesSetting, readConcern, uuidRepresentation, autoEncryptionSettings, timeoutSettings, executor); } - @Override - public MongoDatabase withTimeout(final long timeout, final TimeUnit timeUnit) { - return new MongoDatabaseImpl(name, codecRegistry, readPreference, writeConcern, retryWrites, retryReads, - maxAdaptiveRetriesSetting, readConcern, uuidRepresentation, autoEncryptionSettings, timeoutSettings.withTimeout(timeout, timeUnit), executor); - } - @Override public MongoCollection getCollection(final String collectionName) { return getCollection(collectionName, Document.class); diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java index b642f0f1189..ce7f4ae3932 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoIterableImpl.java @@ -22,7 +22,6 @@ import com.mongodb.client.ClientSession; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.internal.TimeoutSettings; import com.mongodb.internal.operation.BatchCursor; import com.mongodb.internal.operation.ReadOperationCursor; @@ -32,7 +31,6 @@ import java.util.concurrent.TimeUnit; import java.util.function.Consumer; -import static com.mongodb.assertions.Assertions.isTrueArgument; import static com.mongodb.assertions.Assertions.notNull; /** @@ -46,7 +44,6 @@ public abstract class MongoIterableImpl implements MongoIterable batchSize(final int batchSize) { return this; } - @Nullable - public TimeoutMode getTimeoutMode() { - return timeoutMode; - } - - public MongoIterable timeoutMode(final TimeoutMode timeoutMode) { - if (timeoutSettings.getTimeoutMS() == null) { - throw new IllegalArgumentException("TimeoutMode requires timeoutMS to be set."); - } - this.timeoutMode = timeoutMode; - return this; - } - @Override public MongoCursor iterator() { return new MongoBatchCursorAdapter<>(execute()); @@ -159,12 +143,6 @@ private BatchCursor execute() { protected long validateMaxAwaitTime(final long maxAwaitTime, final TimeUnit timeUnit) { notNull("timeUnit", timeUnit); - Long timeoutMS = timeoutSettings.getTimeoutMS(); - long maxAwaitTimeMS = TimeUnit.MILLISECONDS.convert(maxAwaitTime, timeUnit); - - isTrueArgument("maxAwaitTimeMS must be less than timeoutMS", timeoutMS == null || timeoutMS == 0 - || timeoutMS > maxAwaitTimeMS); - - return maxAwaitTimeMS; + return TimeUnit.MILLISECONDS.convert(maxAwaitTime, timeUnit); } } diff --git a/driver-sync/src/main/com/mongodb/client/internal/TimeoutHelper.java b/driver-sync/src/main/com/mongodb/client/internal/TimeoutHelper.java deleted file mode 100644 index 2556388aed7..00000000000 --- a/driver-sync/src/main/com/mongodb/client/internal/TimeoutHelper.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.client.internal; - -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.internal.TimeoutContext; -import com.mongodb.internal.time.Timeout; -import com.mongodb.lang.Nullable; - -import static com.mongodb.internal.TimeoutContext.DEFAULT_TIMEOUT_MESSAGE; -import static java.util.concurrent.TimeUnit.MILLISECONDS; - -/** - *

      This class is not part of the public API and may be removed or changed at any time

      - */ -public final class TimeoutHelper { - private TimeoutHelper() { - //NOP - } - - public static MongoCollection collectionWithTimeout(final MongoCollection collection, - final String message, - @Nullable final Timeout timeout) { - if (timeout != null) { - return timeout.call(MILLISECONDS, - () -> collection.withTimeout(0, MILLISECONDS), - ms -> collection.withTimeout(ms, MILLISECONDS), - () -> TimeoutContext.throwMongoTimeoutException(message)); - } - return collection; - } - - public static MongoCollection collectionWithTimeout(final MongoCollection collection, - @Nullable final Timeout timeout) { - return collectionWithTimeout(collection, DEFAULT_TIMEOUT_MESSAGE, timeout); - } - - public static MongoDatabase databaseWithTimeout(final MongoDatabase database, - final String message, - @Nullable final Timeout timeout) { - if (timeout != null) { - return timeout.call(MILLISECONDS, - () -> database.withTimeout(0, MILLISECONDS), - ms -> database.withTimeout(ms, MILLISECONDS), - () -> TimeoutContext.throwMongoTimeoutException(message)); - } - return database; - } - - public static MongoDatabase databaseWithTimeout(final MongoDatabase database, - @Nullable final Timeout timeout) { - return databaseWithTimeout(database, DEFAULT_TIMEOUT_MESSAGE, timeout); - } - -} diff --git a/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideOperationsTimeoutProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideOperationsTimeoutProseTest.java deleted file mode 100644 index 5a22e81b4df..00000000000 --- a/driver-sync/src/test/functional/com/mongodb/client/AbstractClientSideOperationsTimeoutProseTest.java +++ /dev/null @@ -1,1288 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.client; - -import com.mongodb.ClientBulkWriteException; -import com.mongodb.ClientSessionOptions; -import com.mongodb.ClusterFixture; -import com.mongodb.ConnectionString; -import com.mongodb.CursorType; -import com.mongodb.MongoClientSettings; -import com.mongodb.MongoCredential; -import com.mongodb.MongoException; -import com.mongodb.MongoNamespace; -import com.mongodb.MongoOperationTimeoutException; -import com.mongodb.MongoSocketReadTimeoutException; -import com.mongodb.MongoTimeoutException; -import com.mongodb.ReadConcern; -import com.mongodb.ReadPreference; -import com.mongodb.TransactionOptions; -import com.mongodb.WriteConcern; -import com.mongodb.client.gridfs.GridFSBucket; -import com.mongodb.client.gridfs.GridFSDownloadStream; -import com.mongodb.client.gridfs.GridFSUploadStream; -import com.mongodb.client.model.CreateCollectionOptions; -import com.mongodb.client.model.bulk.ClientNamespacedWriteModel; -import com.mongodb.client.model.changestream.ChangeStreamDocument; -import com.mongodb.client.model.changestream.FullDocument; -import com.mongodb.client.test.CollectionHelper; -import com.mongodb.event.CommandEvent; -import com.mongodb.event.CommandFailedEvent; -import com.mongodb.event.CommandStartedEvent; -import com.mongodb.event.CommandSucceededEvent; -import com.mongodb.event.ConnectionClosedEvent; -import com.mongodb.event.ConnectionCreatedEvent; -import com.mongodb.event.ConnectionReadyEvent; -import com.mongodb.internal.InternalMongoClientSettings; -import com.mongodb.internal.connection.ServerHelper; -import com.mongodb.internal.connection.TestCommandListener; -import com.mongodb.internal.connection.TestConnectionPoolListener; -import com.mongodb.test.FlakyTest; -import org.bson.BsonDocument; -import org.bson.BsonInt32; -import org.bson.BsonTimestamp; -import org.bson.Document; -import org.bson.codecs.BsonDocumentCodec; -import org.bson.types.ObjectId; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; -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; -import org.junit.jupiter.params.provider.MethodSource; - -import java.time.Instant; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static com.mongodb.ClusterFixture.getConnectionString; -import static com.mongodb.ClusterFixture.isAuthenticated; -import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; -import static com.mongodb.ClusterFixture.isLoadBalanced; -import static com.mongodb.ClusterFixture.isStandalone; -import static com.mongodb.ClusterFixture.scaleForWindows; -import static com.mongodb.ClusterFixture.serverVersionAtLeast; -import static com.mongodb.ClusterFixture.sleep; -import static com.mongodb.MongoException.TRANSIENT_TRANSACTION_ERROR_LABEL; -import static com.mongodb.client.Fixture.getDefaultDatabaseName; -import static com.mongodb.client.Fixture.getPrimary; -import static com.mongodb.internal.connection.CommandHelper.HELLO; -import static com.mongodb.internal.connection.CommandHelper.LEGACY_HELLO; -import static java.lang.Long.MAX_VALUE; -import static java.lang.String.join; -import static java.util.Arrays.asList; -import static java.util.Collections.nCopies; -import static java.util.Collections.singletonList; -import static java.util.concurrent.TimeUnit.NANOSECONDS; -import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeFalse; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * See - * Prose Tests. - * - *

      Each test declares its timeout/block/sleep values as local {@code int} variables (in milliseconds) after the - * assume checks. Tests where a fresh-client foreground operation races connection establishment wrap those values in - * {@link ClusterFixture#scaleForWindows(int)}, which widens them on the slower Windows + TLS CI hosts so setup does - * not consume the tight budget. Tests are intentionally left unscaled (plain literals) when they assert a - * fast-timeout upper bound or a timeout-precedence relationship, exercise pool-wait / connection-close behaviour - * (where a background op holds the pool connection and scaling would outlive {@code close()}), or already use an - * ample timeout; such tests carry a brief "not scaled" comment explaining why.

      - */ -@SuppressWarnings("checkstyle:VisibilityModifier") -public abstract class AbstractClientSideOperationsTimeoutProseTest { - - protected static final String FAIL_COMMAND_NAME = "failCommand"; - protected static final String GRID_FS_BUCKET_NAME = "db.fs"; - private static final AtomicInteger COUNTER = new AtomicInteger(); - private ExecutorService executor; - - protected MongoNamespace namespace; - protected MongoNamespace gridFsFileNamespace; - protected MongoNamespace gridFsChunksNamespace; - - protected CollectionHelper collectionHelper; - private CollectionHelper filesCollectionHelper; - private CollectionHelper chunksCollectionHelper; - - protected TestCommandListener commandListener; - - protected abstract MongoClient createMongoClient(MongoClientSettings mongoClientSettings); - - /** - * Creates a MongoClient with the given settings and internal settings. - * Used for tests that need to configure internal settings like recordEverything. - * - * @param mongoClientSettings the client settings - * @param internalSettings the internal settings - * @return the MongoClient - */ - protected abstract MongoClient createMongoClientWithInternalSettings(MongoClientSettings mongoClientSettings, - InternalMongoClientSettings internalSettings); - - protected abstract GridFSBucket createGridFsBucket(MongoDatabase mongoDatabase, String bucketName); - - protected abstract boolean isAsync(); - - protected int postSessionCloseSleep() { - return 0; - } - - @SuppressWarnings("try") - @FlakyTest(maxAttempts = 3) - @DisplayName("4. Background Connection Pooling - timeoutMS used for handshake commands") - public void testBackgroundConnectionPoolingTimeoutMSUsedForHandshakeCommands() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeTrue(isAuthenticated()); - - // not scaled: background-pool handshake under connectTimeoutMS; blockTimeMS must stay above timeoutMS so the - // handshake times out and the connection is closed. - int blockTimeMS = 150; - int timeoutMS = 100; - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"" + FAIL_COMMAND_NAME + "\"," - + " mode: {" - + " times: 1" - + " }," - + " data: {" - + " failCommands: [\"saslContinue\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS + "," - + " appName: \"timeoutBackgroundPoolTest\"" - + " }" - + "}"); - - TestConnectionPoolListener connectionPoolListener = new TestConnectionPoolListener(); - - try (MongoClient ignoredClient = createMongoClient(getMongoClientSettingsBuilder() - .applicationName("timeoutBackgroundPoolTest") - .applyToConnectionPoolSettings(builder -> { - builder.minSize(1); - builder.addConnectionPoolListener(connectionPoolListener); - }) - .timeout(timeoutMS, TimeUnit.MILLISECONDS))) { - - assertDoesNotThrow(() -> - connectionPoolListener.waitForEvents(asList(ConnectionCreatedEvent.class, ConnectionClosedEvent.class), - 10, TimeUnit.SECONDS)); - } - } - - @SuppressWarnings("try") - @FlakyTest(maxAttempts = 3) - @DisplayName("4. Background Connection Pooling - timeoutMS is refreshed for each handshake command") - public void testBackgroundConnectionPoolingTimeoutMSIsRefreshedForEachHandshakeCommand() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeTrue(isAuthenticated()); - - // not scaled: background-pool handshake; verifies the per-command timeout is refreshed while establishing. - int blockTimeMS = 150; - int timeoutMS = 250; - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"" + FAIL_COMMAND_NAME + "\"," - + " mode: \"alwaysOn\"," - + " data: {" - + " failCommands: [\"hello\", \"isMaster\", \"saslContinue\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS + "," - + " appName: \"refreshTimeoutBackgroundPoolTest\"" - + " }" - + "}"); - - TestConnectionPoolListener connectionPoolListener = new TestConnectionPoolListener(); - - try (MongoClient ignoredClient = createMongoClient(getMongoClientSettingsBuilder() - .applicationName("refreshTimeoutBackgroundPoolTest") - .applyToConnectionPoolSettings(builder -> { - builder.minSize(1); - builder.addConnectionPoolListener(connectionPoolListener); - }) - .timeout(timeoutMS, TimeUnit.MILLISECONDS))) { - - assertDoesNotThrow(() -> - connectionPoolListener.waitForEvents(asList(ConnectionCreatedEvent.class, ConnectionReadyEvent.class), - 10, TimeUnit.SECONDS)); - } - } - - @FlakyTest(maxAttempts = 3) - @DisplayName("5. Blocking Iteration Methods - Tailable cursors") - public void testBlockingIterationMethodsTailableCursor() { - assumeTrue(serverVersionAtLeast(4, 4)); - - int blockTimeMS = scaleForWindows(150); - int timeoutMS = scaleForWindows(250); - - collectionHelper.create(namespace.getCollectionName(), - new CreateCollectionOptions().capped(true).sizeInBytes(10 * 1024 * 1024)); - collectionHelper.insertDocuments(singletonList(BsonDocument.parse("{x: 1}")), WriteConcern.MAJORITY); - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: \"alwaysOn\"," - + " data: {" - + " failCommands: [\"getMore\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient client = createMongoClient(getMongoClientSettingsBuilder() - .timeout(timeoutMS, TimeUnit.MILLISECONDS))) { - MongoCollection collection = client.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - try (MongoCursor cursor = collection.find().cursorType(CursorType.Tailable).cursor()) { - Document document = assertDoesNotThrow(cursor::next); - assertEquals(1, document.get("x")); - assertThrows(MongoOperationTimeoutException.class, cursor::next); - } - - List events = commandListener.getCommandSucceededEvents(); - assertEquals(1, events.stream().filter(e -> e.getCommandName().equals("find")).count()); - long getMoreCount = events.stream().filter(e -> e.getCommandName().equals("getMore")).count(); - assertTrue(getMoreCount <= 2, "getMoreCount expected to less than or equal to two but was: " + getMoreCount); - } - } - - @FlakyTest(maxAttempts = 3) - @DisplayName("5. Blocking Iteration Methods - Change Streams") - public void testBlockingIterationMethodsChangeStream() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeTrue(isDiscoverableReplicaSet()); - assumeFalse(isAsync()); // Async change stream cursor is non-deterministic for cursor::next - - int blockTimeMS = scaleForWindows(150); - int timeoutMS = scaleForWindows(250); - int sleepMS = 2000; - - BsonTimestamp startTime = new BsonTimestamp((int) Instant.now().getEpochSecond(), 0); - sleep(sleepMS); - collectionHelper.insertDocuments(singletonList(BsonDocument.parse("{x: 1}")), WriteConcern.MAJORITY); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: \"alwaysOn\"," - + " data: {" - + " failCommands: [\"getMore\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder() - .timeout(timeoutMS, TimeUnit.MILLISECONDS))) { - - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()).withReadPreference(ReadPreference.primary()); - try (MongoChangeStreamCursor> cursor = collection.watch( - singletonList(Document.parse("{ '$match': {'operationType': 'insert'}}"))) - .startAtOperationTime(startTime) - .fullDocument(FullDocument.UPDATE_LOOKUP) - .cursor()) { - ChangeStreamDocument document = assertDoesNotThrow(cursor::next); - - Document fullDocument = document.getFullDocument(); - assertNotNull(fullDocument); - assertEquals(1, fullDocument.get("x")); - assertThrows(MongoOperationTimeoutException.class, cursor::next); - } - List events = commandListener.getCommandSucceededEvents(); - assertEquals(1, events.stream().filter(e -> e.getCommandName().equals("aggregate")).count()); - long getMoreCount = events.stream().filter(e -> e.getCommandName().equals("getMore")).count(); - assertTrue(getMoreCount <= 2, "getMoreCount expected to less than or equal to two but was: " + getMoreCount); - } - } - - @DisplayName("6. GridFS Upload - uploads via openUploadStream can be timed out") - @FlakyTest(maxAttempts = 3) - public void testGridFSUploadViaOpenUploadStreamTimeout() { - assumeTrue(serverVersionAtLeast(4, 4)); - - int blockTimeMS = scaleForWindows(205); - int timeoutMS = scaleForWindows(200); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"insert\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - chunksCollectionHelper.create(); - filesCollectionHelper.create(); - - try (MongoClient client = createMongoClient(getMongoClientSettingsBuilder() - .timeout(timeoutMS, TimeUnit.MILLISECONDS))) { - MongoDatabase database = client.getDatabase(namespace.getDatabaseName()); - GridFSBucket gridFsBucket = createGridFsBucket(database, GRID_FS_BUCKET_NAME); - - try (GridFSUploadStream uploadStream = gridFsBucket.openUploadStream("filename")){ - uploadStream.write(0x12); - assertThrows(MongoOperationTimeoutException.class, uploadStream::close); - } - } - } - - @DisplayName("6. GridFS Upload - Aborting an upload stream can be timed out") - @Test - public void testAbortingGridFsUploadStreamTimeout() throws Throwable { - assumeTrue(serverVersionAtLeast(4, 4)); - - int blockTimeMS = scaleForWindows(320); - int timeoutMS = scaleForWindows(300); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"delete\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - chunksCollectionHelper.create(); - filesCollectionHelper.create(); - - try (MongoClient client = createMongoClient(getMongoClientSettingsBuilder() - .timeout(timeoutMS, TimeUnit.MILLISECONDS))) { - MongoDatabase database = client.getDatabase(namespace.getDatabaseName()); - GridFSBucket gridFsBucket = createGridFsBucket(database, GRID_FS_BUCKET_NAME).withChunkSizeBytes(2); - - try (GridFSUploadStream uploadStream = gridFsBucket.openUploadStream("filename")){ - uploadStream.write(new byte[]{0x01, 0x02, 0x03, 0x04}); - assertThrows(MongoOperationTimeoutException.class, uploadStream::abort); - } - } - } - - @DisplayName("6. GridFS Download") - @Test - public void testGridFsDownloadStreamTimeout() { - assumeTrue(serverVersionAtLeast(4, 4)); - - int blockTimeMS = scaleForWindows(500); - int timeoutMS = scaleForWindows(300); - - chunksCollectionHelper.create(); - filesCollectionHelper.create(); - - filesCollectionHelper.insertDocuments(singletonList(BsonDocument.parse( - "{" - + " _id: {" - + " $oid: \"000000000000000000000005\"" - + " }," - + " length: 10," - + " chunkSize: 4," - + " uploadDate: {" - + " $date: \"1970-01-01T00:00:00.000Z\"" - + " }," - + " md5: \"57d83cd477bfb1ccd975ab33d827a92b\"," - + " filename: \"length-10\"," - + " contentType: \"application/octet-stream\"," - + " aliases: []," - + " metadata: {}" - + "}" - )), WriteConcern.MAJORITY); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { skip: 1 }," - + " data: {" - + " failCommands: [\"find\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient client = createMongoClient(getMongoClientSettingsBuilder() - .timeout(timeoutMS, TimeUnit.MILLISECONDS))) { - MongoDatabase database = client.getDatabase(namespace.getDatabaseName()); - GridFSBucket gridFsBucket = createGridFsBucket(database, GRID_FS_BUCKET_NAME).withChunkSizeBytes(2); - - try (GridFSDownloadStream downloadStream = gridFsBucket.openDownloadStream(new ObjectId("000000000000000000000005"))){ - assertThrows(MongoOperationTimeoutException.class, downloadStream::read); - - List events = commandListener.getCommandStartedEvents(); - List findCommands = events.stream() - .filter(e -> e.getCommandName().equals("find")) - .collect(Collectors.toList()); - - assertEquals(2, findCommands.size()); - assertEquals(gridFsFileNamespace.getCollectionName(), findCommands.get(0).getCommand().getString("find").getValue()); - assertEquals(gridFsChunksNamespace.getCollectionName(), findCommands.get(1).getCommand().getString("find").getValue()); - } - } - } - - @DisplayName("8. Server Selection 1 / 2") - @ParameterizedTest(name = "[{index}] {0}") - @MethodSource("test8ServerSelectionArguments") - public void test8ServerSelection(final String connectionString) { - int timeoutBuffer = 150; // 5 in spec, Java is slower - // 1. Create a MongoClient - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder() - .applyConnectionString(new ConnectionString(connectionString))) - ) { - long start = System.nanoTime(); - // 2. Using client, execute: - Throwable throwable = assertThrows(MongoTimeoutException.class, () -> { - mongoClient.getDatabase("admin").runCommand(new BsonDocument("ping", new BsonInt32(1))); - }); - // Expect this to fail with a server selection timeout error after no more than 15ms [this is increased] - long elapsed = msElapsedSince(start); - assertTrue(throwable.getMessage().contains("while waiting for a server")); - assertTrue(elapsed < 10 + timeoutBuffer, "Took too long to time out, elapsedMS: " + elapsed); - } - } - - @DisplayName("8. Server Selection 2 / 2") - @ParameterizedTest(name = "[{index}] {0}") - @MethodSource("test8ServerSelectionHandshakeArguments") - public void test8ServerSelectionHandshake(final String ignoredTestName, final int timeoutMS, final int serverSelectionTimeoutMS) { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeTrue(isAuthenticated()); - - // not scaled: asserts a fast-timeout upper bound (maxElapsedMS) and timeoutMS-vs-serverSelectionTimeoutMS - // precedence; scaling would change what is being asserted. - int blockTimeMS = 600; - int maxElapsedMS = 350; - - MongoCredential credential = getConnectionString().getCredential(); - assertNotNull(credential); - assertNull(credential.getAuthenticationMechanism()); - - MongoNamespace namespace = generateNamespace(); - collectionHelper = new CollectionHelper<>(new BsonDocumentCodec(), namespace); - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: \"alwaysOn\"," - + " data: {" - + " failCommands: [\"saslContinue\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder() - .timeout(timeoutMS, TimeUnit.MILLISECONDS) - .applyToClusterSettings(b -> b.serverSelectionTimeout(serverSelectionTimeoutMS, TimeUnit.MILLISECONDS)) - .retryWrites(false))) { - - long start = System.nanoTime(); - assertThrows(MongoOperationTimeoutException.class, () -> { - mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()) - .insertOne(new Document("x", 1)); - }); - long elapsed = msElapsedSince(start); - assertTrue(elapsed <= maxElapsedMS, "Took too long to time out, elapsedMS: " + elapsed); - } - } - - @SuppressWarnings("try") - @DisplayName("9. End Session. The timeout specified via the MongoClient timeoutMS option") - @FlakyTest(maxAttempts = 3) - public void test9EndSessionClientTimeout() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeFalse(isStandalone()); - - int blockTimeMS = scaleForWindows(500); - int timeoutMS = scaleForWindows(250); - int maxElapsedMS = scaleForWindows(300); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"abortTransaction\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder().retryWrites(false) - .timeout(timeoutMS, TimeUnit.MILLISECONDS))) { - MongoDatabase database = mongoClient.getDatabase(namespace.getDatabaseName()); - MongoCollection collection = database - .getCollection(namespace.getCollectionName()); - - try (ClientSession session = mongoClient.startSession()) { - session.startTransaction(); - collection.insertOne(session, new Document("x", 1)); - long start = System.nanoTime(); - session.close(); - long elapsed = msElapsedSince(start); - assertTrue(elapsed <= maxElapsedMS, "Took too long to time out, elapsedMS: " + elapsed); - } - } - CommandFailedEvent abortTransactionEvent = assertDoesNotThrow(() -> - commandListener.getCommandFailedEvent("abortTransaction")); - assertInstanceOf(MongoOperationTimeoutException.class, abortTransactionEvent.getThrowable()); - } - - @SuppressWarnings("try") - @DisplayName("9. End Session. The timeout specified via the ClientSession defaultTimeoutMS option") - @Test - public void test9EndSessionSessionTimeout() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeFalse(isStandalone()); - - int blockTimeMS = scaleForWindows(400); - int defaultTimeoutMS = scaleForWindows(300); - int maxElapsedMS = scaleForWindows(400); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"abortTransaction\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder())) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - try (ClientSession session = mongoClient.startSession(ClientSessionOptions.builder() - .defaultTimeout(defaultTimeoutMS, TimeUnit.MILLISECONDS).build())) { - session.startTransaction(); - collection.insertOne(session, new Document("x", 1)); - - long start = System.nanoTime(); - session.close(); - long elapsed = msElapsedSince(start); - assertTrue(elapsed <= maxElapsedMS, "Took too long to time out, elapsedMS: " + elapsed); - } - } - CommandFailedEvent abortTransactionEvent = assertDoesNotThrow(() -> - commandListener.getCommandFailedEvent("abortTransaction")); - assertInstanceOf(MongoOperationTimeoutException.class, abortTransactionEvent.getThrowable()); - } - - @DisplayName("9. End Session - Custom Test: Each operation has its own timeout with commit") - @Test - public void test9EndSessionCustomTesEachOperationHasItsOwnTimeoutWithCommit() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeFalse(isStandalone()); - - int blockTimeMS = scaleForWindows(25); - int defaultTimeoutMS = scaleForWindows(300); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"insert\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder())) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - try (ClientSession session = mongoClient.startSession(ClientSessionOptions.builder() - .defaultTimeout(defaultTimeoutMS, TimeUnit.MILLISECONDS).build())) { - session.startTransaction(); - collection.insertOne(session, new Document("x", 1)); - sleep(defaultTimeoutMS); - - assertDoesNotThrow(session::commitTransaction); - } - } - assertDoesNotThrow(() -> commandListener.getCommandSucceededEvent("commitTransaction")); - } - - @DisplayName("9. End Session - Custom Test: Each operation has its own timeout with abort") - @Test - public void test9EndSessionCustomTesEachOperationHasItsOwnTimeoutWithAbort() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeFalse(isStandalone()); - - int blockTimeMS = scaleForWindows(25); - int defaultTimeoutMS = scaleForWindows(300); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"insert\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder())) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - try (ClientSession session = mongoClient.startSession(ClientSessionOptions.builder() - .defaultTimeout(defaultTimeoutMS, TimeUnit.MILLISECONDS).build())) { - session.startTransaction(); - collection.insertOne(session, new Document("x", 1)); - sleep(defaultTimeoutMS); - - assertDoesNotThrow(session::close); - } - } - assertDoesNotThrow(() -> commandListener.getCommandSucceededEvent("abortTransaction")); - } - - @DisplayName("10. Convenient Transactions") - @Test - public void test10ConvenientTransactions() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeFalse(isStandalone()); - assumeFalse(isAsync()); - - int blockTimeMS = scaleForWindows(200); - int timeoutMS = scaleForWindows(150); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 2 }," - + " data: {" - + " failCommands: [\"insert\", \"abortTransaction\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder() - .timeout(timeoutMS, TimeUnit.MILLISECONDS))) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - try (ClientSession session = mongoClient.startSession()) { - assertThrows(MongoOperationTimeoutException.class, - () -> session.withTransaction(() -> collection.insertOne(session, new Document("x", 1)))); - } - - List failedEvents = commandListener.getEvents().stream() - .filter(e -> e instanceof CommandFailedEvent) - .collect(Collectors.toList()); - - assertEquals(1, failedEvents.stream().filter(e -> e.getCommandName().equals("insert")).count()); - assertEquals(1, failedEvents.stream().filter(e -> e.getCommandName().equals("abortTransaction")).count()); - } - } - - @DisplayName("10. Convenient Transactions - Custom Test: with transaction uses a single timeout") - @Test - public void test10CustomTestWithTransactionUsesASingleTimeout() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeFalse(isStandalone()); - assumeFalse(isAsync()); - - int blockTimeMS = scaleForWindows(25); - int defaultTimeoutMS = scaleForWindows(200); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"insert\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder())) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - try (ClientSession session = mongoClient.startSession(ClientSessionOptions.builder() - .defaultTimeout(defaultTimeoutMS, TimeUnit.MILLISECONDS).build())) { - assertThrows(MongoOperationTimeoutException.class, - () -> session.withTransaction(() -> { - collection.insertOne(session, new Document("x", 1)); - sleep(defaultTimeoutMS); - return true; - }) - ); - } - } - } - - @DisplayName("10. Convenient Transactions - Custom Test: with transaction uses a single timeout - lock") - @Test - public void test10CustomTestWithTransactionUsesASingleTimeoutWithLock() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeFalse(isStandalone()); - assumeFalse(isAsync()); - - int blockTimeMS = scaleForWindows(25); - int defaultTimeoutMS = scaleForWindows(200); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: \"alwaysOn\"," - + " data: {" - + " failCommands: [\"insert\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " errorCode: " + 24 - + " errorLabels: [\"" + TRANSIENT_TRANSACTION_ERROR_LABEL + "\"]" - + " }" - + "}"); - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder())) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - try (ClientSession session = mongoClient.startSession(ClientSessionOptions.builder() - .defaultTimeout(defaultTimeoutMS, TimeUnit.MILLISECONDS).build())) { - assertThrows(MongoOperationTimeoutException.class, - () -> session.withTransaction(() -> { - collection.insertOne(session, new Document("x", 1)); - sleep(defaultTimeoutMS); - return true; - }) - ); - } - } - } - - @DisplayName("11. Multi-batch bulkWrites") - @FlakyTest(maxAttempts = 3) - @SuppressWarnings("try") - protected void test11MultiBatchBulkWrites() throws InterruptedException { - assumeTrue(serverVersionAtLeast(8, 0)); - - // not scaled: timeoutMS is already ample relative to connection setup. - int blockTimeMS = 2020; - int timeoutMS = 4000; - - try (MongoClient client = createMongoClient(getMongoClientSettingsBuilder())) { - // a workaround for https://jira.mongodb.org/browse/DRIVERS-2997, remove this block when the aforementioned bug is fixed - client.getDatabase(namespace.getDatabaseName()).drop(); - } - BsonDocument failPointDocument = BsonDocument.parse("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 2}," - + " data: {" - + " failCommands: [\"bulkWrite\" ]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient client = createMongoClient(getMongoClientSettingsBuilder().timeout(timeoutMS, TimeUnit.MILLISECONDS)); - FailPoint ignored = FailPoint.enable(failPointDocument, getPrimary())) { - MongoDatabase db = client.getDatabase(namespace.getDatabaseName()); - db.drop(); - Document helloResponse = db.runCommand(new Document("hello", 1)); - int maxBsonObjectSize = helloResponse.getInteger("maxBsonObjectSize"); - int maxMessageSizeBytes = helloResponse.getInteger("maxMessageSizeBytes"); - ClientNamespacedWriteModel model = ClientNamespacedWriteModel.insertOne( - namespace, - new Document("a", join("", nCopies(maxBsonObjectSize - 500, "b")))); - MongoException topLevelError = assertThrows(ClientBulkWriteException.class, () -> - client.bulkWrite(nCopies(maxMessageSizeBytes / maxBsonObjectSize + 1, model))) - .getCause(); - assertNotNull(topLevelError); - assertInstanceOf(MongoOperationTimeoutException.class, topLevelError); - assertEquals(2, commandListener.getCommandStartedEvents("bulkWrite").size()); - } - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @Test - @DisplayName("Should not include wTimeoutMS of WriteConcern to initial and subsequent commitTransaction operations") - public void shouldNotIncludeWtimeoutMsOfWriteConcernToInitialAndSubsequentCommitTransactionOperations() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeFalse(isStandalone()); - - // not scaled: asserts wTimeoutMS is excluded from the commitTransaction command; not a setup-race timing test. - int defaultTimeoutMS = 200; - int wTimeoutMS = 100; - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder())) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - try (ClientSession session = mongoClient.startSession(ClientSessionOptions.builder() - .defaultTimeout(defaultTimeoutMS, TimeUnit.MILLISECONDS) - .build())) { - session.startTransaction(TransactionOptions.builder() - .writeConcern(WriteConcern.ACKNOWLEDGED.withWTimeout(wTimeoutMS, TimeUnit.MILLISECONDS)) - .build()); - collection.insertOne(session, new Document("x", 1)); - sleep(defaultTimeoutMS); - - assertDoesNotThrow(session::commitTransaction); - //repeat commit. - assertDoesNotThrow(session::commitTransaction); - } - } - List commandStartedEvents = commandListener.getCommandStartedEvents("commitTransaction"); - assertEquals(2, commandStartedEvents.size()); - - commandStartedEvents.forEach(e -> { - BsonDocument command = e.getCommand(); - if (command.containsKey("writeConcern")) { - BsonDocument writeConcern = command.getDocument("writeConcern"); - assertFalse(writeConcern.isEmpty()); - assertFalse(writeConcern.containsKey("wtimeout")); - }}); - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @Test - @DisplayName("Should ignore waitQueueTimeoutMS when timeoutMS is set") - public void shouldIgnoreWaitQueueTimeoutMSWhenTimeoutMsIsSet() { - assumeTrue(serverVersionAtLeast(4, 4)); - - // not scaled: a background op holds the single pool connection for blockTimeMS; scaling it would keep the - // connection checked out past client close() and trip the "all connections closed" assertion. - int timeoutMS = 500; - int maxWaitTimeMS = 1; - int blockTimeMS = 450; - int sleepMS = 150; - - //given - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder() - .timeout(timeoutMS, TimeUnit.MILLISECONDS) - .applyToConnectionPoolSettings(builder -> builder - .maxWaitTime(maxWaitTimeMS, TimeUnit.MILLISECONDS) - .maxSize(1) - ))) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1}," - + " data: {" - + " failCommands: [\"find\" ]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - executor.execute(() -> collection.find().first()); - sleep(sleepMS); - - //when && then - assertDoesNotThrow(() -> collection.find().first()); - } - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @Test - @DisplayName("Should throw MongoOperationTimeoutException when connection is not available and timeoutMS is set") - public void shouldThrowOperationTimeoutExceptionWhenConnectionIsNotAvailableAndTimeoutMSIsSet() { - assumeTrue(serverVersionAtLeast(4, 4)); - - // not scaled: a background op holds the single pool connection for blockTimeMS; scaling it would keep the - // connection checked out past client close() and trip the "all connections closed" assertion. - int timeoutMS = 100; - int blockTimeMS = 500; - int sleepMS = 100; - - //given - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder() - .timeout(timeoutMS, TimeUnit.MILLISECONDS) - .applyToConnectionPoolSettings(builder -> builder - .maxSize(1) - ))) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1}," - + " data: {" - + " failCommands: [\"find\" ]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - executor.execute(() -> collection.withTimeout(0, TimeUnit.MILLISECONDS).find().first()); - sleep(sleepMS); - - //when && then - assertThrows(MongoOperationTimeoutException.class, () -> collection.find().first()); - } - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @Test - @DisplayName("Should use waitQueueTimeoutMS when timeoutMS is not set") - public void shouldUseWaitQueueTimeoutMSWhenTimeoutIsNotSet() { - assumeTrue(serverVersionAtLeast(4, 4)); - - // not scaled: timeoutMS is not set here (exercises waitQueueTimeoutMS), and a background op holds the pool - // connection for blockTimeMS. - int maxWaitTimeMS = 20; - int blockTimeMS = 400; - int sleepMS = 200; - - //given - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder() - .applyToConnectionPoolSettings(builder -> builder - .maxWaitTime(maxWaitTimeMS, TimeUnit.MILLISECONDS) - .maxSize(1) - ))) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1}," - + " data: {" - + " failCommands: [\"find\" ]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - executor.execute(() -> collection.find().first()); - sleep(sleepMS); - - //when & then - assertThrows(MongoTimeoutException.class, () -> collection.find().first()); - } - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @DisplayName("KillCursors is not executed after getMore network error when timeoutMs is not enabled") - @Test - public void testKillCursorsIsNotExecutedAfterGetMoreNetworkErrorWhenTimeoutMsIsNotEnabled() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeTrue(isLoadBalanced()); - - // not scaled: exercises socket readTimeoutMS (not CSOT timeoutMS) and killCursors behaviour after a network - // error, independent of connection-setup timing. - int blockTimeMS = 600; - int readTimeoutMS = 500; - - collectionHelper.create(namespace.getCollectionName(), new CreateCollectionOptions()); - collectionHelper.insertDocuments(new Document(), new Document()); - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1}," - + " data: {" - + " failCommands: [\"getMore\" ]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder() - .retryReads(true) - .applyToSocketSettings(builder -> builder.readTimeout(readTimeoutMS, TimeUnit.MILLISECONDS)))) { - - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()).withReadPreference(ReadPreference.primary()); - - MongoCursor cursor = collection.find() - .batchSize(1) - .cursor(); - - cursor.next(); - assertThrows(MongoSocketReadTimeoutException.class, cursor::next); - cursor.close(); - } - - List events = commandListener.getCommandStartedEvents(); - assertEquals(2, events.size(), "Actual events: " + events.stream() - .map(CommandStartedEvent::getCommandName) - .collect(Collectors.toList())); - assertEquals(1, events.stream().filter(e -> e.getCommandName().equals("find")).count()); - assertEquals(1, events.stream().filter(e -> e.getCommandName().equals("getMore")).count()); - - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @DisplayName("KillCursors is not executed after getMore network error") - @Test - public void testKillCursorsIsNotExecutedAfterGetMoreNetworkError() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeTrue(isLoadBalanced()); - - // not scaled: verifies killCursors is not executed after a getMore network error, independent of - // connection-setup timing. - int blockTimeMS = 600; - int timeoutMS = 500; - - collectionHelper.create(namespace.getCollectionName(), new CreateCollectionOptions()); - collectionHelper.insertDocuments(new Document(), new Document()); - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1}," - + " data: {" - + " failCommands: [\"getMore\" ]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder() - .timeout(timeoutMS, TimeUnit.MILLISECONDS))) { - - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()).withReadPreference(ReadPreference.primary()); - - MongoCursor cursor = collection.find() - .batchSize(1) - .cursor(); - - cursor.next(); - assertThrows(MongoOperationTimeoutException.class, cursor::next); - cursor.close(); - } - - List events = commandListener.getCommandStartedEvents(); - assertEquals(2, events.size(), "Actual events: " + events.stream() - .map(CommandStartedEvent::getCommandName) - .collect(Collectors.toList())); - assertEquals(1, events.stream().filter(e -> e.getCommandName().equals("find")).count()); - assertEquals(1, events.stream().filter(e -> e.getCommandName().equals("getMore")).count()); - - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @Test - @DisplayName("Should throw timeout exception for subsequent commit transaction") - public void shouldThrowTimeoutExceptionForSubsequentCommitTransaction() { - assumeTrue(serverVersionAtLeast(4, 4)); - assumeFalse(isStandalone()); - - int defaultTimeoutMS = scaleForWindows(200); - int blockTimeMS = scaleForWindows(500); - int sleepMS = 200; - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder())) { - MongoCollection collection = mongoClient.getDatabase(namespace.getDatabaseName()) - .getCollection(namespace.getCollectionName()); - - try (ClientSession session = mongoClient.startSession(ClientSessionOptions.builder() - .defaultTimeout(defaultTimeoutMS, TimeUnit.MILLISECONDS) - .build())) { - session.startTransaction(TransactionOptions.builder().build()); - collection.insertOne(session, new Document("x", 1)); - sleep(sleepMS); - - assertDoesNotThrow(session::commitTransaction); - - collectionHelper.runAdminCommand("{" - + " configureFailPoint: \"failCommand\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"commitTransaction\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - //repeat commit. - assertThrows(MongoOperationTimeoutException.class, session::commitTransaction); - } - } - List commandStartedEvents = commandListener.getCommandStartedEvents("commitTransaction"); - assertEquals(2, commandStartedEvents.size()); - - List failedEvents = commandListener.getCommandFailedEvents("commitTransaction"); - assertEquals(1, failedEvents.size()); - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - *

      - * From the spec: - * - When doing `minPoolSize` maintenance, `connectTimeoutMS` is used as the timeout for socket establishment. - */ - @Test - @DisplayName("Should use connectTimeoutMS when establishing connection in background") - public void shouldUseConnectTimeoutMsWhenEstablishingConnectionInBackground() { - assumeTrue(serverVersionAtLeast(4, 4)); - - // not scaled: deliberately uses a very short timeoutMS to force the background handshake command to time out. - int blockTimeMS = 500; - int timeoutMS = 10; - int sleepMS = 1000; - - collectionHelper.runAdminCommand("{" - + "configureFailPoint: \"" + FAIL_COMMAND_NAME + "\"," - + "mode: \"alwaysOn\"," - + " data: {" - + " failCommands: [\"hello\", \"isMaster\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS + "," - // The appName is unique to prevent this failpoint from affecting ClusterFixture's ServerMonitor. - // Without the appName, ClusterFixture's heartbeats would be blocked, polluting RTT measurements with 500ms values, - // which would cause flakiness in other prose tests that use ClusterFixture.getPrimaryRTT() for timeout adjustments. - + " appName: \"connectTimeoutBackgroundTest\"" - + " }" - + "}"); - - try (MongoClient ignored = createMongoClientWithInternalSettings(getMongoClientSettingsBuilder() - .applicationName("connectTimeoutBackgroundTest") - .applyToConnectionPoolSettings(builder -> builder.minSize(1)) - // Use a very short timeout to ensure that the connection establishment will fail on the first handshake command. - .timeout(timeoutMS, TimeUnit.MILLISECONDS) - .build(), - InternalMongoClientSettings.builder().recordEverything(true).build())) { - - // Wait for the connection to start establishment in the background. - sleep(sleepMS); - } - List commandFailedEvents = commandListener.getCommandFailedEvents(getHandshakeCommandName()); - assertFalse(commandFailedEvents.isEmpty()); - assertInstanceOf(MongoOperationTimeoutException.class, commandFailedEvents.get(0).getThrowable()); - } - - private static Stream test8ServerSelectionArguments() { - return Stream.of( - Arguments.of(Named.of("serverSelectionTimeoutMS honored if timeoutMS is not set", - "mongodb://invalid/?serverSelectionTimeoutMS=10")), - Arguments.of(Named.of("timeoutMS honored for server selection if it's lower than serverSelectionTimeoutMS", - "mongodb://invalid/?timeoutMS=200&serverSelectionTimeoutMS=10")), - Arguments.of(Named.of("serverSelectionTimeoutMS honored for server selection if it's lower than timeoutMS", - "mongodb://invalid/?timeoutMS=10&serverSelectionTimeoutMS=200")), - Arguments.of(Named.of("serverSelectionTimeoutMS honored for server selection if timeoutMS=0", - "mongodb://invalid/?timeoutMS=0&serverSelectionTimeoutMS=10")) - - ); - } - - private static Stream test8ServerSelectionHandshakeArguments() { - - return Stream.of( - Arguments.of("timeoutMS honored for connection handshake commands if it's lower than serverSelectionTimeoutMS", 200, 500), - Arguments.of("serverSelectionTimeoutMS honored for connection handshake commands if it's lower than timeoutMS", 500, 200) - ); - } - - protected MongoNamespace generateNamespace() { - return new MongoNamespace(getDefaultDatabaseName(), - getClass().getSimpleName() + "_" + COUNTER.incrementAndGet()); - } - - protected MongoClientSettings.Builder getMongoClientSettingsBuilder() { - commandListener.reset(); - MongoClientSettings.Builder mongoClientSettingsBuilder = Fixture.getMongoClientSettingsBuilder(); - return mongoClientSettingsBuilder - .readConcern(ReadConcern.MAJORITY) - .writeConcern(WriteConcern.MAJORITY) - .readPreference(ReadPreference.primary()) - .addCommandListener(commandListener); - } - - @BeforeEach - public void setUp() { - namespace = generateNamespace(); - executor = Executors.newSingleThreadExecutor(); - gridFsFileNamespace = new MongoNamespace(getDefaultDatabaseName(), GRID_FS_BUCKET_NAME + ".files"); - gridFsChunksNamespace = new MongoNamespace(getDefaultDatabaseName(), GRID_FS_BUCKET_NAME + ".chunks"); - - collectionHelper = new CollectionHelper<>(new BsonDocumentCodec(), namespace); - // in some test collection might not have been created yet, thus dropping it in afterEach will throw an error - collectionHelper.create(); - - filesCollectionHelper = new CollectionHelper<>(new BsonDocumentCodec(), gridFsFileNamespace); - chunksCollectionHelper = new CollectionHelper<>(new BsonDocumentCodec(), gridFsChunksNamespace); - commandListener = new TestCommandListener(); - } - - @AfterEach - public void tearDown() throws InterruptedException { - ClusterFixture.disableFailPoint(FAIL_COMMAND_NAME); - if (collectionHelper != null) { - // Due to testing abortTransaction via failpoint, there may be open transactions - // after the test finishes, thus drop() command hangs for 60 seconds until transaction - // is automatically rolled back. - collectionHelper.runAdminCommand("{killAllSessions: []}"); - collectionHelper.drop(); - filesCollectionHelper.drop(); - chunksCollectionHelper.drop(); - try { - ServerHelper.checkPool(getPrimary()); - } catch (InterruptedException e) { - // ignore - } - } - - if (executor != null) { - executor.shutdownNow(); - //noinspection ResultOfMethodCallIgnored - executor.awaitTermination(MAX_VALUE, NANOSECONDS); - } - } - - @AfterAll - public static void finalTearDown() { - CollectionHelper.dropDatabase(getDefaultDatabaseName()); - } - - private MongoClient createMongoClient(final MongoClientSettings.Builder builder) { - return createMongoClient(builder.build()); - } - - protected long msElapsedSince(final long t1) { - return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t1); - } - - /** - * Get the handshake command name based on the server API version. - * @return the handshake command name - */ - private String getHandshakeCommandName() { - return ClusterFixture.getServerApi() == null ? LEGACY_HELLO : HELLO; - } -} diff --git a/driver-sync/src/test/functional/com/mongodb/client/ClientSideOperationTimeoutProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/ClientSideOperationTimeoutProseTest.java deleted file mode 100644 index 2f73ea3cb0d..00000000000 --- a/driver-sync/src/test/functional/com/mongodb/client/ClientSideOperationTimeoutProseTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.client; - -import com.mongodb.MongoClientSettings; -import com.mongodb.client.gridfs.GridFSBucket; -import com.mongodb.client.gridfs.GridFSBuckets; -import com.mongodb.client.internal.InternalMongoClients; -import com.mongodb.internal.InternalMongoClientSettings; -import com.mongodb.internal.time.ExponentialBackoff; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; - - -/** - * See https://github.com/mongodb/specifications/blob/master/source/client-side-operations-timeout/tests/README.md#prose-tests - */ -public final class ClientSideOperationTimeoutProseTest extends AbstractClientSideOperationsTimeoutProseTest { - - @Override - protected MongoClient createMongoClient(final MongoClientSettings mongoClientSettings) { - return MongoClients.create(mongoClientSettings); - } - - @Override - protected MongoClient createMongoClientWithInternalSettings(final MongoClientSettings mongoClientSettings, - final InternalMongoClientSettings internalSettings) { - return InternalMongoClients.create(mongoClientSettings, null, internalSettings); - } - - @Override - protected GridFSBucket createGridFsBucket(final MongoDatabase mongoDatabase, final String bucketName) { - return GridFSBuckets.create(mongoDatabase, bucketName); - } - - @BeforeEach - @Override - public void setUp() { - super.setUp(); - ExponentialBackoff.setTestJitterSupplier(() -> 0); - } - - @AfterEach - @Override - public void tearDown() throws InterruptedException { - try { - super.tearDown(); - } finally { - ExponentialBackoff.clearTestJitterSupplier(); - } - } - - @Override - protected boolean isAsync() { - return false; - } -} diff --git a/driver-sync/src/test/functional/com/mongodb/client/ClientSideOperationTimeoutTest.java b/driver-sync/src/test/functional/com/mongodb/client/ClientSideOperationTimeoutTest.java deleted file mode 100644 index 9fc2f0e6acc..00000000000 --- a/driver-sync/src/test/functional/com/mongodb/client/ClientSideOperationTimeoutTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.client; - -import com.mongodb.client.unified.UnifiedSyncTest; -import org.junit.jupiter.params.provider.Arguments; - -import java.util.Collection; - -import static org.junit.jupiter.api.Assumptions.assumeFalse; - -// See https://github.com/mongodb/specifications/tree/master/source/client-side-operation-timeout/tests -public class ClientSideOperationTimeoutTest extends UnifiedSyncTest { - - private static Collection data() { - return getTestData("client-side-operations-timeout"); - } - - @Override - protected void skips(final String fileDescription, final String testDescription) { - skipOperationTimeoutTests(fileDescription, testDescription); - - /* - * The test is occasionally racy. Sometimes multiple getMores can be triggered. - */ - ignoreExtraCommandEvents(testDescription.contains("timeoutMS is refreshed for getMore if maxAwaitTimeMS is set")); - } - - public static void skipOperationTimeoutTests(final String fileDescription, final String testDescription) { - assumeFalse(testDescription.contains("maxTimeMS is ignored if timeoutMS is set - createIndex on collection"), - "No maxTimeMS parameter for createIndex() method"); - assumeFalse(fileDescription.startsWith("runCursorCommand"), "No run cursor command"); - assumeFalse(testDescription.contains("runCommand on database"), "No special handling of runCommand"); - assumeFalse(testDescription.endsWith("count on collection"), "No count command helper"); - assumeFalse(fileDescription.equals("timeoutMS can be overridden for an operation"), "No operation based overrides"); - assumeFalse(testDescription.equals("timeoutMS can be overridden for commitTransaction") - || testDescription.equals("timeoutMS applied to abortTransaction"), - "No operation session based overrides"); - - assumeFalse(fileDescription.equals("operations ignore deprecated timeout options if timeoutMS is set") - && (testDescription.startsWith("abortTransaction ignores") || testDescription.startsWith("commitTransaction ignores")), - "No operation session based overrides"); - - assumeFalse(fileDescription.equals("timeoutMS behaves correctly when closing cursors") - && testDescription.equals("timeoutMS can be overridden for close"), "No operation based overrides"); - } -} diff --git a/driver-sync/src/test/functional/com/mongodb/client/WithTransactionProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/WithTransactionProseTest.java index fea61262c04..7c12213b41f 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/WithTransactionProseTest.java +++ b/driver-sync/src/test/functional/com/mongodb/client/WithTransactionProseTest.java @@ -16,14 +16,10 @@ package com.mongodb.client; -import com.mongodb.ClientSessionOptions; -import com.mongodb.MongoClientException; import com.mongodb.MongoCommandException; import com.mongodb.MongoException; import com.mongodb.MongoNodeIsRecoveringException; -import com.mongodb.TransactionOptions; import com.mongodb.WithTransactionTimeoutException; -import com.mongodb.client.model.Sorts; import com.mongodb.internal.time.ExponentialBackoff; import com.mongodb.internal.time.StartTime; import com.mongodb.internal.time.SystemNanoTime; @@ -36,17 +32,14 @@ import org.mockito.Mockito; import java.time.Duration; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; -import static com.mongodb.ClusterFixture.TIMEOUT; import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; import static com.mongodb.ClusterFixture.isSharded; import static com.mongodb.client.Fixture.getPrimary; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assumptions.assumeTrue; @@ -188,43 +181,6 @@ public void testRetryTimeoutEnforcedTransientTransactionErrorOnCommit() { } } - /** - * This test is not from the specification. Ensures cannot override timeout in transaction. - */ - @Test - public void testTimeoutMS() { - try (ClientSession session = client.startSession(ClientSessionOptions.builder() - .defaultTransactionOptions(TransactionOptions.builder().timeout(TIMEOUT, TimeUnit.SECONDS).build()) - .build())) { - assertThrows(MongoClientException.class, () -> session.withTransaction(() -> { - collection.insertOne(session, Document.parse("{ _id : 1 }")); - collection.withTimeout(2, TimeUnit.MINUTES).find(session).first(); - return -1; - })); - } - } - - /** - * This test is not from the specification. Ensures legacy settings don't cause issues in sessions. - */ - @Test - public void testTimeoutMSAndLegacySettings() { - try (ClientSession session = client.startSession(ClientSessionOptions.builder() - .defaultTransactionOptions(TransactionOptions.builder().timeout(TIMEOUT, TimeUnit.SECONDS).build()) - .build())) { - Document document = Document.parse("{ _id : 1 }"); - Document returnValueFromCallback = session.withTransaction(() -> { - collection.insertOne(session, document); - Document found = collection.find(session) - .maxAwaitTime(1, TimeUnit.MINUTES) - .sort(Sorts.descending("_id")) - .first(); - return found != null ? found : new Document(); - }); - assertEquals(document, returnValueFromCallback); - } - } - /** * See * Retry Backoff is Enforced. diff --git a/driver-sync/src/test/functional/com/mongodb/client/csot/AbstractClientSideOperationsEncryptionTimeoutProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/csot/AbstractClientSideOperationsEncryptionTimeoutProseTest.java deleted file mode 100644 index 69dcb10f26f..00000000000 --- a/driver-sync/src/test/functional/com/mongodb/client/csot/AbstractClientSideOperationsEncryptionTimeoutProseTest.java +++ /dev/null @@ -1,397 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.client.csot; - -import com.mongodb.AutoEncryptionSettings; -import com.mongodb.ClientEncryptionSettings; -import com.mongodb.ClusterFixture; -import com.mongodb.MongoClientSettings; -import com.mongodb.MongoNamespace; -import com.mongodb.MongoOperationTimeoutException; -import com.mongodb.MongoUpdatedEncryptedFieldsException; -import com.mongodb.ReadConcern; -import com.mongodb.ReadPreference; -import com.mongodb.WriteConcern; -import com.mongodb.client.Fixture; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.CreateCollectionOptions; -import com.mongodb.client.model.CreateEncryptedCollectionParams; -import com.mongodb.client.model.ValidationOptions; -import com.mongodb.client.model.vault.DataKeyOptions; -import com.mongodb.client.model.vault.EncryptOptions; -import com.mongodb.client.test.CollectionHelper; -import com.mongodb.client.vault.ClientEncryption; -import com.mongodb.event.CommandStartedEvent; -import com.mongodb.internal.connection.TestCommandListener; -import com.mongodb.test.FlakyTest; -import org.bson.BsonBinary; -import org.bson.BsonDocument; -import org.bson.BsonString; -import org.bson.Document; -import org.bson.codecs.BsonDocumentCodec; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; - -import java.util.Arrays; -import java.util.Base64; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import static com.mongodb.ClusterFixture.scaleForWindows; -import static com.mongodb.ClusterFixture.serverVersionAtLeast; -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.lessThan; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -/** - * See - * Prose Tests. - */ -public abstract class AbstractClientSideOperationsEncryptionTimeoutProseTest { - - protected static final String FAIL_COMMAND_NAME = "failCommand"; - private static final Map> KMS_PROVIDERS = new HashMap<>(); - - private final MongoNamespace keyVaultNamespace = new MongoNamespace("keyvault", "datakeys"); - - private CollectionHelper keyVaultCollectionHelper; - - private TestCommandListener commandListener; - - private static final String MASTER_KEY = "Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBMUN3YkQ5a" - + "XRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk"; - - protected abstract ClientEncryption createClientEncryption(ClientEncryptionSettings.Builder builder); - - protected abstract MongoClient createMongoClient(MongoClientSettings.Builder builder); - - // TODO-JAVA-6341: this test intermittently timesout in CI - @FlakyTest(maxAttempts = 3) - void shouldThrowOperationTimeoutExceptionWhenCreateDataKey() { - assumeTrue(serverVersionAtLeast(4, 4)); - - int timeoutMS = scaleForWindows(100); - int blockTimeMS = scaleForWindows(100); - - Map> kmsProviders = new HashMap<>(); - Map localProviderMap = new HashMap<>(); - localProviderMap.put("key", Base64.getDecoder().decode(MASTER_KEY)); - kmsProviders.put("local", localProviderMap); - - try (ClientEncryption clientEncryption = createClientEncryption(getClientEncryptionSettingsBuilder(timeoutMS))) { - - keyVaultCollectionHelper.runAdminCommand("{" - + " configureFailPoint: \"" + FAIL_COMMAND_NAME + "\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"insert\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - assertThrows(MongoOperationTimeoutException.class, () -> clientEncryption.createDataKey("local")); - - List commandStartedEvents = commandListener.getCommandStartedEvents(); - assertEquals(1, commandStartedEvents.size()); - assertEquals(keyVaultNamespace.getCollectionName(), - commandStartedEvents.get(0).getCommand().get("insert").asString().getValue()); - assertNotNull(commandListener.getCommandFailedEvent("insert")); - } - - } - - @Test - void shouldThrowOperationTimeoutExceptionWhenEncryptData() { - assumeTrue(serverVersionAtLeast(4, 4)); - - int timeoutMS = scaleForWindows(150); - int blockTimeMS = scaleForWindows(150); - - try (ClientEncryption clientEncryption = createClientEncryption(getClientEncryptionSettingsBuilder(timeoutMS))) { - - clientEncryption.createDataKey("local"); - - keyVaultCollectionHelper.runAdminCommand("{" - + " configureFailPoint: \"" + FAIL_COMMAND_NAME + "\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"find\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - BsonBinary dataKey = clientEncryption.createDataKey("local"); - - EncryptOptions encryptOptions = new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"); - encryptOptions.keyId(dataKey); - commandListener.reset(); - assertThrows(MongoOperationTimeoutException.class, () -> clientEncryption.encrypt(new BsonString("hello"), encryptOptions)); - - List commandStartedEvents = commandListener.getCommandStartedEvents(); - assertEquals(1, commandStartedEvents.size()); - assertEquals(keyVaultNamespace.getCollectionName(), commandStartedEvents.get(0).getCommand().get("find").asString().getValue()); - assertNotNull(commandListener.getCommandFailedEvent("find")); - } - - } - - @Test - void shouldThrowOperationTimeoutExceptionWhenDecryptData() { - assumeTrue(serverVersionAtLeast(4, 4)); - - int timeoutMS = scaleForWindows(400); - int blockTimeMS = scaleForWindows(500); - - BsonBinary encrypted; - try (ClientEncryption clientEncryption = createClientEncryption(getClientEncryptionSettingsBuilder(timeoutMS))) { - clientEncryption.createDataKey("local"); - BsonBinary dataKey = clientEncryption.createDataKey("local"); - EncryptOptions encryptOptions = new EncryptOptions("AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"); - encryptOptions.keyId(dataKey); - encrypted = clientEncryption.encrypt(new BsonString("hello"), encryptOptions); - } - - try (ClientEncryption clientEncryption = createClientEncryption(getClientEncryptionSettingsBuilder(timeoutMS))) { - keyVaultCollectionHelper.runAdminCommand("{" - + " configureFailPoint: \"" + FAIL_COMMAND_NAME + "\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"find\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - commandListener.reset(); - assertThrows(MongoOperationTimeoutException.class, () -> clientEncryption.decrypt(encrypted)); - - List commandStartedEvents = commandListener.getCommandStartedEvents(); - assertEquals(1, commandStartedEvents.size()); - assertEquals(keyVaultNamespace.getCollectionName(), commandStartedEvents.get(0).getCommand().get("find").asString().getValue()); - assertNotNull(commandListener.getCommandFailedEvent("find")); - } - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @Test - void shouldDecreaseOperationTimeoutForSubsequentOperations() { - assumeTrue(serverVersionAtLeast(4, 4)); - - // not scaled: initialTimeoutMS is already ample relative to connection setup. - long initialTimeoutMS = 2500; - int blockTimeMS = 10; - - keyVaultCollectionHelper.runAdminCommand("{" - + " configureFailPoint: \"" + FAIL_COMMAND_NAME + "\"," - + " mode: \"alwaysOn\"," - + " data: {" - + " failCommands: [\"insert\", \"find\", \"listCollections\"]," - + " blockConnection: true," - + " blockTimeMS: " + blockTimeMS - + " }" - + "}"); - - try (ClientEncryption clientEncryption = createClientEncryption(getClientEncryptionSettingsBuilder() - .timeout(initialTimeoutMS, MILLISECONDS))) { - BsonBinary dataKeyId = clientEncryption.createDataKey("local", new DataKeyOptions()); - String base64DataKeyId = Base64.getEncoder().encodeToString(dataKeyId.getData()); - - final String dbName = "test"; - final String collName = "coll"; - - AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder() - .keyVaultNamespace(keyVaultNamespace.getFullName()) - .keyVaultMongoClientSettings(getMongoClientSettingsBuilder() - .build()) - .kmsProviders(KMS_PROVIDERS) - .build(); - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder() - .autoEncryptionSettings(autoEncryptionSettings) - .timeout(initialTimeoutMS, MILLISECONDS))) { - - CreateCollectionOptions createCollectionOptions = new CreateCollectionOptions(); - createCollectionOptions.validationOptions(new ValidationOptions() - .validator(new BsonDocument("$jsonSchema", BsonDocument.parse("{" - + " properties: {" - + " encryptedField: {" - + " encrypt: {" - + " keyId: [{" - + " \"$binary\": {" - + " \"base64\": \"" + base64DataKeyId + "\"," - + " \"subType\": \"04\"" - + " }" - + " }]," - + " bsonType: \"string\"," - + " algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic\"" - + " }" - + " }" - + " }," - + " \"bsonType\": \"object\"" - + "}")))); - - MongoCollection collection = mongoClient.getDatabase(dbName).getCollection(collName); - collection.drop(); - - mongoClient.getDatabase(dbName).createCollection(collName, createCollectionOptions); - - commandListener.reset(); - collection.insertOne(new Document("encryptedField", "123456789")); - - List commandStartedEvents = commandListener.getCommandStartedEvents(); - assertTimeoutIsDecreasingForCommands(Arrays.asList("listCollections", "find", "insert"), commandStartedEvents, - initialTimeoutMS); - } - } - } - - /** - * Not a prose spec test. However, it is additional test case for better coverage. - */ - @ParameterizedTest - @ValueSource(strings = {"insert", "create"}) - void shouldThrowTimeoutExceptionWhenCreateEncryptedCollection(final String commandToTimeout) { - assumeTrue(serverVersionAtLeast(7, 0)); - //given - long initialTimeoutMS = scaleForWindows(200); - - try (ClientEncryption clientEncryption = createClientEncryption(getClientEncryptionSettingsBuilder() - .timeout(initialTimeoutMS, MILLISECONDS))) { - final String dbName = "test"; - final String collName = "coll"; - - try (MongoClient mongoClient = createMongoClient(getMongoClientSettingsBuilder() - .timeout(initialTimeoutMS, MILLISECONDS))) { - CreateCollectionOptions createCollectionOptions = new CreateCollectionOptions().encryptedFields(Document.parse( - "{" - + " fields: [{" - + " path: 'ssn'," - + " bsonType: 'string'," - + " keyId: null" - + " }]" - + "}")); - - keyVaultCollectionHelper.runAdminCommand("{" - + " configureFailPoint: \"" + FAIL_COMMAND_NAME + "\"," - + " mode: { times: 1 }," - + " data: {" - + " failCommands: [\"" + commandToTimeout + "\"]," - + " blockConnection: true," - + " blockTimeMS: " + initialTimeoutMS - + " }" - + "}"); - - MongoDatabase database = mongoClient.getDatabase(dbName); - database.getCollection(collName).drop(); - commandListener.reset(); - - //when - MongoUpdatedEncryptedFieldsException encryptionException = assertThrows(MongoUpdatedEncryptedFieldsException.class, () -> - clientEncryption.createEncryptedCollection(database, collName, createCollectionOptions, - new CreateEncryptedCollectionParams("local"))); - //then - assertInstanceOf(MongoOperationTimeoutException.class, encryptionException.getCause()); - } - } - } - - private static void assertTimeoutIsDecreasingForCommands(final List commandNames, - final List commandStartedEvents, - final long initialTimeoutMs) { - long previousMaxTimeMS = initialTimeoutMs; - assertEquals(commandNames.size(), commandStartedEvents.size(), "There have been more commands then expected"); - for (int i = 0; i < commandStartedEvents.size(); i++) { - CommandStartedEvent commandStartedEvent = commandStartedEvents.get(i); - String expectedCommandName = commandNames.get(i); - assertEquals(expectedCommandName, commandStartedEvent.getCommandName()); - - BsonDocument command = commandStartedEvent.getCommand(); - assertTrue(command.containsKey("maxTimeMS"), "Command " + expectedCommandName + " should have maxTimeMS set"); - - long maxTimeMS = command.getInt64("maxTimeMS").getValue(); - - if (i > 0) { - assertThat(commandStartedEvent.getCommandName() + " " + "maxTimeMS should be less than that of a previous " - + commandStartedEvents.get(i - 1).getCommandName() + " command", maxTimeMS, lessThan(previousMaxTimeMS)); - } else { - assertThat("maxTimeMS should be less than the configured timeout " + initialTimeoutMs + "ms", - maxTimeMS, lessThan(previousMaxTimeMS)); - } - previousMaxTimeMS = maxTimeMS; - } - } - - protected ClientEncryptionSettings.Builder getClientEncryptionSettingsBuilder(final long vaultTimeout) { - return ClientEncryptionSettings - .builder() - .keyVaultNamespace(keyVaultNamespace.getFullName()) - .keyVaultMongoClientSettings(getMongoClientSettingsBuilder() - .timeout(vaultTimeout, TimeUnit.MILLISECONDS).build()) - .kmsProviders(KMS_PROVIDERS); - } - - protected ClientEncryptionSettings.Builder getClientEncryptionSettingsBuilder() { - return ClientEncryptionSettings - .builder() - .keyVaultNamespace(keyVaultNamespace.getFullName()) - .keyVaultMongoClientSettings(getMongoClientSettingsBuilder().build()) - .kmsProviders(KMS_PROVIDERS); - } - - protected MongoClientSettings.Builder getMongoClientSettingsBuilder() { - return Fixture.getMongoClientSettingsBuilder() - .readConcern(ReadConcern.MAJORITY) - .writeConcern(WriteConcern.MAJORITY) - .readPreference(ReadPreference.primary()) - .addCommandListener(commandListener); - } - - @BeforeEach - public void setUp() { - Map localProviderMap = new HashMap<>(); - localProviderMap.put("key", Base64.getDecoder().decode(MASTER_KEY)); - KMS_PROVIDERS.put("local", localProviderMap); - - keyVaultCollectionHelper = new CollectionHelper<>(new BsonDocumentCodec(), keyVaultNamespace); - keyVaultCollectionHelper.create(); - commandListener = new TestCommandListener(); - } - - @AfterEach - public void tearDown() { - ClusterFixture.disableFailPoint(FAIL_COMMAND_NAME); - if (keyVaultCollectionHelper != null) { - keyVaultCollectionHelper.drop(); - } - } -} diff --git a/driver-sync/src/test/functional/com/mongodb/client/csot/ClientSideOperationsEncryptionTimeoutProseTest.java b/driver-sync/src/test/functional/com/mongodb/client/csot/ClientSideOperationsEncryptionTimeoutProseTest.java deleted file mode 100644 index 25a1102914a..00000000000 --- a/driver-sync/src/test/functional/com/mongodb/client/csot/ClientSideOperationsEncryptionTimeoutProseTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.client.csot; - -import com.mongodb.ClientEncryptionSettings; -import com.mongodb.MongoClientSettings; -import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoClients; -import com.mongodb.client.vault.ClientEncryption; -import com.mongodb.client.vault.ClientEncryptions; - -public class ClientSideOperationsEncryptionTimeoutProseTest extends AbstractClientSideOperationsEncryptionTimeoutProseTest { - public ClientEncryption createClientEncryption(final ClientEncryptionSettings.Builder builder) { - return ClientEncryptions.create(builder.build()); - } - - @Override - protected MongoClient createMongoClient(final MongoClientSettings.Builder builder) { - return MongoClients.create(builder.build()); - } -} diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/Entities.java b/driver-sync/src/test/functional/com/mongodb/client/unified/Entities.java index a1da54601a8..b56b0c5bc76 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/Entities.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/Entities.java @@ -30,7 +30,6 @@ import com.mongodb.TransactionOptions; import com.mongodb.client.ClientSession; import com.mongodb.client.MongoClient; -import com.mongodb.client.MongoCluster; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; @@ -46,7 +45,6 @@ import com.mongodb.internal.connection.TestConnectionPoolListener; import com.mongodb.internal.connection.TestServerListener; import com.mongodb.internal.logging.LogMessage; -import com.mongodb.lang.Nullable; import com.mongodb.logging.TestLoggingInterceptor; import com.mongodb.observability.ObservabilitySettings; import io.micrometer.observation.ObservationRegistry; @@ -203,18 +201,6 @@ public MongoCollection getCollection(final String id) { return getEntity(id, collections, "collection"); } - public MongoCluster getMongoClusterWithTimeoutMS(final String id, @Nullable final Long timeoutMS) { - return timeoutMS != null ? getClient(id).withTimeout(timeoutMS, TimeUnit.MILLISECONDS) : getClient(id); - } - - public MongoDatabase getDatabaseWithTimeoutMS(final String id, @Nullable final Long timeoutMS) { - return timeoutMS != null ? getDatabase(id).withTimeout(timeoutMS, TimeUnit.MILLISECONDS) : getDatabase(id); - } - - public MongoCollection getCollectionWithTimeoutMS(final String id, @Nullable final Long timeoutMS) { - return timeoutMS != null ? getCollection(id).withTimeout(timeoutMS, TimeUnit.MILLISECONDS) : getCollection(id); - } - public ClientSession getSession(final String id) { return getEntity(id, sessions, "session"); } @@ -461,9 +447,6 @@ private void initClient(final BsonDocument entity, final String id, case "appName": clientSettingsBuilder.applicationName(value.asString().getValue()); break; - case "timeoutMS": - clientSettingsBuilder.timeout(value.asNumber().longValue(), TimeUnit.MILLISECONDS); - break; case "serverMonitoringMode": clientSettingsBuilder.applyToServerSettings(builder -> builder.serverMonitoringMode( ServerMonitoringModeUtil.fromString(value.asString().getValue()))); @@ -684,9 +667,6 @@ private void initDatabase(final BsonDocument entity, final String id) { case "writeConcern": database = database.withWriteConcern(asWriteConcern(entry.getValue().asDocument())); break; - case "timeoutMS": - database = database.withTimeout(entry.getValue().asNumber().longValue(), TimeUnit.MILLISECONDS); - break; default: throw new UnsupportedOperationException("Unsupported database option: " + entry.getKey()); } @@ -711,9 +691,6 @@ private void initCollection(final BsonDocument entity, final String id) { case "writeConcern": collection = collection.withWriteConcern(asWriteConcern(entry.getValue().asDocument())); break; - case "timeoutMS": - collection = collection.withTimeout(entry.getValue().asNumber().longValue(), TimeUnit.MILLISECONDS); - break; default: throw new UnsupportedOperationException("Unsupported collection option: " + entry.getKey()); } @@ -734,9 +711,6 @@ private void initSession(final BsonDocument entity, final String id, final BsonD case "snapshot": optionsBuilder.snapshot(entry.getValue().asBoolean().getValue()); break; - case "defaultTimeoutMS": - optionsBuilder.defaultTimeout(entry.getValue().asNumber().longValue(), TimeUnit.MILLISECONDS); - break; case "causalConsistency": optionsBuilder.causallyConsistent(entry.getValue().asBoolean().getValue()); break; diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/ErrorMatcher.java b/driver-sync/src/test/functional/com/mongodb/client/unified/ErrorMatcher.java index 8147daa5dba..cb878d5e9ea 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/ErrorMatcher.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/ErrorMatcher.java @@ -24,7 +24,6 @@ import com.mongodb.MongoGridFSException; import com.mongodb.MongoSecurityException; import com.mongodb.MongoExecutionTimeoutException; -import com.mongodb.MongoOperationTimeoutException; import com.mongodb.MongoServerException; import com.mongodb.MongoSocketException; import com.mongodb.MongoWriteConcernException; @@ -83,10 +82,8 @@ void assertErrorsMatch(final BsonDocument expectedError, final Exception e) { } if (expectedError.containsKey("isTimeoutError")) { - assertEquals(context.getMessage("Exception must be of type MongoOperationTimeoutException when checking for results"), - expectedError.getBoolean("isTimeoutError").getValue(), - e instanceof MongoOperationTimeoutException - ); + assertFalse(context.getMessage("Exception must be of timeout exception when checking for results"), + expectedError.getBoolean("isTimeoutError").getValue()); } if (expectedError.containsKey("errorContains")) { diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedCrudHelper.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedCrudHelper.java index d94a3f94428..4e7c96e766e 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedCrudHelper.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedCrudHelper.java @@ -46,7 +46,6 @@ import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoIterable; -import com.mongodb.client.cursor.TimeoutMode; import com.mongodb.client.model.BulkWriteOptions; import com.mongodb.client.model.ChangeStreamPreAndPostImagesOptions; import com.mongodb.client.model.ClusteredIndexOptions; @@ -118,8 +117,6 @@ import org.bson.codecs.ValueCodecProvider; import org.bson.codecs.configuration.CodecRegistries; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -319,9 +316,6 @@ OperationResult executeListCollections(final BsonDocument operation) { case "batchSize": iterable.batchSize(cur.getValue().asNumber().intValue()); break; - case "timeoutMode": - setTimeoutMode(iterable, cur); - break; case "maxTimeMS": iterable.maxTime(cur.getValue().asNumber().longValue(), TimeUnit.MILLISECONDS); break; @@ -392,9 +386,6 @@ private ListIndexesIterable createListIndexesIterable(final BsonDo case "batchSize": iterable.batchSize(cur.getValue().asNumber().intValue()); break; - case "timeoutMode": - setTimeoutMode(iterable, cur); - break; case "maxTimeMS": iterable.maxTime(cur.getValue().asNumber().longValue(), TimeUnit.MILLISECONDS); break; @@ -497,9 +488,6 @@ private FindIterable createFindIterable(final BsonDocument operati case "cursorType": setCursorType(iterable, cur); break; - case "timeoutMode": - setTimeoutMode(iterable, cur); - break; default: throw new UnsupportedOperationException("Unsupported argument: " + cur.getKey()); } @@ -811,14 +799,12 @@ OperationResult executeAggregate(final BsonDocument operation) { List pipeline = arguments.getArray("pipeline").stream().map(BsonValue::asDocument).collect(toList()); AggregateIterable iterable; if (entities.hasDatabase(entityName)) { - Long timeoutMS = getAndRemoveTimeoutMS(operation.getDocument("arguments")); - MongoDatabase database = entities.getDatabaseWithTimeoutMS(entityName, timeoutMS); + MongoDatabase database = entities.getDatabase(entityName); iterable = session == null ? database.aggregate(requireNonNull(pipeline), BsonDocument.class) : database.aggregate(session, requireNonNull(pipeline), BsonDocument.class); } else if (entities.hasCollection(entityName)) { - Long timeoutMS = getAndRemoveTimeoutMS(operation.getDocument("arguments")); - MongoCollection collection = entities.getCollectionWithTimeoutMS(entityName, timeoutMS); + MongoCollection collection = entities.getCollection(entityName); iterable = session == null ? collection.aggregate(requireNonNull(pipeline)) : collection.aggregate(session, requireNonNull(pipeline)); @@ -846,9 +832,6 @@ OperationResult executeAggregate(final BsonDocument operation) { case "comment": iterable.comment(cur.getValue()); break; - case "timeoutMode": - setTimeoutMode(iterable, cur); - break; case "maxTimeMS": iterable.maxTime(cur.getValue().asNumber().longValue(), TimeUnit.MILLISECONDS); break; @@ -1294,9 +1277,6 @@ OperationResult executeStartTransaction(final BsonDocument operation) { case "readConcern": optionsBuilder.readConcern(asReadConcern(cur.getValue().asDocument())); break; - case "timeoutMS": - optionsBuilder.timeout(cur.getValue().asInt32().longValue(), TimeUnit.MILLISECONDS); - break; case "maxCommitTimeMS": optionsBuilder.maxCommitTime(cur.getValue().asNumber().longValue(), TimeUnit.MILLISECONDS); break; @@ -1351,9 +1331,6 @@ OperationResult executeWithTransaction(final BsonDocument operation, final Opera case "writeConcern": optionsBuilder.writeConcern(asWriteConcern(entry.getValue().asDocument())); break; - case "timeoutMS": - optionsBuilder.timeout(entry.getValue().asNumber().longValue(), TimeUnit.MILLISECONDS); - break; case "maxCommitTimeMS": optionsBuilder.maxCommitTime(entry.getValue().asNumber().longValue(), TimeUnit.MILLISECONDS); break; @@ -1848,13 +1825,12 @@ public OperationResult createChangeStreamCursor(final BsonDocument operation) { List pipeline = arguments.getArray("pipeline").stream().map(BsonValue::asDocument).collect(toList()); ChangeStreamIterable iterable; - Long timeoutMS = arguments.containsKey("timeoutMS") ? arguments.remove("timeoutMS").asNumber().longValue() : null; if (entities.hasCollection(entityName)) { - iterable = entities.getCollectionWithTimeoutMS(entityName, timeoutMS).watch(pipeline); + iterable = entities.getCollection(entityName).watch(pipeline); } else if (entities.hasDatabase(entityName)) { - iterable = entities.getDatabaseWithTimeoutMS(entityName, timeoutMS).watch(pipeline, BsonDocument.class); + iterable = entities.getDatabase(entityName).watch(pipeline, BsonDocument.class); } else if (entities.hasClient(entityName)) { - iterable = entities.getMongoClusterWithTimeoutMS(entityName, timeoutMS).watch(pipeline, BsonDocument.class); + iterable = entities.getClient(entityName).watch(pipeline, BsonDocument.class); } else { throw new UnsupportedOperationException("No entity found for id: " + entityName); } @@ -2377,37 +2353,14 @@ private BsonDocument encodeChangeStreamDocumentToBsonDocument(final ChangeStream } private MongoCollection getMongoCollection(final BsonDocument operation) { - MongoCollection collection = entities.getCollection(operation.getString("object").getValue()); - Long timeoutMS = getAndRemoveTimeoutMS(operation.getDocument("arguments", new BsonDocument())); - if (timeoutMS != null) { - collection = collection.withTimeout(timeoutMS, TimeUnit.MILLISECONDS); - } - return collection; + return entities.getCollection(operation.getString("object").getValue()); } private MongoDatabase getMongoDatabase(final BsonDocument operation) { - MongoDatabase database = entities.getDatabase(operation.getString("object").getValue()); - if (operation.containsKey("arguments")) { - BsonDocument arguments = operation.getDocument("arguments", new BsonDocument()); - Long timeoutMS = getAndRemoveTimeoutMS(arguments); - if (timeoutMS != null) { - database = database.withTimeout(timeoutMS, TimeUnit.MILLISECONDS); - arguments.remove("timeoutMS"); - } - } - return database; + return entities.getDatabase(operation.getString("object").getValue()); } private MongoCluster getMongoCluster(final BsonDocument operation) { - MongoCluster mongoCluster = entities.getClient(operation.getString("object").getValue()); - if (operation.containsKey("arguments")) { - BsonDocument arguments = operation.getDocument("arguments", new BsonDocument()); - Long timeoutMS = getAndRemoveTimeoutMS(arguments); - if (timeoutMS != null) { - mongoCluster = mongoCluster.withTimeout(timeoutMS, TimeUnit.MILLISECONDS); - arguments.remove("timeoutMS"); - } - } - return mongoCluster; + return entities.getClient(operation.getString("object").getValue()); } private static void setCursorType(final FindIterable iterable, final Map.Entry cur) { @@ -2425,35 +2378,4 @@ private static void setCursorType(final FindIterable iterable, fin throw new UnsupportedOperationException("Unsupported cursorType: " + cur.getValue()); } } - - private static void setTimeoutMode(final MongoIterable iterable, final Map.Entry cur) { - switch (cur.getValue().asString().getValue()) { - case "cursorLifetime": - invokeTimeoutMode(iterable, TimeoutMode.CURSOR_LIFETIME); - break; - case "iteration": - invokeTimeoutMode(iterable, TimeoutMode.ITERATION); - break; - default: - throw new UnsupportedOperationException("Unsupported timeoutMode: " + cur.getValue()); - } - } - - private static void invokeTimeoutMode(final MongoIterable iterable, final TimeoutMode timeoutMode) { - try { - Method timeoutModeMethod = iterable.getClass().getDeclaredMethod("timeoutMode", TimeoutMode.class); - timeoutModeMethod.setAccessible(true); - timeoutModeMethod.invoke(iterable, timeoutMode); - } catch (NoSuchMethodException e) { - throw new UnsupportedOperationException("Unsupported timeoutMode method for class: " + iterable.getClass(), e); - } catch (IllegalAccessException e) { - throw new UnsupportedOperationException("Unable to set timeoutMode method for class: " + iterable.getClass(), e); - } catch (InvocationTargetException e) { - Throwable targetException = e.getTargetException(); - if (targetException instanceof IllegalArgumentException) { - throw (IllegalArgumentException) targetException; - } - throw new UnsupportedOperationException("Unable to set timeoutMode method for class: " + iterable.getClass(), targetException); - } - } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedGridFSHelper.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedGridFSHelper.java index 13e95a58463..bfd8c5a400c 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedGridFSHelper.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedGridFSHelper.java @@ -220,12 +220,7 @@ Document asDocument(final BsonDocument bsonDocument) { } private GridFSBucket getGridFsBucket(final BsonDocument operation) { - GridFSBucket bucket = entities.getBucket(operation.getString("object").getValue()); - Long timeoutMS = getAndRemoveTimeoutMS(operation.getDocument("arguments", new BsonDocument())); - if (timeoutMS != null) { - bucket = bucket.withTimeout(timeoutMS, TimeUnit.MILLISECONDS); - } - return bucket; + return entities.getBucket(operation.getString("object").getValue()); } private GridFSFindIterable createGridFSFindIterable(final BsonDocument operation) { diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedHelper.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedHelper.java index 027ccf92fb5..291ea82c7a2 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedHelper.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedHelper.java @@ -16,16 +16,5 @@ package com.mongodb.client.unified; -import org.bson.BsonDocument; - abstract class UnifiedHelper { - - static Long getAndRemoveTimeoutMS(final BsonDocument arguments) { - Long timeoutMS = null; - if (arguments.containsKey("timeoutMS")) { - timeoutMS = arguments.getNumber("timeoutMS").longValue(); - arguments.remove("timeoutMS"); - } - return timeoutMS; - } } diff --git a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestModifications.java b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestModifications.java index 2de6e982aa2..cc0f48ef994 100644 --- a/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestModifications.java +++ b/driver-sync/src/test/functional/com/mongodb/client/unified/UnifiedTestModifications.java @@ -32,10 +32,8 @@ import java.util.function.Function; import java.util.function.Supplier; -import static com.mongodb.ClusterFixture.WINDOWS_CSOT_TIMEOUT_MULTIPLIER; import static com.mongodb.ClusterFixture.isDiscoverableReplicaSet; import static com.mongodb.ClusterFixture.isSharded; -import static com.mongodb.ClusterFixture.isWindows; import static com.mongodb.ClusterFixture.serverVersionLessThan; import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.assertions.Assertions.assertTrue; @@ -81,239 +79,8 @@ public static void applyCustomizations(final TestDef def) { .file("client-side-encryption/tests/unified", "QE-Text-substringPreview"); // client-side-operation-timeout (CSOT) - // The expected change stream timeout-refresh behaviour is unspecified on server 9.0+ (DRIVERS-3006), so the - // CSOT suite fails there (most visibly on sharded clusters, where extra mongos round-trips exceed the tight - // timeoutMS). Skip the suite on 9.0+ until the spec is clarified. - def.skipJira("https://jira.mongodb.org/browse/JAVA-6078 change stream timeout-refresh behaviour is " - + "unspecified on server 9.0+ (DRIVERS-3006)") - .when(() -> !serverVersionLessThan(9, 0)) - .directory("client-side-operations-timeout"); - - //TODO-invistigate - /* - As to the background connection pooling section: - timeoutMS set at the MongoClient level MUST be used as the timeout for all commands sent as part of the handshake. - We first configure a failpoint to block all hello/isMaster commands for 50 ms, then set timeoutMS = 10 ms on MongoClient - and wait for awaitMinPoolSize = 1000. So that means the background thread tries to populate connections under a 10ms timeout - cap while the failpoint blocks for 50ms, so all attempts effectively fail. - */ - def.skipAccordingToSpec("background connection pooling section") - .test("client-side-operations-timeout", "timeoutMS behaves correctly during command execution", - "short-circuit is not enabled with only 1 RTT measurement") - .test("client-side-operations-timeout", "timeoutMS behaves correctly during command execution", - "command is not sent if RTT is greater than timeoutMS"); - def.skipNoncompliantReactive("No good way to fulfill tryNext() requirement with a Publisher") - .test("client-side-operations-timeout", "timeoutMS behaves correctly for tailable awaitData cursors", - "apply remaining timeoutMS if less than maxAwaitTimeMS"); - - def.skipNoncompliantReactive("No good way to fulfill tryNext() requirement with a Publisher") - .test("client-side-operations-timeout", "timeoutMS behaves correctly for tailable awaitData cursors", - "apply maxAwaitTimeMS if less than remaining timeout"); - - def.skipJira("https://jira.mongodb.org/browse/JAVA-5491") - .when(() -> !serverVersionLessThan(8, 3)) - .test("client-side-operations-timeout", "operations ignore deprecated timeout options if timeoutMS is set", - "socketTimeoutMS is ignored if timeoutMS is set - dropIndex on collection") - .test("client-side-operations-timeout", "operations ignore deprecated timeout options if timeoutMS is set", - "wTimeoutMS is ignored if timeoutMS is set - dropIndex on collection") - .test("client-side-operations-timeout", "operations ignore deprecated timeout options if timeoutMS is set", - "maxTimeMS is ignored if timeoutMS is set - dropIndex on collection") - .test("client-side-operations-timeout", "operations ignore deprecated timeout options if timeoutMS is set", - "socketTimeoutMS is ignored if timeoutMS is set - dropIndexes on collection") - .test("client-side-operations-timeout", "operations ignore deprecated timeout options if timeoutMS is set", - "wTimeoutMS is ignored if timeoutMS is set - dropIndexes on collection") - .test("client-side-operations-timeout", "operations ignore deprecated timeout options if timeoutMS is set", - "maxTimeMS is ignored if timeoutMS is set - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoDatabase", - "timeoutMS can be configured on a MongoDatabase - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoDatabase", - "timeoutMS can be set to 0 on a MongoDatabase - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoDatabase", - "timeoutMS can be configured on a MongoDatabase - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoDatabase", - "timeoutMS can be set to 0 on a MongoDatabase - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoCollection", - "timeoutMS can be configured on a MongoCollection - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoCollection", - "timeoutMS can be set to 0 on a MongoCollection - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoCollection", - "timeoutMS can be configured on a MongoCollection - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoCollection", - "timeoutMS can be set to 0 on a MongoCollection - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for an operation", - "timeoutMS can be configured for an operation - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for an operation", - "timeoutMS can be set to 0 for an operation - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for an operation", - "timeoutMS can be configured for an operation - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for an operation", - "timeoutMS can be set to 0 for an operation - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be configured on a MongoClient", - "timeoutMS can be configured on a MongoClient - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be configured on a MongoClient", - "timeoutMS can be set to 0 on a MongoClient - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be configured on a MongoClient", - "timeoutMS can be configured on a MongoClient - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be configured on a MongoClient", - "timeoutMS can be set to 0 on a MongoClient - dropIndexes on collection") - .test("client-side-operations-timeout", "operations ignore deprecated timeout options if timeoutMS is set", - "socketTimeoutMS is ignored if timeoutMS is set - dropIndex on collection") - .test("client-side-operations-timeout", "operations ignore deprecated timeout options if timeoutMS is set", - "wTimeoutMS is ignored if timeoutMS is set - dropIndex on collection") - .test("client-side-operations-timeout", "operations ignore deprecated timeout options if timeoutMS is set", - "maxTimeMS is ignored if timeoutMS is set - dropIndex on collection") - .test("client-side-operations-timeout", "operations ignore deprecated timeout options if timeoutMS is set", - "socketTimeoutMS is ignored if timeoutMS is set - dropIndexes on collection") - .test("client-side-operations-timeout", "operations ignore deprecated timeout options if timeoutMS is set", - "wTimeoutMS is ignored if timeoutMS is set - dropIndexes on collection") - .test("client-side-operations-timeout", "operations ignore deprecated timeout options if timeoutMS is set", - "maxTimeMS is ignored if timeoutMS is set - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoDatabase", - "timeoutMS can be configured on a MongoDatabase - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoDatabase", - "timeoutMS can be set to 0 on a MongoDatabase - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoDatabase", - "timeoutMS can be configured on a MongoDatabase - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoDatabase", - "timeoutMS can be set to 0 on a MongoDatabase - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoCollection", - "timeoutMS can be configured on a MongoCollection - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoCollection", - "timeoutMS can be set to 0 on a MongoCollection - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoCollection", - "timeoutMS can be configured on a MongoCollection - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for a MongoCollection", - "timeoutMS can be set to 0 on a MongoCollection - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for an operation", - "timeoutMS can be configured for an operation - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for an operation", - "timeoutMS can be set to 0 for an operation - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for an operation", - "timeoutMS can be configured for an operation - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be overridden for an operation", - "timeoutMS can be set to 0 for an operation - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be configured on a MongoClient", - "timeoutMS can be configured on a MongoClient - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be configured on a MongoClient", - "timeoutMS can be set to 0 on a MongoClient - dropIndex on collection") - .test("client-side-operations-timeout", "timeoutMS can be configured on a MongoClient", - "timeoutMS can be configured on a MongoClient - dropIndexes on collection") - .test("client-side-operations-timeout", "timeoutMS can be configured on a MongoClient", - "timeoutMS can be set to 0 on a MongoClient - dropIndexes on collection"); - - def.retry("Unified CSOT tests do not account for RTT which varies in TLS vs non-TLS runs") - .whenFailureContains("timeout") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for non-tailable cursors", - "timeoutMS is refreshed for getMore if timeoutMode is iteration - success"); - def.retry("Unified CSOT tests do not account for RTT which varies in TLS vs non-TLS runs") - .whenFailureContains("timeout") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for tailable non-awaitData cursors", - "timeoutMS is refreshed for getMore - success"); - - // Windows / slower-TLS-host CSOT timeout adjustments (JAVA-6057): these tests are calibrated for the fast - // Linux CI hosts; on Windows connection establishment consumes the tight budgets. See - // ClusterFixture.scaleForWindows and scaleForWindows(BsonArray, BsonDocument, int) below. - - // "Whole operation" tests block two commands sharing one budget and expect the 2nd to time out. Scale - // timeoutMS and blockTimeMS by the same factor so the ordering is preserved with more setup headroom. - def.transform("JAVA-6057: whole-operation CSOT timeouts (cursor-lifetime, bulkWrite) are too tight for the " - + "slower Windows TLS hosts, where the budget is consumed by connection establishment before " - + "the command under test is sent", - (entitiesArray, definition) -> - scaleForWindows(entitiesArray, definition, WINDOWS_CSOT_TIMEOUT_MULTIPLIER)) - .when(ClusterFixture::isWindows) - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for non-tailable cursors", - "remaining timeoutMS applied to getMore if timeoutMode is cursor_lifetime") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for non-tailable cursors", - "remaining timeoutMS applied to getMore if timeoutMode is unset") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for bulkWrite operations", - "timeoutMS applied to entire bulkWrite, not individual commands"); - - // getMore-refresh "success" tests (timeoutMS 200/250, expect no error): on Windows setup eats the budget so - // they time out unexpectedly. Raise timeoutMS to a value-agnostic 1000ms floor (safe since they expect success). - def.transform("JAVA-6057: getMore-refresh success timeouts are too tight for the slower Windows TLS hosts, " - + "where connection setup consumes the budget before the command completes", - (entitiesArray, definition) -> - raiseIntToFloor(definition.getArray("operations"), "arguments.timeoutMS", 1000)) - .when(ClusterFixture::isWindows) - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for change streams", - "timeoutMS is refreshed for getMore if maxAwaitTimeMS is set") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for non-tailable cursors", - "timeoutMS is refreshed for getMore if timeoutMode is iteration - success") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for tailable awaitData cursors", - "timeoutMS is refreshed for getMore if maxAwaitTimeMS is set") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for tailable awaitData cursors", - "timeoutMS is refreshed for getMore if maxAwaitTimeMS is not set") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for tailable non-awaitData cursors", - "timeoutMS is refreshed for getMore - success"); - - // Retryable tests use client timeoutMS=100 + minPoolSize=1; on Windows the background handshake exceeds 100ms - // so the pool never populates ("Error waiting for awaitMinPoolSizeMS"). Scale by - // WINDOWS_CSOT_TIMEOUT_MULTIPLIER (whole-op block ordering kept). - def.transform("JAVA-6057: retryable CSOT tests cannot populate minPoolSize under the tight client-level " - + "timeoutMS on the slower Windows TLS hosts, where background connection establishment " - + "exceeds the timeout", - (entitiesArray, definition) -> - scaleForWindows(entitiesArray, definition, WINDOWS_CSOT_TIMEOUT_MULTIPLIER)) - .when(ClusterFixture::isWindows) - .file("client-side-operations-timeout", "timeoutMS behaves correctly for retryable operations"); - - def.transform("JAVA-5839: Bump blocking/timeout to avoid CI latency failures", - (entitiesArray, definition) -> { - // Two blocked finds (times:2); the 2nd must time out (2 events). On Windows 1000/600 keeps - // 2*600 > 1000 with setup headroom so the first find completes. - findAndSetInt(entitiesArray, "client.uriOptions.timeoutMS", 75, isWindows() ? 1000 : 250); - findAndSetInt(definition.getArray("operations"), - "arguments.failPoint.data.blockTimeMS", 50, isWindows() ? 600 : 200); - }) - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for GridFS download operations", - "timeoutMS applied to entire download, not individual parts"); - - // Single-command GridFS CSOT tests: on Windows the tight 75ms budget is spent on connection setup before the - // command is sent (expected:<1> but was:<0>). Bump timeoutMS/blockTimeMS so the timeout triggers on the command. - def.transform("JAVA-6057: GridFS CSOT timeouts are too tight for the slower Windows TLS hosts, where the " - + "timeout elapses during connection establishment before the command under test is sent", - (entitiesArray, definition) -> { - findAndSetInt(entitiesArray, "client.uriOptions.timeoutMS", 75, 250); - findAndSetInt(definition.getArray("operations"), - "arguments.failPoint.data.blockTimeMS", 100, 400); - }) - .when(ClusterFixture::isWindows) - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for GridFS download operations", - "timeoutMS applied to find to get files document") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for GridFS download operations", - "timeoutMS applied to find to get chunks") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for GridFS delete operations", - "timeoutMS applied to delete against the files collection") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for GridFS delete operations", - "timeoutMS applied to delete against the chunks collection") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for advanced GridFS API operations", - "timeoutMS applied to update during a rename") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for advanced GridFS API operations", - "timeoutMS applied to files collection drop") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for advanced GridFS API operations", - "timeoutMS applied to chunks collection drop") - .test("client-side-operations-timeout", - "timeoutMS behaves correctly for GridFS find operations", - "timeoutMS applied to find command"); + def.skipDeprecated("CSOT is being removed") + .file("client-side-encryption/tests/unified", "timeoutMS"); // OpenTelemetry def.skipNoncompliantReactive("withTransaction is not supported in the reactive driver unified test runner") @@ -638,11 +405,7 @@ public static void applyCustomizations(final TestDef def) { def.modify(FORCE_FLAKY) .test("client-side-encryption", "rewrapManyDataKey", "rewrap with new local KMS provider") .test("client-side-encryption", "rewrapManyDataKey", "rewrap with new Azure KMS provider") - .test("client-side-encryption", "types", "type=symbol") - .test("client-side-operations-timeout", "retryability-timeoutMS", - "timeoutMS applies to whole operation, not individual attempts - deleteOne on collection") - .test("client-side-operations-timeout", "gridfs-find", - "timeoutMS behaves correctly for GridFS find operations"); + .test("client-side-encryption", "types", "type=symbol"); // Server problems def.skipJira("https://jira.mongodb.org/browse/JAVA-6342") @@ -718,58 +481,6 @@ static void raiseIntToFloor(final BsonArray array, final String path, final int } } - /** - * Unified analogue of {@link ClusterFixture#scaleForWindows(int)}: multiplies a test's CSOT knobs by - * {@code factor} — {@code client.uriOptions.timeoutMS} and the operations' {@code arguments.timeoutMS} / - * {@code arguments.failPoint.data.blockTimeMS} — preserving their ordering so a test that expects a specific - * command to time out still does. Use for timeout-expecting tests; success-only tests use {@link #raiseIntToFloor}. - * Fails if nothing was scaled, to catch spec drift. - */ - static void scaleForWindows(final BsonArray entitiesArray, final BsonDocument definition, final int factor) { - int changes = 0; - changes += multiplyInt(entitiesArray, "client.uriOptions.timeoutMS", factor); - BsonArray operations = definition.getArray("operations"); - changes += multiplyInt(operations, "arguments.timeoutMS", factor); - changes += multiplyInt(operations, "arguments.failPoint.data.blockTimeMS", factor); - if (changes == 0) { - throw new AssertionFailedError( - "scaleForWindows: no timeoutMS/blockTimeMS found to scale. Spec may have changed."); - } - } - - /** - * Walks {@code array} for the numeric leaf at the dot-separated {@code path} and multiplies each occurrence by - * {@code factor} (logging each change). Tolerates the path being absent. Returns the number of values changed. - */ - private static int multiplyInt(final BsonArray array, final String path, final int factor) { - String[] segments = path.split("\\."); - int count = 0; - for (BsonValue element : array) { - if (!element.isDocument()) { - continue; - } - BsonDocument current = element.asDocument(); - boolean found = true; - for (int i = 0; i < segments.length - 1; i++) { - if (current.containsKey(segments[i]) && current.get(segments[i]).isDocument()) { - current = current.getDocument(segments[i]); - } else { - found = false; - break; - } - } - String leafKey = segments[segments.length - 1]; - if (found && current.containsKey(leafKey) && current.get(leafKey).isNumber()) { - int oldValue = current.get(leafKey).asNumber().intValue(); - int newValue = oldValue * factor; - LOGGER.info(format(" %s: %d -> %d", path, oldValue, newValue)); - current.put(leafKey, new BsonInt32(newValue)); - count++; - } - } - return count; - } - /** * Variant of {@link #findAndSetInt(BsonArray, String, int, int)} that, when {@code required} is * {@code false}, tolerates the path being absent (no replacement made) instead of failing. Useful when a diff --git a/driver-sync/src/test/functional/com/mongodb/internal/connection/OidcAuthenticationProseTests.java b/driver-sync/src/test/functional/com/mongodb/internal/connection/OidcAuthenticationProseTests.java index c2d77da9570..d356f273fc3 100644 --- a/driver-sync/src/test/functional/com/mongodb/internal/connection/OidcAuthenticationProseTests.java +++ b/driver-sync/src/test/functional/com/mongodb/internal/connection/OidcAuthenticationProseTests.java @@ -16,7 +16,6 @@ package com.mongodb.internal.connection; -import com.mongodb.ClusterFixture; import com.mongodb.ConnectionString; import com.mongodb.MongoClientSettings; import com.mongodb.MongoCommandException; @@ -42,11 +41,7 @@ import org.bson.BsonString; import org.bson.Document; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; import java.io.IOException; import java.lang.reflect.Field; @@ -55,7 +50,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.time.Duration; -import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -64,11 +58,9 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import java.util.stream.Collectors; -import java.util.stream.Stream; import static com.mongodb.MongoCredential.ALLOWED_HOSTS_KEY; import static com.mongodb.MongoCredential.ENVIRONMENT_KEY; @@ -80,11 +72,9 @@ import static com.mongodb.MongoCredential.TOKEN_RESOURCE_KEY; import static com.mongodb.assertions.Assertions.assertNotNull; import static com.mongodb.testing.MongoAssertions.assertCause; -import static java.lang.String.format; import static java.lang.System.getenv; import static java.util.Arrays.asList; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -203,101 +193,6 @@ public void test2p1ValidCallbackInputs() { } } - // Not a prose test - @ParameterizedTest(name = "{0}. " - + "Parameters: timeoutMs={1}, " - + "serverSelectionTimeoutMS={2}," - + " expectedTimeoutThreshold={3}") - @MethodSource - void testValidCallbackInputsTimeoutWhenTimeoutMsIsSet(final String testName, - final long timeoutMs, - final long serverSelectionTimeoutMS, - final long expectedTimeoutThreshold) { - TestCallback callback1 = createCallback(); - - OidcCallback callback2 = (context) -> { - assertTrue(context.getTimeout().toMillis() < expectedTimeoutThreshold, - format("Expected timeout to be less than %d, but was %d", - expectedTimeoutThreshold, - context.getTimeout().toMillis())); - return callback1.onRequest(context); - }; - - MongoClientSettings clientSettings = MongoClientSettings.builder(createSettings(callback2)) - .applyToClusterSettings(builder -> - builder.serverSelectionTimeout( - serverSelectionTimeoutMS, - TimeUnit.MILLISECONDS)) - .timeout(timeoutMs, TimeUnit.MILLISECONDS) - .build(); - - try (MongoClient mongoClient = createMongoClient(clientSettings)) { - long start = System.nanoTime(); - performFind(mongoClient); - assertEquals(1, callback1.getInvocations()); - long elapsed = msElapsedSince(start); - - - assertFalse(elapsed > minTimeout(timeoutMs, serverSelectionTimeoutMS), - format("Elapsed time %d is greater then minimum of serverSelectionTimeoutMS and timeoutMs, which is %d. " - + "This indicates that the callback was not called with the expected timeout.", - elapsed, - minTimeout(timeoutMs, serverSelectionTimeoutMS))); - - } - } - - private static Stream testValidCallbackInputsTimeoutWhenTimeoutMsIsSet() { - long rtt = ClusterFixture.getPrimaryRTT(); - return Stream.of( - Arguments.of("serverSelectionTimeoutMS honored for oidc callback if it's lower than timeoutMS", - 1000 + rtt, // timeoutMS - 500 + rtt, // serverSelectionTimeoutMS - 499 + rtt), // expectedTimeoutThreshold - Arguments.of("timeoutMS honored for oidc callback if it's lower than serverSelectionTimeoutMS", - 500 + rtt, // timeoutMS - 1000 + rtt, // serverSelectionTimeoutMS - 499 + rtt), // expectedTimeoutThreshold - Arguments.of("timeoutMS honored for oidc callback if serverSelectionTimeoutMS is infinite", - 500 + rtt, // timeoutMS - -1, // serverSelectionTimeoutMS - 499 + rtt), // expectedTimeoutThreshold, - Arguments.of("serverSelectionTimeoutMS honored for oidc callback if timeoutMS=0", - 0, // infinite timeoutMS - 500 + rtt, // serverSelectionTimeoutMS - 499 + rtt) // expectedTimeoutThreshold - ); - } - - // Not a prose test - @Test - @DisplayName("test callback timeout when serverSelectionTimeoutMS and timeoutMS are infinite") - void testCallbackTimeoutWhenServerSelectionTimeoutMsIsInfiniteTimeoutMsIsSet() { - TestCallback callback1 = createCallback(); - Duration expectedTimeout = ChronoUnit.FOREVER.getDuration(); - - OidcCallback callback2 = (context) -> { - assertEquals(expectedTimeout, context.getTimeout(), - format("Expected timeout to be infinite (%s), but was %s", - expectedTimeout, context.getTimeout())); - - return callback1.onRequest(context); - }; - - MongoClientSettings clientSettings = MongoClientSettings.builder(createSettings(callback2)) - .applyToClusterSettings(builder -> - builder.serverSelectionTimeout( - -1, // -1 means infinite - TimeUnit.MILLISECONDS)) - .timeout(0, TimeUnit.MILLISECONDS) - .build(); - - try (MongoClient mongoClient = createMongoClient(clientSettings)) { - performFind(mongoClient); - assertEquals(1, callback1.getInvocations()); - } - } - @Test public void test2p2RequestCallbackReturnsNull() { //noinspection ConstantConditions @@ -1243,14 +1138,4 @@ public TestCallback createHumanCallback() { .setPathSupplier(() -> oidcTokenDirectory() + "test_user1") .setRefreshToken("refreshToken"); } - - private long msElapsedSince(final long timeOfStart) { - return TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - timeOfStart); - } - - private static long minTimeout(final long timeoutMs, final long serverSelectionTimeoutMS) { - long timeoutMsEffective = timeoutMs != 0 ? timeoutMs : Long.MAX_VALUE; - long serverSelectionTimeoutMSEffective = serverSelectionTimeoutMS != -1 ? serverSelectionTimeoutMS : Long.MAX_VALUE; - return Math.min(timeoutMsEffective, serverSelectionTimeoutMSEffective); - } } diff --git a/driver-sync/src/test/unit/com/mongodb/client/MongoClientSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/MongoClientSpecification.groovy index 6b9a1c1a7d8..20a0420291c 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/MongoClientSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/MongoClientSpecification.groovy @@ -62,7 +62,7 @@ import static spock.util.matcher.HamcrestSupport.expect class MongoClientSpecification extends Specification { private static final CodecRegistry CODEC_REGISTRY = fromProviders(new ValueCodecProvider()) - private static final TimeoutSettings TIMEOUT_SETTINGS = new TimeoutSettings(30_000, 10_000, 0, null, SECONDS.toMillis(120)) + private static final TimeoutSettings TIMEOUT_SETTINGS = new TimeoutSettings(30_000, 10_000, 0, SECONDS.toMillis(120)) def 'should pass the correct settings to getDatabase'() { given: diff --git a/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSBucketQueryFilterTest.java b/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSBucketQueryFilterTest.java index 4820d3caa12..bc61c75a01f 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSBucketQueryFilterTest.java +++ b/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSBucketQueryFilterTest.java @@ -36,7 +36,6 @@ import org.mockito.ArgumentCaptor; import java.util.Date; -import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -66,10 +65,6 @@ private static Stream ids() { @BeforeEach void setUp() { - // Mockito answers 0L rather than null for the Long-returning getTimeout, which would make the bucket apply a 0ms timeout. - when(filesCollection.getTimeout(any(TimeUnit.class))).thenReturn(null); - when(chunksCollection.getTimeout(any(TimeUnit.class))).thenReturn(null); - when(filesCollection.deleteOne(any(Bson.class))).thenReturn(DeleteResult.acknowledged(1)); when(filesCollection.deleteOne(any(ClientSession.class), any(Bson.class))).thenReturn(DeleteResult.acknowledged(1)); } @@ -121,7 +116,7 @@ void openDownloadStreamUsesEqualityFilter(final BsonValue id) { @MethodSource("ids") void abortUsesEqualityFilter(final BsonValue id) { GridFSUploadStream uploadStream = new GridFSUploadStreamImpl(null, filesCollection, chunksCollection, id, "filename", 255, - null, null); + null); uploadStream.abort(); diff --git a/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSBucketSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSBucketSpecification.groovy index 8bcee27e6f5..de55ca27fb5 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSBucketSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSBucketSpecification.groovy @@ -47,8 +47,6 @@ import org.bson.types.ObjectId import spock.lang.Specification import spock.lang.Unroll -import java.util.concurrent.TimeUnit - import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS import static com.mongodb.CustomMatchers.isTheSameAs import static com.mongodb.ReadPreference.primary @@ -161,7 +159,7 @@ class GridFSBucketSpecification extends Specification { def defaultChunkSizeBytes = 255 * 1024 def database = new MongoDatabaseImpl('test', fromProviders(new DocumentCodecProvider()), secondary(), WriteConcern.ACKNOWLEDGED, false, false, null, readConcern, JAVA_LEGACY, null, - new TimeoutSettings(0, 0, 0, null, 0), + new TimeoutSettings(0, 0, 0, 0), new TestOperationExecutor([])) when: @@ -178,8 +176,6 @@ class GridFSBucketSpecification extends Specification { given: def filesCollection = Stub(MongoCollection) def chunksCollection = Stub(MongoCollection) - filesCollection.getTimeout(TimeUnit.MILLISECONDS) >> null - chunksCollection.getTimeout(TimeUnit.MILLISECONDS) >> null def gridFSBucket = new GridFSBucketImpl('fs', 255, filesCollection, chunksCollection) @@ -193,7 +189,7 @@ class GridFSBucketSpecification extends Specification { then: expect stream, isTheSameAs(new GridFSUploadStreamImpl(clientSession, filesCollection, chunksCollection, stream.getId(), 'filename', - 255, null, null), ['closeLock']) + 255, null), ['closeLock']) where: clientSession << [null, Stub(ClientSession)] @@ -300,9 +296,7 @@ class GridFSBucketSpecification extends Specification { def fileInfo = new GridFSFile(fileId, 'File 1', 10, 255, new Date(), new Document()) def findIterable = Mock(FindIterable) def filesCollection = Mock(MongoCollection) - filesCollection.getTimeout(TimeUnit.MILLISECONDS) >> null def chunksCollection = Stub(MongoCollection) - chunksCollection.getTimeout(TimeUnit.MILLISECONDS) >> null def gridFSBucket = new GridFSBucketImpl('fs', 255, filesCollection, chunksCollection) when: @@ -323,8 +317,8 @@ class GridFSBucketSpecification extends Specification { 1 * findIterable.first() >> fileInfo then: - expect stream, isTheSameAs(new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection, - null), ['closeLock', 'cursorLock']) + expect stream, isTheSameAs(new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection + ), ['closeLock', 'cursorLock']) where: @@ -534,9 +528,7 @@ class GridFSBucketSpecification extends Specification { def fileInfo = new GridFSFile(bsonFileId, filename, 10, 255, new Date(), new Document()) def findIterable = Mock(FindIterable) def filesCollection = Mock(MongoCollection) - filesCollection.getTimeout(TimeUnit.MILLISECONDS) >> null def chunksCollection = Stub(MongoCollection) - chunksCollection.getTimeout(TimeUnit.MILLISECONDS) >> null def gridFSBucket = new GridFSBucketImpl('fs', 255, filesCollection, chunksCollection) when: @@ -554,7 +546,7 @@ class GridFSBucketSpecification extends Specification { 1 * findIterable.first() >> fileInfo then: - expect stream, isTheSameAs(new GridFSDownloadStreamImpl(null, fileInfo, chunksCollection, null), ['closeLock', 'cursorLock']) + expect stream, isTheSameAs(new GridFSDownloadStreamImpl(null, fileInfo, chunksCollection), ['closeLock', 'cursorLock']) where: version | skip | sortOrder diff --git a/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSDownloadStreamSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSDownloadStreamSpecification.groovy index 5ecc2f2cd3d..54dacc97acc 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSDownloadStreamSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSDownloadStreamSpecification.groovy @@ -35,7 +35,7 @@ class GridFSDownloadStreamSpecification extends Specification { def 'should return the file info'() { when: - def downloadStream = new GridFSDownloadStreamImpl(null, fileInfo, Stub(MongoCollection), null) + def downloadStream = new GridFSDownloadStreamImpl(null, fileInfo, Stub(MongoCollection)) then: downloadStream.getGridFSFile() == fileInfo @@ -59,7 +59,7 @@ class GridFSDownloadStreamSpecification extends Specification { def mongoCursor = Mock(MongoCursor) def findIterable = Mock(FindIterable) def chunksCollection = Mock(MongoCollection) - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection, null) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection) then: downloadStream.available() == 0 @@ -132,8 +132,8 @@ class GridFSDownloadStreamSpecification extends Specification { def mongoCursor = Mock(MongoCursor) def findIterable = Mock(FindIterable) def chunksCollection = Mock(MongoCollection) - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection, - null).batchSize(1) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection) + .batchSize(1) then: downloadStream.available() == 0 @@ -216,7 +216,7 @@ class GridFSDownloadStreamSpecification extends Specification { def mongoCursor = Mock(MongoCursor) def findIterable = Mock(FindIterable) def chunksCollection = Mock(MongoCollection) - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection, null) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection) when: def skipResult = downloadStream.skip(15) @@ -294,7 +294,7 @@ class GridFSDownloadStreamSpecification extends Specification { def mongoCursor = Mock(MongoCursor) def findIterable = Mock(FindIterable) def chunksCollection = Mock(MongoCollection) - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection, null) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection) when: def readByte = new byte[10] @@ -363,7 +363,7 @@ class GridFSDownloadStreamSpecification extends Specification { def mongoCursor = Mock(MongoCursor) def findIterable = Mock(FindIterable) def chunksCollection = Mock(MongoCollection) - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection, null) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection) when: downloadStream.mark() @@ -440,7 +440,7 @@ class GridFSDownloadStreamSpecification extends Specification { def mongoCursor = Mock(MongoCursor) def findIterable = Mock(FindIterable) def chunksCollection = Mock(MongoCollection) - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection, null) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection) when: def readByte = new byte[25] @@ -497,7 +497,7 @@ class GridFSDownloadStreamSpecification extends Specification { def 'should not throw an exception when trying to mark post close'() { given: - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, Stub(MongoCollection), null) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, Stub(MongoCollection)) downloadStream.close() when: @@ -518,7 +518,7 @@ class GridFSDownloadStreamSpecification extends Specification { def 'should handle negative skip value correctly '() { given: - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, Stub(MongoCollection), null) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, Stub(MongoCollection)) when: def result = downloadStream.skip(-1) @@ -533,7 +533,7 @@ class GridFSDownloadStreamSpecification extends Specification { def 'should handle skip that is larger or equal to the file length'() { given: def chunksCollection = Mock(MongoCollection) - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection, null) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection) when: def result = downloadStream.skip(skipValue) @@ -554,7 +554,7 @@ class GridFSDownloadStreamSpecification extends Specification { def 'should throw if trying to pass negative batchSize'() { given: - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, Stub(MongoCollection), null) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, Stub(MongoCollection)) when: downloadStream.batchSize(0) @@ -578,7 +578,7 @@ class GridFSDownloadStreamSpecification extends Specification { def mongoCursor = Mock(MongoCursor) def findIterable = Mock(FindIterable) def chunksCollection = Mock(MongoCollection) - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection, null) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection) when: downloadStream.read() @@ -610,7 +610,7 @@ class GridFSDownloadStreamSpecification extends Specification { def mongoCursor = Mock(MongoCursor) def findIterable = Mock(FindIterable) def chunksCollection = Mock(MongoCollection) - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection, null) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, chunksCollection) when: downloadStream.read() @@ -636,7 +636,7 @@ class GridFSDownloadStreamSpecification extends Specification { def 'should throw an exception when trying to action post close'() { given: - def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, Stub(MongoCollection), null) + def downloadStream = new GridFSDownloadStreamImpl(clientSession, fileInfo, Stub(MongoCollection)) downloadStream.close() when: diff --git a/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSUploadStreamSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSUploadStreamSpecification.groovy index de1e19c43eb..a19777fc962 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSUploadStreamSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/gridfs/GridFSUploadStreamSpecification.groovy @@ -35,7 +35,7 @@ class GridFSUploadStreamSpecification extends Specification { def 'should return the file id'() { when: def uploadStream = new GridFSUploadStreamImpl(null, Stub(MongoCollection), Stub(MongoCollection), fileId, filename, 255 - , metadata, null) + , metadata) then: uploadStream.getId() == fileId } @@ -45,7 +45,7 @@ class GridFSUploadStreamSpecification extends Specification { def filesCollection = Mock(MongoCollection) def chunksCollection = Mock(MongoCollection) def uploadStream = new GridFSUploadStreamImpl(clientSession, filesCollection, chunksCollection, fileId, filename, 2 - , metadata, null) + , metadata) when: uploadStream.write(1) @@ -71,7 +71,7 @@ class GridFSUploadStreamSpecification extends Specification { def filesCollection = Mock(MongoCollection) def chunksCollection = Mock(MongoCollection) def uploadStream = new GridFSUploadStreamImpl(clientSession, filesCollection, chunksCollection, fileId, filename, 255 - , null, null) + , null) when: uploadStream.write('file content ' as byte[]) @@ -102,7 +102,7 @@ class GridFSUploadStreamSpecification extends Specification { def content = 'file content ' as byte[] def metadata = new Document('contentType', 'text/txt') def uploadStream = new GridFSUploadStreamImpl(clientSession, filesCollection, chunksCollection, fileId, filename, 255, - metadata, null) + metadata) def filesId = fileId when: @@ -160,7 +160,7 @@ class GridFSUploadStreamSpecification extends Specification { def filesCollection = Mock(MongoCollection) def chunksCollection = Mock(MongoCollection) def uploadStream = new GridFSUploadStreamImpl(clientSession, filesCollection, chunksCollection, fileId, filename, 255 - , metadata, null) + , metadata) when: uploadStream.close() @@ -180,7 +180,7 @@ class GridFSUploadStreamSpecification extends Specification { given: def chunksCollection = Mock(MongoCollection) def uploadStream = new GridFSUploadStreamImpl(clientSession, Stub(MongoCollection), chunksCollection, fileId, filename, 255 - , metadata, null) + , metadata) when: uploadStream.write('file content ' as byte[]) @@ -200,7 +200,7 @@ class GridFSUploadStreamSpecification extends Specification { def 'should close the stream on abort'() { given: def uploadStream = new GridFSUploadStreamImpl(clientSession, Stub(MongoCollection), Stub(MongoCollection), fileId, filename, 255 - , metadata, null) + , metadata) uploadStream.write('file content ' as byte[]) uploadStream.abort() @@ -218,7 +218,7 @@ class GridFSUploadStreamSpecification extends Specification { given: def chunksCollection = Mock(MongoCollection) def uploadStream = new GridFSUploadStreamImpl(clientSession, Stub(MongoCollection), chunksCollection, fileId, filename, 255 - , metadata, null) + , metadata) when: uploadStream.write('file content ' as byte[]) @@ -236,7 +236,7 @@ class GridFSUploadStreamSpecification extends Specification { def filesCollection = Mock(MongoCollection) def chunksCollection = Mock(MongoCollection) def uploadStream = new GridFSUploadStreamImpl(clientSession, filesCollection, chunksCollection, fileId, filename, 255 - , metadata, null) + , metadata) when: uploadStream.close() uploadStream.write(1) @@ -254,7 +254,7 @@ class GridFSUploadStreamSpecification extends Specification { def filesCollection = Mock(MongoCollection) def chunksCollection = Mock(MongoCollection) def uploadStream = new GridFSUploadStreamImpl(clientSession, filesCollection, chunksCollection, fileId, filename, 255 - , metadata, null) + , metadata) when: uploadStream.getObjectId() 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 3ec9a889e29..fe86ae67b60 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 @@ -29,7 +29,6 @@ import com.mongodb.internal.bulk.WriteRequestWithIndex import com.mongodb.internal.connection.Connection import com.mongodb.internal.connection.MessageSequences import com.mongodb.internal.connection.SplittablePayload -import com.mongodb.internal.time.Timeout import com.mongodb.internal.validator.NoOpFieldNameValidator import org.bson.BsonArray import org.bson.BsonBinary @@ -62,8 +61,6 @@ class CryptConnectionSpecification extends Specification { def codec = new DocumentCodec() def timeoutContext = Mock(TimeoutContext) def operationContext = ClusterFixture.createOperationContext().withTimeoutContext(timeoutContext) - def operationTimeout = Mock(Timeout) - timeoutContext.getTimeout() >> operationTimeout def encryptedCommand = toRaw(new BsonDocument('find', new BsonString('test')) .append('ssid', new BsonBinary(6 as byte, new byte[10]))) @@ -93,14 +90,14 @@ class CryptConnectionSpecification extends Specification { 1000, 1024 * 16_000, 1024 * 48_000, []) } 1 * crypt.encrypt('db', toRaw(new BsonDocument('find', new BsonString('test')) - .append('filter', new BsonDocument('ssid', new BsonString('555-55-5555')))), operationTimeout) >> { + .append('filter', new BsonDocument('ssid', new BsonString('555-55-5555'))))) >> { encryptedCommand } 1 * wrappedConnection.command('db', encryptedCommand, _ as NoOpFieldNameValidator, ReadPreference.primary(), _ as RawBsonDocumentCodec, operationContext, true, MessageSequences.EmptyMessageSequences.INSTANCE) >> { encryptedResponse } - 1 * crypt.decrypt(encryptedResponse, operationTimeout) >> { + 1 * crypt.decrypt(encryptedResponse) >> { decryptedResponse } response == rawToDocument(decryptedResponse) @@ -128,8 +125,6 @@ class CryptConnectionSpecification extends Specification { def decryptedResponse = encryptedResponse def timeoutContext = Mock(TimeoutContext) def operationContext = ClusterFixture.createOperationContext().withTimeoutContext(timeoutContext) - def operationTimeout = Mock(Timeout) - timeoutContext.getTimeout() >> operationTimeout when: def response = cryptConnection.command('db', @@ -147,14 +142,14 @@ class CryptConnectionSpecification extends Specification { new BsonDocument('_id', new BsonInt32(1)) .append('ssid', new BsonString('555-55-5555')) .append('b', new BsonBinary(bytes)) - ]))), operationTimeout) >> { + ])))) >> { encryptedCommand } 1 * wrappedConnection.command('db', encryptedCommand, _ as NoOpFieldNameValidator, ReadPreference.primary(), _ as RawBsonDocumentCodec, operationContext, true, MessageSequences.EmptyMessageSequences.INSTANCE) >> { encryptedResponse } - 1 * crypt.decrypt(encryptedResponse, operationTimeout) >> { + 1 * crypt.decrypt(encryptedResponse) >> { decryptedResponse } response == rawToBsonDocument(decryptedResponse) @@ -184,8 +179,6 @@ class CryptConnectionSpecification extends Specification { def decryptedResponse = encryptedResponse def timeoutContext = Mock(TimeoutContext) def operationContext = ClusterFixture.createOperationContext().withTimeoutContext(timeoutContext) - def operationTimeout = Mock(Timeout) - timeoutContext.getTimeout() >> operationTimeout when: def response = cryptConnection.command('db', @@ -202,14 +195,14 @@ class CryptConnectionSpecification extends Specification { new BsonArray([ new BsonDocument('_id', new BsonInt32(1)), new BsonDocument('_id', new BsonInt32(2)) - ]))), operationTimeout) >> { + ])))) >> { encryptedCommand } 1 * wrappedConnection.command('db', encryptedCommand, _ as NoOpFieldNameValidator, ReadPreference.primary(), _ as RawBsonDocumentCodec, operationContext, true, MessageSequences.EmptyMessageSequences.INSTANCE) >> { encryptedResponse } - 1 * crypt.decrypt(encryptedResponse, operationTimeout) >> { + 1 * crypt.decrypt(encryptedResponse) >> { decryptedResponse } response == rawToBsonDocument(decryptedResponse) diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/KeyManagementServiceTest.java b/driver-sync/src/test/unit/com/mongodb/client/internal/KeyManagementServiceTest.java deleted file mode 100644 index 38b74035f40..00000000000 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/KeyManagementServiceTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.client.internal; - -import com.mongodb.MongoOperationTimeoutException; -import com.mongodb.internal.time.Timeout; -import org.junit.jupiter.api.Test; - -import static com.mongodb.internal.time.Timeout.ZeroSemantics.ZERO_DURATION_MEANS_EXPIRED; -import static java.util.Collections.emptyMap; -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -/** - * The specification requires that a driver supporting CSOT pass the remaining {@code timeoutMS} when establishing a - * connection to a KMS host. Prose test 28 asserts this by observing a {@code kmsConnectCallback}; this covers the same - * requirement directly, including the branches that prose test does not reach. - */ -final class KeyManagementServiceTest { - - private static final int CONNECT_TIMEOUT_MILLIS = 10_000; - - private final KeyManagementService keyManagementService = - new KeyManagementService(emptyMap(), null, CONNECT_TIMEOUT_MILLIS); - - @Test - void shouldUseConfiguredConnectTimeoutWhenNoOperationTimeoutApplies() { - assertEquals(CONNECT_TIMEOUT_MILLIS, keyManagementService.remainingMillis(null)); - } - - @Test - void shouldPassRemainingOperationTimeoutWhenItIsShorter() { - Timeout operationTimeout = Timeout.expiresIn(500, MILLISECONDS, ZERO_DURATION_MEANS_EXPIRED); - - long remaining = keyManagementService.remainingMillis(operationTimeout); - - assertTrue(remaining > 0 && remaining <= 500, - () -> "expected the remaining operation timeout to be passed, but got " + remaining); - } - - @Test - void shouldNotExceedConfiguredConnectTimeoutWhenOperationTimeoutIsLonger() { - Timeout operationTimeout = Timeout.expiresIn(60_000, MILLISECONDS, ZERO_DURATION_MEANS_EXPIRED); - - assertEquals(CONNECT_TIMEOUT_MILLIS, keyManagementService.remainingMillis(operationTimeout)); - } - - @Test - void shouldThrowWhenOperationTimeoutHasExpired() { - Timeout expired = Timeout.expiresIn(0, MILLISECONDS, ZERO_DURATION_MEANS_EXPIRED); - - assertThrows(MongoOperationTimeoutException.class, () -> keyManagementService.remainingMillis(expired)); - } -} diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoClusterSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoClusterSpecification.groovy index 77464fa0183..8a2e40f5a06 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoClusterSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoClusterSpecification.groovy @@ -37,8 +37,6 @@ import org.bson.codecs.ValueCodecProvider import org.bson.codecs.configuration.CodecRegistry import spock.lang.Specification -import java.util.concurrent.TimeUnit - import static com.mongodb.CustomMatchers.isTheSameAs import static com.mongodb.MongoClientSettings.getDefaultCodecRegistry import static com.mongodb.ReadPreference.primary @@ -134,23 +132,6 @@ class MongoClusterSpecification extends Specification { MongoClientSettings.builder(CLIENT_SETTINGS).readConcern(newReadConcern).build())) } - def 'should behave correctly when using withTimeout'() { - when: - def mongoCluster = createMongoCluster().withTimeout(10_000, TimeUnit.MILLISECONDS) - - then: - mongoCluster.getTimeout(TimeUnit.MILLISECONDS) == 10_000 - expect mongoCluster, isTheSameAs(createMongoCluster(MongoClientSettings.builder(CLIENT_SETTINGS) - .timeout(10_000, TimeUnit.MILLISECONDS).build())) - - when: - createMongoCluster().withTimeout(500, TimeUnit.NANOSECONDS) - - then: - thrown(IllegalArgumentException) - } - - def 'should use ListDatabasesIterableImpl correctly'() { given: def executor = new TestOperationExecutor([null, null]) diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionSpecification.groovy index 69aedcd4790..670a5a89929 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionSpecification.groovy @@ -204,27 +204,6 @@ class MongoCollectionSpecification extends Specification { true, true, null, newReadConcern, JAVA_LEGACY, null, TIMEOUT_SETTINGS, executor)) } - def 'should behave correctly when using withTimeout'() { - given: - def executor = new TestOperationExecutor([]) - def collection = new MongoCollectionImpl(namespace, Document, codecRegistry, readPreference, ACKNOWLEDGED, - true, true, null, readConcern, JAVA_LEGACY, null, TIMEOUT_SETTINGS, executor) - - when: - def newCollection = collection.withTimeout(10_000, MILLISECONDS) - - then: - newCollection.getTimeout(MILLISECONDS) == 10_000 - expect newCollection, isTheSameAs(new MongoCollectionImpl(namespace, Document, codecRegistry, readPreference, ACKNOWLEDGED, - true, true, null, readConcern, JAVA_LEGACY, null, TIMEOUT_SETTINGS.withTimeout(10_000, MILLISECONDS), executor)) - - when: - collection.withTimeout(500, TimeUnit.NANOSECONDS) - - then: - thrown(IllegalArgumentException) - } - def 'should use CountOperation correctly with documentCount'() { given: def executor = new TestOperationExecutor([1L, 2L, 3L, 4L]) diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoDatabaseSpecification.groovy b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoDatabaseSpecification.groovy index 4e8ac62d8cb..8bdfe10baa5 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoDatabaseSpecification.groovy +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoDatabaseSpecification.groovy @@ -44,8 +44,6 @@ import org.bson.codecs.UuidCodec import org.bson.codecs.ValueCodecProvider import spock.lang.Specification -import java.util.concurrent.TimeUnit - import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS import static com.mongodb.CustomMatchers.isTheSameAs import static com.mongodb.ReadPreference.primary @@ -161,27 +159,6 @@ class MongoDatabaseSpecification extends Specification { newReadConcern, JAVA_LEGACY, null, TIMEOUT_SETTINGS, executor)) } - def 'should behave correctly when using withTimeout'() { - given: - def executor = new TestOperationExecutor([]) - def database = new MongoDatabaseImpl(name, codecRegistry, readPreference, writeConcern, false, false, null, - readConcern, JAVA_LEGACY, null, TIMEOUT_SETTINGS, executor) - - when: - def newDatabase = database.withTimeout(10_000, TimeUnit.MILLISECONDS) - - then: - newDatabase.getTimeout(TimeUnit.MILLISECONDS) == 10_000 - expect newDatabase, isTheSameAs(new MongoDatabaseImpl(name, codecRegistry, readPreference, writeConcern, false, false, null, - readConcern, JAVA_LEGACY, null, TIMEOUT_SETTINGS.withTimeout(10_000, TimeUnit.MILLISECONDS), executor)) - - when: - database.withTimeout(500, TimeUnit.NANOSECONDS) - - then: - thrown(IllegalArgumentException) - } - def 'should be able to executeCommand correctly'() { given: def command = new BsonDocument('command', new BsonInt32(1)) diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/TimeoutHelperTest.java b/driver-sync/src/test/unit/com/mongodb/client/internal/TimeoutHelperTest.java deleted file mode 100644 index c3569624414..00000000000 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/TimeoutHelperTest.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright 2008-present MongoDB, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.mongodb.client.internal; - -import com.mongodb.MongoOperationTimeoutException; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.internal.time.Timeout; -import org.bson.Document; -import org.junit.jupiter.api.Test; - -import java.util.concurrent.TimeUnit; - -import static com.mongodb.client.internal.TimeoutHelper.collectionWithTimeout; -import static com.mongodb.client.internal.TimeoutHelper.databaseWithTimeout; -import static com.mongodb.internal.mockito.MongoMockito.mock; -import static com.mongodb.internal.time.Timeout.ZeroSemantics.ZERO_DURATION_MEANS_EXPIRED; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.longThat; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -@SuppressWarnings("unchecked") -class TimeoutHelperTest { - - private static final String TIMEOUT_ERROR_MESSAGE = "message"; - - @Test - void shouldNotSetRemainingTimeoutOnCollectionWhenTimeoutIsNull() { - //given - MongoCollection collection = mock(MongoCollection.class); - - //when - MongoCollection result = collectionWithTimeout(collection, TIMEOUT_ERROR_MESSAGE, null); - - //then - assertEquals(collection, result); - } - - @Test - void shouldNotSetRemainingTimeoutDatabaseWhenTimeoutIsNull() { - //given - MongoDatabase database = mock(MongoDatabase.class); - - //when - MongoDatabase result = databaseWithTimeout(database, TIMEOUT_ERROR_MESSAGE, null); - - //then - assertEquals(database, result); - } - - @Test - void shouldSetRemainingTimeoutOnCollectionWhenTimeoutIsInfinite() { - //given - MongoCollection collectionWithTimeout = mock(MongoCollection.class); - MongoCollection collection = mock(MongoCollection.class, mongoCollection -> { - when(mongoCollection.withTimeout(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(collectionWithTimeout); - }); - - //when - MongoCollection result = collectionWithTimeout(collection, TIMEOUT_ERROR_MESSAGE, Timeout.infinite()); - - //then - assertEquals(collectionWithTimeout, result); - verify(collection).withTimeout(0L, TimeUnit.MILLISECONDS); - } - - @Test - void shouldNotSetRemainingTimeoutOnDatabaseWhenTimeoutIsInfinite() { - //given - MongoDatabase databaseWithTimeout = mock(MongoDatabase.class); - MongoDatabase database = mock(MongoDatabase.class, mongoDatabase -> { - when(mongoDatabase.withTimeout(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(databaseWithTimeout); - }); - - //when - MongoDatabase result = databaseWithTimeout(database, TIMEOUT_ERROR_MESSAGE, Timeout.infinite()); - - //then - assertEquals(databaseWithTimeout, result); - verify(database).withTimeout(0L, TimeUnit.MILLISECONDS); - } - - @Test - void shouldSetRemainingTimeoutOnCollectionWhenTimeout() { - //given - MongoCollection collectionWithTimeout = mock(MongoCollection.class); - MongoCollection collection = mock(MongoCollection.class, mongoCollection -> { - when(mongoCollection.withTimeout(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(collectionWithTimeout); - }); - Timeout timeout = Timeout.expiresIn(1, TimeUnit.DAYS, ZERO_DURATION_MEANS_EXPIRED); - - //when - MongoCollection result = collectionWithTimeout(collection, TIMEOUT_ERROR_MESSAGE, timeout); - - //then - verify(collection).withTimeout(longThat(remaining -> remaining > 0), eq(TimeUnit.MILLISECONDS)); - assertEquals(collectionWithTimeout, result); - } - - @Test - void shouldSetRemainingTimeoutOnDatabaseWhenTimeout() { - //given - MongoDatabase databaseWithTimeout = mock(MongoDatabase.class); - MongoDatabase database = mock(MongoDatabase.class, mongoDatabase -> { - when(mongoDatabase.withTimeout(anyLong(), eq(TimeUnit.MILLISECONDS))).thenReturn(databaseWithTimeout); - }); - Timeout timeout = Timeout.expiresIn(1, TimeUnit.DAYS, ZERO_DURATION_MEANS_EXPIRED); - - //when - MongoDatabase result = databaseWithTimeout(database, TIMEOUT_ERROR_MESSAGE, timeout); - - //then - verify(database).withTimeout(longThat(remaining -> remaining > 0), eq(TimeUnit.MILLISECONDS)); - assertEquals(databaseWithTimeout, result); - } - - @Test - void shouldThrowErrorWhenTimeoutHasExpiredOnCollection() { - //given - MongoCollection collection = mock(MongoCollection.class); - Timeout timeout = Timeout.expiresIn(1, TimeUnit.MICROSECONDS, ZERO_DURATION_MEANS_EXPIRED); - - //when - MongoOperationTimeoutException mongoExecutionTimeoutException = - assertThrows(MongoOperationTimeoutException.class, () -> collectionWithTimeout(collection, TIMEOUT_ERROR_MESSAGE, timeout)); - - //then - assertEquals(TIMEOUT_ERROR_MESSAGE, mongoExecutionTimeoutException.getMessage()); - verifyNoInteractions(collection); - } - - @Test - void shouldThrowErrorWhenTimeoutHasExpiredOnDatabase() { - //given - MongoDatabase database = mock(MongoDatabase.class); - Timeout timeout = Timeout.expiresIn(1, TimeUnit.MICROSECONDS, ZERO_DURATION_MEANS_EXPIRED); - - //when - MongoOperationTimeoutException mongoExecutionTimeoutException = - assertThrows(MongoOperationTimeoutException.class, () -> databaseWithTimeout(database, TIMEOUT_ERROR_MESSAGE, timeout)); - - //then - assertEquals(TIMEOUT_ERROR_MESSAGE, mongoExecutionTimeoutException.getMessage()); - verifyNoInteractions(database); - } - - @Test - void shouldThrowErrorWhenTimeoutHasExpiredWithZeroRemainingOnCollection() { - //given - MongoCollection collection = mock(MongoCollection.class); - Timeout timeout = Timeout.expiresIn(0, TimeUnit.NANOSECONDS, ZERO_DURATION_MEANS_EXPIRED); - - //when - assertThrows(MongoOperationTimeoutException.class, () -> collectionWithTimeout(collection, TIMEOUT_ERROR_MESSAGE, timeout)); - - //then - - } - - @Test - void shouldThrowErrorWhenTimeoutHasExpiredWithZeroRemainingOnDatabase() { - //given - MongoDatabase database = mock(MongoDatabase.class); - Timeout timeout = Timeout.expiresIn(0, TimeUnit.NANOSECONDS, ZERO_DURATION_MEANS_EXPIRED); - - //when - assertThrows(MongoOperationTimeoutException.class, () -> databaseWithTimeout(database, TIMEOUT_ERROR_MESSAGE, timeout)); - - //then - verifyNoInteractions(database); - } - -}