From de8c0ce0934937aca282627f5a17444a62e0b89c Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Tue, 27 May 2025 11:18:50 -0700 Subject: [PATCH 01/13] CSHARP-3550: CSOT: Server Selection --- .../Core/Bindings/ChannelChannelSource.cs | 5 +- .../Core/Bindings/ChannelReadBinding.cs | 13 +- .../Core/Bindings/ChannelReadWriteBinding.cs | 41 ++- .../Core/Bindings/ChannelSourceHandle.cs | 9 +- .../Bindings/ChannelSourceReadWriteBinding.cs | 41 ++- .../Core/Bindings/CoreSession.cs | 34 ++- src/MongoDB.Driver/Core/Bindings/IBinding.cs | 24 +- .../Core/Bindings/IChannelSource.cs | 5 +- .../Core/Bindings/ReadBindingHandle.cs | 17 +- .../Core/Bindings/ReadPreferenceBinding.cs | 17 +- .../Core/Bindings/ReadWriteBindingHandle.cs | 49 ++-- .../Core/Bindings/ServerChannelSource.cs | 9 +- .../Core/Bindings/SingleServerReadBinding.cs | 12 +- .../Bindings/SingleServerReadWriteBinding.cs | 41 ++- .../Core/Bindings/WritableServerBinding.cs | 49 ++-- src/MongoDB.Driver/Core/Clusters/Cluster.cs | 164 +++-------- src/MongoDB.Driver/Core/Clusters/ICluster.cs | 5 +- .../Core/Clusters/IClusterExtensions.cs | 9 +- .../Core/Clusters/LoadBalancedCluster.cs | 33 ++- .../ExclusiveConnectionPool.Helpers.cs | 163 +++++------ .../ExclusiveConnectionPool.cs | 11 +- .../Core/ConnectionPools/IConnectionPool.cs | 5 +- .../Core/ConnectionPools/MaintenanceHelper.cs | 9 +- src/MongoDB.Driver/Core/Misc/Feature.cs | 12 +- .../Core/Operations/AggregateOperation.cs | 21 +- .../AggregateToCollectionOperation.cs | 17 +- .../Core/Operations/AsyncCursor.cs | 18 +- .../Operations/BulkMixedWriteOperation.cs | 21 +- .../BulkUnmixedWriteOperationBase.cs | 37 ++- .../Core/Operations/ChangeStreamCursor.cs | 8 +- .../Core/Operations/ChangeStreamOperation.cs | 37 ++- .../Operations/ClientBulkWriteOperation.cs | 17 +- .../Core/Operations/CommandOperationBase.cs | 12 +- .../Operations/CompositeWriteOperation.cs | 9 +- .../Operations/CountDocumentsOperation.cs | 13 +- .../Core/Operations/CountOperation.cs | 21 +- .../Operations/CreateCollectionOperation.cs | 17 +- .../Core/Operations/CreateIndexesOperation.cs | 17 +- .../CreateSearchIndexesOperation.cs | 17 +- .../Core/Operations/CreateViewOperation.cs | 16 +- .../Operations/DatabaseExistsOperation.cs | 15 +- .../Core/Operations/DistinctOperation.cs | 13 +- .../Operations/DropCollectionOperation.cs | 17 +- .../Core/Operations/DropDatabaseOperation.cs | 21 +- .../Core/Operations/DropIndexOperation.cs | 19 +- .../Operations/DropSearchIndexOperation.cs | 17 +- .../Operations/EndTransactionOperation.cs | 25 +- .../EstimatedDocumentCountOperation.cs | 13 +- .../Core/Operations/EvalOperation.cs | 13 +- .../Operations/FindAndModifyOperationBase.cs | 35 ++- .../Core/Operations/FindOperation.cs | 21 +- .../Core/Operations/GroupOperation.cs | 17 +- .../Core/Operations/IOperation.cs | 9 +- .../Core/Operations/IRetryableOperation.cs | 17 +- .../Operations/ListCollectionsOperation.cs | 21 +- .../Core/Operations/ListDatabasesOperation.cs | 13 +- .../Core/Operations/ListIndexesOperation.cs | 13 +- .../ListIndexesUsingCommandOperation.cs | 21 +- .../Core/Operations/MapReduceOperation.cs | 17 +- .../MapReduceOutputToCollectionOperation.cs | 17 +- .../Operations/OperationExtensionMethods.cs | 17 +- .../Core/Operations/PingOperation.cs | 71 ----- .../Core/Operations/ReadCommandOperation.cs | 29 +- .../Operations/RenameCollectionOperation.cs | 21 +- .../Core/Operations/RetryableReadContext.cs | 29 +- .../RetryableReadOperationExecutor.cs | 37 ++- .../RetryableWriteCommandOperationBase.cs | 33 ++- .../Core/Operations/RetryableWriteContext.cs | 29 +- .../RetryableWriteOperationExecutor.cs | 37 ++- .../Operations/UpdateSearchIndexOperation.cs | 17 +- .../Core/Operations/WriteCommandOperation.cs | 13 +- src/MongoDB.Driver/Core/Servers/IServer.cs | 4 +- src/MongoDB.Driver/Core/Servers/Server.cs | 8 +- src/MongoDB.Driver/GridFS/GridFSBucket.cs | 272 +++++++++++------- .../GridFS/GridFSForwardOnlyDownloadStream.cs | 8 +- .../GridFS/GridFSForwardOnlyUploadStream.cs | 8 +- .../GridFS/GridFSSeekableDownloadStream.cs | 10 +- src/MongoDB.Driver/MongoClient.cs | 5 +- src/MongoDB.Driver/MongoCollectionImpl.cs | 5 +- src/MongoDB.Driver/MongoDatabase.cs | 6 +- .../OperationCancellationContext.cs | 122 ++++++++ src/MongoDB.Driver/OperationExecutor.cs | 12 +- src/MongoDB.Driver/OperationOptionsBase.cs | 27 ++ src/MongoDB.Driver/ReadOperationOptions.cs | 5 +- src/MongoDB.Driver/WriteOperationOptions.cs | 5 +- .../Core/CoreTestConfiguration.cs | 12 +- .../Core/FailPoint.cs | 4 +- .../Core/MockClusterableServerFactory.cs | 6 +- .../DriverTestConfiguration.cs | 4 +- .../AuthenticationTests.cs | 5 +- tests/MongoDB.Driver.Tests/ClusterTests.cs | 4 +- .../Bindings/ChannelChannelSourceTests.cs | 38 +-- .../Core/Bindings/ChannelReadBindingTests.cs | 39 +-- .../Bindings/ChannelReadWriteBindingTests.cs | 74 ++--- .../Core/Bindings/ChannelSourceHandleTests.cs | 27 +- .../ChannelSourceReadWriteBindingTests.cs | 68 ++--- .../Core/Bindings/ReadBindingHandleTests.cs | 28 +- .../Bindings/ReadPreferenceBindingTests.cs | 52 ++-- .../Bindings/ReadWriteBindingHandleTests.cs | 55 ++-- .../Core/Bindings/ServerChannelSourceTests.cs | 41 ++- .../Bindings/SingleServerReadBindingTests.cs | 38 +-- .../SingleServerReadWriteBindingTests.cs | 76 ++--- .../Bindings/WritableServerBindingTests.cs | 87 +++--- .../Core/Clusters/ClusterTests.cs | 216 +++++--------- .../Core/Clusters/LoadBalancedClusterTests.cs | 51 ++-- .../ExclusiveConnectionPoolTests.cs | 192 ++++--------- .../ConnectionPools/MaintenanceHelperTests.cs | 4 +- .../Core/Jira/CSharp3173Tests.cs | 12 +- .../Core/Jira/CSharp3302Tests.cs | 10 +- .../Core/LoadBalancingIntergationTests.cs | 17 +- .../Operations/AggregateOperationTests.cs | 11 +- .../Core/Operations/AsyncCursorTests.cs | 84 ++---- .../BulkMixedWriteOperationTests.cs | 16 +- .../Operations/ChangeStreamCursorTests.cs | 34 ++- .../Operations/ChangeStreamOperationTests.cs | 10 +- .../CompositeWriteOperationTests.cs | 21 +- .../CreateCollectionOperationTests.cs | 6 +- .../Operations/CreateViewOperationTests.cs | 2 +- .../Core/Operations/EvalOperationTests.cs | 4 +- .../Core/Operations/GroupOperationTests.cs | 12 +- .../Core/Operations/OperationTestBase.cs | 48 ++-- .../Operations/ReadCommandOperationTests.cs | 68 ++--- .../RetryableWriteOperationExecutorTests.cs | 6 +- .../Operations/WriteCommandOperationTests.cs | 47 +-- .../Core/Servers/LoadBalancedServerTests.cs | 132 +++------ .../Core/Servers/ServerTests.cs | 173 ++++------- .../Encryption/ClientEncryptionTests.cs | 16 +- .../JsonDrivenConfigureFailPointTest.cs | 4 +- .../JsonDrivenTargetedFailPointTest.cs | 7 +- .../OperationCancellationContextTests.cs | 133 +++++++++ .../OperationExecutorTests.cs | 34 +-- .../ReadOperationOptionsTests.cs | 3 +- .../MongoClientJsonDrivenTestRunnerBase.cs | 4 +- .../prose-tests/ClientEncryptionProseTests.cs | 2 +- ...onnectionMonitoringAndPoolingTestRunner.cs | 19 +- .../RetryableReadsProseTests.cs | 8 +- .../prose-tests/PoolClearRetryability.cs | 3 +- .../prose-tests/RetryWriteOnOtherMongos.cs | 6 +- .../ServerDiscoveryAndMonitoringProseTests.cs | 6 +- .../server-selection/InWindowTestRunner.cs | 5 +- .../UnifiedTargetedFailPointOperation.cs | 3 +- 141 files changed, 1928 insertions(+), 2418 deletions(-) delete mode 100644 src/MongoDB.Driver/Core/Operations/PingOperation.cs create mode 100644 src/MongoDB.Driver/OperationCancellationContext.cs create mode 100644 src/MongoDB.Driver/OperationOptionsBase.cs create mode 100644 tests/MongoDB.Driver.Tests/OperationCancellationContextTests.cs diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs b/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs index 26f7ee2881d..324b49200c0 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; @@ -64,13 +63,13 @@ public void Dispose() } } - public IChannelHandle GetChannel(CancellationToken cancellationToken) + public IChannelHandle GetChannel(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return GetChannelHelper(); } - public Task GetChannelAsync(CancellationToken cancellationToken) + public Task GetChannelAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelHelper()); diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs b/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs index 81173ad3639..8d755cc0f61 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; @@ -58,26 +57,26 @@ public void Dispose() } } - public IChannelSourceHandle GetReadChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return GetReadChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return Task.FromResult(GetReadChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetReadChannelSource(cancellationToken); + return GetReadChannelSource(cancellationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetReadChannelSourceAsync(cancellationToken); + return GetReadChannelSourceAsync(cancellationContext); } private IChannelSourceHandle GetReadChannelSourceHelper() diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs b/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs index 71a8e76c429..3d04c9d7b09 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; @@ -56,68 +55,68 @@ public void Dispose() } } - public IChannelSourceHandle GetReadChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetReadChannelSource(cancellationToken); + return GetReadChannelSource(cancellationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetReadChannelSourceAsync(cancellationToken); + return GetReadChannelSourceAsync(cancellationContext); } - public IChannelSourceHandle GetWriteChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetWriteChannelSource(cancellationToken); + return GetWriteChannelSource(cancellationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSource(cancellationToken); // ignore mayUseSecondary + return GetWriteChannelSource(cancellationContext); // ignore mayUseSecondary } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSource(mayUseSecondary, cancellationToken); + return GetWriteChannelSource(mayUseSecondary, cancellationContext); } - public Task GetWriteChannelSourceAsync(CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetWriteChannelSourceAsync(cancellationToken); + return GetWriteChannelSourceAsync(cancellationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSourceAsync(cancellationToken); // ignore mayUseSecondary + return GetWriteChannelSourceAsync(cancellationContext); // ignore mayUseSecondary } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSourceAsync(mayUseSecondary, cancellationToken); + return GetWriteChannelSourceAsync(mayUseSecondary, cancellationContext); } private IChannelSourceHandle GetChannelSourceHelper() diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs b/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs index c7c04912d7b..8bc8674cfd4 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; @@ -55,16 +54,16 @@ public ICoreSessionHandle Session } // methods - public IChannelHandle GetChannel(CancellationToken cancellationToken) + public IChannelHandle GetChannel(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetChannel(cancellationToken); + return _reference.Instance.GetChannel(cancellationContext); } - public Task GetChannelAsync(CancellationToken cancellationToken) + public Task GetChannelAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetChannelAsync(cancellationToken); + return _reference.Instance.GetChannelAsync(cancellationContext); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelSourceReadWriteBinding.cs b/src/MongoDB.Driver/Core/Bindings/ChannelSourceReadWriteBinding.cs index c6fef30f1e6..38f92f7a000 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelSourceReadWriteBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelSourceReadWriteBinding.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; @@ -46,68 +45,68 @@ public ICoreSessionHandle Session get { return _session; } } - public IChannelSourceHandle GetReadChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetReadChannelSource(cancellationToken); + return GetReadChannelSource(cancellationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetReadChannelSourceAsync(cancellationToken); + return GetReadChannelSourceAsync(cancellationContext); } - public IChannelSourceHandle GetWriteChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetWriteChannelSource(cancellationToken); + return GetWriteChannelSource(cancellationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSource(cancellationToken); // ignore mayUseSecondary + return GetWriteChannelSource(cancellationContext); // ignore mayUseSecondary } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSource(mayUseSecondary, cancellationToken); + return GetWriteChannelSource(mayUseSecondary, cancellationContext); } - public Task GetWriteChannelSourceAsync(CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetWriteChannelSourceAsync(cancellationToken); + return GetWriteChannelSourceAsync(cancellationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSourceAsync(cancellationToken); // ignore mayUseSecondary + return GetWriteChannelSourceAsync(cancellationContext); // ignore mayUseSecondary } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSourceAsync(mayUseSecondary, cancellationToken); + return GetWriteChannelSourceAsync(mayUseSecondary, cancellationContext); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/CoreSession.cs b/src/MongoDB.Driver/Core/Bindings/CoreSession.cs index 66fa294a14f..5adaab71b65 100644 --- a/src/MongoDB.Driver/Core/Bindings/CoreSession.cs +++ b/src/MongoDB.Driver/Core/Bindings/CoreSession.cs @@ -145,6 +145,8 @@ public bool IsInTransaction { EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { if (_currentTransaction.IsEmpty) @@ -155,7 +157,7 @@ public bool IsInTransaction try { var firstAttempt = CreateAbortTransactionOperation(); - ExecuteEndTransactionOnPrimary(firstAttempt, cancellationToken); + ExecuteEndTransactionOnPrimary(firstAttempt, operationCancellationContext); return; } catch (Exception exception) when (ShouldRetryEndTransactionException(exception)) @@ -173,7 +175,7 @@ public bool IsInTransaction try { var secondAttempt = CreateAbortTransactionOperation(); - ExecuteEndTransactionOnPrimary(secondAttempt, cancellationToken); + ExecuteEndTransactionOnPrimary(secondAttempt, operationCancellationContext); } catch { @@ -194,6 +196,8 @@ public bool IsInTransaction { EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { if (_currentTransaction.IsEmpty) @@ -204,7 +208,7 @@ public bool IsInTransaction try { var firstAttempt = CreateAbortTransactionOperation(); - await ExecuteEndTransactionOnPrimaryAsync(firstAttempt, cancellationToken).ConfigureAwait(false); + await ExecuteEndTransactionOnPrimaryAsync(firstAttempt, operationCancellationContext).ConfigureAwait(false); return; } catch (Exception exception) when (ShouldRetryEndTransactionException(exception)) @@ -222,7 +226,7 @@ public bool IsInTransaction try { var secondAttempt = CreateAbortTransactionOperation(); - await ExecuteEndTransactionOnPrimaryAsync(secondAttempt, cancellationToken).ConfigureAwait(false); + await ExecuteEndTransactionOnPrimaryAsync(secondAttempt, operationCancellationContext).ConfigureAwait(false); } catch { @@ -292,6 +296,8 @@ public long AdvanceTransactionNumber() { EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { _isCommitTransactionInProgress = true; @@ -303,7 +309,7 @@ public long AdvanceTransactionNumber() try { var firstAttempt = CreateCommitTransactionOperation(IsFirstCommitAttemptRetry()); - ExecuteEndTransactionOnPrimary(firstAttempt, cancellationToken); + ExecuteEndTransactionOnPrimary(firstAttempt, operationCancellationContext); return; } catch (Exception exception) when (ShouldRetryEndTransactionException(exception)) @@ -313,7 +319,7 @@ public long AdvanceTransactionNumber() } var secondAttempt = CreateCommitTransactionOperation(isCommitRetry: true); - ExecuteEndTransactionOnPrimary(secondAttempt, cancellationToken); + ExecuteEndTransactionOnPrimary(secondAttempt, operationCancellationContext); } finally { @@ -327,6 +333,8 @@ public long AdvanceTransactionNumber() { EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { _isCommitTransactionInProgress = true; @@ -338,7 +346,7 @@ public long AdvanceTransactionNumber() try { var firstAttempt = CreateCommitTransactionOperation(IsFirstCommitAttemptRetry()); - await ExecuteEndTransactionOnPrimaryAsync(firstAttempt, cancellationToken).ConfigureAwait(false); + await ExecuteEndTransactionOnPrimaryAsync(firstAttempt, operationCancellationContext).ConfigureAwait(false); return; } catch (Exception exception) when (ShouldRetryEndTransactionException(exception)) @@ -348,7 +356,7 @@ public long AdvanceTransactionNumber() } var secondAttempt = CreateCommitTransactionOperation(isCommitRetry: true); - await ExecuteEndTransactionOnPrimaryAsync(secondAttempt, cancellationToken).ConfigureAwait(false); + await ExecuteEndTransactionOnPrimaryAsync(secondAttempt, operationCancellationContext).ConfigureAwait(false); } finally { @@ -404,7 +412,7 @@ public void StartTransaction(TransactionOptions transactionOptions = null) throw new InvalidOperationException("Transactions do not support unacknowledged write concerns."); } - _currentTransaction?.UnpinAll(); // unpin data if any when a new transaction is started + _currentTransaction?.UnpinAll(); // unpin data if any when a new transaction is started _currentTransaction = new CoreTransaction(transactionNumber, effectiveTransactionOptions); } @@ -537,21 +545,21 @@ private void EnsureTransactionsAreSupported() } } - private TResult ExecuteEndTransactionOnPrimary(IReadOperation operation, CancellationToken cancellationToken) + private TResult ExecuteEndTransactionOnPrimary(IReadOperation operation, OperationCancellationContext operationCancellationContext) { using (var sessionHandle = new NonDisposingCoreSessionHandle(this)) using (var binding = ChannelPinningHelper.CreateReadWriteBinding(_cluster, sessionHandle)) { - return operation.Execute(binding, cancellationToken); + return operation.Execute(binding, operationCancellationContext); } } - private async Task ExecuteEndTransactionOnPrimaryAsync(IReadOperation operation, CancellationToken cancellationToken) + private async Task ExecuteEndTransactionOnPrimaryAsync(IReadOperation operation, OperationCancellationContext operationCancellationContext) { using (var sessionHandle = new NonDisposingCoreSessionHandle(this)) using (var binding = ChannelPinningHelper.CreateReadWriteBinding(_cluster, sessionHandle)) { - return await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Bindings/IBinding.cs b/src/MongoDB.Driver/Core/Bindings/IBinding.cs index 304796f1a9b..f174d3fbe0f 100644 --- a/src/MongoDB.Driver/Core/Bindings/IBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/IBinding.cs @@ -30,24 +30,24 @@ internal interface IReadBinding : IBinding { ReadPreference ReadPreference { get; } - IChannelSourceHandle GetReadChannelSource(CancellationToken cancellationToken); - Task GetReadChannelSourceAsync(CancellationToken cancellationToken); + IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationToken); + Task GetReadChannelSourceAsync(OperationCancellationContext cancellationToken); - IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken); - Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken); + IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationToken); + Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationToken); } internal interface IWriteBinding : IBinding { - IChannelSourceHandle GetWriteChannelSource(CancellationToken cancellationToken); - IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken); - IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken); - IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken); + IChannelSourceHandle GetWriteChannelSource(OperationCancellationContext cancellationToken); + IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationToken); + IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationToken); + IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationToken); - Task GetWriteChannelSourceAsync(CancellationToken cancellationToken); - Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken); - Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken); - Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken); + Task GetWriteChannelSourceAsync(OperationCancellationContext cancellationToken); + Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationToken); + Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationToken); + Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationToken); } internal interface IReadWriteBinding : IReadBinding, IWriteBinding diff --git a/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs b/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs index 8582a50e7b8..4b7e6dfaff6 100644 --- a/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs +++ b/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Servers; @@ -26,8 +25,8 @@ internal interface IChannelSource : IDisposable ServerDescription ServerDescription { get; } ICoreSessionHandle Session { get; } - IChannelHandle GetChannel(CancellationToken cancellationToken); - Task GetChannelAsync(CancellationToken cancellationToken); + IChannelHandle GetChannel(OperationCancellationContext cancellationContext); + Task GetChannelAsync(OperationCancellationContext cancellationContext); } internal interface IChannelSourceHandle : IChannelSource diff --git a/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs b/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs index 63605e4b6c3..d1ce34fff88 100644 --- a/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs +++ b/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; @@ -47,28 +46,28 @@ public ICoreSessionHandle Session get { return _reference.Instance.Session; } } - public IChannelSourceHandle GetReadChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(cancellationToken); + return _reference.Instance.GetReadChannelSource(cancellationContext); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(cancellationToken); + return _reference.Instance.GetReadChannelSourceAsync(cancellationContext); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(deprioritizedServers, cancellationToken); + return _reference.Instance.GetReadChannelSource(deprioritizedServers, cancellationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(deprioritizedServers, cancellationToken); + return _reference.Instance.GetReadChannelSourceAsync(deprioritizedServers, cancellationContext); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs b/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs index 54cd2faf4a2..a91bc35151c 100644 --- a/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Clusters.ServerSelectors; @@ -52,27 +51,27 @@ public ICoreSessionHandle Session get { return _session; } } - public IChannelSourceHandle GetReadChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) { - return GetReadChannelSource(null, cancellationToken); + return GetReadChannelSource(null, cancellationContext); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) { - return GetReadChannelSourceAsync(null, cancellationToken); + return GetReadChannelSourceAsync(null, cancellationContext); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(_session, _serverSelector, deprioritizedServers, cancellationToken); + var server = _cluster.SelectServerAndPinIfNeeded(_session, _serverSelector, deprioritizedServers, cancellationContext); return GetChannelSourceHelper(server); } - public async Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public async Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, _serverSelector, deprioritizedServers, cancellationToken).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, _serverSelector, deprioritizedServers, cancellationContext).ConfigureAwait(false); return GetChannelSourceHelper(server); } diff --git a/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs b/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs index 7a298b3af60..34cbc5eae7d 100644 --- a/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs +++ b/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; @@ -47,76 +46,76 @@ public ICoreSessionHandle Session get { return _reference.Instance.Session; } } - public IChannelSourceHandle GetReadChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(cancellationToken); + return _reference.Instance.GetReadChannelSource(cancellationContext); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(cancellationToken); + return _reference.Instance.GetReadChannelSourceAsync(cancellationContext); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(deprioritizedServers, cancellationToken); + return _reference.Instance.GetReadChannelSource(deprioritizedServers, cancellationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(deprioritizedServers, cancellationToken); + return _reference.Instance.GetReadChannelSourceAsync(deprioritizedServers, cancellationContext); } - public IChannelSourceHandle GetWriteChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(cancellationToken); + return _reference.Instance.GetWriteChannelSource(cancellationContext); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(deprioritizedServers, cancellationToken); + return _reference.Instance.GetWriteChannelSource(deprioritizedServers, cancellationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(mayUseSecondary, cancellationToken); + return _reference.Instance.GetWriteChannelSource(mayUseSecondary, cancellationContext); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(deprioritizedServers, mayUseSecondary, cancellationToken); + return _reference.Instance.GetWriteChannelSource(deprioritizedServers, mayUseSecondary, cancellationContext); } - public Task GetWriteChannelSourceAsync(CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(cancellationToken); + return _reference.Instance.GetWriteChannelSourceAsync(cancellationContext); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(deprioritizedServers, cancellationToken); + return _reference.Instance.GetWriteChannelSourceAsync(deprioritizedServers, cancellationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(mayUseSecondary, cancellationToken); + return _reference.Instance.GetWriteChannelSourceAsync(mayUseSecondary, cancellationContext); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(deprioritizedServers, mayUseSecondary, cancellationToken); + return _reference.Instance.GetWriteChannelSourceAsync(deprioritizedServers, mayUseSecondary, cancellationContext); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs b/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs index a4cadb0001f..5f52bc702e3 100644 --- a/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs +++ b/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; @@ -61,16 +60,16 @@ public void Dispose() } } - public IChannelHandle GetChannel(CancellationToken cancellationToken) + public IChannelHandle GetChannel(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _server.GetChannel(cancellationToken); + return _server.GetChannel(cancellationContext); } - public Task GetChannelAsync(CancellationToken cancellationToken) + public Task GetChannelAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - return _server.GetChannelAsync(cancellationToken); + return _server.GetChannelAsync(cancellationContext); } private void ThrowIfDisposed() diff --git a/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs b/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs index 6bd5b858021..8d760aa9f0c 100644 --- a/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs @@ -48,26 +48,26 @@ public ICoreSessionHandle Session get { return _session; } } - public IChannelSourceHandle GetReadChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetReadChannelSource(cancellationToken); + return GetReadChannelSource(cancellationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetReadChannelSourceAsync(cancellationToken); + return GetReadChannelSourceAsync(cancellationContext); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs b/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs index 4f7756a1d7d..4604a2322a2 100644 --- a/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.Servers; @@ -53,68 +52,68 @@ public void Dispose() } } - public IChannelSourceHandle GetReadChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetReadChannelSource(cancellationToken); + return GetReadChannelSource(cancellationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetReadChannelSourceAsync(cancellationToken); + return GetReadChannelSourceAsync(cancellationContext); } - public IChannelSourceHandle GetWriteChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetWriteChannelSource(cancellationToken); + return GetWriteChannelSource(cancellationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSource(cancellationToken); // ignore mayUseSecondary + return GetWriteChannelSource(cancellationContext); // ignore mayUseSecondary } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSource(mayUseSecondary, cancellationToken); + return GetWriteChannelSource(mayUseSecondary, cancellationContext); } - public Task GetWriteChannelSourceAsync(CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationCancellationContext cancellationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { - return GetWriteChannelSourceAsync(cancellationToken); + return GetWriteChannelSourceAsync(cancellationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSourceAsync(cancellationToken); // ignore mayUseSecondary + return GetWriteChannelSourceAsync(cancellationContext); // ignore mayUseSecondary } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSourceAsync(mayUseSecondary, cancellationToken); + return GetWriteChannelSourceAsync(mayUseSecondary, cancellationContext); } private IChannelSourceHandle GetChannelSourceHelper() diff --git a/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs b/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs index 27ea948577e..8295484bf5d 100644 --- a/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Clusters.ServerSelectors; @@ -48,48 +47,48 @@ public ICoreSessionHandle Session get { return _session; } } - public IChannelSourceHandle GetReadChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) { - return GetReadChannelSource(null, cancellationToken); + return GetReadChannelSource(null, cancellationContext); } - public Task GetReadChannelSourceAsync(CancellationToken cancellationToken) + public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) { - return GetReadChannelSourceAsync(null, cancellationToken); + return GetReadChannelSourceAsync(null, cancellationContext); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationToken); + var server = _cluster.SelectServerAndPinIfNeeded(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationContext); return CreateServerChannelSource(server); } - public async Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public async Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationToken).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationContext).ConfigureAwait(false); return CreateServerChannelSource(server); } - public IChannelSourceHandle GetWriteChannelSource(CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(OperationCancellationContext cancellationContext) { - return GetWriteChannelSource(deprioritizedServers: null, cancellationToken); + return GetWriteChannelSource(deprioritizedServers: null, cancellationContext); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationToken); + var server = _cluster.SelectServerAndPinIfNeeded(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationContext); return CreateServerChannelSource(server); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSource(null, mayUseSecondary, cancellationToken); + return GetWriteChannelSource(null, mayUseSecondary, cancellationContext); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { if (IsSessionPinnedToServer()) { @@ -102,28 +101,28 @@ public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection GetWriteChannelSourceAsync(CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(OperationCancellationContext cancellationContext) { - return GetWriteChannelSourceAsync(deprioritizedServers: null, cancellationToken); + return GetWriteChannelSourceAsync(deprioritizedServers: null, cancellationContext); } - public async Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, CancellationToken cancellationToken) + public async Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationToken).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationContext).ConfigureAwait(false); return CreateServerChannelSource(server); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { - return GetWriteChannelSourceAsync(null, mayUseSecondary, cancellationToken); + return GetWriteChannelSourceAsync(null, mayUseSecondary, cancellationContext); } - public async Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, CancellationToken cancellationToken) + public async Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) { if (IsSessionPinnedToServer()) { @@ -136,7 +135,7 @@ public async Task GetWriteChannelSourceAsync(IReadOnlyColl ? new CompositeServerSelector(new IServerSelector[] { new PriorityServerSelector(deprioritizedServers), writableServerSelector }) : writableServerSelector; - var server = await _cluster.SelectServerAsync(selector, cancellationToken).ConfigureAwait(false); + var server = await _cluster.SelectServerAsync(selector, cancellationContext).ConfigureAwait(false); return CreateServerChannelSource(server); } diff --git a/src/MongoDB.Driver/Core/Clusters/Cluster.cs b/src/MongoDB.Driver/Core/Clusters/Cluster.cs index f1031387530..f7bf3869f52 100644 --- a/src/MongoDB.Driver/Core/Clusters/Cluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/Cluster.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; @@ -217,10 +216,13 @@ protected void OnDescriptionChanged(ClusterDescription oldDescription, ClusterDe DescriptionChanged?.Invoke(this, new ClusterDescriptionChangedEventArgs(oldDescription, newDescription)); } - public IServer SelectServer(IServerSelector selector, CancellationToken cancellationToken) + public IServer SelectServer(IServerSelector selector, OperationCancellationContext cancellationContext) { ThrowIfDisposedOrNotOpen(); Ensure.IsNotNull(selector, nameof(selector)); + Ensure.IsNotNull(cancellationContext, nameof(cancellationContext)); + + var serverSelectionCancellationContext = cancellationContext.WithTimeout(Settings.ServerSelectionTimeout); using (var helper = new SelectServerHelper(this, selector)) { @@ -228,16 +230,23 @@ public IServer SelectServer(IServerSelector selector, CancellationToken cancella { while (true) { - var server = helper.SelectServer(); + var server = helper.SelectServer(serverSelectionCancellationContext); if (server != null) { return server; } - helper.WaitingForDescriptionToChange(); - WaitForDescriptionChanged(helper.Selector, helper.Description, helper.DescriptionChangedTask, helper.TimeoutRemaining, cancellationToken); + helper.WaitForDescriptionChanged(serverSelectionCancellationContext); } } + catch (TimeoutException) + { + var message = BuildTimeoutExceptionMessage(_settings.ServerSelectionTimeout, selector, helper.Description); + var timeoutException = new TimeoutException(message); + helper.HandleException(timeoutException); + + throw timeoutException; + } catch (Exception ex) { helper.HandleException(ex); @@ -246,10 +255,13 @@ public IServer SelectServer(IServerSelector selector, CancellationToken cancella } } - public async Task SelectServerAsync(IServerSelector selector, CancellationToken cancellationToken) + public async Task SelectServerAsync(IServerSelector selector, OperationCancellationContext cancellationContext) { ThrowIfDisposedOrNotOpen(); Ensure.IsNotNull(selector, nameof(selector)); + Ensure.IsNotNull(cancellationContext, nameof(cancellationContext)); + + var serverSelectionCancellationContext = cancellationContext.WithTimeout(Settings.ServerSelectionTimeout); using (var helper = new SelectServerHelper(this, selector)) { @@ -257,16 +269,23 @@ public async Task SelectServerAsync(IServerSelector selector, Cancellat { while (true) { - var server = helper.SelectServer(); + var server = helper.SelectServer(serverSelectionCancellationContext); if (server != null) { return server; } - helper.WaitingForDescriptionToChange(); - await WaitForDescriptionChangedAsync(helper.Selector, helper.Description, helper.DescriptionChangedTask, helper.TimeoutRemaining, cancellationToken).ConfigureAwait(false); + await helper.WaitForDescriptionChangedAsync(serverSelectionCancellationContext).ConfigureAwait(false); } } + catch (TimeoutException) + { + var message = BuildTimeoutExceptionMessage(_settings.ServerSelectionTimeout, selector, helper.Description); + var timeoutException = new TimeoutException(message); + helper.HandleException(timeoutException); + + throw timeoutException; + } catch (Exception ex) { helper.HandleException(ex); @@ -320,30 +339,6 @@ private void ThrowIfDisposedOrNotOpen() } } - private void WaitForDescriptionChanged(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken) - { - using (var helper = new WaitForDescriptionChangedHelper(this, selector, description, descriptionChangedTask, timeout, cancellationToken)) - { - var index = Task.WaitAny(helper.Tasks); - helper.HandleCompletedTask(helper.Tasks[index]); - } - } - - private async Task WaitForDescriptionChangedAsync(IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken) - { - using (var helper = new WaitForDescriptionChangedHelper(this, selector, description, descriptionChangedTask, timeout, cancellationToken)) - { - var completedTask = await Task.WhenAny(helper.Tasks).ConfigureAwait(false); - helper.HandleCompletedTask(completedTask); - } - } - - private void ThrowTimeoutException(IServerSelector selector, ClusterDescription description) - { - var message = BuildTimeoutExceptionMessage(_settings.ServerSelectionTimeout, selector, description); - throw new TimeoutException(message); - } - // nested classes internal sealed class ClusterDescriptionChangeSource { @@ -374,20 +369,15 @@ private class SelectServerHelper : IDisposable private bool _serverSelectionWaitQueueEntered; private readonly IServerSelector _selector; private readonly OperationsCountServerSelector _operationCountServerSelector; - private readonly Stopwatch _stopwatch; - private readonly DateTime _timeoutAt; public SelectServerHelper(Cluster cluster, IServerSelector selector) { _cluster = cluster; - _connectedServers = new List(_cluster._descriptionWithChangedTaskCompletionSource.ClusterDescription?.Servers?.Count ?? 1); _connectedServerDescriptions = new List(_connectedServers.Count); _operationCountServerSelector = new OperationsCountServerSelector(_connectedServers); _selector = DecorateSelector(selector); - _stopwatch = Stopwatch.StartNew(); - _timeoutAt = DateTime.UtcNow + _cluster.Settings.ServerSelectionTimeout; } public ClusterDescription Description @@ -405,11 +395,6 @@ public IServerSelector Selector get { return _selector; } } - public TimeSpan TimeoutRemaining - { - get { return _timeoutAt - DateTime.UtcNow; } - } - public void Dispose() { if (_serverSelectionWaitQueueEntered) @@ -428,7 +413,7 @@ public void HandleException(Exception exception) EventContext.OperationName)); } - public IServer SelectServer() + public IServer SelectServer(OperationCancellationContext cancellationContext) { var clusterDescription = _cluster._descriptionWithChangedTaskCompletionSource; _descriptionChangedTask = clusterDescription.Changed; @@ -476,13 +461,11 @@ public IServer SelectServer() if (selectedServer != null) { - _stopwatch.Stop(); - _cluster._serverSelectionEventLogger.LogAndPublish(new ClusterSelectedServerEvent( _description, _selector, selectedServer.Description, - _stopwatch.Elapsed, + cancellationContext.Elapsed, EventContext.OperationId, EventContext.OperationName)); } @@ -490,19 +473,27 @@ public IServer SelectServer() return selectedServer; } - public void WaitingForDescriptionToChange() + public void WaitForDescriptionChanged(OperationCancellationContext cancellationContext) { - if (!_serverSelectionWaitQueueEntered) - { - _cluster.EnterServerSelectionWaitQueue(_selector, _description, EventContext.OperationId, _timeoutAt - DateTime.UtcNow); - _serverSelectionWaitQueueEntered = true; - } + EnsureEnteredServerSelectionQueue(cancellationContext); + cancellationContext.WaitTask(DescriptionChangedTask); + } + + public Task WaitForDescriptionChangedAsync(OperationCancellationContext cancellationContext) + { + EnsureEnteredServerSelectionQueue(cancellationContext); + return cancellationContext.WaitTaskAsync(DescriptionChangedTask); + } - var timeoutRemaining = _timeoutAt - DateTime.UtcNow; - if (timeoutRemaining <= TimeSpan.Zero) + private void EnsureEnteredServerSelectionQueue(OperationCancellationContext cancellationContext) + { + if (_serverSelectionWaitQueueEntered) { - _cluster.ThrowTimeoutException(_selector, _description); + return; } + + _cluster.EnterServerSelectionWaitQueue(_selector, _description, EventContext.OperationId, cancellationContext.RemainingTimeout); + _serverSelectionWaitQueueEntered = true; } private IServerSelector DecorateSelector(IServerSelector selector) @@ -529,67 +520,6 @@ private IServerSelector DecorateSelector(IServerSelector selector) } } - private sealed class WaitForDescriptionChangedHelper : IDisposable - { - private readonly CancellationToken _cancellationToken; - private readonly TaskCompletionSource _cancellationTaskCompletionSource; - private readonly CancellationTokenRegistration _cancellationTokenRegistration; - private readonly Cluster _cluster; - private readonly ClusterDescription _description; - private readonly Task _descriptionChangedTask; - private readonly IServerSelector _selector; - private readonly CancellationTokenSource _timeoutCancellationTokenSource; - private readonly Task _timeoutTask; - - public WaitForDescriptionChangedHelper(Cluster cluster, IServerSelector selector, ClusterDescription description, Task descriptionChangedTask, TimeSpan timeout, CancellationToken cancellationToken) - { - _cluster = cluster; - _description = description; - _selector = selector; - _descriptionChangedTask = descriptionChangedTask; - _cancellationToken = cancellationToken; - _cancellationTaskCompletionSource = new TaskCompletionSource(); - _cancellationTokenRegistration = cancellationToken.Register(() => _cancellationTaskCompletionSource.TrySetCanceled()); - _timeoutCancellationTokenSource = new CancellationTokenSource(); - _timeoutTask = Task.Delay(timeout, _timeoutCancellationTokenSource.Token); - } - - public Task[] Tasks - { - get - { - return new Task[] - { - _descriptionChangedTask, - _timeoutTask, - _cancellationTaskCompletionSource.Task - }; - } - } - - public void Dispose() - { - _cancellationTokenRegistration.Dispose(); - _timeoutCancellationTokenSource.Dispose(); - } - - public void HandleCompletedTask(Task completedTask) - { - if (completedTask == _timeoutTask) - { - _cluster.ThrowTimeoutException(_selector, _description); - } - _timeoutCancellationTokenSource.Cancel(); - - if (completedTask == _cancellationTaskCompletionSource.Task) - { - _cancellationToken.ThrowIfCancellationRequested(); - } - - _descriptionChangedTask.GetAwaiter().GetResult(); // propagate exceptions - } - } - private static class State { public const int Initial = 0; diff --git a/src/MongoDB.Driver/Core/Clusters/ICluster.cs b/src/MongoDB.Driver/Core/Clusters/ICluster.cs index fcc817ec844..88ca766c310 100644 --- a/src/MongoDB.Driver/Core/Clusters/ICluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/ICluster.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters.ServerSelectors; @@ -62,8 +61,8 @@ internal interface IClusterInternal : ICluster void Initialize(); - IServer SelectServer(IServerSelector selector, CancellationToken cancellationToken); - Task SelectServerAsync(IServerSelector selector, CancellationToken cancellationToken); + IServer SelectServer(IServerSelector selector, OperationCancellationContext cancellationContext); + Task SelectServerAsync(IServerSelector selector, OperationCancellationContext cancellationContext); ICoreSessionHandle StartSession(CoreSessionOptions options = null); } diff --git a/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs b/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs index 245ba8a48a3..025d8346486 100644 --- a/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs +++ b/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs @@ -14,7 +14,6 @@ */ using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters.ServerSelectors; @@ -29,7 +28,7 @@ public static IServer SelectServerAndPinIfNeeded( ICoreSessionHandle session, IServerSelector selector, IReadOnlyCollection deprioritizedServers, - CancellationToken cancellationToken) + OperationCancellationContext cancellationContext) { var pinnedServer = GetPinnedServerIfValid(cluster, session); if (pinnedServer != null) @@ -43,7 +42,7 @@ public static IServer SelectServerAndPinIfNeeded( // Server selection also updates the cluster type, allowing us to to determine if the server // should be pinned. - var server = cluster.SelectServer(selector, cancellationToken); + var server = cluster.SelectServer(selector, cancellationContext); PinServerIfNeeded(cluster, session, server); return server; } @@ -53,7 +52,7 @@ public static async Task SelectServerAndPinIfNeededAsync( ICoreSessionHandle session, IServerSelector selector, IReadOnlyCollection deprioritizedServers, - CancellationToken cancellationToken) + OperationCancellationContext cancellationContext) { var pinnedServer = GetPinnedServerIfValid(cluster, session); if (pinnedServer != null) @@ -67,7 +66,7 @@ public static async Task SelectServerAndPinIfNeededAsync( // Server selection also updates the cluster type, allowing us to to determine if the server // should be pinned. - var server = await cluster.SelectServerAsync(selector, cancellationToken).ConfigureAwait(false); + var server = await cluster.SelectServerAsync(selector, cancellationContext).ConfigureAwait(false); PinServerIfNeeded(cluster, session, server); return server; diff --git a/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs b/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs index 712d9f52fc7..59b51e5c204 100644 --- a/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs @@ -170,20 +170,26 @@ public void Initialize() } } - public IServer SelectServer(IServerSelector selector, CancellationToken cancellationToken) + public IServer SelectServer(IServerSelector selector, OperationCancellationContext cancellationContext) { + Ensure.IsNotNull(selector, nameof(selector)); + Ensure.IsNotNull(cancellationContext, nameof(cancellationContext)); ThrowIfDisposed(); + var serverSelectionCancellationContext = cancellationContext.WithTimeout(_settings.ServerSelectionTimeout); + _serverSelectionEventLogger.LogAndPublish(new ClusterSelectingServerEvent( _description, selector, null, EventContext.OperationName)); - var index = Task.WaitAny(new[] { _serverReadyTaskCompletionSource.Task }, (int)_settings.ServerSelectionTimeout.TotalMilliseconds, cancellationToken); - if (index != 0) + try + { + serverSelectionCancellationContext.WaitTask(_serverReadyTaskCompletionSource.Task); + } + catch (TimeoutException) { - cancellationToken.ThrowIfCancellationRequested(); throw CreateTimeoutException(_description); // _description will contain dnsException } @@ -193,7 +199,7 @@ public IServer SelectServer(IServerSelector selector, CancellationToken cancella _description, selector, _server.Description, - TimeSpan.FromSeconds(1), + serverSelectionCancellationContext.Elapsed, null, EventContext.OperationName)); } @@ -202,21 +208,26 @@ public IServer SelectServer(IServerSelector selector, CancellationToken cancella throw new InvalidOperationException("The server must be created before usage."); // should not be reached } - public async Task SelectServerAsync(IServerSelector selector, CancellationToken cancellationToken) + public async Task SelectServerAsync(IServerSelector selector, OperationCancellationContext cancellationContext) { + Ensure.IsNotNull(selector, nameof(selector)); + Ensure.IsNotNull(cancellationContext, nameof(cancellationContext)); ThrowIfDisposed(); + var serverSelectionCancellationContext = cancellationContext.WithTimeout(_settings.ServerSelectionTimeout); + _serverSelectionEventLogger.LogAndPublish(new ClusterSelectingServerEvent( _description, selector, null, EventContext.OperationName)); - var timeoutTask = Task.Delay(_settings.ServerSelectionTimeout, cancellationToken); - var triggeredTask = await Task.WhenAny(_serverReadyTaskCompletionSource.Task, timeoutTask).ConfigureAwait(false); - if (triggeredTask == timeoutTask) + try + { + await serverSelectionCancellationContext.WaitTaskAsync(_serverReadyTaskCompletionSource.Task).ConfigureAwait(false); + } + catch (TimeoutException) { - cancellationToken.ThrowIfCancellationRequested(); throw CreateTimeoutException(_description); // _description will contain dnsException } @@ -226,7 +237,7 @@ public async Task SelectServerAsync(IServerSelector selector, Cancellat _description, selector, _server.Description, - TimeSpan.FromSeconds(1), + serverSelectionCancellationContext.Elapsed, null, EventContext.OperationName)); } diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs index 77895ed99a4..932b4c118d7 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs @@ -33,7 +33,7 @@ namespace MongoDB.Driver.Core.ConnectionPools internal sealed partial class ExclusiveConnectionPool { // private methods - private Exception CreateTimeoutException(Stopwatch stopwatch, string message) + private Exception CreateTimeoutException(OperationCancellationContext cancellationContext, string message) { var checkOutsForCursorCount = _checkOutReasonCounter.GetCheckOutsCount(CheckOutReason.Cursor); var checkOutsForTransactionCount = _checkOutReasonCounter.GetCheckOutsCount(CheckOutReason.Transaction); @@ -47,7 +47,7 @@ private Exception CreateTimeoutException(Stopwatch stopwatch, string message) var checkOutsForOtherCount = checkOutsCount - checkOutsForCursorCount - checkOutsForTransactionCount; message = - $"Timed out after {stopwatch.ElapsedMilliseconds}ms waiting for a connection from the connection pool. " + + $"Timed out after {cancellationContext.Elapsed.TotalMilliseconds}ms waiting for a connection from the connection pool. " + $"maxPoolSize: {maxPoolSize}, " + $"connections in use by cursors: {checkOutsForCursorCount}, " + $"connections in use by transactions: {checkOutsForTransactionCount}, " + @@ -166,7 +166,6 @@ private sealed class AcquireConnectionHelper : IDisposable { // private fields private readonly ExclusiveConnectionPool _pool; - private readonly TimeSpan _timeout; private bool _enteredWaitQueue; private SemaphoreSlimSignalable.SemaphoreWaitResult _poolQueueWaitResult; @@ -175,69 +174,62 @@ private sealed class AcquireConnectionHelper : IDisposable public AcquireConnectionHelper(ExclusiveConnectionPool pool) { _pool = pool; - _timeout = pool._settings.WaitQueueTimeout; } - public IConnectionHandle AcquireConnection(CancellationToken cancellationToken) + public IConnectionHandle AcquireConnection(OperationCancellationContext cancellationContext) { - var stopwatch = new Stopwatch(); try { - StartCheckingOut(stopwatch); - _poolQueueWaitResult = _pool._maxConnectionsQueue.WaitSignaled(_timeout, cancellationToken); + StartCheckingOut(); + _poolQueueWaitResult = _pool._maxConnectionsQueue.WaitSignaled(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken); if (_poolQueueWaitResult == SemaphoreSlimSignalable.SemaphoreWaitResult.Entered) { PooledConnection pooledConnection; - var timeout = EnsureTimeout(stopwatch); + EnsureTimeout(cancellationContext); - using (var connectionCreator = new ConnectionCreator(_pool, timeout)) + using (var connectionCreator = new ConnectionCreator(_pool)) { - pooledConnection = connectionCreator.CreateOpenedOrReuse(cancellationToken); + pooledConnection = connectionCreator.CreateOpenedOrReuse(cancellationContext); } - return EndCheckingOut(pooledConnection, stopwatch); + return EndCheckingOut(pooledConnection, cancellationContext); } - stopwatch.Stop(); - throw CreateException(stopwatch); + throw CreateException(cancellationContext); } catch (Exception ex) { - stopwatch.Stop(); - HandleException(ex, stopwatch.Elapsed); + HandleException(ex, cancellationContext.Elapsed); throw; } } - public async Task AcquireConnectionAsync(CancellationToken cancellationToken) + public async Task AcquireConnectionAsync(OperationCancellationContext cancellationContext) { - var stopwatch = new Stopwatch(); try { - StartCheckingOut(stopwatch); - _poolQueueWaitResult = await _pool._maxConnectionsQueue.WaitSignaledAsync(_timeout, cancellationToken).ConfigureAwait(false); + StartCheckingOut(); + _poolQueueWaitResult = await _pool._maxConnectionsQueue.WaitSignaledAsync(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken).ConfigureAwait(false); if (_poolQueueWaitResult == SemaphoreSlimSignalable.SemaphoreWaitResult.Entered) { PooledConnection pooledConnection; - var timeout = EnsureTimeout(stopwatch); + EnsureTimeout(cancellationContext); - using (var connectionCreator = new ConnectionCreator(_pool, timeout)) + using (var connectionCreator = new ConnectionCreator(_pool)) { - pooledConnection = await connectionCreator.CreateOpenedOrReuseAsync(cancellationToken).ConfigureAwait(false); + pooledConnection = await connectionCreator.CreateOpenedOrReuseAsync(cancellationContext).ConfigureAwait(false); } - return EndCheckingOut(pooledConnection, stopwatch); + return EndCheckingOut(pooledConnection, cancellationContext); } - stopwatch.Stop(); - throw CreateException(stopwatch); + throw CreateException(cancellationContext); } catch (Exception ex) { - stopwatch.Stop(); - HandleException(ex, stopwatch.Elapsed); + HandleException(ex, cancellationContext.Elapsed); throw; } } @@ -281,23 +273,20 @@ private void AcquireWaitQueueSlot() _enteredWaitQueue = true; } - private void StartCheckingOut(Stopwatch stopwatch) + private void StartCheckingOut() { _pool._eventLogger.LogAndPublish(new ConnectionPoolCheckingOutConnectionEvent(_pool._serverId, EventContext.OperationId)); - - stopwatch.Start(); _pool._poolState.ThrowIfNotReady(); AcquireWaitQueueSlot(); } - private IConnectionHandle EndCheckingOut(PooledConnection pooledConnection, Stopwatch stopwatch) + private IConnectionHandle EndCheckingOut(PooledConnection pooledConnection, OperationCancellationContext cancellationContext) { var reference = new ReferenceCounted(pooledConnection, _pool.ReleaseConnection); var connectionHandle = new AcquiredConnection(_pool, reference); - stopwatch.Stop(); - _pool._eventLogger.LogAndPublish(new ConnectionPoolCheckedOutConnectionEvent(connectionHandle.ConnectionId, stopwatch.Elapsed, EventContext.OperationId)); + _pool._eventLogger.LogAndPublish(new ConnectionPoolCheckedOutConnectionEvent(connectionHandle.ConnectionId, cancellationContext.Elapsed, EventContext.OperationId)); // no need to release the semaphore _poolQueueWaitResult = SemaphoreSlimSignalable.SemaphoreWaitResult.None; @@ -305,26 +294,21 @@ private IConnectionHandle EndCheckingOut(PooledConnection pooledConnection, Stop return connectionHandle; } - private TimeSpan EnsureTimeout(Stopwatch stopwatch) + private void EnsureTimeout(OperationCancellationContext cancellationContext) { - var timeSpentInWaitQueue = stopwatch.Elapsed; - var timeout = _timeout - timeSpentInWaitQueue; - - if (timeout < TimeSpan.Zero) + if (cancellationContext.IsTimedOut()) { - throw _pool.CreateTimeoutException(stopwatch, $"Timed out waiting for a connection after {timeSpentInWaitQueue.TotalMilliseconds}ms."); + throw _pool.CreateTimeoutException(cancellationContext, $"Timed out waiting for a connection after {cancellationContext.Elapsed.TotalMilliseconds}ms."); } - - return timeout; } - private Exception CreateException(Stopwatch stopwatch) => + private Exception CreateException(OperationCancellationContext cancellationContext) => _poolQueueWaitResult switch { SemaphoreSlimSignalable.SemaphoreWaitResult.Signaled => MongoConnectionPoolPausedException.ForConnectionPool(_pool._endPoint), SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => - _pool.CreateTimeoutException(stopwatch, $"Timed out waiting for a connection after {stopwatch.ElapsedMilliseconds}ms."), + _pool.CreateTimeoutException(cancellationContext, $"Timed out waiting for a connection after {cancellationContext.Elapsed.TotalMilliseconds}ms."), // should not be reached _ => new InvalidOperationException($"Invalid {_poolQueueWaitResult}.") }; @@ -846,41 +830,33 @@ public void UntrackInUseConnection(PooledConnection connection) internal sealed class ConnectionCreator : IDisposable { private readonly ExclusiveConnectionPool _pool; - private readonly TimeSpan _connectingTimeout; private PooledConnection _connection; private bool _disposeConnection; private SemaphoreSlimSignalable.SemaphoreWaitResult _connectingWaitStatus; - private Stopwatch _stopwatch; - - public ConnectionCreator(ExclusiveConnectionPool pool, TimeSpan connectingTimeout) + public ConnectionCreator(ExclusiveConnectionPool pool) { _pool = pool; - _connectingTimeout = connectingTimeout; _connectingWaitStatus = SemaphoreSlimSignalable.SemaphoreWaitResult.None; _connection = null; _disposeConnection = true; - _stopwatch = null; } - public PooledConnection CreateOpened(CancellationToken cancellationToken) + public PooledConnection CreateOpened(OperationCancellationContext cancellationContext) { try { - var stopwatch = Stopwatch.StartNew(); - _connectingWaitStatus = _pool._maxConnectingQueue.Wait(_connectingTimeout, cancellationToken); - stopwatch.Stop(); - + _connectingWaitStatus = _pool._maxConnectingQueue.Wait(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken); _pool._poolState.ThrowIfNotReady(); if (_connectingWaitStatus == SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut) { - _pool.CreateTimeoutException(stopwatch, $"Timed out waiting for in connecting queue after {stopwatch.ElapsedMilliseconds}ms."); + _pool.CreateTimeoutException(cancellationContext, $"Timed out waiting for in connecting queue after {cancellationContext.Elapsed.TotalMilliseconds}ms."); } - return CreateOpenedInternal(cancellationToken); + return CreateOpenedInternal(cancellationContext); } catch (Exception ex) { @@ -889,13 +865,11 @@ public PooledConnection CreateOpened(CancellationToken cancellationToken) } } - public PooledConnection CreateOpenedOrReuse(CancellationToken cancellationToken) + public PooledConnection CreateOpenedOrReuse(OperationCancellationContext cancellationContext) { try { var connection = _pool._connectionHolder.Acquire(); - var waitTimeout = _connectingTimeout; - var stopwatch = Stopwatch.StartNew(); while (connection == null) { @@ -905,21 +879,19 @@ public PooledConnection CreateOpenedOrReuse(CancellationToken cancellationToken) // Entered: The request was successfully fulfilled, and a connection establishment can start // Signaled: The request was interrupted because Connection was return to pool and can be reused // Timeout: The request was timed out after WaitQueueTimeout period. - _connectingWaitStatus = _pool._maxConnectingQueue.WaitSignaled(waitTimeout, cancellationToken); + _connectingWaitStatus = _pool._maxConnectingQueue.WaitSignaled(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken); connection = _connectingWaitStatus switch { SemaphoreSlimSignalable.SemaphoreWaitResult.Signaled => _pool._connectionHolder.Acquire(), - SemaphoreSlimSignalable.SemaphoreWaitResult.Entered => CreateOpenedInternal(cancellationToken), - SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(stopwatch), + SemaphoreSlimSignalable.SemaphoreWaitResult.Entered => CreateOpenedInternal(cancellationContext), + SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(cancellationContext), _ => throw new InvalidOperationException($"Invalid wait result {_connectingWaitStatus}") }; - waitTimeout = _connectingTimeout - stopwatch.Elapsed; - - if (connection == null && waitTimeout <= TimeSpan.Zero) + if (connection == null && cancellationContext.IsTimedOut()) { - throw CreateTimeoutException(stopwatch); + throw CreateTimeoutException(cancellationContext); } } @@ -932,15 +904,12 @@ public PooledConnection CreateOpenedOrReuse(CancellationToken cancellationToken) } } - public async Task CreateOpenedOrReuseAsync(CancellationToken cancellationToken) + public async Task CreateOpenedOrReuseAsync(OperationCancellationContext cancellationContext) { try { var connection = _pool._connectionHolder.Acquire(); - var waitTimeout = _connectingTimeout; - var stopwatch = Stopwatch.StartNew(); - while (connection == null) { _pool._poolState.ThrowIfNotReady(); @@ -949,21 +918,19 @@ public async Task CreateOpenedOrReuseAsync(CancellationToken c // Entered: The request was successfully fulfilled, and a connection establishment can start // Signaled: The request was interrupted because Connection was return to pool and can be reused // Timeout: The request was timed out after WaitQueueTimeout period. - _connectingWaitStatus = await _pool._maxConnectingQueue.WaitSignaledAsync(waitTimeout, cancellationToken).ConfigureAwait(false); + _connectingWaitStatus = await _pool._maxConnectingQueue.WaitSignaledAsync(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken).ConfigureAwait(false); connection = _connectingWaitStatus switch { SemaphoreSlimSignalable.SemaphoreWaitResult.Signaled => _pool._connectionHolder.Acquire(), - SemaphoreSlimSignalable.SemaphoreWaitResult.Entered => await CreateOpenedInternalAsync(cancellationToken).ConfigureAwait(false), - SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(stopwatch), + SemaphoreSlimSignalable.SemaphoreWaitResult.Entered => await CreateOpenedInternalAsync(cancellationContext).ConfigureAwait(false), + SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(cancellationContext), _ => throw new InvalidOperationException($"Invalid wait result {_connectingWaitStatus}") }; - waitTimeout = _connectingTimeout - stopwatch.Elapsed; - - if (connection == null && waitTimeout <= TimeSpan.Zero) + if (connection == null && cancellationContext.IsTimedOut()) { - throw CreateTimeoutException(stopwatch); + throw CreateTimeoutException(cancellationContext); } } @@ -991,54 +958,56 @@ public void Dispose() } // private methods - private PooledConnection CreateOpenedInternal(CancellationToken cancellationToken) + private PooledConnection CreateOpenedInternal(OperationCancellationContext cancellationContext) { - StartCreating(cancellationToken); + StartCreating(cancellationContext); - _connection.Open(cancellationToken); + // TODO: CSOT add support of CSOT timeout in connection open code too. + _connection.Open(cancellationContext.CancellationToken); - FinishCreating(_connection.Description); + FinishCreating(_connection.Description, cancellationContext); return _connection; } - private async Task CreateOpenedInternalAsync(CancellationToken cancellationToken) + private async Task CreateOpenedInternalAsync(OperationCancellationContext cancellationContext) { - StartCreating(cancellationToken); + StartCreating(cancellationContext); - await _connection.OpenAsync(cancellationToken).ConfigureAwait(false); + // TODO: CSOT add support of CSOT timeout in connection open code too. + await _connection.OpenAsync(cancellationContext.CancellationToken).ConfigureAwait(false); - FinishCreating(_connection.Description); + FinishCreating(_connection.Description, cancellationContext); return _connection; } - private void StartCreating(CancellationToken cancellationToken) + private void StartCreating(OperationCancellationContext cancellationContext) { _pool._eventLogger.LogAndPublish(new ConnectionPoolAddingConnectionEvent(_pool._serverId, EventContext.OperationId)); - cancellationToken.ThrowIfCancellationRequested(); - - _stopwatch = Stopwatch.StartNew(); + cancellationContext.CancellationToken.ThrowIfCancellationRequested(); + if (cancellationContext.IsTimedOut()) + { + throw new TimeoutException(); + } _connection = _pool.CreateNewConnection(); } - private void FinishCreating(ConnectionDescription description) + private void FinishCreating(ConnectionDescription description, OperationCancellationContext cancellationContext) { - _stopwatch.Stop(); - - _pool._eventLogger.LogAndPublish(new ConnectionPoolAddedConnectionEvent(_connection.ConnectionId, _stopwatch.Elapsed, EventContext.OperationId)); + _pool._eventLogger.LogAndPublish(new ConnectionPoolAddedConnectionEvent(_connection.ConnectionId, cancellationContext.Elapsed, EventContext.OperationId)); // Only if reached this stage, connection should not be disposed _disposeConnection = false; _pool._serviceStates.IncrementConnectionCount(description?.ServiceId); } - private Exception CreateTimeoutException(Stopwatch stopwatch) + private Exception CreateTimeoutException(OperationCancellationContext cancellationContext) { - var message = $"Timed out waiting in connecting queue after {stopwatch.ElapsedMilliseconds}ms."; - return _pool.CreateTimeoutException(stopwatch, message); + var message = $"Timed out waiting in connecting queue after {cancellationContext.Elapsed.TotalMilliseconds}ms."; + return _pool.CreateTimeoutException(cancellationContext, message); } } } diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.cs index 8490bba1b07..0dc075b603e 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.cs @@ -15,7 +15,6 @@ using System; using System.Net; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver.Core.Configuration; @@ -140,16 +139,18 @@ public int UsedCount internal ListConnectionHolder ConnectionHolder => _connectionHolder; // public methods - public IConnectionHandle AcquireConnection(CancellationToken cancellationToken) + public IConnectionHandle AcquireConnection(OperationCancellationContext cancellationContext) { + cancellationContext = cancellationContext.WithTimeout(Settings.WaitQueueTimeout); using var helper = new AcquireConnectionHelper(this); - return helper.AcquireConnection(cancellationToken); + return helper.AcquireConnection(cancellationContext); } - public async Task AcquireConnectionAsync(CancellationToken cancellationToken) + public async Task AcquireConnectionAsync(OperationCancellationContext cancellationContext) { + cancellationContext = cancellationContext.WithTimeout(Settings.WaitQueueTimeout); using var helper = new AcquireConnectionHelper(this); - return await helper.AcquireConnectionAsync(cancellationToken).ConfigureAwait(false); + return await helper.AcquireConnectionAsync(cancellationContext).ConfigureAwait(false); } public void Clear(bool closeInUseConnections = false) diff --git a/src/MongoDB.Driver/Core/ConnectionPools/IConnectionPool.cs b/src/MongoDB.Driver/Core/ConnectionPools/IConnectionPool.cs index 24f2ff48e4e..583e717dada 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/IConnectionPool.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/IConnectionPool.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver.Core.Connections; @@ -27,8 +26,8 @@ internal interface IConnectionPool : IDisposable int Generation { get; } ServerId ServerId { get; } - IConnectionHandle AcquireConnection(CancellationToken cancellationToken); - Task AcquireConnectionAsync(CancellationToken cancellationToken); + IConnectionHandle AcquireConnection(OperationCancellationContext cancellationContext); + Task AcquireConnectionAsync(OperationCancellationContext cancellationContext); void Clear(bool closeInUseConnections = false); void Clear(ObjectId serviceId); int GetGeneration(ObjectId? serviceId); diff --git a/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs b/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs index a8f2bdfa12f..91a4b6d405e 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs @@ -113,21 +113,20 @@ private void RunMaintenance(MaintenanceExecutingContext maintenanceExecutingCont private void EnsureMinSize(CancellationToken cancellationToken) { - var minTimeout = TimeSpan.FromMilliseconds(20); - while (_connectionPool.CreatedCount < _connectionPool.Settings.MinConnections && !cancellationToken.IsCancellationRequested) { using (var poolAwaiter = _connectionPool.CreateMaxConnectionsAwaiter()) { - var entered = poolAwaiter.WaitSignaled(minTimeout, cancellationToken); + var cancellationContext = new OperationCancellationContext(TimeSpan.FromMilliseconds(20), cancellationToken); + var entered = poolAwaiter.WaitSignaled(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken); if (!entered) { return; } - using (var connectionCreator = new ConnectionCreator(_connectionPool, minTimeout)) + using (var connectionCreator = new ConnectionCreator(_connectionPool)) { - var connection = connectionCreator.CreateOpened(cancellationToken); + var connection = connectionCreator.CreateOpened(cancellationContext); _connectionPool.ConnectionHolder.Return(connection); } } diff --git a/src/MongoDB.Driver/Core/Misc/Feature.cs b/src/MongoDB.Driver/Core/Misc/Feature.cs index 506e28de10c..cfcfb59dd98 100644 --- a/src/MongoDB.Driver/Core/Misc/Feature.cs +++ b/src/MongoDB.Driver/Core/Misc/Feature.cs @@ -565,9 +565,11 @@ internal int LastNotSupportedWireVersion public void ThrowIfNotSupported(IMongoClient client, CancellationToken cancellationToken = default) { var cluster = client.GetClusterInternal(); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, NoCoreSession.NewHandle()))) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(operationCancellationContext)) + using (var channel = channelSource.GetChannel(operationCancellationContext)) { // Use WireVersion from a connection since server level value may be null ThrowIfNotSupported(channel.ConnectionDescription.MaxWireVersion); @@ -582,9 +584,11 @@ public void ThrowIfNotSupported(IMongoClient client, CancellationToken cancellat public async Task ThrowIfNotSupportedAsync(IMongoClient client, CancellationToken cancellationToken = default) { var cluster = client.GetClusterInternal(); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, NoCoreSession.NewHandle()))) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationCancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationCancellationContext).ConfigureAwait(false)) { // Use WireVersion from a connection since server level value may be null ThrowIfNotSupported(channel.ConnectionDescription.MaxWireVersion); diff --git a/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs b/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs index a66161543a9..bd575f7bff5 100644 --- a/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs @@ -16,7 +16,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.IO; @@ -270,19 +269,19 @@ public bool? UseCursor // methods /// - public IAsyncCursor Execute(IReadBinding binding, CancellationToken cancellationToken) + public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) { - return Execute(context, cancellationToken); + return Execute(context, cancellationContext); } } /// - public IAsyncCursor Execute(RetryableReadContext context, CancellationToken cancellationToken) + public IAsyncCursor Execute(RetryableReadContext context, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(context, nameof(context)); EnsureIsReadOnlyPipeline(); @@ -290,7 +289,7 @@ public IAsyncCursor Execute(RetryableReadContext context, CancellationT using (EventContext.BeginOperation()) { var operation = CreateOperation(context); - var result = operation.Execute(context, cancellationToken); + var result = operation.Execute(context, cancellationContext); context.ChannelSource.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); @@ -299,19 +298,19 @@ public IAsyncCursor Execute(RetryableReadContext context, CancellationT } /// - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); } } /// - public async Task> ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken) + public async Task> ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(context, nameof(context)); EnsureIsReadOnlyPipeline(); @@ -319,7 +318,7 @@ public async Task> ExecuteAsync(RetryableReadContext conte using (EventContext.BeginOperation()) { var operation = CreateOperation(context); - var result = await operation.ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + var result = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); context.ChannelSource.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); diff --git a/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs index 88bc86f854c..db3c4e455a2 100644 --- a/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs @@ -16,7 +16,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -148,33 +147,33 @@ public WriteConcern WriteConcern set { _writeConcern = value; } } - public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); var mayUseSecondary = new MayUseSecondary(_readPreference); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(mayUseSecondary, cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(mayUseSecondary, cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, mayUseSecondary.EffectiveReadPreference); - return operation.Execute(channelBinding, cancellationToken); + return operation.Execute(channelBinding, cancellationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); var mayUseSecondary = new MayUseSecondary(_readPreference); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(mayUseSecondary, cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(mayUseSecondary, cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, mayUseSecondary.EffectiveReadPreference); - return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs b/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs index 1f0e4e46138..769d6f6aaaf 100644 --- a/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs +++ b/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs @@ -409,8 +409,10 @@ private void DisposeChannelSourceIfNoLongerNeeded() private CursorBatch GetNextBatch(CancellationToken cancellationToken) { + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var cancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) - using (var channel = _channelSource.GetChannel(cancellationToken)) + using (var channel = _channelSource.GetChannel(cancellationContext)) { return ExecuteGetMoreCommand(channel, cancellationToken); } @@ -418,8 +420,10 @@ private CursorBatch GetNextBatch(CancellationToken cancellationToken) private async Task> GetNextBatchAsync(CancellationToken cancellationToken) { + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var cancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) - using (var channel = await _channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channel = await _channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) { return await ExecuteGetMoreCommandAsync(channel, cancellationToken).ConfigureAwait(false); } @@ -432,10 +436,11 @@ private bool IsMongoCursorNotFoundException(MongoCommandException exception) private void KillCursors(CancellationToken cancellationToken) { + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var cancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) using (EventContext.BeginKillCursors(_collectionNamespace)) - using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10))) - using (var channel = _channelSource.GetChannel(cancellationTokenSource.Token)) + using (var channel = _channelSource.GetChannel(cancellationContext.WithTimeout(TimeSpan.FromSeconds(10)))) { if (!channel.Connection.IsExpired) { @@ -446,10 +451,11 @@ private void KillCursors(CancellationToken cancellationToken) private async Task KillCursorsAsync(CancellationToken cancellationToken) { + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var cancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) using (EventContext.BeginKillCursors(_collectionNamespace)) - using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(10))) - using (var channel = await _channelSource.GetChannelAsync(cancellationTokenSource.Token).ConfigureAwait(false)) + using (var channel = await _channelSource.GetChannelAsync(cancellationContext.WithTimeout(TimeSpan.FromSeconds(10))).ConfigureAwait(false)) { if (!channel.Connection.IsExpired) { diff --git a/src/MongoDB.Driver/Core/Operations/BulkMixedWriteOperation.cs b/src/MongoDB.Driver/Core/Operations/BulkMixedWriteOperation.cs index c529c2ebc56..24c8832c1cc 100644 --- a/src/MongoDB.Driver/Core/Operations/BulkMixedWriteOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/BulkMixedWriteOperation.cs @@ -16,7 +16,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver.Core.Bindings; @@ -137,33 +136,33 @@ public WriteConcern WriteConcern set { _writeConcern = Ensure.IsNotNull(value, nameof(value)); } } - public BulkWriteOperationResult Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BulkWriteOperationResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { using (BeginOperation()) - using (var context = RetryableWriteContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableWriteContext.Create(binding, _retryRequested, cancellationContext)) { EnsureHintIsSupportedIfAnyRequestHasHint(); context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); var helper = new BatchHelper(_requests, _isOrdered, _writeConcern); foreach (var batch in helper.GetBatches()) { - batch.Result = ExecuteBatch(context, batch, cancellationToken); + batch.Result = ExecuteBatch(context, batch, cancellationContext); } return helper.GetFinalResultOrThrow(context.Channel.ConnectionDescription.ConnectionId); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { using (BeginOperation()) - using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) { EnsureHintIsSupportedIfAnyRequestHasHint(); context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); var helper = new BatchHelper(_requests, _isOrdered, _writeConcern); foreach (var batch in helper.GetBatches()) { - batch.Result = await ExecuteBatchAsync(context, batch, cancellationToken).ConfigureAwait(false); + batch.Result = await ExecuteBatchAsync(context, batch, cancellationContext).ConfigureAwait(false); } return helper.GetFinalResultOrThrow(context.Channel.ConnectionDescription.ConnectionId); } @@ -242,14 +241,14 @@ private void EnsureHintIsSupportedIfAnyRequestHasHint() } } - private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken) + private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch batch, OperationCancellationContext cancellationContext) { BulkWriteOperationResult result; MongoBulkWriteOperationException exception = null; try { var operation = CreateUnmixedBatchOperation(batch); - result = operation.Execute(context, cancellationToken); + result = operation.Execute(context, cancellationContext); } catch (MongoBulkWriteOperationException ex) { @@ -260,14 +259,14 @@ private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch b return BulkWriteBatchResult.Create(result, exception, batch.IndexMap); } - private async Task ExecuteBatchAsync(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken) + private async Task ExecuteBatchAsync(RetryableWriteContext context, Batch batch, OperationCancellationContext cancellationContext) { BulkWriteOperationResult result; MongoBulkWriteOperationException exception = null; try { var operation = CreateUnmixedBatchOperation(batch); - result = await operation.ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + result = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); } catch (MongoBulkWriteOperationException ex) { diff --git a/src/MongoDB.Driver/Core/Operations/BulkUnmixedWriteOperationBase.cs b/src/MongoDB.Driver/Core/Operations/BulkUnmixedWriteOperationBase.cs index 616b150b155..4f9d2b34b70 100644 --- a/src/MongoDB.Driver/Core/Operations/BulkUnmixedWriteOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/BulkUnmixedWriteOperationBase.cs @@ -16,7 +16,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver.Core.Bindings; @@ -120,37 +119,37 @@ public WriteConcern WriteConcern } // public methods - public BulkWriteOperationResult Execute(RetryableWriteContext context, CancellationToken cancellationToken) + public BulkWriteOperationResult Execute(RetryableWriteContext context, OperationCancellationContext cancellationContext) { EnsureHintIsSupportedIfAnyRequestHasHint(); - return ExecuteBatches(context, cancellationToken); + return ExecuteBatches(context, cancellationContext); } - public BulkWriteOperationResult Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BulkWriteOperationResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { using (BeginOperation()) - using (var context = RetryableWriteContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableWriteContext.Create(binding, _retryRequested, cancellationContext)) { context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); - return Execute(context, cancellationToken); + return Execute(context, cancellationContext); } } - public Task ExecuteAsync(RetryableWriteContext context, CancellationToken cancellationToken) + public Task ExecuteAsync(RetryableWriteContext context, OperationCancellationContext cancellationContext) { EnsureHintIsSupportedIfAnyRequestHasHint(); - return ExecuteBatchesAsync(context, cancellationToken); + return ExecuteBatchesAsync(context, cancellationContext); } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { using (BeginOperation()) - using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) { context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); } } @@ -190,14 +189,14 @@ private void EnsureHintIsSupportedIfAnyRequestHasHint() } } - private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken) + private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch batch, OperationCancellationContext cancellationContext) { var operation = CreateBatchOperation(batch); BsonDocument operationResult; MongoWriteConcernException writeConcernException = null; try { - operationResult = RetryableWriteOperationExecutor.Execute(operation, context, cancellationToken); + operationResult = RetryableWriteOperationExecutor.Execute(operation, context, cancellationContext); } catch (MongoWriteConcernException exception) when (exception.IsWriteConcernErrorOnly()) { @@ -208,14 +207,14 @@ private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch b return CreateBatchResult(batch, operationResult, writeConcernException); } - private async Task ExecuteBatchAsync(RetryableWriteContext context, Batch batch, CancellationToken cancellationToken) + private async Task ExecuteBatchAsync(RetryableWriteContext context, Batch batch, OperationCancellationContext cancellationContext) { var operation = CreateBatchOperation(batch); BsonDocument operationResult; MongoWriteConcernException writeConcernException = null; try { - operationResult = await RetryableWriteOperationExecutor.ExecuteAsync(operation, context, cancellationToken).ConfigureAwait(false); + operationResult = await RetryableWriteOperationExecutor.ExecuteAsync(operation, context, cancellationContext).ConfigureAwait(false); } catch (MongoWriteConcernException exception) when (exception.IsWriteConcernErrorOnly()) { @@ -226,22 +225,22 @@ private async Task ExecuteBatchAsync(RetryableWriteContext return CreateBatchResult(batch, operationResult, writeConcernException); } - private BulkWriteOperationResult ExecuteBatches(RetryableWriteContext context, CancellationToken cancellationToken) + private BulkWriteOperationResult ExecuteBatches(RetryableWriteContext context, OperationCancellationContext cancellationContext) { var helper = new BatchHelper(_requests, _writeConcern, _isOrdered); foreach (var batch in helper.GetBatches()) { - batch.Result = ExecuteBatch(context, batch, cancellationToken); + batch.Result = ExecuteBatch(context, batch, cancellationContext); } return helper.CreateFinalResultOrThrow(context.Channel); } - private async Task ExecuteBatchesAsync(RetryableWriteContext context, CancellationToken cancellationToken) + private async Task ExecuteBatchesAsync(RetryableWriteContext context, OperationCancellationContext cancellationContext) { var helper = new BatchHelper(_requests, _writeConcern, _isOrdered); foreach (var batch in helper.GetBatches()) { - batch.Result = await ExecuteBatchAsync(context, batch, cancellationToken).ConfigureAwait(false); + batch.Result = await ExecuteBatchAsync(context, batch, cancellationContext).ConfigureAwait(false); } return helper.CreateFinalResultOrThrow(context.Channel); } diff --git a/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs b/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs index 4dfabd9a026..c73c4f36252 100644 --- a/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs +++ b/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs @@ -261,13 +261,17 @@ private void ReconfigureOperationResumeValues() private IAsyncCursor Resume(CancellationToken cancellationToken) { ReconfigureOperationResumeValues(); - return _changeStreamOperation.Resume(_binding, cancellationToken); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + return _changeStreamOperation.Resume(_binding, operationCancellationContext); } private async Task> ResumeAsync(CancellationToken cancellationToken) { ReconfigureOperationResumeValues(); - return await _changeStreamOperation.ResumeAsync(_binding, cancellationToken).ConfigureAwait(false); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + return await _changeStreamOperation.ResumeAsync(_binding, operationCancellationContext).ConfigureAwait(false); } internal struct ResumeValues diff --git a/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs b/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs index b9ed21931b0..8dd08e0024a 100644 --- a/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs @@ -16,7 +16,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization; @@ -34,8 +33,8 @@ internal interface IChangeStreamOperation : IReadOperation Resume(IReadBinding binding, CancellationToken cancellationToken); - Task> ResumeAsync(IReadBinding binding, CancellationToken cancellationToken); + IAsyncCursor Resume(IReadBinding binding, OperationCancellationContext cancellationContext); + Task> ResumeAsync(IReadBinding binding, OperationCancellationContext cancellationContext); } internal sealed class ChangeStreamOperation : IChangeStreamOperation @@ -250,7 +249,7 @@ public BsonTimestamp StartAtOperationTime // public methods /// - public IChangeStreamCursor Execute(IReadBinding binding, CancellationToken cancellationToken) + public IChangeStreamCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); var bindingHandle = binding as IReadBindingHandle; @@ -262,9 +261,9 @@ public IChangeStreamCursor Execute(IReadBinding binding, CancellationTo IAsyncCursor cursor; ICursorBatchInfo cursorBatchInfo; BsonTimestamp initialOperationTime; - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) { - cursor = ExecuteAggregateOperation(context, cancellationToken); + cursor = ExecuteAggregateOperation(context, cancellationContext); cursorBatchInfo = (ICursorBatchInfo)cursor; initialOperationTime = GetInitialOperationTimeIfRequired(context, cursorBatchInfo); @@ -285,7 +284,7 @@ public IChangeStreamCursor Execute(IReadBinding binding, CancellationTo } /// - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); var bindingHandle = binding as IReadBindingHandle; @@ -297,9 +296,9 @@ public async Task> ExecuteAsync(IReadBinding bindin IAsyncCursor cursor; ICursorBatchInfo cursorBatchInfo; BsonTimestamp initialOperationTime; - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) { - cursor = await ExecuteAggregateOperationAsync(context, cancellationToken).ConfigureAwait(false); + cursor = await ExecuteAggregateOperationAsync(context, cancellationContext).ConfigureAwait(false); cursorBatchInfo = (ICursorBatchInfo)cursor; initialOperationTime = GetInitialOperationTimeIfRequired(context, cursorBatchInfo); @@ -320,20 +319,20 @@ public async Task> ExecuteAsync(IReadBinding bindin } /// - public IAsyncCursor Resume(IReadBinding binding, CancellationToken cancellationToken) + public IAsyncCursor Resume(IReadBinding binding, OperationCancellationContext cancellationContext) { - using (var context = RetryableReadContext.Create(binding, retryRequested: false, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, retryRequested: false, cancellationContext)) { - return ExecuteAggregateOperation(context, cancellationToken); + return ExecuteAggregateOperation(context, cancellationContext); } } /// - public async Task> ResumeAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ResumeAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { - using (var context = await RetryableReadContext.CreateAsync(binding, retryRequested: false, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, retryRequested: false, cancellationContext).ConfigureAwait(false)) { - return await ExecuteAggregateOperationAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAggregateOperationAsync(context, cancellationContext).ConfigureAwait(false); } } @@ -392,16 +391,16 @@ private List CreateCombinedPipeline(BsonDocument changeStreamStage return combinedPipeline; } - private IAsyncCursor ExecuteAggregateOperation(RetryableReadContext context, CancellationToken cancellationToken) + private IAsyncCursor ExecuteAggregateOperation(RetryableReadContext context, OperationCancellationContext cancellationContext) { var aggregateOperation = CreateAggregateOperation(); - return aggregateOperation.Execute(context, cancellationToken); + return aggregateOperation.Execute(context, cancellationContext); } - private Task> ExecuteAggregateOperationAsync(RetryableReadContext context, CancellationToken cancellationToken) + private Task> ExecuteAggregateOperationAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) { var aggregateOperation = CreateAggregateOperation(); - return aggregateOperation.ExecuteAsync(context, cancellationToken); + return aggregateOperation.ExecuteAsync(context, cancellationContext); } private BsonDocument GetInitialPostBatchResumeTokenIfRequired(ICursorBatchInfo cursorBatchInfo) diff --git a/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs b/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs index b994a95388d..e6dfbc20191 100644 --- a/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs @@ -16,7 +16,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -89,17 +88,17 @@ protected override IEnumerable CreateCommandPayl return new[] { payload }; } - public new ClientBulkWriteResult Execute(IWriteBinding binding, CancellationToken cancellationToken) + public new ClientBulkWriteResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { using var operation = BeginOperation(); var bulkWriteResults = new BulkWriteRawResult(); while (true) { - using var context = RetryableWriteContext.Create(binding, GetEffectiveRetryRequested(), cancellationToken); + using var context = RetryableWriteContext.Create(binding, GetEffectiveRetryRequested(), cancellationContext); BsonDocument serverResponse = null; try { - serverResponse = base.Execute(context, cancellationToken); + serverResponse = base.Execute(context, cancellationContext); } catch (MongoWriteConcernException concernException) { @@ -124,7 +123,7 @@ protected override IEnumerable CreateCommandPayl { try { - while (individualResults.MoveNext(cancellationToken)) + while (individualResults.MoveNext(cancellationContext.CancellationToken)) { PopulateIndividualResponses(individualResults.Current, bulkWriteResults); } @@ -146,17 +145,17 @@ protected override IEnumerable CreateCommandPayl } } - public new async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public new async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { using var operation = BeginOperation(); var bulkWriteResults = new BulkWriteRawResult(); while (true) { - using var context = RetryableWriteContext.Create(binding, GetEffectiveRetryRequested(), cancellationToken); + using var context = RetryableWriteContext.Create(binding, GetEffectiveRetryRequested(), cancellationContext); BsonDocument serverResponse = null; try { - serverResponse = await base.ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + serverResponse = await base.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); } catch (MongoWriteConcernException concernException) { @@ -181,7 +180,7 @@ protected override IEnumerable CreateCommandPayl { try { - while (await individualResults.MoveNextAsync(cancellationToken).ConfigureAwait(false)) + while (await individualResults.MoveNextAsync(cancellationContext.CancellationToken).ConfigureAwait(false)) { PopulateIndividualResponses(individualResults.Current, bulkWriteResults); } diff --git a/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs b/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs index 18f18b14b6d..35bb200e2f7 100644 --- a/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs @@ -108,11 +108,11 @@ protected TCommandResult ExecuteProtocol( IChannelSource channelSource, ICoreSessionHandle session, ReadPreference readPreference, - CancellationToken cancellationToken) + OperationCancellationContext cancellationContext) { - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channel = channelSource.GetChannel(cancellationContext)) { - return ExecuteProtocol(channel, session, readPreference, cancellationToken); + return ExecuteProtocol(channel, session, readPreference, cancellationContext.CancellationToken); } } @@ -139,11 +139,11 @@ protected async Task ExecuteProtocolAsync( IChannelSource channelSource, ICoreSessionHandle session, ReadPreference readPreference, - CancellationToken cancellationToken) + OperationCancellationContext cancellationContext) { - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) { - return await ExecuteProtocolAsync(channel, session, readPreference, cancellationToken).ConfigureAwait(false); + return await ExecuteProtocolAsync(channel, session, readPreference, cancellationContext.CancellationToken).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/CompositeWriteOperation.cs b/src/MongoDB.Driver/Core/Operations/CompositeWriteOperation.cs index 64a270c4486..71caa80e40e 100644 --- a/src/MongoDB.Driver/Core/Operations/CompositeWriteOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CompositeWriteOperation.cs @@ -14,7 +14,6 @@ */ using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Misc; @@ -32,12 +31,12 @@ public CompositeWriteOperation(params (IWriteOperation, bool IsMainOper Ensure.That(operations.Count(o => o.IsMainOperation) == 1, message: $"{nameof(CompositeWriteOperation)} must have a single main operation."); } - public TResult Execute(IWriteBinding binding, CancellationToken cancellationToken) + public TResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { TResult result = default; foreach (var operationInfo in _operations) { - var itemResult = operationInfo.Operation.Execute(binding, cancellationToken); + var itemResult = operationInfo.Operation.Execute(binding, cancellationContext); if (operationInfo.IsMainOperation) { result = itemResult; @@ -47,12 +46,12 @@ public TResult Execute(IWriteBinding binding, CancellationToken cancellationToke return result; } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { TResult result = default; foreach (var operationInfo in _operations) { - var itemResult = await operationInfo.Operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + var itemResult = await operationInfo.Operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); if (operationInfo.IsMainOperation) { result = itemResult; diff --git a/src/MongoDB.Driver/Core/Operations/CountDocumentsOperation.cs b/src/MongoDB.Driver/Core/Operations/CountDocumentsOperation.cs index 2871029e2a1..eb88438ba10 100644 --- a/src/MongoDB.Driver/Core/Operations/CountDocumentsOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CountDocumentsOperation.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -110,28 +109,28 @@ public long? Skip set { _skip = value; } } - public long Execute(IReadBinding binding, CancellationToken cancellationToken) + public long Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var cursor = operation.Execute(binding, cancellationToken); - var result = cursor.ToList(cancellationToken); + var cursor = operation.Execute(binding, cancellationContext); + var result = cursor.ToList(cancellationContext.CancellationToken); return ExtractCountFromResult(result); } } - public async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); - var result = await cursor.ToListAsync(cancellationToken).ConfigureAwait(false); + var cursor = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); + var result = await cursor.ToListAsync(cancellationContext.CancellationToken).ConfigureAwait(false); return ExtractCountFromResult(result); } } diff --git a/src/MongoDB.Driver/Core/Operations/CountOperation.cs b/src/MongoDB.Driver/Core/Operations/CountOperation.cs index dc33440c61f..b7ea4a668ae 100644 --- a/src/MongoDB.Driver/Core/Operations/CountOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CountOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -127,39 +126,39 @@ public BsonDocument CreateCommand(ConnectionDescription connectionDescription, I }; } - public long Execute(IReadBinding binding, CancellationToken cancellationToken) + public long Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) { - return Execute(context, cancellationToken); + return Execute(context, cancellationContext); } } - public long Execute(RetryableReadContext context, CancellationToken cancellationToken) + public long Execute(RetryableReadContext context, OperationCancellationContext cancellationContext) { var operation = CreateOperation(context); - var document = operation.Execute(context, cancellationToken); + var document = operation.Execute(context, cancellationContext); return document["n"].ToInt64(); } - public async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); } } - public async Task ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken) + public async Task ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) { var operation = CreateOperation(context); - var document = await operation.ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + var document = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); return document["n"].ToInt64(); } diff --git a/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs index 9f9923a5c75..bf36d7e5a53 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -274,36 +273,36 @@ internal BsonDocument CreateCommand(ICoreSessionHandle session) } } - public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) { EnsureServerIsValid(channel.ConnectionDescription.MaxWireVersion); using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); - return operation.Execute(channelBinding, cancellationToken); + return operation.Execute(channelBinding, cancellationContext); } } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) { EnsureServerIsValid(channel.ConnectionDescription.MaxWireVersion); using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); - return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs index 1a19dc5787a..4d8789ee80d 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs @@ -16,7 +16,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -87,27 +86,27 @@ public TimeSpan? MaxTime set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); } } - public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return operation.Execute(channelBinding, cancellationToken); + return operation.Execute(channelBinding, cancellationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs index bb96493a076..1de7d07b176 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs @@ -15,7 +15,6 @@ using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -55,28 +54,28 @@ public CreateSearchIndexesOperation( // public methods /// - public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { using (EventContext.BeginOperation("createSearchIndexes")) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return operation.Execute(channelBinding, cancellationToken); + return operation.Execute(channelBinding, cancellationContext); } } /// - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { using (EventContext.BeginOperation("createSearchIndexes")) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs index cd291bfbf19..da19474048f 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs @@ -87,29 +87,29 @@ public WriteConcern WriteConcern set { _writeConcern = value; } } - public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return operation.Execute(channelBinding, cancellationToken); + return operation.Execute(channelBinding, cancellationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/DatabaseExistsOperation.cs b/src/MongoDB.Driver/Core/Operations/DatabaseExistsOperation.cs index ec4b4a42e4a..6f09f0a1caa 100644 --- a/src/MongoDB.Driver/Core/Operations/DatabaseExistsOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DatabaseExistsOperation.cs @@ -14,7 +14,6 @@ */ using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Misc; @@ -50,21 +49,23 @@ public bool RetryRequested set { _retryRequested = value; } } - public bool Execute(IReadBinding binding, CancellationToken cancellationToken) + public bool Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = operation.Execute(binding, cancellationToken); - var list = result.ToList(cancellationToken); + var result = operation.Execute(binding, cancellationContext); + // TODO: CSOT find a way to apply CSOT timeout to ToList as well. + var list = result.ToList(cancellationContext.CancellationToken); return list.Any(x => x["name"] == _databaseNamespace.DatabaseName); } - public async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); - var list = await result.ToListAsync(cancellationToken).ConfigureAwait(false); + var result = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); + // TODO: CSOT find a way to apply CSOT timeout to ToList as well. + var list = await result.ToListAsync(cancellationContext.CancellationToken).ConfigureAwait(false); return list.Any(x => x["name"] == _databaseNamespace.DatabaseName); } diff --git a/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs b/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs index 441996f2889..cabd2e2d56b 100644 --- a/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.IO; @@ -105,15 +104,15 @@ public IBsonSerializer ValueSerializer get { return _valueSerializer; } } - public IAsyncCursor Execute(IReadBinding binding, CancellationToken cancellationToken) + public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) { var operation = CreateOperation(context); - var result = operation.Execute(context, cancellationToken); + var result = operation.Execute(context, cancellationContext); binding.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); @@ -121,15 +120,15 @@ public IAsyncCursor Execute(IReadBinding binding, CancellationToken canc } } - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) { var operation = CreateOperation(context); - var result = await operation.ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + var result = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); binding.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); diff --git a/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs index fa7e11f8c70..e4af7f3a7c6 100644 --- a/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -96,20 +95,20 @@ public WriteConcern WriteConcern set { _writeConcern = value; } } - public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); BsonDocument result; try { - result = operation.Execute(channelBinding, cancellationToken); + result = operation.Execute(channelBinding, cancellationContext); } catch (MongoCommandException ex) { @@ -123,20 +122,20 @@ public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellatio } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); BsonDocument result; try { - result = await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + result = await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } catch (MongoCommandException ex) { diff --git a/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs b/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs index 315a5307409..1a566015e2b 100644 --- a/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -53,8 +52,8 @@ public WriteConcern WriteConcern { get { return _writeConcern; } set { _writeConcern = value; } - } - + } + public BsonDocument CreateCommand(ICoreSessionHandle session) { var writeConcern = WriteConcernHelper.GetEffectiveWriteConcern(session, _writeConcern); @@ -65,31 +64,31 @@ public BsonDocument CreateCommand(ICoreSessionHandle session) }; } - public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); - return operation.Execute(channelBinding, cancellationToken); + return operation.Execute(channelBinding, cancellationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); - return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs index 577ed62e448..193fb301ad4 100644 --- a/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -98,20 +97,20 @@ public BsonDocument CreateCommand(ICoreSessionHandle session) }; } - public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); BsonDocument result; try { - result = operation.Execute(channelBinding, cancellationToken); + result = operation.Execute(channelBinding, cancellationContext); } catch (MongoCommandException ex) { @@ -125,20 +124,20 @@ public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellatio } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); BsonDocument result; try { - result = await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + result = await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } catch (MongoCommandException ex) { @@ -150,7 +149,7 @@ public async Task ExecuteAsync(IWriteBinding binding, Cancellation } return result; } - } + } private IDisposable BeginOperation() => EventContext.BeginOperation("dropIndexes"); diff --git a/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs index 653039feb98..c8364680c2e 100644 --- a/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs @@ -13,7 +13,6 @@ * limitations under the License. */ -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -63,20 +62,20 @@ private WriteCommandOperation CreateOperation() => new(_collectionNamespace.DatabaseNamespace, CreateCommand(), BsonDocumentSerializer.Instance, _messageEncoderSettings); /// - public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation("dropSearchIndex")) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); try { - return operation.Execute(channelBinding, cancellationToken); + return operation.Execute(channelBinding, cancellationContext); } catch (MongoCommandException ex) when (ShouldIgnoreException(ex)) { @@ -86,20 +85,20 @@ public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellatio } /// - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation("dropSearchIndex")) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); try { - return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } catch (MongoCommandException ex) when (ShouldIgnoreException(ex)) { diff --git a/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs b/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs index 90e5f44c882..346e9d22e1b 100644 --- a/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -51,29 +50,29 @@ public MessageEncoderSettings MessageEncoderSettings protected abstract string CommandName { get; } - public virtual BsonDocument Execute(IReadBinding binding, CancellationToken cancellationToken) + public virtual BsonDocument Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetReadChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetReadChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return operation.Execute(channelBinding, cancellationToken); + return operation.Execute(channelBinding, cancellationContext); } } - public virtual async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public virtual async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = await binding.GetReadChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetReadChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } } @@ -134,11 +133,11 @@ public TimeSpan? MaxCommitTime protected override string CommandName => "commitTransaction"; - public override BsonDocument Execute(IReadBinding binding, CancellationToken cancellationToken) + public override BsonDocument Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { try { - return base.Execute(binding, cancellationToken); + return base.Execute(binding, cancellationContext); } catch (MongoException exception) when (ShouldReplaceTransientTransactionErrorWithUnknownTransactionCommitResult(exception)) { @@ -147,11 +146,11 @@ public override BsonDocument Execute(IReadBinding binding, CancellationToken can } } - public override async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public override async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { try { - return await base.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + return await base.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); } catch (MongoException exception) when (ShouldReplaceTransientTransactionErrorWithUnknownTransactionCommitResult(exception)) { diff --git a/src/MongoDB.Driver/Core/Operations/EstimatedDocumentCountOperation.cs b/src/MongoDB.Driver/Core/Operations/EstimatedDocumentCountOperation.cs index 27958d906f4..4dc34ecbb04 100644 --- a/src/MongoDB.Driver/Core/Operations/EstimatedDocumentCountOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/EstimatedDocumentCountOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver.Core.Bindings; @@ -67,29 +66,29 @@ public bool RetryRequested set => _retryRequested = value; } - public long Execute(IReadBinding binding, CancellationToken cancellationToken) + public long Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) { var operation = CreateCountOperation(); - return operation.Execute(context, cancellationToken); + return operation.Execute(context, cancellationContext); } } - public async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) { var operation = CreateCountOperation(); - return await operation.ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/EvalOperation.cs b/src/MongoDB.Driver/Core/Operations/EvalOperation.cs index 218d4b91e11..a1eb93ea1bb 100644 --- a/src/MongoDB.Driver/Core/Operations/EvalOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/EvalOperation.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -75,8 +74,8 @@ public bool? NoLock { get { return _noLock; } set { _noLock = value; } - } - + } + public BsonDocument CreateCommand() { return new BsonDocument @@ -88,19 +87,19 @@ public BsonDocument CreateCommand() }; } - public BsonValue Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonValue Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = operation.Execute(binding, cancellationToken); + var result = operation.Execute(binding, cancellationContext); return result["retval"]; } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + var result = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); return result["retval"]; } diff --git a/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs b/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs index 8bad1138f40..12c6835a0b6 100644 --- a/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs @@ -15,7 +15,6 @@ using System; using System.Text; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.IO; @@ -85,39 +84,39 @@ public bool RetryRequested set { _retryRequested = value; } } - public TResult Execute(IWriteBinding binding, CancellationToken cancellationToken) + public TResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.Execute(this, binding, _retryRequested, cancellationToken); + return RetryableWriteOperationExecutor.Execute(this, binding, _retryRequested, cancellationContext); } } - public TResult Execute(RetryableWriteContext context, CancellationToken cancellationToken) + public TResult Execute(RetryableWriteContext context, OperationCancellationContext cancellationContext) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.Execute(this, context, cancellationToken); + return RetryableWriteOperationExecutor.Execute(this, context, cancellationContext); } } - public Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { using (BeginOperation()) - { - return RetryableWriteOperationExecutor.ExecuteAsync(this, binding, _retryRequested, cancellationToken); + { + return RetryableWriteOperationExecutor.ExecuteAsync(this, binding, _retryRequested, cancellationContext); } } - public Task ExecuteAsync(RetryableWriteContext context, CancellationToken cancellationToken) + public Task ExecuteAsync(RetryableWriteContext context, OperationCancellationContext cancellationContext) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.ExecuteAsync(this, context, cancellationToken); + return RetryableWriteOperationExecutor.ExecuteAsync(this, context, cancellationContext); } } - public TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken) + public TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext) { var binding = context.Binding; var channelSource = context.ChannelSource; @@ -126,14 +125,14 @@ public TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, transactionNumber); - using (var rawBsonDocument = operation.Execute(channelBinding, cancellationToken)) + using (var rawBsonDocument = operation.Execute(channelBinding, cancellationContext)) { return ProcessCommandResult(channel.ConnectionDescription.ConnectionId, rawBsonDocument); } } } - public async Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken) + public async Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext) { var binding = context.Binding; var channelSource = context.ChannelSource; @@ -142,17 +141,17 @@ public async Task ExecuteAttemptAsync(RetryableWriteContext context, in using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, transactionNumber); - using (var rawBsonDocument = await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false)) + using (var rawBsonDocument = await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false)) { return ProcessCommandResult(channel.ConnectionDescription.ConnectionId, rawBsonDocument); } } - } - + } + public abstract BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber); - protected abstract IElementNameValidator GetCommandValidator(); - + protected abstract IElementNameValidator GetCommandValidator(); + private IDisposable BeginOperation() => EventContext.BeginOperation("findAndModify"); private WriteCommandOperation CreateOperation(ICoreSessionHandle session, ConnectionDescription connectionDescription, long? transactionNumber) diff --git a/src/MongoDB.Driver/Core/Operations/FindOperation.cs b/src/MongoDB.Driver/Core/Operations/FindOperation.cs index 236476cf4c2..593cfdcfc3a 100644 --- a/src/MongoDB.Driver/Core/Operations/FindOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/FindOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization; @@ -292,48 +291,48 @@ public BsonDocument CreateCommand(ConnectionDescription connectionDescription, I }; } - public IAsyncCursor Execute(IReadBinding binding, CancellationToken cancellationToken = default(CancellationToken)) + public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) { - return Execute(context, cancellationToken); + return Execute(context, cancellationContext); } } - public IAsyncCursor Execute(RetryableReadContext context, CancellationToken cancellationToken = default(CancellationToken)) + public IAsyncCursor Execute(RetryableReadContext context, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginFind(_batchSize, _limit)) { var operation = CreateOperation(context); - var commandResult = operation.Execute(context, cancellationToken); + var commandResult = operation.Execute(context, cancellationContext); return CreateCursor(context.ChannelSource, context.Channel, commandResult); } } - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); } } - public async Task> ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginFind(_batchSize, _limit)) { var operation = CreateOperation(context); - var commandResult = await operation.ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + var commandResult = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); return CreateCursor(context.ChannelSource, context.Channel, commandResult); } } diff --git a/src/MongoDB.Driver/Core/Operations/GroupOperation.cs b/src/MongoDB.Driver/Core/Operations/GroupOperation.cs index 7ae72c2444b..aa1f1e54f6c 100644 --- a/src/MongoDB.Driver/Core/Operations/GroupOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/GroupOperation.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization; @@ -139,27 +138,27 @@ public BsonDocument CreateCommand() }; } - public IEnumerable Execute(IReadBinding binding, CancellationToken cancellationToken) + public IEnumerable Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetReadChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetReadChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(); - return operation.Execute(channelBinding, cancellationToken); + return operation.Execute(channelBinding, cancellationContext); } } - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = await binding.GetReadChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetReadChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(); - return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/IOperation.cs b/src/MongoDB.Driver/Core/Operations/IOperation.cs index 06fa1fbabbf..cfc7c79e6f6 100644 --- a/src/MongoDB.Driver/Core/Operations/IOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/IOperation.cs @@ -13,7 +13,6 @@ * limitations under the License. */ -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Bindings; @@ -21,13 +20,13 @@ namespace MongoDB.Driver.Core.Operations { internal interface IReadOperation { - TResult Execute(IReadBinding binding, CancellationToken cancellationToken); - Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken); + TResult Execute(IReadBinding binding, OperationCancellationContext cancellationContext); + Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext); } internal interface IWriteOperation { - TResult Execute(IWriteBinding binding, CancellationToken cancellationToken); - Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken); + TResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext); + Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext); } } diff --git a/src/MongoDB.Driver/Core/Operations/IRetryableOperation.cs b/src/MongoDB.Driver/Core/Operations/IRetryableOperation.cs index efa510c1553..7bb816915e9 100644 --- a/src/MongoDB.Driver/Core/Operations/IRetryableOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/IRetryableOperation.cs @@ -13,34 +13,33 @@ * limitations under the License. */ -using System.Threading; using System.Threading.Tasks; namespace MongoDB.Driver.Core.Operations { internal interface IExecutableInRetryableReadContext { - TResult Execute(RetryableReadContext context, CancellationToken cancellationToken); - Task ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken); + TResult Execute(RetryableReadContext context, OperationCancellationContext cancellationContext); + Task ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext); } internal interface IExecutableInRetryableWriteContext { - TResult Execute(RetryableWriteContext context, CancellationToken cancellationToken); - Task ExecuteAsync(RetryableWriteContext context, CancellationToken cancellationToken); + TResult Execute(RetryableWriteContext context, OperationCancellationContext cancellationContext); + Task ExecuteAsync(RetryableWriteContext context, OperationCancellationContext cancellationContext); } internal interface IRetryableReadOperation : IExecutableInRetryableReadContext { - TResult ExecuteAttempt(RetryableReadContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken); - Task ExecuteAttemptAsync(RetryableReadContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken); + TResult ExecuteAttempt(RetryableReadContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext); + Task ExecuteAttemptAsync(RetryableReadContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext); } internal interface IRetryableWriteOperation : IExecutableInRetryableWriteContext { WriteConcern WriteConcern { get; } - TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken); - Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken); + TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext); + Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs b/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs index e25b97bbbd7..d0d06bd20fe 100644 --- a/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs @@ -15,7 +15,6 @@ using System; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -91,52 +90,52 @@ public bool RetryRequested set => _retryRequested = value; } - public IAsyncCursor Execute(IReadBinding binding, CancellationToken cancellationToken) + public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) { - return Execute(context, cancellationToken); + return Execute(context, cancellationContext); } } } - public IAsyncCursor Execute(RetryableReadContext context, CancellationToken cancellationToken) + public IAsyncCursor Execute(RetryableReadContext context, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(context, nameof(context)); using (BeginOperation()) { var operation = CreateOperation(); - var result = operation.Execute(context, cancellationToken); + var result = operation.Execute(context, cancellationContext); return CreateCursor(context.ChannelSource, context.Channel, result); } } - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); } } } - public async Task> ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken) + public async Task> ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(context, nameof(context)); using (BeginOperation()) { var operation = CreateOperation(); - var result = await operation.ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + var result = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); return CreateCursor(context.ChannelSource, context.Channel, result); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs b/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs index fb9ec4fbfa5..16f88eea2ca 100644 --- a/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs @@ -15,7 +15,6 @@ using System; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -73,8 +72,8 @@ public bool RetryRequested { get { return _retryRequested; } set { _retryRequested = value; } - } - + } + public BsonDocument CreateCommand() { return new BsonDocument @@ -87,26 +86,26 @@ public BsonDocument CreateCommand() }; } - public IAsyncCursor Execute(IReadBinding binding, CancellationToken cancellationToken) + public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var reply = operation.Execute(binding, cancellationToken); + var reply = operation.Execute(binding, cancellationContext); return CreateCursor(reply); } } - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var reply = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + var reply = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); return CreateCursor(reply); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs index 1bd4fb40102..d03b2b4addb 100644 --- a/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver.Core.Bindings; @@ -68,27 +67,27 @@ public bool RetryRequested set => _retryRequested = value; } - public IAsyncCursor Execute(IReadBinding binding, CancellationToken cancellationToken) + public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) { var operation = CreateOperation(); - return operation.Execute(context, cancellationToken); + return operation.Execute(context, cancellationContext); } } - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) { var operation = CreateOperation(); - return await operation.ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs index a16ba814dbc..9a52a5890e3 100644 --- a/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs @@ -15,7 +15,6 @@ using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -70,17 +69,17 @@ public bool RetryRequested set => _retryRequested = value; } - public IAsyncCursor Execute(IReadBinding binding, CancellationToken cancellationToken) + public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) { - return Execute(context, cancellationToken); + return Execute(context, cancellationContext); } } - public IAsyncCursor Execute(RetryableReadContext context, CancellationToken cancellationToken) + public IAsyncCursor Execute(RetryableReadContext context, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(context, nameof(context)); @@ -89,7 +88,7 @@ public IAsyncCursor Execute(RetryableReadContext context, Cancella var operation = CreateOperation(); try { - var result = operation.Execute(context, cancellationToken); + var result = operation.Execute(context, cancellationContext); return CreateCursor(context.ChannelSource, context.Channel, result); } catch (MongoCommandException ex) when (IsCollectionNotFoundException(ex)) @@ -99,17 +98,17 @@ public IAsyncCursor Execute(RetryableReadContext context, Cancella } } - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); } } - public async Task> ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken) + public async Task> ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(context, nameof(context)); @@ -118,7 +117,7 @@ public async Task> ExecuteAsync(RetryableReadContext var operation = CreateOperation(); try { - var result = await operation.ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + var result = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); return CreateCursor(context.ChannelSource, context.Channel, result); } catch (MongoCommandException ex) when (IsCollectionNotFoundException(ex)) diff --git a/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs b/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs index a509cfd33ed..439021408fa 100644 --- a/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization; @@ -88,31 +87,31 @@ protected override BsonDocument CreateOutputOptions() } /// - public IAsyncCursor Execute(IReadBinding binding, CancellationToken cancellationToken) + public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetReadChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetReadChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - var result = operation.Execute(channelBinding, cancellationToken); + var result = operation.Execute(channelBinding, cancellationContext); return new SingleBatchAsyncCursor(result); } } /// - public async Task> ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = await binding.GetReadChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetReadChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - var result = await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + var result = await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); return new SingleBatchAsyncCursor(result); } } diff --git a/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs index 53e787daf15..1ebcd51bab9 100644 --- a/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -170,30 +169,30 @@ protected override BsonDocument CreateOutputOptions() } /// - public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return operation.Execute(channelBinding, cancellationToken); + return operation.Execute(channelBinding, cancellationContext); } } /// - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/OperationExtensionMethods.cs b/src/MongoDB.Driver/Core/Operations/OperationExtensionMethods.cs index bf9fe96b58b..d9a29fa2cd8 100644 --- a/src/MongoDB.Driver/Core/Operations/OperationExtensionMethods.cs +++ b/src/MongoDB.Driver/Core/Operations/OperationExtensionMethods.cs @@ -13,7 +13,6 @@ * limitations under the License. */ -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Misc; @@ -27,12 +26,12 @@ public static TResult Execute( IChannelSourceHandle channelSource, ReadPreference readPreference, ICoreSessionHandle session, - CancellationToken cancellationToken) + OperationCancellationContext cancellationContext) { Ensure.IsNotNull(operation, nameof(operation)); using (var readBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), readPreference, session.Fork())) { - return operation.Execute(readBinding, cancellationToken); + return operation.Execute(readBinding, cancellationContext); } } @@ -40,12 +39,12 @@ public static TResult Execute( this IWriteOperation operation, IChannelSourceHandle channelSource, ICoreSessionHandle session, - CancellationToken cancellationToken) + OperationCancellationContext cancellationContext) { Ensure.IsNotNull(operation, nameof(operation)); using (var writeBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), ReadPreference.Primary, session.Fork())) { - return operation.Execute(writeBinding, cancellationToken); + return operation.Execute(writeBinding, cancellationContext); } } @@ -54,12 +53,12 @@ public static async Task ExecuteAsync( IChannelSourceHandle channelSource, ReadPreference readPreference, ICoreSessionHandle session, - CancellationToken cancellationToken) + OperationCancellationContext cancellationContext) { Ensure.IsNotNull(operation, nameof(operation)); using (var readBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), readPreference, session.Fork())) { - return await operation.ExecuteAsync(readBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(readBinding, cancellationContext).ConfigureAwait(false); } } @@ -67,12 +66,12 @@ public static async Task ExecuteAsync( this IWriteOperation operation, IChannelSourceHandle channelSource, ICoreSessionHandle session, - CancellationToken cancellationToken) + OperationCancellationContext cancellationContext) { Ensure.IsNotNull(operation, nameof(operation)); using (var writeBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), ReadPreference.Primary, session.Fork())) { - return await operation.ExecuteAsync(writeBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(writeBinding, cancellationContext).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/Core/Operations/PingOperation.cs b/src/MongoDB.Driver/Core/Operations/PingOperation.cs deleted file mode 100644 index cf86b18243c..00000000000 --- a/src/MongoDB.Driver/Core/Operations/PingOperation.cs +++ /dev/null @@ -1,71 +0,0 @@ -/* Copyright 2013-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. -*/ - -using System.Threading; -using System.Threading.Tasks; -using MongoDB.Bson; -using MongoDB.Bson.Serialization.Serializers; -using MongoDB.Driver.Core.Bindings; -using MongoDB.Driver.Core.Misc; -using MongoDB.Driver.Core.WireProtocol.Messages.Encoders; - -namespace MongoDB.Driver.Core.Operations -{ - internal sealed class PingOperation : IReadOperation - { - private MessageEncoderSettings _messageEncoderSettings; - - public PingOperation(MessageEncoderSettings messageEncoderSettings) - { - _messageEncoderSettings = messageEncoderSettings; - } - - public MessageEncoderSettings MessageEncoderSettings - { - get { return _messageEncoderSettings; } - } - - public BsonDocument CreateCommand() - { - return new BsonDocument - { - { "ping", 1 } - }; - } - - public BsonDocument Execute(IReadBinding binding, CancellationToken cancellationToken) - { - Ensure.IsNotNull(binding, nameof(binding)); - var operation = CreateOperation(); - return operation.Execute(binding, cancellationToken); - } - - public async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) - { - Ensure.IsNotNull(binding, nameof(binding)); - var operation = CreateOperation(); - return await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); - } - - private ReadCommandOperation CreateOperation() - { - var command = CreateCommand(); - return new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, _messageEncoderSettings) - { - RetryRequested = false - }; - } - } -} diff --git a/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs index 386bc77c4dd..d857aac7205 100644 --- a/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs @@ -13,7 +13,6 @@ * limitations under the License. */ -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization; @@ -43,54 +42,54 @@ public bool RetryRequested set => _retryRequested = value; } - public TCommandResult Execute(IReadBinding binding, CancellationToken cancellationToken) + public TCommandResult Execute(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) { - return Execute(context, cancellationToken); + return Execute(context, cancellationContext); } } - public TCommandResult Execute(RetryableReadContext context, CancellationToken cancellationToken) + public TCommandResult Execute(RetryableReadContext context, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginOperation()) { - return RetryableReadOperationExecutor.Execute(this, context, cancellationToken); + return RetryableReadOperationExecutor.Execute(this, context, cancellationContext); } } - public async Task ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); } } - public async Task ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken) + public async Task ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginOperation()) { - return await RetryableReadOperationExecutor.ExecuteAsync(this, context, cancellationToken).ConfigureAwait(false); + return await RetryableReadOperationExecutor.ExecuteAsync(this, context, cancellationContext).ConfigureAwait(false); } } - public TCommandResult ExecuteAttempt(RetryableReadContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken) + public TCommandResult ExecuteAttempt(RetryableReadContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext) { - return ExecuteProtocol(context.Channel, context.Binding.Session, context.Binding.ReadPreference, cancellationToken); + return ExecuteProtocol(context.Channel, context.Binding.Session, context.Binding.ReadPreference, cancellationContext.CancellationToken); } - public Task ExecuteAttemptAsync(RetryableReadContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken) + public Task ExecuteAttemptAsync(RetryableReadContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext) { - return ExecuteProtocolAsync(context.Channel, context.Binding.Session, context.Binding.ReadPreference, cancellationToken); + return ExecuteProtocolAsync(context.Channel, context.Binding.Session, context.Binding.ReadPreference, cancellationContext.CancellationToken); } } } diff --git a/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs index 7f5fb113da5..d6d116c4790 100644 --- a/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -83,34 +82,34 @@ public BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescript }; } - public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return operation.Execute(channelBinding, cancellationToken); + return operation.Execute(channelBinding, cancellationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } - } - + } + private IDisposable BeginOperation() => EventContext.BeginOperation("renameCollection"); private WriteCommandOperation CreateOperation(ICoreSessionHandle session, ConnectionDescription connectionDescription) diff --git a/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs b/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs index 4593b1c06e8..2e4b6c5c336 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Misc; @@ -25,12 +24,12 @@ internal sealed class RetryableReadContext : IDisposable { #region static - public static RetryableReadContext Create(IReadBinding binding, bool retryRequested, CancellationToken cancellationToken) + public static RetryableReadContext Create(IReadBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) { var context = new RetryableReadContext(binding, retryRequested); try { - context.Initialize(cancellationToken); + context.Initialize(cancellationContext); ChannelPinningHelper.PinChannellIfRequired( context.ChannelSource, @@ -46,12 +45,12 @@ public static RetryableReadContext Create(IReadBinding binding, bool retryReques } } - public static async Task CreateAsync(IReadBinding binding, bool retryRequested, CancellationToken cancellationToken) + public static async Task CreateAsync(IReadBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) { var context = new RetryableReadContext(binding, retryRequested); try { - await context.InitializeAsync(cancellationToken).ConfigureAwait(false); + await context.InitializeAsync(cancellationContext).ConfigureAwait(false); ChannelPinningHelper.PinChannellIfRequired( context.ChannelSource, @@ -113,33 +112,33 @@ public void ReplaceChannelSource(IChannelSourceHandle channelSource) _channel = null; } - private void Initialize(CancellationToken cancellationToken) + private void Initialize(OperationCancellationContext cancellationContext) { - _channelSource = _binding.GetReadChannelSource(cancellationToken); + _channelSource = _binding.GetReadChannelSource(cancellationContext); try { - _channel = _channelSource.GetChannel(cancellationToken); + _channel = _channelSource.GetChannel(cancellationContext); } catch (Exception ex) when (RetryableReadOperationExecutor.ShouldConnectionAcquireBeRetried(this, ex)) { - ReplaceChannelSource(_binding.GetReadChannelSource(cancellationToken)); - ReplaceChannel(_channelSource.GetChannel(cancellationToken)); + ReplaceChannelSource(_binding.GetReadChannelSource(cancellationContext)); + ReplaceChannel(_channelSource.GetChannel(cancellationContext)); } } - private async Task InitializeAsync(CancellationToken cancellationToken) + private async Task InitializeAsync(OperationCancellationContext cancellationContext) { - _channelSource = await _binding.GetReadChannelSourceAsync(cancellationToken).ConfigureAwait(false); + _channelSource = await _binding.GetReadChannelSourceAsync(cancellationContext).ConfigureAwait(false); try { - _channel = await _channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false); + _channel = await _channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false); } catch (Exception ex) when (RetryableReadOperationExecutor.ShouldConnectionAcquireBeRetried(this, ex)) { - ReplaceChannelSource(await _binding.GetReadChannelSourceAsync(cancellationToken).ConfigureAwait(false)); - ReplaceChannel(await _channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)); + ReplaceChannelSource(await _binding.GetReadChannelSourceAsync(cancellationContext).ConfigureAwait(false)); + ReplaceChannel(await _channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)); } } } diff --git a/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs b/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs index cdb74827dc0..534360ad6cc 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Bindings; @@ -23,25 +22,25 @@ namespace MongoDB.Driver.Core.Operations internal static class RetryableReadOperationExecutor { // public static methods - public static TResult Execute(IRetryableReadOperation operation, IReadBinding binding, bool retryRequested, CancellationToken cancellationToken) + public static TResult Execute(IRetryableReadOperation operation, IReadBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) { - using (var context = RetryableReadContext.Create(binding, retryRequested, cancellationToken)) + using (var context = RetryableReadContext.Create(binding, retryRequested, cancellationContext)) { - return Execute(operation, context, cancellationToken); + return Execute(operation, context, cancellationContext); } } - public static TResult Execute(IRetryableReadOperation operation, RetryableReadContext context, CancellationToken cancellationToken) + public static TResult Execute(IRetryableReadOperation operation, RetryableReadContext context, OperationCancellationContext cancellationContext) { if (!ShouldReadBeRetried(context)) { - return operation.ExecuteAttempt(context, attempt: 1, transactionNumber: null, cancellationToken); + return operation.ExecuteAttempt(context, attempt: 1, transactionNumber: null, cancellationContext); } Exception originalException; try { - return operation.ExecuteAttempt(context, attempt: 1, transactionNumber: null, cancellationToken); + return operation.ExecuteAttempt(context, attempt: 1, transactionNumber: null, cancellationContext); } catch (Exception ex) when (RetryabilityHelper.IsRetryableReadException(ex)) @@ -51,8 +50,8 @@ public static TResult Execute(IRetryableReadOperation operatio try { - context.ReplaceChannelSource(context.Binding.GetReadChannelSource(new[] { context.ChannelSource.ServerDescription }, cancellationToken)); - context.ReplaceChannel(context.ChannelSource.GetChannel(cancellationToken)); + context.ReplaceChannelSource(context.Binding.GetReadChannelSource(new[] { context.ChannelSource.ServerDescription }, cancellationContext)); + context.ReplaceChannel(context.ChannelSource.GetChannel(cancellationContext)); } catch { @@ -61,7 +60,7 @@ public static TResult Execute(IRetryableReadOperation operatio try { - return operation.ExecuteAttempt(context, attempt: 2, transactionNumber: null, cancellationToken); + return operation.ExecuteAttempt(context, attempt: 2, transactionNumber: null, cancellationContext); } catch (Exception ex) when (ShouldThrowOriginalException(ex)) { @@ -69,25 +68,25 @@ public static TResult Execute(IRetryableReadOperation operatio } } - public static async Task ExecuteAsync(IRetryableReadOperation operation, IReadBinding binding, bool retryRequested, CancellationToken cancellationToken) + public static async Task ExecuteAsync(IRetryableReadOperation operation, IReadBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) { - using (var context = await RetryableReadContext.CreateAsync(binding, retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, retryRequested, cancellationContext).ConfigureAwait(false)) { - return await ExecuteAsync(operation, context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(operation, context, cancellationContext).ConfigureAwait(false); } } - public static async Task ExecuteAsync(IRetryableReadOperation operation, RetryableReadContext context, CancellationToken cancellationToken) + public static async Task ExecuteAsync(IRetryableReadOperation operation, RetryableReadContext context, OperationCancellationContext cancellationContext) { if (!ShouldReadBeRetried(context)) { - return await operation.ExecuteAttemptAsync(context, attempt: 1, transactionNumber: null, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(context, attempt: 1, transactionNumber: null, cancellationContext).ConfigureAwait(false); } Exception originalException; try { - return await operation.ExecuteAttemptAsync(context, attempt: 1, transactionNumber: null, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(context, attempt: 1, transactionNumber: null, cancellationContext).ConfigureAwait(false); } catch (Exception ex) when (RetryabilityHelper.IsRetryableReadException(ex)) { @@ -96,8 +95,8 @@ public static async Task ExecuteAsync(IRetryableReadOperation< try { - context.ReplaceChannelSource(context.Binding.GetReadChannelSource(new[] { context.ChannelSource.ServerDescription }, cancellationToken)); - context.ReplaceChannel(context.ChannelSource.GetChannel(cancellationToken)); + context.ReplaceChannelSource(context.Binding.GetReadChannelSource(new[] { context.ChannelSource.ServerDescription }, cancellationContext)); + context.ReplaceChannel(context.ChannelSource.GetChannel(cancellationContext)); } catch { @@ -106,7 +105,7 @@ public static async Task ExecuteAsync(IRetryableReadOperation< try { - return await operation.ExecuteAttemptAsync(context, attempt: 2, transactionNumber: null, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(context, attempt: 2, transactionNumber: null, cancellationContext).ConfigureAwait(false); } catch (Exception ex) when (ShouldThrowOriginalException(ex)) { diff --git a/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs b/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs index cd5e3e87dc9..89e106ccacd 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs @@ -16,7 +16,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.IO; @@ -87,36 +86,36 @@ public WriteConcern WriteConcern set { _writeConcern = value; } } - public virtual BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public virtual BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { - using (var context = RetryableWriteContext.Create(binding, _retryRequested, cancellationToken)) + using (var context = RetryableWriteContext.Create(binding, _retryRequested, cancellationContext)) { - return Execute(context, cancellationToken); + return Execute(context, cancellationContext); } } - public virtual BsonDocument Execute(RetryableWriteContext context, CancellationToken cancellationToken) + public virtual BsonDocument Execute(RetryableWriteContext context, OperationCancellationContext cancellationContext) { - return RetryableWriteOperationExecutor.Execute(this, context, cancellationToken); + return RetryableWriteOperationExecutor.Execute(this, context, cancellationContext); } - public virtual async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public virtual async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { - using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); } } - public virtual Task ExecuteAsync(RetryableWriteContext context, CancellationToken cancellationToken) + public virtual Task ExecuteAsync(RetryableWriteContext context, OperationCancellationContext cancellationContext) { - return RetryableWriteOperationExecutor.ExecuteAsync(this, context, cancellationToken); + return RetryableWriteOperationExecutor.ExecuteAsync(this, context, cancellationContext); } - public BsonDocument ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken) + public BsonDocument ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext) { var args = GetCommandArgs(context, attempt, transactionNumber); - + // TODO: CSOT implement timeout in Command Execution return context.Channel.Command( context.ChannelSource.Session, ReadPreference.Primary, @@ -129,13 +128,13 @@ public BsonDocument ExecuteAttempt(RetryableWriteContext context, int attempt, l args.ResponseHandling, BsonDocumentSerializer.Instance, args.MessageEncoderSettings, - cancellationToken); + cancellationContext.CancellationToken); } - public Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, CancellationToken cancellationToken) + public Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext) { var args = GetCommandArgs(context, attempt, transactionNumber); - + // TODO: CSOT implement timeout in Command Execution return context.Channel.CommandAsync( context.ChannelSource.Session, ReadPreference.Primary, @@ -148,7 +147,7 @@ public Task ExecuteAttemptAsync(RetryableWriteContext context, int args.ResponseHandling, BsonDocumentSerializer.Instance, args.MessageEncoderSettings, - cancellationToken); + cancellationContext.CancellationToken); } protected abstract BsonDocument CreateCommand(ICoreSessionHandle session, int attempt, long? transactionNumber); diff --git a/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs b/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs index 4aa1a3eb9fd..656db3c9d7a 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs @@ -16,7 +16,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Misc; @@ -27,12 +26,12 @@ internal sealed class RetryableWriteContext : IDisposable { #region static - public static RetryableWriteContext Create(IWriteBinding binding, bool retryRequested, CancellationToken cancellationToken) + public static RetryableWriteContext Create(IWriteBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) { var context = new RetryableWriteContext(binding, retryRequested); try { - context.Initialize(cancellationToken); + context.Initialize(cancellationContext); ChannelPinningHelper.PinChannellIfRequired( context.ChannelSource, @@ -48,12 +47,12 @@ public static RetryableWriteContext Create(IWriteBinding binding, bool retryRequ } } - public static async Task CreateAsync(IWriteBinding binding, bool retryRequested, CancellationToken cancellationToken) + public static async Task CreateAsync(IWriteBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) { var context = new RetryableWriteContext(binding, retryRequested); try { - await context.InitializeAsync(cancellationToken).ConfigureAwait(false); + await context.InitializeAsync(cancellationContext).ConfigureAwait(false); ChannelPinningHelper.PinChannellIfRequired( context.ChannelSource, @@ -126,35 +125,35 @@ public void ReplaceChannelSource(IChannelSourceHandle channelSource) _channel = null; } - private void Initialize(CancellationToken cancellationToken) + private void Initialize(OperationCancellationContext cancellationContext) { - _channelSource = _binding.GetWriteChannelSource(cancellationToken); + _channelSource = _binding.GetWriteChannelSource(cancellationContext); var serverDescription = _channelSource.ServerDescription; try { - _channel = _channelSource.GetChannel(cancellationToken); + _channel = _channelSource.GetChannel(cancellationContext); } catch (Exception ex) when (RetryableWriteOperationExecutor.ShouldConnectionAcquireBeRetried(this, serverDescription, ex)) { - ReplaceChannelSource(_binding.GetWriteChannelSource(cancellationToken)); - ReplaceChannel(_channelSource.GetChannel(cancellationToken)); + ReplaceChannelSource(_binding.GetWriteChannelSource(cancellationContext)); + ReplaceChannel(_channelSource.GetChannel(cancellationContext)); } } - private async Task InitializeAsync(CancellationToken cancellationToken) + private async Task InitializeAsync(OperationCancellationContext cancellationContext) { - _channelSource = await _binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false); + _channelSource = await _binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false); var serverDescription = _channelSource.ServerDescription; try { - _channel = await _channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false); + _channel = await _channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false); } catch (Exception ex) when (RetryableWriteOperationExecutor.ShouldConnectionAcquireBeRetried(this, serverDescription, ex)) { - ReplaceChannelSource(await _binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)); - ReplaceChannel(await _channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)); + ReplaceChannelSource(await _binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)); + ReplaceChannel(await _channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)); } } } diff --git a/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs b/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs index 6e73af1e758..d6773a8c342 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Connections; @@ -25,26 +24,26 @@ namespace MongoDB.Driver.Core.Operations internal static class RetryableWriteOperationExecutor { // public static methods - public static TResult Execute(IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested, CancellationToken cancellationToken) + public static TResult Execute(IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) { - using (var context = RetryableWriteContext.Create(binding, retryRequested, cancellationToken)) + using (var context = RetryableWriteContext.Create(binding, retryRequested, cancellationContext)) { - return Execute(operation, context, cancellationToken); + return Execute(operation, context, cancellationContext); } } - public static TResult Execute(IRetryableWriteOperation operation, RetryableWriteContext context, CancellationToken cancellationToken) + public static TResult Execute(IRetryableWriteOperation operation, RetryableWriteContext context, OperationCancellationContext cancellationContext) { if (!AreRetriesAllowed(operation, context)) { - return operation.ExecuteAttempt(context, 1, null, cancellationToken); + return operation.ExecuteAttempt(context, 1, null, cancellationContext); } var transactionNumber = context.Binding.Session.AdvanceTransactionNumber(); Exception originalException; try { - return operation.ExecuteAttempt(context, 1, transactionNumber, cancellationToken); + return operation.ExecuteAttempt(context, 1, transactionNumber, cancellationContext); } catch (Exception ex) when (RetryabilityHelper.IsRetryableWriteException(ex)) { @@ -53,8 +52,8 @@ public static TResult Execute(IRetryableWriteOperation operati try { - context.ReplaceChannelSource(context.Binding.GetWriteChannelSource(new[] { context.ChannelSource.ServerDescription }, cancellationToken)); - context.ReplaceChannel(context.ChannelSource.GetChannel(cancellationToken)); + context.ReplaceChannelSource(context.Binding.GetWriteChannelSource(new[] { context.ChannelSource.ServerDescription }, cancellationContext)); + context.ReplaceChannel(context.ChannelSource.GetChannel(cancellationContext)); } catch { @@ -68,7 +67,7 @@ public static TResult Execute(IRetryableWriteOperation operati try { - return operation.ExecuteAttempt(context, 2, transactionNumber, cancellationToken); + return operation.ExecuteAttempt(context, 2, transactionNumber, cancellationContext); } catch (Exception ex) when (ShouldThrowOriginalException(ex)) { @@ -76,26 +75,26 @@ public static TResult Execute(IRetryableWriteOperation operati } } - public async static Task ExecuteAsync(IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested, CancellationToken cancellationToken) + public async static Task ExecuteAsync(IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) { - using (var context = await RetryableWriteContext.CreateAsync(binding, retryRequested, cancellationToken).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(binding, retryRequested, cancellationContext).ConfigureAwait(false)) { - return await ExecuteAsync(operation, context, cancellationToken).ConfigureAwait(false); + return await ExecuteAsync(operation, context, cancellationContext).ConfigureAwait(false); } } - public static async Task ExecuteAsync(IRetryableWriteOperation operation, RetryableWriteContext context, CancellationToken cancellationToken) + public static async Task ExecuteAsync(IRetryableWriteOperation operation, RetryableWriteContext context, OperationCancellationContext cancellationContext) { if (!AreRetriesAllowed(operation, context)) { - return await operation.ExecuteAttemptAsync(context, 1, null, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(context, 1, null, cancellationContext).ConfigureAwait(false); } var transactionNumber = context.Binding.Session.AdvanceTransactionNumber(); Exception originalException; try { - return await operation.ExecuteAttemptAsync(context, 1, transactionNumber, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(context, 1, transactionNumber, cancellationContext).ConfigureAwait(false); } catch (Exception ex) when (RetryabilityHelper.IsRetryableWriteException(ex)) { @@ -104,8 +103,8 @@ public static async Task ExecuteAsync(IRetryableWriteOperation try { - context.ReplaceChannelSource(await context.Binding.GetWriteChannelSourceAsync(new[] { context.ChannelSource.ServerDescription }, cancellationToken).ConfigureAwait(false)); - context.ReplaceChannel(await context.ChannelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)); + context.ReplaceChannelSource(await context.Binding.GetWriteChannelSourceAsync(new[] { context.ChannelSource.ServerDescription }, cancellationContext).ConfigureAwait(false)); + context.ReplaceChannel(await context.ChannelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)); } catch { @@ -119,7 +118,7 @@ public static async Task ExecuteAsync(IRetryableWriteOperation try { - return await operation.ExecuteAttemptAsync(context, 2, transactionNumber, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(context, 2, transactionNumber, cancellationContext).ConfigureAwait(false); } catch (Exception ex) when (ShouldThrowOriginalException(ex)) { diff --git a/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs index 90657153792..de907057525 100644 --- a/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs @@ -13,7 +13,6 @@ * limitations under the License. */ -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -44,27 +43,27 @@ public UpdateSearchIndexOperation( _messageEncoderSettings = Ensure.IsNotNull(messageEncoderSettings, nameof(messageEncoderSettings)); } - public BsonDocument Execute(IWriteBinding binding, CancellationToken cancellationToken) + public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { using (EventContext.BeginOperation("updateSearchIndex")) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) + using (var channel = channelSource.GetChannel(cancellationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return operation.Execute(channelBinding, cancellationToken); + return operation.Execute(channelBinding, cancellationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { using (EventContext.BeginOperation("updateSearchIndex")) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return await operation.ExecuteAsync(channelBinding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs index 183efdf9888..0fc7eff2138 100644 --- a/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs @@ -13,7 +13,6 @@ * limitations under the License. */ -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization; @@ -39,25 +38,25 @@ public ReadPreference ReadPreference set => _readPreference = Ensure.IsNotNull(value, nameof(value)); } - public TCommandResult Execute(IWriteBinding binding, CancellationToken cancellationToken) + public TCommandResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationToken)) + using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) { - return ExecuteProtocol(channelSource, binding.Session, _readPreference, cancellationToken); + return ExecuteProtocol(channelSource, binding.Session, _readPreference, cancellationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, CancellationToken cancellationToken = default(CancellationToken)) + public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationToken).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) { - return await ExecuteProtocolAsync(channelSource, binding.Session, _readPreference, cancellationToken).ConfigureAwait(false); + return await ExecuteProtocolAsync(channelSource, binding.Session, _readPreference, cancellationContext).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/Core/Servers/IServer.cs b/src/MongoDB.Driver/Core/Servers/IServer.cs index bbd9e0cbb80..7078d39b1b8 100644 --- a/src/MongoDB.Driver/Core/Servers/IServer.cs +++ b/src/MongoDB.Driver/Core/Servers/IServer.cs @@ -29,8 +29,8 @@ internal interface IServer EndPoint EndPoint { get; } ServerId ServerId { get; } - IChannelHandle GetChannel(CancellationToken cancellationToken); - Task GetChannelAsync(CancellationToken cancellationToken); + IChannelHandle GetChannel(OperationCancellationContext cancellationContext); + Task GetChannelAsync(OperationCancellationContext cancellationContext); } internal interface IClusterableServer : IServer, IDisposable diff --git a/src/MongoDB.Driver/Core/Servers/Server.cs b/src/MongoDB.Driver/Core/Servers/Server.cs index e428c50212c..9727fdcde79 100644 --- a/src/MongoDB.Driver/Core/Servers/Server.cs +++ b/src/MongoDB.Driver/Core/Servers/Server.cs @@ -107,7 +107,7 @@ public void Dispose() public void HandleExceptionOnOpen(Exception exception) => HandleBeforeHandshakeCompletesException(exception); - public IChannelHandle GetChannel(CancellationToken cancellationToken) + public IChannelHandle GetChannel(OperationCancellationContext cancellationContext) { ThrowIfNotOpen(); @@ -115,7 +115,7 @@ public IChannelHandle GetChannel(CancellationToken cancellationToken) { Interlocked.Increment(ref _outstandingOperationsCount); - var connection = _connectionPool.AcquireConnection(cancellationToken); + var connection = _connectionPool.AcquireConnection(cancellationContext); return new ServerChannel(this, connection); } catch @@ -126,14 +126,14 @@ public IChannelHandle GetChannel(CancellationToken cancellationToken) } } - public async Task GetChannelAsync(CancellationToken cancellationToken) + public async Task GetChannelAsync(OperationCancellationContext cancellationContext) { ThrowIfNotOpen(); try { Interlocked.Increment(ref _outstandingOperationsCount); - var connection = await _connectionPool.AcquireConnectionAsync(cancellationToken).ConfigureAwait(false); + var connection = await _connectionPool.AcquireConnectionAsync(cancellationContext).ConfigureAwait(false); return new ServerChannel(this, connection); } catch diff --git a/src/MongoDB.Driver/GridFS/GridFSBucket.cs b/src/MongoDB.Driver/GridFS/GridFSBucket.cs index 262939e4f85..b30af6a5991 100644 --- a/src/MongoDB.Driver/GridFS/GridFSBucket.cs +++ b/src/MongoDB.Driver/GridFS/GridFSBucket.cs @@ -83,13 +83,15 @@ public ImmutableGridFSBucketOptions Options public void Delete(TFileId id, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull((object)id, nameof(id)); - using (var binding = GetSingleServerReadWriteBinding(cancellationToken)) + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + using (var binding = GetSingleServerReadWriteBinding(operationCancellationContext)) { var filesCollectionDeleteOperation = CreateDeleteFileOperation(id); - var filesCollectionDeleteResult = filesCollectionDeleteOperation.Execute(binding, cancellationToken); + var filesCollectionDeleteResult = filesCollectionDeleteOperation.Execute(binding, operationCancellationContext); var chunksDeleteOperation = CreateDeleteChunksOperation(id); - chunksDeleteOperation.Execute(binding, cancellationToken); + chunksDeleteOperation.Execute(binding, operationCancellationContext); if (filesCollectionDeleteResult.DeletedCount == 0) { @@ -102,13 +104,15 @@ public ImmutableGridFSBucketOptions Options public async Task DeleteAsync(TFileId id, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull((object)id, nameof(id)); - using (var binding = await GetSingleServerReadWriteBindingAsync(cancellationToken).ConfigureAwait(false)) + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + using (var binding = await GetSingleServerReadWriteBindingAsync(operationCancellationContext).ConfigureAwait(false)) { var filesCollectionDeleteOperation = CreateDeleteFileOperation(id); - var filesCollectionDeleteResult = await filesCollectionDeleteOperation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + var filesCollectionDeleteResult = await filesCollectionDeleteOperation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); var chunksDeleteOperation = CreateDeleteChunksOperation(id); - await chunksDeleteOperation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + await chunksDeleteOperation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); if (filesCollectionDeleteResult.DeletedCount == 0) { @@ -121,10 +125,12 @@ public ImmutableGridFSBucketOptions Options public byte[] DownloadAsBytes(TFileId id, GridFSDownloadOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull((object)id, nameof(id)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationCancellationContext)) { - var fileInfo = GetFileInfo(binding, id, cancellationToken); + var fileInfo = GetFileInfo(binding, id, operationCancellationContext); return DownloadAsBytesHelper(binding, fileInfo, options, cancellationToken); } } @@ -133,10 +139,12 @@ public ImmutableGridFSBucketOptions Options public async Task DownloadAsBytesAsync(TFileId id, GridFSDownloadOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull((object)id, nameof(id)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoAsync(binding, id, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetFileInfoAsync(binding, id, operationCancellationContext).ConfigureAwait(false); return await DownloadAsBytesHelperAsync(binding, fileInfo, options, cancellationToken).ConfigureAwait(false); } } @@ -145,11 +153,13 @@ public ImmutableGridFSBucketOptions Options public byte[] DownloadAsBytesByName(string filename, GridFSDownloadByNameOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filename, nameof(filename)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationCancellationContext)) { - var fileInfo = GetFileInfoByName(binding, filename, options.Revision, cancellationToken); + var fileInfo = GetFileInfoByName(binding, filename, options.Revision, operationCancellationContext); return DownloadAsBytesHelper(binding, fileInfo, options, cancellationToken); } } @@ -158,11 +168,13 @@ public ImmutableGridFSBucketOptions Options public async Task DownloadAsBytesByNameAsync(string filename, GridFSDownloadByNameOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filename, nameof(filename)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, operationCancellationContext).ConfigureAwait(false); return await DownloadAsBytesHelperAsync(binding, fileInfo, options, cancellationToken).ConfigureAwait(false); } } @@ -172,10 +184,12 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(destination, nameof(destination)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationCancellationContext)) { - var fileInfo = GetFileInfo(binding, id, cancellationToken); + var fileInfo = GetFileInfo(binding, id, operationCancellationContext); DownloadToStreamHelper(binding, fileInfo, destination, options, cancellationToken); } } @@ -185,10 +199,12 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(destination, nameof(destination)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoAsync(binding, id, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetFileInfoAsync(binding, id, operationCancellationContext).ConfigureAwait(false); await DownloadToStreamHelperAsync(binding, fileInfo, destination, options, cancellationToken).ConfigureAwait(false); } } @@ -198,11 +214,13 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(destination, nameof(destination)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationCancellationContext)) { - var fileInfo = GetFileInfoByName(binding, filename, options.Revision, cancellationToken); + var fileInfo = GetFileInfoByName(binding, filename, options.Revision, operationCancellationContext); DownloadToStreamHelper(binding, fileInfo, destination, options, cancellationToken); } } @@ -212,11 +230,13 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(destination, nameof(destination)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, operationCancellationContext).ConfigureAwait(false); await DownloadToStreamHelperAsync(binding, fileInfo, destination, options, cancellationToken).ConfigureAwait(false); } } @@ -224,34 +244,38 @@ public ImmutableGridFSBucketOptions Options /// public void Drop(CancellationToken cancellationToken = default(CancellationToken)) { + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); var filesCollectionNamespace = this.GetFilesCollectionNamespace(); var chunksCollectionNamespace = this.GetChunksCollectionNamespace(); var messageEncoderSettings = this.GetMessageEncoderSettings(); - using (var binding = GetSingleServerReadWriteBinding(cancellationToken)) + using (var binding = GetSingleServerReadWriteBinding(operationCancellationContext)) { var filesCollectionDropOperation = CreateDropCollectionOperation(filesCollectionNamespace, messageEncoderSettings); - filesCollectionDropOperation.Execute(binding, cancellationToken); + filesCollectionDropOperation.Execute(binding, operationCancellationContext); var chunksCollectionDropOperation = CreateDropCollectionOperation(chunksCollectionNamespace, messageEncoderSettings); - chunksCollectionDropOperation.Execute(binding, cancellationToken); + chunksCollectionDropOperation.Execute(binding, operationCancellationContext); } } /// public async Task DropAsync(CancellationToken cancellationToken = default(CancellationToken)) { + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); var filesCollectionNamespace = this.GetFilesCollectionNamespace(); var chunksCollectionNamespace = this.GetChunksCollectionNamespace(); var messageEncoderSettings = this.GetMessageEncoderSettings(); - using (var binding = await GetSingleServerReadWriteBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadWriteBindingAsync(operationCancellationContext).ConfigureAwait(false)) { var filesCollectionDropOperation = CreateDropCollectionOperation(filesCollectionNamespace, messageEncoderSettings); - await filesCollectionDropOperation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + await filesCollectionDropOperation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); var chunksCollectionDropOperation = CreateDropCollectionOperation(chunksCollectionNamespace, messageEncoderSettings); - await chunksCollectionDropOperation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + await chunksCollectionDropOperation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); } } @@ -259,13 +283,15 @@ public ImmutableGridFSBucketOptions Options public IAsyncCursor> Find(FilterDefinition> filter, GridFSFindOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filter, nameof(filter)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSFindOptions(); var translationOptions = _database.Client.Settings.TranslationOptions; var operation = CreateFindOperation(filter, options, translationOptions); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationCancellationContext)) { - return operation.Execute(binding, cancellationToken); + return operation.Execute(binding, operationCancellationContext); } } @@ -273,13 +299,15 @@ public ImmutableGridFSBucketOptions Options public async Task>> FindAsync(FilterDefinition> filter, GridFSFindOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filter, nameof(filter)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSFindOptions(); var translationOptions = _database.Client.Settings.TranslationOptions; var operation = CreateFindOperation(filter, options, translationOptions); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) { - return await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); } } @@ -287,10 +315,12 @@ public ImmutableGridFSBucketOptions Options public GridFSDownloadStream OpenDownloadStream(TFileId id, GridFSDownloadOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull((object)id, nameof(id)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationCancellationContext)) { - var fileInfo = GetFileInfo(binding, id, cancellationToken); + var fileInfo = GetFileInfo(binding, id, operationCancellationContext); return CreateDownloadStream(binding.Fork(), fileInfo, options, cancellationToken); } } @@ -299,10 +329,12 @@ public ImmutableGridFSBucketOptions Options public async Task> OpenDownloadStreamAsync(TFileId id, GridFSDownloadOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull((object)id, nameof(id)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoAsync(binding, id, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetFileInfoAsync(binding, id, operationCancellationContext).ConfigureAwait(false); return CreateDownloadStream(binding.Fork(), fileInfo, options, cancellationToken); } } @@ -311,11 +343,13 @@ public ImmutableGridFSBucketOptions Options public GridFSDownloadStream OpenDownloadStreamByName(string filename, GridFSDownloadByNameOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filename, nameof(filename)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = GetSingleServerReadBinding(cancellationToken)) + using (var binding = GetSingleServerReadBinding(operationCancellationContext)) { - var fileInfo = GetFileInfoByName(binding, filename, options.Revision, cancellationToken); + var fileInfo = GetFileInfoByName(binding, filename, options.Revision, operationCancellationContext); return CreateDownloadStream(binding.Fork(), fileInfo, options); } } @@ -324,11 +358,13 @@ public ImmutableGridFSBucketOptions Options public async Task> OpenDownloadStreamByNameAsync(string filename, GridFSDownloadByNameOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filename, nameof(filename)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = await GetSingleServerReadBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, cancellationToken).ConfigureAwait(false); + var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, operationCancellationContext).ConfigureAwait(false); return CreateDownloadStream(binding.Fork(), fileInfo, options); } } @@ -338,11 +374,13 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(filename, nameof(filename)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); - using (var binding = GetSingleServerReadWriteBinding(cancellationToken)) + using (var binding = GetSingleServerReadWriteBinding(operationCancellationContext)) { - EnsureIndexes(binding, cancellationToken); + EnsureIndexes(binding, operationCancellationContext); return CreateUploadStream(binding, id, filename, options); } } @@ -352,11 +390,13 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(filename, nameof(filename)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); - using (var binding = await GetSingleServerReadWriteBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadWriteBindingAsync(operationCancellationContext).ConfigureAwait(false)) { - await EnsureIndexesAsync(binding, cancellationToken).ConfigureAwait(false); + await EnsureIndexesAsync(binding, operationCancellationContext).ConfigureAwait(false); return CreateUploadStream(binding, id, filename, options); } } @@ -366,10 +406,12 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(newFilename, nameof(newFilename)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); var renameOperation = CreateRenameOperation(id, newFilename); - using (var binding = GetSingleServerReadWriteBinding(cancellationToken)) + using (var binding = GetSingleServerReadWriteBinding(operationCancellationContext)) { - var result = renameOperation.Execute(binding, cancellationToken); + var result = renameOperation.Execute(binding, operationCancellationContext); if (result.IsModifiedCountAvailable && result.ModifiedCount == 0) { @@ -383,10 +425,12 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(newFilename, nameof(newFilename)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); var renameOperation = CreateRenameOperation(id, newFilename); - using (var binding = await GetSingleServerReadWriteBindingAsync(cancellationToken).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadWriteBindingAsync(operationCancellationContext).ConfigureAwait(false)) { - var result = await renameOperation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + var result = await renameOperation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); if (result.IsModifiedCountAvailable && result.ModifiedCount == 0) { @@ -401,6 +445,8 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(source, nameof(source)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); using (var sourceStream = new MemoryStream(source)) @@ -415,6 +461,8 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(source, nameof(source)); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); using (var sourceStream = new MemoryStream(source)) @@ -522,28 +570,28 @@ private bool ChunksCollectionIndexesExist(List indexes) return IndexExists(indexes, key); } - private bool ChunksCollectionIndexesExist(IReadBindingHandle binding, CancellationToken cancellationToken) + private bool ChunksCollectionIndexesExist(IReadBindingHandle binding, OperationCancellationContext cancellationContext) { - var indexes = ListIndexes(binding, this.GetChunksCollectionNamespace(), cancellationToken); + var indexes = ListIndexes(binding, this.GetChunksCollectionNamespace(), cancellationContext); return ChunksCollectionIndexesExist(indexes); } - private async Task ChunksCollectionIndexesExistAsync(IReadBindingHandle binding, CancellationToken cancellationToken) + private async Task ChunksCollectionIndexesExistAsync(IReadBindingHandle binding, OperationCancellationContext cancellationContext) { - var indexes = await ListIndexesAsync(binding, this.GetChunksCollectionNamespace(), cancellationToken).ConfigureAwait(false); + var indexes = await ListIndexesAsync(binding, this.GetChunksCollectionNamespace(), cancellationContext).ConfigureAwait(false); return ChunksCollectionIndexesExist(indexes); } - private void CreateChunksCollectionIndexes(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private void CreateChunksCollectionIndexes(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) { var operation = CreateCreateChunksCollectionIndexesOperation(); - operation.Execute(binding, cancellationToken); + operation.Execute(binding, cancellationContext); } - private async Task CreateChunksCollectionIndexesAsync(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private async Task CreateChunksCollectionIndexesAsync(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) { var operation = CreateCreateChunksCollectionIndexesOperation(); - await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); } internal CreateIndexesOperation CreateCreateChunksCollectionIndexesOperation() @@ -608,16 +656,16 @@ private BulkMixedWriteOperation CreateDeleteFileOperation(TFileId id) this.GetMessageEncoderSettings()); } - private void CreateFilesCollectionIndexes(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private void CreateFilesCollectionIndexes(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) { var operation = CreateCreateFilesCollectionIndexesOperation(); - operation.Execute(binding, cancellationToken); + operation.Execute(binding, cancellationContext); } - private async Task CreateFilesCollectionIndexesAsync(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private async Task CreateFilesCollectionIndexesAsync(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) { var operation = CreateCreateFilesCollectionIndexesOperation(); - await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); } private FindOperation> CreateFindOperation( @@ -810,23 +858,23 @@ private GridFSUploadStream CreateUploadStream(IReadWriteBindingHandle b } } - private void EnsureIndexes(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private void EnsureIndexes(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) { - _ensureIndexesSemaphore.Wait(cancellationToken); + _ensureIndexesSemaphore.Wait(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken); try { if (!_ensureIndexesDone) { - var isFilesCollectionEmpty = IsFilesCollectionEmpty(binding, cancellationToken); + var isFilesCollectionEmpty = IsFilesCollectionEmpty(binding, cancellationContext); if (isFilesCollectionEmpty) { - if (!FilesCollectionIndexesExist(binding, cancellationToken)) + if (!FilesCollectionIndexesExist(binding, cancellationContext)) { - CreateFilesCollectionIndexes(binding, cancellationToken); + CreateFilesCollectionIndexes(binding, cancellationContext); } - if (!ChunksCollectionIndexesExist(binding, cancellationToken)) + if (!ChunksCollectionIndexesExist(binding, cancellationContext)) { - CreateChunksCollectionIndexes(binding, cancellationToken); + CreateChunksCollectionIndexes(binding, cancellationContext); } } @@ -839,23 +887,23 @@ private void EnsureIndexes(IReadWriteBindingHandle binding, CancellationToken ca } } - private async Task EnsureIndexesAsync(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private async Task EnsureIndexesAsync(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) { - await _ensureIndexesSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); + await _ensureIndexesSemaphore.WaitAsync(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken).ConfigureAwait(false); try { if (!_ensureIndexesDone) { - var isFilesCollectionEmpty = await IsFilesCollectionEmptyAsync(binding, cancellationToken).ConfigureAwait(false); + var isFilesCollectionEmpty = await IsFilesCollectionEmptyAsync(binding, cancellationContext).ConfigureAwait(false); if (isFilesCollectionEmpty) { - if (!(await FilesCollectionIndexesExistAsync(binding, cancellationToken).ConfigureAwait(false))) + if (!(await FilesCollectionIndexesExistAsync(binding, cancellationContext).ConfigureAwait(false))) { - await CreateFilesCollectionIndexesAsync(binding, cancellationToken).ConfigureAwait(false); + await CreateFilesCollectionIndexesAsync(binding, cancellationContext).ConfigureAwait(false); } - if (!(await ChunksCollectionIndexesExistAsync(binding, cancellationToken).ConfigureAwait(false))) + if (!(await ChunksCollectionIndexesExistAsync(binding, cancellationContext).ConfigureAwait(false))) { - await CreateChunksCollectionIndexesAsync(binding, cancellationToken).ConfigureAwait(false); + await CreateChunksCollectionIndexesAsync(binding, cancellationContext).ConfigureAwait(false); } } @@ -874,24 +922,25 @@ private bool FilesCollectionIndexesExist(List indexes) return IndexExists(indexes, key); } - private bool FilesCollectionIndexesExist(IReadBindingHandle binding, CancellationToken cancellationToken) + private bool FilesCollectionIndexesExist(IReadBindingHandle binding, OperationCancellationContext cancellationContext) { - var indexes = ListIndexes(binding, this.GetFilesCollectionNamespace(), cancellationToken); + var indexes = ListIndexes(binding, this.GetFilesCollectionNamespace(), cancellationContext); return FilesCollectionIndexesExist(indexes); } - private async Task FilesCollectionIndexesExistAsync(IReadBindingHandle binding, CancellationToken cancellationToken) + private async Task FilesCollectionIndexesExistAsync(IReadBindingHandle binding, OperationCancellationContext cancellationContext) { - var indexes = await ListIndexesAsync(binding, this.GetFilesCollectionNamespace(), cancellationToken).ConfigureAwait(false); + var indexes = await ListIndexesAsync(binding, this.GetFilesCollectionNamespace(), cancellationContext).ConfigureAwait(false); return FilesCollectionIndexesExist(indexes); } - private GridFSFileInfo GetFileInfo(IReadBindingHandle binding, TFileId id, CancellationToken cancellationToken) + private GridFSFileInfo GetFileInfo(IReadBindingHandle binding, TFileId id, OperationCancellationContext cancellationContext) { var operation = CreateGetFileInfoOperation(id); - using (var cursor = operation.Execute(binding, cancellationToken)) + using (var cursor = operation.Execute(binding, cancellationContext)) { - var fileInfo = cursor.FirstOrDefault(cancellationToken); + // TODO: CSOT add a way to propagate cancellationContext into cursor methods. + var fileInfo = cursor.FirstOrDefault(cancellationContext.CancellationToken); if (fileInfo == null) { throw new GridFSFileNotFoundException(_idSerializationInfo.SerializeValue(id)); @@ -900,12 +949,13 @@ private GridFSFileInfo GetFileInfo(IReadBindingHandle binding, TFileId } } - private async Task> GetFileInfoAsync(IReadBindingHandle binding, TFileId id, CancellationToken cancellationToken) + private async Task> GetFileInfoAsync(IReadBindingHandle binding, TFileId id, OperationCancellationContext cancellationContext) { var operation = CreateGetFileInfoOperation(id); - using (var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false)) { - var fileInfo = await cursor.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + // TODO: CSOT add a way to propagate cancellationContext into cursor methods. + var fileInfo = await cursor.FirstOrDefaultAsync(cancellationContext.CancellationToken).ConfigureAwait(false); if (fileInfo == null) { throw new GridFSFileNotFoundException(_idSerializationInfo.SerializeValue(id)); @@ -914,12 +964,13 @@ private async Task> GetFileInfoAsync(IReadBindingHandle } } - private GridFSFileInfo GetFileInfoByName(IReadBindingHandle binding, string filename, int revision, CancellationToken cancellationToken) + private GridFSFileInfo GetFileInfoByName(IReadBindingHandle binding, string filename, int revision, OperationCancellationContext cancellationContext) { var operation = CreateGetFileInfoByNameOperation(filename, revision); - using (var cursor = operation.Execute(binding, cancellationToken)) + using (var cursor = operation.Execute(binding, cancellationContext)) { - var fileInfo = cursor.FirstOrDefault(cancellationToken); + // TODO: CSOT add a way to propagate cancellationContext into cursor methods. + var fileInfo = cursor.FirstOrDefault(cancellationContext.CancellationToken); if (fileInfo == null) { throw new GridFSFileNotFoundException(filename, revision); @@ -928,12 +979,13 @@ private GridFSFileInfo GetFileInfoByName(IReadBindingHandle binding, st } } - private async Task> GetFileInfoByNameAsync(IReadBindingHandle binding, string filename, int revision, CancellationToken cancellationToken) + private async Task> GetFileInfoByNameAsync(IReadBindingHandle binding, string filename, int revision, OperationCancellationContext cancellationContext) { var operation = CreateGetFileInfoByNameOperation(filename, revision); - using (var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false)) { - var fileInfo = await cursor.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + // TODO: CSOT add a way to propagate cancellationContext into cursor methods. + var fileInfo = await cursor.FirstOrDefaultAsync(cancellationContext.CancellationToken).ConfigureAwait(false); if (fileInfo == null) { throw new GridFSFileNotFoundException(filename, revision); @@ -947,36 +999,36 @@ private ReadConcern GetReadConcern() return _options.ReadConcern ?? _database.Settings.ReadConcern; } - private IReadBindingHandle GetSingleServerReadBinding(CancellationToken cancellationToken) + private IReadBindingHandle GetSingleServerReadBinding(OperationCancellationContext cancellationContext) { var readPreference = _options.ReadPreference ?? _database.Settings.ReadPreference; var selector = new ReadPreferenceServerSelector(readPreference); - var server = _cluster.SelectServer(selector, cancellationToken); + var server = _cluster.SelectServer(selector, cancellationContext); var binding = new SingleServerReadBinding(server, readPreference, NoCoreSession.NewHandle()); return new ReadBindingHandle(binding); } - private async Task GetSingleServerReadBindingAsync(CancellationToken cancellationToken) + private async Task GetSingleServerReadBindingAsync(OperationCancellationContext cancellationContext) { var readPreference = _options.ReadPreference ?? _database.Settings.ReadPreference; var selector = new ReadPreferenceServerSelector(readPreference); - var server = await _cluster.SelectServerAsync(selector, cancellationToken).ConfigureAwait(false); + var server = await _cluster.SelectServerAsync(selector, cancellationContext).ConfigureAwait(false); var binding = new SingleServerReadBinding(server, readPreference, NoCoreSession.NewHandle()); return new ReadBindingHandle(binding); } - private IReadWriteBindingHandle GetSingleServerReadWriteBinding(CancellationToken cancellationToken) + private IReadWriteBindingHandle GetSingleServerReadWriteBinding(OperationCancellationContext cancellationContext) { var selector = WritableServerSelector.Instance; - var server = _cluster.SelectServer(selector, cancellationToken); + var server = _cluster.SelectServer(selector, cancellationContext); var binding = new SingleServerReadWriteBinding(server, NoCoreSession.NewHandle()); return new ReadWriteBindingHandle(binding); } - private async Task GetSingleServerReadWriteBindingAsync(CancellationToken cancellationToken) + private async Task GetSingleServerReadWriteBindingAsync(OperationCancellationContext cancellationContext) { var selector = WritableServerSelector.Instance; - var server = await _cluster.SelectServerAsync(selector, cancellationToken).ConfigureAwait(false); + var server = await _cluster.SelectServerAsync(selector, cancellationContext).ConfigureAwait(false); var binding = new SingleServerReadWriteBinding(server, NoCoreSession.NewHandle()); return new ReadWriteBindingHandle(binding); } @@ -993,37 +1045,39 @@ private bool IndexExists(List indexes, BsonDocument key) return false; } - private bool IsFilesCollectionEmpty(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private bool IsFilesCollectionEmpty(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) { var operation = CreateIsFilesCollectionEmptyOperation(); - using (var cursor = operation.Execute(binding, cancellationToken)) + using (var cursor = operation.Execute(binding, cancellationContext)) { - var firstOrDefault = cursor.FirstOrDefault(cancellationToken); + // TODO: CSOT add a way to propagate cancellationContext into cursor methods. + var firstOrDefault = cursor.FirstOrDefault(cancellationContext.CancellationToken); return firstOrDefault == null; } } - private async Task IsFilesCollectionEmptyAsync(IReadWriteBindingHandle binding, CancellationToken cancellationToken) + private async Task IsFilesCollectionEmptyAsync(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) { var operation = CreateIsFilesCollectionEmptyOperation(); - using (var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false)) { - var firstOrDefault = await cursor.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); + // TODO: CSOT add a way to propagate cancellationContext into cursor methods. + var firstOrDefault = await cursor.FirstOrDefaultAsync(cancellationContext.CancellationToken).ConfigureAwait(false); return firstOrDefault == null; } } - private List ListIndexes(IReadBinding binding, CollectionNamespace collectionNamespace, CancellationToken cancellationToken) + private List ListIndexes(IReadBinding binding, CollectionNamespace collectionNamespace, OperationCancellationContext cancellationContext) { var operation = CreateListIndexesOperation(collectionNamespace); - return operation.Execute(binding, cancellationToken).ToList(); + return operation.Execute(binding, cancellationContext).ToList(); } - private async Task> ListIndexesAsync(IReadBinding binding, CollectionNamespace collectionNamespace, CancellationToken cancellationToken) + private async Task> ListIndexesAsync(IReadBinding binding, CollectionNamespace collectionNamespace, OperationCancellationContext cancellationContext) { var operation = CreateListIndexesOperation(collectionNamespace); - var cursor = await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); - return await cursor.ToListAsync(cancellationToken).ConfigureAwait(false); + var cursor = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); + return await cursor.ToListAsync(cancellationContext.CancellationToken).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs index 0f9c09b96fe..932784461d2 100644 --- a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs +++ b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs @@ -196,14 +196,18 @@ private FindOperation CreateFirstBatchOperation() private void GetFirstBatch(CancellationToken cancellationToken) { var operation = CreateFirstBatchOperation(); - _cursor = operation.Execute(Binding, cancellationToken); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + _cursor = operation.Execute(Binding, operationCancellationContext); GetNextBatch(cancellationToken); } private async Task GetFirstBatchAsync(CancellationToken cancellationToken) { var operation = CreateFirstBatchOperation(); - _cursor = await operation.ExecuteAsync(Binding, cancellationToken).ConfigureAwait(false); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + _cursor = await operation.ExecuteAsync(Binding, operationCancellationContext).ConfigureAwait(false); await GetNextBatchAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs index 388b60e1fe8..b09060c4d98 100644 --- a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs +++ b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs @@ -122,7 +122,9 @@ public override long Position _aborted = true; var operation = CreateAbortOperation(); - operation.Execute(_binding, cancellationToken); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + operation.Execute(_binding, operationCancellationContext); } public override async Task AbortAsync(CancellationToken cancellationToken = default(CancellationToken)) @@ -135,7 +137,9 @@ public override long Position _aborted = true; var operation = CreateAbortOperation(); - await operation.ExecuteAsync(_binding, cancellationToken).ConfigureAwait(false); + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + await operation.ExecuteAsync(_binding, operationCancellationContext).ConfigureAwait(false); } public override void Close(CancellationToken cancellationToken) diff --git a/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs b/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs index afbe4a0b6b6..2cdc932daa1 100644 --- a/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs +++ b/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs @@ -16,8 +16,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; @@ -174,7 +172,9 @@ private FindOperation CreateGetChunkOperation(long n) private void GetChunk(long n, CancellationToken cancellationToken) { var operation = CreateGetChunkOperation(n); - using (var cursor = operation.Execute(Binding, cancellationToken)) + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + using (var cursor = operation.Execute(Binding, operationCancellationContext)) { var documents = cursor.ToList(); _chunk = GetChunkHelper(n, documents); @@ -185,7 +185,9 @@ private void GetChunk(long n, CancellationToken cancellationToken) private async Task GetChunkAsync(long n, CancellationToken cancellationToken) { var operation = CreateGetChunkOperation(n); - using (var cursor = await operation.ExecuteAsync(Binding, cancellationToken).ConfigureAwait(false)) + // TODO: CSOT implement proper way to obtain the operationCancellationContext + var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + using (var cursor = await operation.ExecuteAsync(Binding, operationCancellationContext).ConfigureAwait(false)) { var documents = await cursor.ToListAsync().ConfigureAwait(false); _chunk = GetChunkHelper(n, documents); diff --git a/src/MongoDB.Driver/MongoClient.cs b/src/MongoDB.Driver/MongoClient.cs index 55d91940952..0df21ba32cc 100644 --- a/src/MongoDB.Driver/MongoClient.cs +++ b/src/MongoDB.Driver/MongoClient.cs @@ -92,8 +92,9 @@ internal MongoClient(MongoClientSettings settings, Func(); _cluster = _settings.ClusterSource.Get(_settings.ToClusterKey()); _operationExecutor = _operationExecutorFactory(this); - _readOperationOptions = new(DefaultReadPreference: _settings.ReadPreference); - _writeOperationOptions = new(); + // TODO: CSOT populate the timeout from settings + _readOperationOptions = new(Timeout: Timeout.InfiniteTimeSpan, DefaultReadPreference: _settings.ReadPreference); + _writeOperationOptions = new(Timeout: Timeout.InfiniteTimeSpan); if (settings.AutoEncryptionOptions != null) { diff --git a/src/MongoDB.Driver/MongoCollectionImpl.cs b/src/MongoDB.Driver/MongoCollectionImpl.cs index 4b0b144e960..8ad05198a18 100644 --- a/src/MongoDB.Driver/MongoCollectionImpl.cs +++ b/src/MongoDB.Driver/MongoCollectionImpl.cs @@ -58,8 +58,9 @@ private MongoCollectionImpl(IMongoDatabase database, CollectionNamespace collect _documentSerializer = Ensure.IsNotNull(documentSerializer, nameof(documentSerializer)); _messageEncoderSettings = GetMessageEncoderSettings(); - _readOperationOptions = new(DefaultReadPreference: _settings.ReadPreference); - _writeOperationOptions = new(); + // TODO: CSOT populate the timeout from settings + _readOperationOptions = new(Timeout: Timeout.InfiniteTimeSpan, DefaultReadPreference: _settings.ReadPreference); + _writeOperationOptions = new(Timeout: Timeout.InfiniteTimeSpan); } // properties diff --git a/src/MongoDB.Driver/MongoDatabase.cs b/src/MongoDB.Driver/MongoDatabase.cs index cb1e0820dff..00a91ca35e5 100644 --- a/src/MongoDB.Driver/MongoDatabase.cs +++ b/src/MongoDB.Driver/MongoDatabase.cs @@ -50,9 +50,9 @@ public MongoDatabase(IMongoClient client, DatabaseNamespace databaseNamespace, M _settings = Ensure.IsNotNull(settings, nameof(settings)).Freeze(); _cluster = Ensure.IsNotNull(cluster, nameof(cluster)); _operationExecutor = Ensure.IsNotNull(operationExecutor, nameof(operationExecutor)); - - _readOperationOptions = new(DefaultReadPreference: _settings.ReadPreference); - _writeOperationOptions = new(); + // TODO: CSOT populate the timeout from settings + _readOperationOptions = new(Timeout: Timeout.InfiniteTimeSpan, DefaultReadPreference: _settings.ReadPreference); + _writeOperationOptions = new(Timeout: Timeout.InfiniteTimeSpan); } // public properties diff --git a/src/MongoDB.Driver/OperationCancellationContext.cs b/src/MongoDB.Driver/OperationCancellationContext.cs new file mode 100644 index 00000000000..31883afae1c --- /dev/null +++ b/src/MongoDB.Driver/OperationCancellationContext.cs @@ -0,0 +1,122 @@ +/* Copyright 2010-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. + */ + +using System; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; +using MongoDB.Driver.Core.Misc; + +namespace MongoDB.Driver +{ + internal sealed class OperationCancellationContext + { + // TODO: this static field is temporary here and will be removed in a future PRs in scope of CSOT. + public static readonly OperationCancellationContext NoTimeout = new(System.Threading.Timeout.InfiniteTimeSpan, CancellationToken.None); + + private readonly Stopwatch _stopwatch; + + public OperationCancellationContext(TimeSpan timeout, CancellationToken cancellationToken) + : this(Stopwatch.StartNew(), timeout, cancellationToken) + { + } + + internal OperationCancellationContext(Stopwatch stopwatch, TimeSpan timeout, CancellationToken cancellationToken) + { + _stopwatch = stopwatch; + Timeout = timeout; + CancellationToken = cancellationToken; + } + + public CancellationToken CancellationToken { get; } + + public TimeSpan Elapsed => _stopwatch.Elapsed; + + public TimeSpan Timeout { get; } + + public TimeSpan RemainingTimeout + { + get + { + if (Timeout == System.Threading.Timeout.InfiniteTimeSpan) + { + return System.Threading.Timeout.InfiniteTimeSpan; + } + + return Timeout - _stopwatch.Elapsed; + } + } + + public bool IsTimedOut() + { + var remainingTimeout = RemainingTimeout; + if (remainingTimeout == System.Threading.Timeout.InfiniteTimeSpan) + { + return false; + } + + return remainingTimeout < TimeSpan.Zero; + } + + public OperationCancellationContext WithTimeout(TimeSpan timeout) + { + var remainingTimeout = RemainingTimeout; + if (timeout == System.Threading.Timeout.InfiniteTimeSpan) + { + timeout = remainingTimeout; + } + else if (remainingTimeout != System.Threading.Timeout.InfiniteTimeSpan && remainingTimeout < timeout) + { + timeout = remainingTimeout; + } + + return new OperationCancellationContext(timeout, CancellationToken); + } + + public void WaitTask(Task task) + { + var timeout = RemainingTimeout; + if (timeout < TimeSpan.Zero) + { + throw new TimeoutException(); + } + + if (!task.Wait((int)timeout.TotalMilliseconds, CancellationToken)) + { + throw new TimeoutException(); + } + } + + public async Task WaitTaskAsync(Task task) + { + var timeout = RemainingTimeout; + if (timeout < TimeSpan.Zero) + { + throw new TimeoutException(); + } + + try + { + await task.WaitAsync(timeout, CancellationToken).ConfigureAwait(false); + } + catch (TaskCanceledException) + { + CancellationToken.ThrowIfCancellationRequested(); + throw; + } + } + } +} + diff --git a/src/MongoDB.Driver/OperationExecutor.cs b/src/MongoDB.Driver/OperationExecutor.cs index 295d136bd09..6ebdd6ca885 100644 --- a/src/MongoDB.Driver/OperationExecutor.cs +++ b/src/MongoDB.Driver/OperationExecutor.cs @@ -50,9 +50,10 @@ public TResult ExecuteReadOperation( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); + var cancellationContext = options.CreateCancellationContext(cancellationToken); var readPreference = options.GetEffectiveReadPreference(session); using var binding = CreateReadBinding(session, readPreference, allowChannelPinning); - return operation.Execute(binding, cancellationToken); + return operation.Execute(binding, cancellationContext); } public async Task ExecuteReadOperationAsync( @@ -67,9 +68,10 @@ public async Task ExecuteReadOperationAsync( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); + var cancellationContext = options.CreateCancellationContext(cancellationToken); var readPreference = options.GetEffectiveReadPreference(session); using var binding = CreateReadBinding(session, readPreference, allowChannelPinning); - return await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); } public TResult ExecuteWriteOperation( @@ -84,8 +86,9 @@ public TResult ExecuteWriteOperation( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); + var cancellationContext = options.CreateCancellationContext(cancellationToken); using var binding = CreateReadWriteBinding(session, allowChannelPinning); - return operation.Execute(binding, cancellationToken); + return operation.Execute(binding, cancellationContext); } public async Task ExecuteWriteOperationAsync( @@ -100,8 +103,9 @@ public async Task ExecuteWriteOperationAsync( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); + var cancellationContext = options.CreateCancellationContext(cancellationToken); using var binding = CreateReadWriteBinding(session, allowChannelPinning); - return await operation.ExecuteAsync(binding, cancellationToken).ConfigureAwait(false); + return await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); } public IClientSessionHandle StartImplicitSession() diff --git a/src/MongoDB.Driver/OperationOptionsBase.cs b/src/MongoDB.Driver/OperationOptionsBase.cs new file mode 100644 index 00000000000..e270f2c0efd --- /dev/null +++ b/src/MongoDB.Driver/OperationOptionsBase.cs @@ -0,0 +1,27 @@ +/* Copyright 2010-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. + */ + +using System; +using System.Threading; + +namespace MongoDB.Driver +{ + internal abstract record OperationOptionsBase(TimeSpan Timeout) + { + public OperationCancellationContext CreateCancellationContext(CancellationToken cancellationToken) + => new (Timeout, cancellationToken); + } +} + diff --git a/src/MongoDB.Driver/ReadOperationOptions.cs b/src/MongoDB.Driver/ReadOperationOptions.cs index 2473d5dc045..baba0248e8f 100644 --- a/src/MongoDB.Driver/ReadOperationOptions.cs +++ b/src/MongoDB.Driver/ReadOperationOptions.cs @@ -13,9 +13,12 @@ * limitations under the License. */ +using System; + namespace MongoDB.Driver { - internal record ReadOperationOptions(ReadPreference ExplicitReadPreference = null, ReadPreference DefaultReadPreference = null); + internal record ReadOperationOptions(TimeSpan Timeout, ReadPreference ExplicitReadPreference = null, ReadPreference DefaultReadPreference = null) + : OperationOptionsBase(Timeout); internal static class ReadOperationOptionsExtensions { diff --git a/src/MongoDB.Driver/WriteOperationOptions.cs b/src/MongoDB.Driver/WriteOperationOptions.cs index fd56dc0fa78..f141c2ebc39 100644 --- a/src/MongoDB.Driver/WriteOperationOptions.cs +++ b/src/MongoDB.Driver/WriteOperationOptions.cs @@ -13,8 +13,11 @@ * limitations under the License. */ +using System; + namespace MongoDB.Driver { - internal record WriteOperationOptions(); + internal record WriteOperationOptions(TimeSpan Timeout) + : OperationOptionsBase(Timeout); } diff --git a/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs b/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs index 4a50ba002d5..6eef6a12246 100644 --- a/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs +++ b/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs @@ -314,7 +314,7 @@ private static int GetMaxWireVersion() { var command = new BsonDocument("hello", 1); var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var response = operation.Execute(binding, CancellationToken.None); + var response = operation.Execute(binding, OperationCancellationContext.NoTimeout); return response["maxWireVersion"].AsInt32; } } @@ -326,7 +326,7 @@ private static SemanticVersion GetServerVersion() { var command = new BsonDocument("buildinfo", 1); var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var response = operation.Execute(binding, CancellationToken.None); + var response = operation.Execute(binding, OperationCancellationContext.NoTimeout); return SemanticVersion.Parse(response["version"].AsString); } } @@ -338,7 +338,7 @@ public static BsonDocument GetServerParameters() { var command = new BsonDocument("getParameter", new BsonString("*")); var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var serverParameters = operation.Execute(binding, CancellationToken.None); + var serverParameters = operation.Execute(binding, OperationCancellationContext.NoTimeout); return serverParameters; } @@ -404,7 +404,7 @@ private static void DropDatabase() using (var session = StartSession()) using (var binding = CreateReadWriteBinding(session)) { - operation.Execute(binding, CancellationToken.None); + operation.Execute(binding, OperationCancellationContext.NoTimeout); } } @@ -415,7 +415,7 @@ private static IEnumerable FindDocuments(IClusterInternal cluster, { var operation = new FindOperation(collectionNamespace, BsonDocumentSerializer.Instance, __messageEncoderSettings); - return operation.Execute(binding, CancellationToken.None).ToList(); + return operation.Execute(binding, OperationCancellationContext.NoTimeout).ToList(); } } @@ -495,7 +495,7 @@ string GetStorageEngineForCluster(IClusterInternal cluster) { var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var response = operation.Execute(binding, CancellationToken.None); + var response = operation.Execute(binding, OperationCancellationContext.NoTimeout); if (response.TryGetValue("storageEngine", out var storageEngine) && storageEngine.AsBsonDocument.TryGetValue("name", out var name)) { return name.AsString; diff --git a/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs b/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs index c9f6c9f9a4e..0db72e6057f 100644 --- a/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs +++ b/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs @@ -88,7 +88,7 @@ public static FailPoint ConfigureAlwaysOn(IClusterInternal cluster, ICoreSession private static IServer GetWriteableServer(IClusterInternal cluster) { var selector = WritableServerSelector.Instance; - return cluster.SelectServer(selector, CancellationToken.None); + return cluster.SelectServer(selector, OperationCancellationContext.NoTimeout); } private static void MakeFailPointApplicationNameTestableIfConfigured(BsonDocument command, bool async) @@ -186,7 +186,7 @@ private void ExecuteCommand(BsonDocument command, bool waitForConnected) BsonDocumentSerializer.Instance, new MessageEncoderSettings()); - operation.Execute(_binding, CancellationToken.None); + operation.Execute(_binding, OperationCancellationContext.NoTimeout); } } } diff --git a/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs b/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs index d865da3f833..da1b0c0c330 100644 --- a/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs +++ b/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs @@ -93,11 +93,11 @@ public IClusterableServer CreateServer(ClusterType clusterType, ClusterId cluste mockConnectionPool.Setup(p => p.Generation).Returns(valueFunction: () => poolGeneration); Action acquireConnectionCallback = () => { connectionGeneration = poolGeneration; }; mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Callback(acquireConnectionCallback) .Returns(mockConnection.Object); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Callback(acquireConnectionCallback) .ReturnsAsync(mockConnection.Object); mockConnectionPool.Setup(p => p.Clear(It.IsAny())).Callback(() => { ++poolGeneration; }); @@ -186,7 +186,7 @@ public void PublishDescription(ServerDescription description) var maxWireVersion = description.MaxWireVersion; var server = (Server)result.Server; var helloResult = new HelloResult(new BsonDocument { { "compressors", new BsonArray() }, { "maxWireVersion", maxWireVersion } }); - var mockConnection = Mock.Get(server._connectionPool().AcquireConnection(CancellationToken.None)); + var mockConnection = Mock.Get(server._connectionPool().AcquireConnection(OperationCancellationContext.NoTimeout)); mockConnection.SetupGet(c => c.Description) .Returns(new ConnectionDescription(new ConnectionId(description.ServerId, 0), helloResult)); } diff --git a/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs b/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs index a0d0a2a8a4c..b357bac1522 100644 --- a/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs +++ b/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs @@ -197,8 +197,8 @@ public static ConnectionDescription GetConnectionDescription() { var cluster = Client.GetClusterInternal(); using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, NoCoreSession.NewHandle()))) - using (var channelSource = binding.GetWriteChannelSource(default)) - using (var channel = channelSource.GetChannel(default)) + using (var channelSource = binding.GetWriteChannelSource(OperationCancellationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationCancellationContext.NoTimeout)) { return channel.ConnectionDescription; } diff --git a/tests/MongoDB.Driver.Tests/AuthenticationTests.cs b/tests/MongoDB.Driver.Tests/AuthenticationTests.cs index f60b30c80c5..acbec64b4be 100644 --- a/tests/MongoDB.Driver.Tests/AuthenticationTests.cs +++ b/tests/MongoDB.Driver.Tests/AuthenticationTests.cs @@ -337,10 +337,9 @@ private void AssertAuthenticationSucceeds( if (Feature.SpeculativeAuthentication.IsSupported(CoreTestConfiguration.MaxWireVersion) && speculativeAuthenticatationShouldSucceedIfPossible) { - var cancellationToken = CancellationToken.None; var serverSelector = new ReadPreferenceServerSelector(settings.ReadPreference); - var server = client.GetClusterInternal().SelectServer(serverSelector, cancellationToken); - var channel = server.GetChannel(cancellationToken); + var server = client.GetClusterInternal().SelectServer(serverSelector, OperationCancellationContext.NoTimeout); + var channel = server.GetChannel(OperationCancellationContext.NoTimeout); var helloResult = channel.ConnectionDescription.HelloResult; helloResult.SpeculativeAuthenticate.Should().NotBeNull(); } diff --git a/tests/MongoDB.Driver.Tests/ClusterTests.cs b/tests/MongoDB.Driver.Tests/ClusterTests.cs index 1852264edc3..f64a7c99b96 100644 --- a/tests/MongoDB.Driver.Tests/ClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/ClusterTests.cs @@ -100,8 +100,8 @@ public void SelectServer_loadbalancing_prose_test([Values(false, true)] bool asy var channels = new ConcurrentBag(); ThreadingUtilities.ExecuteOnNewThreads(threadsCount, i => { - channels.Add(slowServer.GetChannel(default)); - channels.Add(fastServer.GetChannel(default)); + channels.Add(slowServer.GetChannel(OperationCancellationContext.NoTimeout)); + channels.Add(fastServer.GetChannel(OperationCancellationContext.NoTimeout)); }); foreach (var channel in channels) diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelChannelSourceTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelChannelSourceTests.cs index 76a12582048..30257944773 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelChannelSourceTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelChannelSourceTests.cs @@ -15,7 +15,7 @@ using System; using System.Reflection; -using System.Threading; +using System.Threading.Tasks; using FluentAssertions; using MongoDB.TestHelpers.XunitExtensions; using MongoDB.Driver.Core.Servers; @@ -140,25 +140,17 @@ public void Dispose_can_be_called_more_than_once() [Theory] [ParameterAttributeData] - public void GetChannel_should_return_expected_result( + public async Task GetChannel_should_return_expected_result( [Values(false, true)] bool async) { var mockChannel = new Mock(); var subject = CreateSubject(channel: mockChannel.Object); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; var expectedResult = new Mock().Object; mockChannel.Setup(m => m.Fork()).Returns(expectedResult); - IChannelHandle result; - if (async) - { - result = subject.GetChannelAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - result = subject.GetChannel(cancellationToken); - } + var result = async ? + await subject.GetChannelAsync(OperationCancellationContext.NoTimeout) : + subject.GetChannel(OperationCancellationContext.NoTimeout); result.Should().BeSameAs(expectedResult); mockChannel.Verify(m => m.Fork(), Times.Once); @@ -166,24 +158,14 @@ public void GetChannel_should_return_expected_result( [Theory] [ParameterAttributeData] - public void GetChannel_should_throw_when_disposed( + public async Task GetChannel_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - - var exception = Record.Exception(() => - { - if (async) - { - subject.GetChannelAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - subject.GetChannel(cancellationToken); - } - }); + + var exception = async ? + await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationCancellationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadBindingTests.cs index 121011542cb..3360100430d 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadBindingTests.cs @@ -14,11 +14,7 @@ */ using System; -using System.Collections.Generic; -using System.Linq; using System.Reflection; -using System.Text; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.TestHelpers.XunitExtensions; @@ -151,29 +147,21 @@ public void Dispose_can_be_called_more_than_once() [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_return_expected_result( + public async Task GetReadChannelSource_should_return_expected_result( [Values(false, true)] bool async) { var mockChannel = new Mock(); var mockSession = new Mock(); var subject = CreateSubject(channel: mockChannel.Object, session: mockSession.Object); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; var forkedChannel = new Mock().Object; var forkedSession = new Mock().Object; mockChannel.Setup(m => m.Fork()).Returns(forkedChannel); mockSession.Setup(m => m.Fork()).Returns(forkedSession); - IChannelSourceHandle result; - if (async) - { - result = subject.GetReadChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - result = subject.GetReadChannelSource(cancellationToken); - } + var result = async ? + await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout) : + subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); @@ -184,24 +172,13 @@ public void GetReadChannelSource_should_return_expected_result( [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_throw_when_disposed( + public async Task GetReadChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - - var exception = Record.Exception(() => - { - if (async) - { - subject.GetReadChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - subject.GetReadChannelSource(cancellationToken); - } - }); + var exception = async ? + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs index 15c900f87d3..9ae61ca3ff4 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs @@ -14,11 +14,7 @@ */ using System; -using System.Collections.Generic; -using System.Linq; using System.Reflection; -using System.Text; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.TestHelpers.XunitExtensions; @@ -132,29 +128,21 @@ public void Dispose_can_be_called_more_than_once() [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_return_expected_result( + public async Task GetReadChannelSource_should_return_expected_result( [Values(false, true)] bool async) { var mockChannel = new Mock(); var mockSession = new Mock(); var subject = CreateSubject(channel: mockChannel.Object, session: mockSession.Object); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; var forkedChannel = new Mock().Object; var forkedSession = new Mock().Object; mockChannel.Setup(m => m.Fork()).Returns(forkedChannel); mockSession.Setup(m => m.Fork()).Returns(forkedSession); - IChannelSourceHandle result; - if (async) - { - result = subject.GetReadChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - result = subject.GetReadChannelSource(cancellationToken); - } + var result = async ? + await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout) : + subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); @@ -165,29 +153,21 @@ public void GetReadChannelSource_should_return_expected_result( [Theory] [ParameterAttributeData] - public void GetWriteChannelSource_should_return_expected_result( + public async Task GetWriteChannelSource_should_return_expected_result( [Values(false, true)] bool async) { var mockChannel = new Mock(); var mockSession = new Mock(); var subject = CreateSubject(channel: mockChannel.Object, session: mockSession.Object); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; var forkedChannel = new Mock().Object; var forkedSession = new Mock().Object; mockChannel.Setup(m => m.Fork()).Returns(forkedChannel); mockSession.Setup(m => m.Fork()).Returns(forkedSession); - IChannelSourceHandle result; - if (async) - { - result = subject.GetWriteChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - result = subject.GetWriteChannelSource(cancellationToken); - } + var result = async ? + await subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout) : + subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); @@ -198,24 +178,13 @@ public void GetWriteChannelSource_should_return_expected_result( [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_throw_when_disposed( + public async Task GetReadChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - - var exception = Record.Exception(() => - { - if (async) - { - subject.GetReadChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - subject.GetReadChannelSource(cancellationToken); - } - }); + var exception = async ? + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); @@ -223,24 +192,13 @@ public void GetReadChannelSource_should_throw_when_disposed( [Theory] [ParameterAttributeData] - public void GetWriteChannelSource_should_throw_when_disposed( + public async Task GetWriteChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - - var exception = Record.Exception(() => - { - if (async) - { - subject.GetWriteChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - subject.GetWriteChannelSource(cancellationToken); - } - }); + var exception = async ? + await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceHandleTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceHandleTests.cs index 212ca5f46d9..31af56c6576 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceHandleTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceHandleTests.cs @@ -15,6 +15,7 @@ using System; using System.Threading; +using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson.TestHelpers; using MongoDB.TestHelpers.XunitExtensions; @@ -53,29 +54,23 @@ public void Session_should_delegate_to_reference() [Theory] [ParameterAttributeData] - public void GetChannel_should_throw_if_disposed( + public async Task GetChannel_should_throw_if_disposed( [Values(false, true)] bool async) { var subject = new ChannelSourceHandle(_mockChannelSource.Object); subject.Dispose(); - Action act; - if (async) - { - act = () => subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.GetChannel(CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetChannel_should_delegate_to_reference( + public async Task GetChannel_should_delegate_to_reference( [Values(false, true)] bool async) { @@ -83,15 +78,15 @@ public void GetChannel_should_delegate_to_reference( if (async) { - subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult(); + await subject.GetChannelAsync(OperationCancellationContext.NoTimeout); - _mockChannelSource.Verify(s => s.GetChannelAsync(CancellationToken.None), Times.Once); + _mockChannelSource.Verify(s => s.GetChannelAsync(It.IsAny()), Times.Once); } else { - subject.GetChannel(CancellationToken.None); + subject.GetChannel(OperationCancellationContext.NoTimeout); - _mockChannelSource.Verify(s => s.GetChannel(CancellationToken.None), Times.Once); + _mockChannelSource.Verify(s => s.GetChannel(It.IsAny()), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceReadWriteBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceReadWriteBindingTests.cs index d00f0151e47..e9e6bc41a07 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceReadWriteBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceReadWriteBindingTests.cs @@ -14,11 +14,9 @@ */ using System; -using System.Threading; +using System.Threading.Tasks; using FluentAssertions; using MongoDB.TestHelpers.XunitExtensions; -using MongoDB.Driver.Core.Bindings; -using MongoDB.Driver.Core.Clusters; using Moq; using Xunit; @@ -78,84 +76,60 @@ public void Session_should_return_expected_result() [Theory] [ParameterAttributeData] - public void GetReadChannelSourceAsync_should_throw_if_disposed( + public async Task GetReadChannelSourceAsync_should_throw_if_disposed( [Values(false, true)] bool async) { var subject = new ChannelSourceReadWriteBinding(_mockChannelSource.Object, ReadPreference.Primary, NoCoreSession.NewHandle()); subject.Dispose(); - Action act; - if (async) - { - act = () => subject.GetReadChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.GetReadChannelSource(CancellationToken.None); - } - - act.ShouldThrow(); + var exception = async ? + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); + + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_fork_the_channelSource( + public async Task GetReadChannelSource_should_fork_the_channelSource( [Values(false, true)] bool async) { var subject = new ChannelSourceReadWriteBinding(_mockChannelSource.Object, ReadPreference.Primary, NoCoreSession.NewHandle()); - - if (async) - { - subject.GetReadChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - subject.GetReadChannelSource(CancellationToken.None); - } + var result = async ? + await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout) : + subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); _mockChannelSource.Verify(f => f.Fork(), Times.Once); } [Theory] [ParameterAttributeData] - public void GetWriteChannelSource_should_throw_if_disposed( + public async Task GetWriteChannelSource_should_throw_if_disposed( [Values(false, true)] bool async) { var subject = new ChannelSourceReadWriteBinding(_mockChannelSource.Object, ReadPreference.Primary, NoCoreSession.NewHandle()); subject.Dispose(); - Action act; - if (async) - { - act = () => subject.GetWriteChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.GetWriteChannelSource(CancellationToken.None); - } - - act.ShouldThrow(); + var exception = async ? + await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout)); + + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetWriteChannelSource_should_fork_the_channelSource( + public async Task GetWriteChannelSource_should_fork_the_channelSource( [Values(false, true)] bool async) { var subject = new ChannelSourceReadWriteBinding(_mockChannelSource.Object, ReadPreference.Primary, NoCoreSession.NewHandle()); - - if (async) - { - subject.GetWriteChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - subject.GetWriteChannelSource(CancellationToken.None); - } + var result = async ? + await subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout) : + subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout); _mockChannelSource.Verify(f => f.Fork(), Times.Once); } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadBindingHandleTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadBindingHandleTests.cs index d26b05ff749..6621a9699b0 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadBindingHandleTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadBindingHandleTests.cs @@ -14,7 +14,7 @@ */ using System; -using System.Threading; +using System.Threading.Tasks; using FluentAssertions; using MongoDB.TestHelpers.XunitExtensions; using Moq; @@ -51,29 +51,23 @@ public void Session_should_delegate_to_reference() [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_throw_if_disposed( + public async Task GetReadChannelSource_should_throw_if_disposed( [Values(false, true)] bool async) { var subject = new ReadBindingHandle(_mockReadBinding.Object); subject.Dispose(); - Action act; - if (async) - { - act = () => subject.GetReadChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.GetReadChannelSource(CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_delegate_to_reference( + public async Task GetReadChannelSource_should_delegate_to_reference( [Values(false, true)] bool async) { @@ -81,15 +75,15 @@ public void GetReadChannelSource_should_delegate_to_reference( if (async) { - subject.GetReadChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); + await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout); - _mockReadBinding.Verify(b => b.GetReadChannelSourceAsync(CancellationToken.None), Times.Once); + _mockReadBinding.Verify(b => b.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout), Times.Once); } else { - subject.GetReadChannelSource(CancellationToken.None); + subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); - _mockReadBinding.Verify(b => b.GetReadChannelSource(CancellationToken.None), Times.Once); + _mockReadBinding.Verify(b => b.GetReadChannelSource(OperationCancellationContext.NoTimeout), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs index 744241191af..16db8d16877 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs @@ -16,7 +16,6 @@ using System; using System.Net; using System.Reflection; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Driver.Core.Clusters; @@ -75,29 +74,23 @@ public void Session_should_return_expected_result() [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_throw_if_disposed( + public async Task GetReadChannelSource_should_throw_if_disposed( [Values(false, true)] bool async) { var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary, NoCoreSession.NewHandle()); subject.Dispose(); - Action act; - if (async) - { - act = () => subject.GetReadChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.GetReadChannelSource(CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_use_a_read_preference_server_selector_to_select_the_server_from_the_cluster( + public async Task GetReadChannelSource_should_use_a_read_preference_server_selector_to_select_the_server_from_the_cluster( [Values(false, true)] bool async) { @@ -118,35 +111,32 @@ public void GetReadChannelSource_should_use_a_read_preference_server_selector_to if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), CancellationToken.None)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); - subject.GetReadChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); + await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), It.IsAny()), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), CancellationToken.None)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); - subject.GetReadChannelSource(CancellationToken.None); + subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.IsAny(), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.IsAny(), It.IsAny()), Times.Once); } } [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_fork_the_session( + public async Task GetReadChannelSource_should_fork_the_session( [Values(false, true)] bool async) { var mockSession = new Mock(); var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary, mockSession.Object); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - var selectedServer = new Mock().Object; - _mockCluster.Setup(m => m.SelectServer(It.IsAny(), cancellationToken)).Returns(selectedServer); - _mockCluster.Setup(m => m.SelectServerAsync(It.IsAny(), cancellationToken)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(m => m.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); + _mockCluster.Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); var forkedSession = new Mock().Object; mockSession.Setup(m => m.Fork()).Returns(forkedSession); @@ -162,15 +152,9 @@ public void GetReadChannelSource_should_fork_the_session( var finalClusterDescription = initialClusterDescription.WithType(ClusterType.Standalone); _mockCluster.SetupSequence(c => c.Description).Returns(initialClusterDescription).Returns(finalClusterDescription); - IChannelSourceHandle result; - if (async) - { - result = subject.GetReadChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - result = subject.GetReadChannelSource(cancellationToken); - } + var result = async ? + await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout) : + subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); var handle = result.Should().BeOfType().Subject; var referenceCounted = handle._reference().Should().BeOfType>().Subject; diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadWriteBindingHandleTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadWriteBindingHandleTests.cs index 33f36397c1b..0a551419af5 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadWriteBindingHandleTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadWriteBindingHandleTests.cs @@ -14,10 +14,9 @@ */ using System; -using System.Threading; +using System.Threading.Tasks; using FluentAssertions; using MongoDB.TestHelpers.XunitExtensions; -using MongoDB.Driver.Core.Bindings; using Moq; using Xunit; @@ -52,29 +51,23 @@ public void Session_should_delegate_to_reference() [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_throw_if_disposed( + public async Task GetReadChannelSource_should_throw_if_disposed( [Values(false, true)] bool async) { var subject = new ReadWriteBindingHandle(_mockReadWriteBinding.Object); subject.Dispose(); - Action act; - if (async) - { - act = () => subject.GetReadChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.GetReadChannelSource(CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_delegate_to_reference( + public async Task GetReadChannelSource_should_delegate_to_reference( [Values(false, true)] bool async) { @@ -82,43 +75,37 @@ public void GetReadChannelSource_should_delegate_to_reference( if (async) { - subject.GetReadChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); + await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout); - _mockReadWriteBinding.Verify(b => b.GetReadChannelSourceAsync(CancellationToken.None), Times.Once); + _mockReadWriteBinding.Verify(b => b.GetReadChannelSourceAsync(It.IsAny()), Times.Once); } else { - subject.GetReadChannelSource(CancellationToken.None); + subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); - _mockReadWriteBinding.Verify(b => b.GetReadChannelSource(CancellationToken.None), Times.Once); + _mockReadWriteBinding.Verify(b => b.GetReadChannelSource(It.IsAny()), Times.Once); } } [Theory] [ParameterAttributeData] - public void GetWriteChannelSource_should_throw_if_disposed( + public async Task GetWriteChannelSource_should_throw_if_disposed( [Values(false, true)] bool async) { var subject = new ReadWriteBindingHandle(_mockReadWriteBinding.Object); subject.Dispose(); - Action act; - if (async) - { - act = () => subject.GetWriteChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.GetWriteChannelSource(CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetWriteChannelSource_should_delegate_to_reference( + public async Task GetWriteChannelSource_should_delegate_to_reference( [Values(false, true)] bool async) { @@ -126,15 +113,15 @@ public void GetWriteChannelSource_should_delegate_to_reference( if (async) { - subject.GetWriteChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); + await subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout); - _mockReadWriteBinding.Verify(b => b.GetWriteChannelSourceAsync(CancellationToken.None), Times.Once); + _mockReadWriteBinding.Verify(b => b.GetWriteChannelSourceAsync(It.IsAny()), Times.Once); } else { - subject.GetWriteChannelSource(CancellationToken.None); + subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout); - _mockReadWriteBinding.Verify(b => b.GetWriteChannelSource(CancellationToken.None), Times.Once); + _mockReadWriteBinding.Verify(b => b.GetWriteChannelSource(It.IsAny()), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ServerChannelSourceTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ServerChannelSourceTests.cs index 9b20a631e7b..02631cf70b2 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ServerChannelSourceTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ServerChannelSourceTests.cs @@ -14,13 +14,8 @@ */ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; -using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters; using MongoDB.Driver.Core.Servers; using MongoDB.Driver.Core.Helpers; @@ -43,17 +38,19 @@ public ServerChannelSourceTests() public void Constructor_should_throw_when_server_is_null() { var session = new Mock().Object; - Action act = () => new ServerChannelSource(null, session); + var exception = Record.Exception(() => new ServerChannelSource(null, session)); - act.ShouldThrow(); + exception.Should().BeOfType() + .Subject.ParamName.Should().Be("server"); } [Fact] public void Constructor_should_throw_when_session_is_null() { - Action act = () => new ServerChannelSource(_mockServer.Object, null); + var exception = Record.Exception(() => new ServerChannelSource(_mockServer.Object, null)); - act.ShouldThrow(); + exception.Should().BeOfType() + .Subject.ParamName.Should().Be("session"); } [Fact] @@ -84,7 +81,7 @@ public void Session_should_return_expected_result() [Theory] [ParameterAttributeData] - public void GetChannel_should_throw_if_disposed( + public async Task GetChannel_should_throw_if_disposed( [Values(false, true)] bool async) { @@ -92,22 +89,16 @@ public void GetChannel_should_throw_if_disposed( var subject = new ServerChannelSource(_mockServer.Object, session); subject.Dispose(); - Action act; - if (async) - { - act = () => subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.GetChannel(CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetChannel_should_get_connection_from_server( + public async Task GetChannel_should_get_connection_from_server( [Values(false, true)] bool async) { @@ -116,15 +107,15 @@ public void GetChannel_should_get_connection_from_server( if (async) { - subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult(); + await subject.GetChannelAsync(OperationCancellationContext.NoTimeout); - _mockServer.Verify(s => s.GetChannelAsync(CancellationToken.None), Times.Once); + _mockServer.Verify(s => s.GetChannelAsync(It.IsAny()), Times.Once); } else { - subject.GetChannel(CancellationToken.None); + subject.GetChannel(OperationCancellationContext.NoTimeout); - _mockServer.Verify(s => s.GetChannel(CancellationToken.None), Times.Once); + _mockServer.Verify(s => s.GetChannel(It.IsAny()), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadBindingTests.cs index 0c8e53a5321..cb9eaba20f1 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadBindingTests.cs @@ -17,6 +17,7 @@ using System.Net; using System.Reflection; using System.Threading; +using System.Threading.Tasks; using FluentAssertions; using MongoDB.TestHelpers.XunitExtensions; using MongoDB.Driver.Core.Servers; @@ -126,26 +127,17 @@ public void Dispose_can_be_called_more_than_once() [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_return_expected_result( + public async Task GetReadChannelSource_should_return_expected_result( [Values(false, true)] bool async) { var mockSession = new Mock(); var subject = CreateSubject(session: mockSession.Object); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - var forkedSession = new Mock().Object; mockSession.Setup(m => m.Fork()).Returns(forkedSession); - IChannelSourceHandle result; - if (async) - { - result = subject.GetReadChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - result = subject.GetReadChannelSource(cancellationToken); - } + var result = async ? + await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout) : + subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); @@ -155,24 +147,14 @@ public void GetReadChannelSource_should_return_expected_result( [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_throw_when_disposed( + public async Task GetReadChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - - var exception = Record.Exception(() => - { - if (async) - { - subject.GetReadChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - subject.GetReadChannelSource(cancellationToken); - } - }); + + var exception = async ? + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs index 1087d544760..067554e8775 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs @@ -14,11 +14,7 @@ */ using System; -using System.Collections.Generic; -using System.Linq; using System.Reflection; -using System.Text; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.TestHelpers.XunitExtensions; @@ -112,26 +108,17 @@ public void Dispose_can_be_called_more_than_once() [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_return_expected_result( + public async Task GetReadChannelSource_should_return_expected_result( [Values(false, true)] bool async) { var mockSession = new Mock(); var subject = CreateSubject(session: mockSession.Object); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - var forkedSession = new Mock().Object; mockSession.Setup(m => m.Fork()).Returns(forkedSession); - IChannelSourceHandle result; - if (async) - { - result = subject.GetReadChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - result = subject.GetReadChannelSource(cancellationToken); - } + var result = async ? + await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout) : + subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); @@ -141,24 +128,13 @@ public void GetReadChannelSource_should_return_expected_result( [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_throw_when_disposed( + public async Task GetReadChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - - var exception = Record.Exception(() => - { - if (async) - { - subject.GetReadChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - subject.GetReadChannelSource(cancellationToken); - } - }); + var exception = async ? + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); @@ -166,26 +142,17 @@ public void GetReadChannelSource_should_throw_when_disposed( [Theory] [ParameterAttributeData] - public void GetWriteChannelSource_should_return_expected_result( + public async Task GetWriteChannelSource_should_return_expected_result( [Values(false, true)] bool async) { var mockSession = new Mock(); var subject = CreateSubject(session: mockSession.Object); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - var forkedSession = new Mock().Object; mockSession.Setup(m => m.Fork()).Returns(forkedSession); - IChannelSourceHandle result; - if (async) - { - result = subject.GetWriteChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - result = subject.GetWriteChannelSource(cancellationToken); - } + var result = async ? + await subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout) : + subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); @@ -195,24 +162,13 @@ public void GetWriteChannelSource_should_return_expected_result( [Theory] [ParameterAttributeData] - public void GetWriteChannelSource_should_throw_when_disposed( + public async Task GetWriteChannelSource_should_throw_when_disposed( [Values(false, true)] bool async) { var subject = CreateDisposedSubject(); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - - var exception = Record.Exception(() => - { - if (async) - { - subject.GetWriteChannelSourceAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - subject.GetWriteChannelSource(cancellationToken); - } - }); + var exception = async ? + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs index a5796c5e5a0..5c7f2e49805 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs @@ -16,7 +16,6 @@ using System; using System.Net; using System.Reflection; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Driver.Core.Clusters; @@ -77,29 +76,23 @@ public void Session_should_return_expected_result() [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_throw_if_disposed( + public async Task GetReadChannelSource_should_throw_if_disposed( [Values(false, true)] bool async) { var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle()); subject.Dispose(); - Action act; - if (async) - { - act = () => subject.GetReadChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.GetReadChannelSource(CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetReadChannelSource_should_use_a_writable_server_selector_to_select_the_server_from_the_cluster( + public async Task GetReadChannelSource_should_use_a_writable_server_selector_to_select_the_server_from_the_cluster( [Values(false, true)] bool async) { @@ -122,47 +115,41 @@ public void GetReadChannelSource_should_use_a_writable_server_selector_to_select if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), CancellationToken.None)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), OperationCancellationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); - subject.GetReadChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); + await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), OperationCancellationContext.NoTimeout), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), CancellationToken.None)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), OperationCancellationContext.NoTimeout)).Returns(selectedServer); - subject.GetReadChannelSource(CancellationToken.None); + subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.IsAny(), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.IsAny(), OperationCancellationContext.NoTimeout), Times.Once); } } [Theory] [ParameterAttributeData] - public void GetWriteChannelSource_should_throw_if_disposed( + public async Task GetWriteChannelSource_should_throw_if_disposed( [Values(false, true)] bool async) { var subject = new WritableServerBinding(_mockCluster.Object, NoCoreSession.NewHandle()); subject.Dispose(); - Action act; - if (async) - { - act = () => subject.GetWriteChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.GetWriteChannelSource(CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetWriteChannelSourceAsync_should_use_a_writable_server_selector_to_select_the_server_from_the_cluster( + public async Task GetWriteChannelSourceAsync_should_use_a_writable_server_selector_to_select_the_server_from_the_cluster( [Values(false, true)] bool async) { @@ -184,19 +171,19 @@ public void GetWriteChannelSourceAsync_should_use_a_writable_server_selector_to_ if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), CancellationToken.None)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), OperationCancellationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); - subject.GetWriteChannelSourceAsync(CancellationToken.None).GetAwaiter().GetResult(); + await subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), OperationCancellationContext.NoTimeout), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), CancellationToken.None)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), OperationCancellationContext.NoTimeout)).Returns(selectedServer); - subject.GetWriteChannelSource(CancellationToken.None); + subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.IsAny(), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.IsAny(), OperationCancellationContext.NoTimeout), Times.Once); } } @@ -225,25 +212,25 @@ public async Task GetWriteChannelSource_should_use_a_composite_server_selector_t if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), CancellationToken.None)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), OperationCancellationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); - await subject.GetWriteChannelSourceAsync(deprioritizedServers, CancellationToken.None); + await subject.GetWriteChannelSourceAsync(deprioritizedServers, OperationCancellationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), OperationCancellationContext.NoTimeout), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), CancellationToken.None)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), OperationCancellationContext.NoTimeout)).Returns(selectedServer); - subject.GetWriteChannelSource(deprioritizedServers, CancellationToken.None); + subject.GetWriteChannelSource(deprioritizedServers, OperationCancellationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.Is(c => c.ToString().Contains("PriorityServerSelector")), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.Is(c => c.ToString().Contains("PriorityServerSelector")), OperationCancellationContext.NoTimeout), Times.Once); } } [Theory] [ParameterAttributeData] - public void GetWriteChannelSource_with_mayUseSecondary_should_pass_mayUseSecondary_to_server_selector( + public async Task GetWriteChannelSource_with_mayUseSecondary_should_pass_mayUseSecondary_to_server_selector( [Values(false, true)] bool async) { @@ -269,19 +256,19 @@ public void GetWriteChannelSource_with_mayUseSecondary_should_pass_mayUseSeconda if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), CancellationToken.None)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), OperationCancellationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); - subject.GetWriteChannelSourceAsync(mayUseSecondary, CancellationToken.None).GetAwaiter().GetResult(); + await subject.GetWriteChannelSourceAsync(mayUseSecondary, OperationCancellationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.Is(s => s.MayUseSecondary == mayUseSecondary), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.Is(s => s.MayUseSecondary == mayUseSecondary), OperationCancellationContext.NoTimeout), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), CancellationToken.None)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), OperationCancellationContext.NoTimeout)).Returns(selectedServer); - subject.GetWriteChannelSource(mayUseSecondary, CancellationToken.None); + subject.GetWriteChannelSource(mayUseSecondary, OperationCancellationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.Is(s => s.MayUseSecondary == mayUseSecondary), CancellationToken.None), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.Is(s => s.MayUseSecondary == mayUseSecondary), OperationCancellationContext.NoTimeout), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs b/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs index 0d2b8bd2d20..b30e9c2992c 100644 --- a/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs @@ -120,29 +120,23 @@ public void AcquireServerSession_should_call_serverSessionPool_AcquireSession() [Theory] [ParameterAttributeData] - public void SelectServer_should_throw_if_not_initialized( + public async Task SelectServer_should_throw_if_not_initialized( [Values(false, true)] bool async) { var selector = new Mock().Object; var subject = CreateSubject(); - Action act; - if (async) - { - act = () => subject.SelectServerAsync(selector, CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.SelectServer(selector, CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(selector, OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void SelectServer_should_throw_if_disposed( + public async Task SelectServer_should_throw_if_disposed( [Values(false, true)] bool async) { @@ -150,44 +144,32 @@ public void SelectServer_should_throw_if_disposed( var subject = CreateSubject(); subject.Dispose(); - Action act; - if (async) - { - act = () => subject.SelectServerAsync(selector, CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.SelectServer(selector, CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(selector, OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void SelectServer_should_throw_if_serverSelector_is_null( + public async Task SelectServer_should_throw_if_serverSelector_is_null( [Values(false, true)] bool async) { var subject = CreateSubject(); subject.Initialize(); - Action act; - if (async) - { - act = () => subject.SelectServerAsync(null, CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.SelectServer(null, CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.SelectServerAsync(null, OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(null, OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void SelectServer_should_return_a_server_if_one_matches( + public async Task SelectServer_should_return_a_server_if_one_matches( [Values(false, true)] bool async) { @@ -200,15 +182,9 @@ public void SelectServer_should_return_a_server_if_one_matches( var selector = new DelegateServerSelector((c, s) => s); - IServer result; - if (async) - { - result = subject.SelectServerAsync(selector, CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - result = subject.SelectServer(selector, CancellationToken.None); - } + var result = async ? + await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout) : + subject.SelectServer(selector, OperationCancellationContext.NoTimeout); result.Should().NotBeNull(); @@ -219,7 +195,7 @@ public void SelectServer_should_return_a_server_if_one_matches( [Theory] [ParameterAttributeData] - public void SelectServer_should_return_second_server_if_first_cannot_be_found( + public async Task SelectServer_should_return_second_server_if_first_cannot_be_found( [Values(false, true)] bool async) { @@ -236,15 +212,10 @@ public void SelectServer_should_return_second_server_if_first_cannot_be_found( var selector = new DelegateServerSelector((c, s) => s); - IServer result; - if (async) - { - result = subject.SelectServerAsync(selector, CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - result = subject.SelectServer(selector, CancellationToken.None); - } + var result = async ? + await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout) : + subject.SelectServer(selector, OperationCancellationContext.NoTimeout); + result.Should().NotBeNull(); result.EndPoint.Should().Be(endPoint2); @@ -256,11 +227,11 @@ public void SelectServer_should_return_second_server_if_first_cannot_be_found( [Theory] [ParameterAttributeData] - public void SelectServer_should_throw_if_no_servers_match( + public async Task SelectServer_should_throw_if_no_servers_match( [Values(false, true)] bool async) { - var subject = CreateSubject(); + var subject = CreateSubject(serverSelectionTimeout: TimeSpan.FromMilliseconds(10)); subject.Initialize(); var connected = ServerDescriptionHelper.Connected(subject.Description.ClusterId); @@ -269,17 +240,11 @@ public void SelectServer_should_throw_if_no_servers_match( var selector = new DelegateServerSelector((c, s) => Enumerable.Empty()); - Action act; - if (async) - { - act = () => subject.SelectServerAsync(selector, CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.SelectServer(selector, CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(selector, OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); @@ -289,7 +254,7 @@ public void SelectServer_should_throw_if_no_servers_match( [Theory] [ParameterAttributeData] - public void SelectServer_should_throw_if_the_matched_server_cannot_be_found_and_no_others_matched( + public async Task SelectServer_should_throw_if_the_matched_server_cannot_be_found_and_no_others_matched( [Values(false, true)] bool async) { @@ -303,17 +268,11 @@ public void SelectServer_should_throw_if_the_matched_server_cannot_be_found_and_ var selector = new DelegateServerSelector((c, s) => s); - Action act; - if (async) - { - act = () => subject.SelectServerAsync(selector, CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.SelectServer(selector, CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(selector, OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); @@ -326,7 +285,7 @@ public void SelectServer_should_throw_if_the_matched_server_cannot_be_found_and_ [InlineData(0, 0, true)] [InlineData(28, 29, false)] [InlineData(28, 29, true)] - public void SelectServer_should_throw_if_any_servers_are_incompatible(int min, int max, bool async) + public async Task SelectServer_should_throw_if_any_servers_are_incompatible(int min, int max, bool async) { var subject = CreateSubject(); subject.Initialize(); @@ -337,17 +296,11 @@ public void SelectServer_should_throw_if_any_servers_are_incompatible(int min, i var selector = new DelegateServerSelector((c, s) => s); - Action act; - if (async) - { - act = () => subject.SelectServerAsync(selector, CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => subject.SelectServer(selector, CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(selector, OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); @@ -356,7 +309,7 @@ public void SelectServer_should_throw_if_any_servers_are_incompatible(int min, i [Theory] [ParameterAttributeData] - public void SelectServer_should_keep_trying_to_match_by_waiting_on_cluster_description_changes( + public async Task SelectServer_should_keep_trying_to_match_by_waiting_on_cluster_description_changes( [Values(false, true)] bool async) { @@ -369,7 +322,7 @@ public void SelectServer_should_keep_trying_to_match_by_waiting_on_cluster_descr subject.SetServerDescriptions(connecting); _capturedEvents.Clear(); - Task.Run(() => + _ = Task.Run(() => { _capturedEvents.WaitForEventOrThrowIfTimeout(TimeSpan.FromSeconds(1)); @@ -384,15 +337,9 @@ public void SelectServer_should_keep_trying_to_match_by_waiting_on_cluster_descr var selector = new DelegateServerSelector((c, s) => s); - IServer result; - if (async) - { - result = subject.SelectServerAsync(selector, CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - result = subject.SelectServer(selector, CancellationToken.None); - } + var result = async ? + await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout) : + subject.SelectServer(selector, OperationCancellationContext.NoTimeout); result.Should().NotBeNull(); @@ -429,15 +376,9 @@ public async Task SelectServer_should_ignore_deprioritized_servers_if_cluster_is { _capturedEvents.Clear(); - IServer result; - if (async) - { - result = await subject.SelectServerAsync(selector, CancellationToken.None); - } - else - { - result = subject.SelectServer(selector, CancellationToken.None); - } + var result = async ? + await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout) : + subject.SelectServer(selector, OperationCancellationContext.NoTimeout); result.Should().NotBeNull(); @@ -469,15 +410,9 @@ public async Task SelectServer_should_return_deprioritized_servers_if_no_other_s var selector = new PriorityServerSelector(deprioritizedServers); _capturedEvents.Clear(); - IServer result; - if (async) - { - result = await subject.SelectServerAsync(selector, CancellationToken.None); - } - else - { - result = subject.SelectServer(selector, CancellationToken.None); - } + var result = async ? + await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout) : + subject.SelectServer(selector, OperationCancellationContext.NoTimeout); result.Should().NotBeNull(); @@ -525,7 +460,7 @@ public void DescriptionChanged_should_be_raised_when_the_description_changes() [Theory] [ParameterAttributeData] - public void SelectServer_should_apply_both_pre_and_post_server_selectors( + public async Task SelectServer_should_apply_both_pre_and_post_server_selectors( [Values(false, true)] bool async) { @@ -556,15 +491,9 @@ public void SelectServer_should_apply_both_pre_and_post_server_selectors( ServerDescriptionHelper.Connected(subject.Description.ClusterId, new DnsEndPoint("localhost", 27020))); _capturedEvents.Clear(); - IServer result; - if (async) - { - result = subject.SelectServerAsync(middleSelector, CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - result = subject.SelectServer(middleSelector, CancellationToken.None); - } + var result = async ? + await subject.SelectServerAsync(middleSelector, OperationCancellationContext.NoTimeout) : + subject.SelectServer(middleSelector, OperationCancellationContext.NoTimeout); ((DnsEndPoint)result.EndPoint).Port.Should().Be(27020); _capturedEvents.Next().Should().BeOfType(); @@ -574,7 +503,7 @@ public void SelectServer_should_apply_both_pre_and_post_server_selectors( [Theory] [ParameterAttributeData] - public void SelectServer_should_call_custom_selector( + public async Task SelectServer_should_call_custom_selector( [Values(true, false)] bool withEligibleServers, [Values(true, false)] bool async) { @@ -596,10 +525,10 @@ public void SelectServer_should_call_custom_selector( if (withEligibleServers) { - var selectedServer = SelectServerAttempt( - subject, - new DelegateServerSelector((c, s) => s), // do not filter servers - async); + var selector = new DelegateServerSelector((c, s) => s); + var selectedServer = async ? + await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout): + subject.SelectServer(selector, OperationCancellationContext.NoTimeout); var selectedServerPort = ((DnsEndPoint)selectedServer.EndPoint).Port; selectedServerPort.Should().Be(27020); @@ -608,12 +537,10 @@ public void SelectServer_should_call_custom_selector( } else { - var exception = Record.Exception( - () => - SelectServerAttempt( - subject, - new DelegateServerSelector((c, s) => new ServerDescription[0]), // no eligible servers - async)); + var selector = new DelegateServerSelector((c, s) => new ServerDescription[0]); + var exception = async ? + await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(selector, OperationCancellationContext.NoTimeout)); exception.Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); @@ -636,21 +563,6 @@ private StubCluster CreateSubject(TimeSpan? serverSelectionTimeout = null, Clust return new StubCluster(_settings, _mockServerFactory.Object, _capturedEvents, LoggerFactory, clusterType); } - private IServer SelectServerAttempt(Cluster cluster, IServerSelector operationSelector, bool async) - { - if (async) - { - return cluster - .SelectServerAsync(operationSelector, CancellationToken.None) - .GetAwaiter() - .GetResult(); - } - else - { - return cluster.SelectServer(operationSelector, CancellationToken.None); - } - } - // nested types private class StubCluster : Cluster { diff --git a/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs b/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs index c5f65fe9fa5..4a2d865ed65 100644 --- a/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs @@ -17,6 +17,7 @@ using System.Linq; using System.Net; using System.Threading; +using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson.TestHelpers; using MongoDB.Driver.Core.Clusters; @@ -63,8 +64,8 @@ public void Constructor_should_initialize_instance() } [Theory] - [ParameterAttributeData()] - public void Constructor_should_handle_directConnection_correctly([Values(null, false, true)]bool directConnection) + [ParameterAttributeData] + public void Constructor_should_handle_directConnection_correctly([Values(false, true)]bool directConnection) { _settings = _settings.With(directConnection: directConnection); @@ -81,7 +82,7 @@ public void Constructor_should_handle_directConnection_correctly([Values(null, f } [Theory] - [ParameterAttributeData()] + [ParameterAttributeData] public void Constructor_should_handle_loadBalanced_correctly([Values(false, true)] bool loadBalanced) { _settings = _settings.With(loadBalanced: loadBalanced); @@ -309,7 +310,7 @@ public void ProcessDnsResults_should_throw_when_srv_records_number_is_unexpected [Theory] [ParameterAttributeData] - public void SelectServer_should_return_expected_server( + public async Task SelectServer_should_return_expected_server( [Values(ConnectionStringScheme.MongoDB, ConnectionStringScheme.MongoDBPlusSrv)] ConnectionStringScheme connectionStringScheme, [Values(false, true)] bool async) { @@ -326,15 +327,9 @@ public void SelectServer_should_return_expected_server( PublishDescription(_endPoint); - IServer result; - if (async) - { - result = subject.SelectServerAsync(Mock.Of(), CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - result = subject.SelectServer(Mock.Of(), CancellationToken.None); - } + var result = async ? + await subject.SelectServerAsync(Mock.Of(), OperationCancellationContext.NoTimeout) : + subject.SelectServer(Mock.Of(), OperationCancellationContext.NoTimeout); result.EndPoint.Should().Be(_endPoint); } @@ -342,7 +337,7 @@ public void SelectServer_should_return_expected_server( [Theory] [ParameterAttributeData] - public void SelectServer_should_throw_server_selection_timeout_if_server_has_not_been_created_in_time( + public async Task SelectServer_should_throw_server_selection_timeout_if_server_has_not_been_created_in_time( [Values(ConnectionStringScheme.MongoDB, ConnectionStringScheme.MongoDBPlusSrv)] ConnectionStringScheme connectionStringScheme, [Values(false, true)] bool async) { @@ -356,19 +351,13 @@ public void SelectServer_should_throw_server_selection_timeout_if_server_has_not var dnsException = new Exception("Dns exception"); if (connectionStringScheme == ConnectionStringScheme.MongoDBPlusSrv) { - // it has affect only on srv mode + // it has an effect only on srv mode PublishDnsException(subject, dnsException); } - Exception exception; - if (async) - { - exception = Record.Exception(() => subject.SelectServerAsync(Mock.Of(), CancellationToken.None).GetAwaiter().GetResult()); - } - else - { - exception = Record.Exception(() => subject.SelectServer(Mock.Of(), CancellationToken.None)); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.SelectServerAsync(Mock.Of(), OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(Mock.Of(), OperationCancellationContext.NoTimeout)); var ex = exception.Should().BeOfType().Subject; ex.Message.Should().StartWith($"A timeout occurred after {serverSelectionTimeout.TotalMilliseconds}ms selecting a server. Client view of cluster state is "); @@ -385,7 +374,7 @@ public void SelectServer_should_throw_server_selection_timeout_if_server_has_not [Theory] [ParameterAttributeData] - public void SelectServer_should_be_cancelled_by_cancellationToken( + public async Task SelectServer_should_be_cancelled_by_cancellationToken( [Values(ConnectionStringScheme.MongoDB, ConnectionStringScheme.MongoDBPlusSrv)] ConnectionStringScheme connectionStringScheme, [Values(false, true)] bool async) { @@ -398,14 +387,10 @@ public void SelectServer_should_be_cancelled_by_cancellationToken( Exception exception; using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(100))) { - if (async) - { - exception = Record.Exception(() => subject.SelectServerAsync(Mock.Of(), cancellationTokenSource.Token).GetAwaiter().GetResult()); - } - else - { - exception = Record.Exception(() => subject.SelectServer(Mock.Of(), cancellationTokenSource.Token)); - } + var cancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationTokenSource.Token); + exception = async ? + await Record.ExceptionAsync(() => subject.SelectServerAsync(Mock.Of(), cancellationContext)) : + Record.Exception(() => subject.SelectServer(Mock.Of(), cancellationContext)); } exception.Should().BeOfType(); diff --git a/tests/MongoDB.Driver.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs b/tests/MongoDB.Driver.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs index 56570e094f9..5e2c0449e9b 100644 --- a/tests/MongoDB.Driver.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs @@ -175,7 +175,7 @@ public void AcquireConnection_should_iterate_over_all_dormant_connections() // acquire all connections and return them var allConnections = Enumerable.Range(0, connectionsCount) - .Select(i => subject.AcquireConnection(default)) + .Select(i => subject.AcquireConnection(OperationCancellationContext.NoTimeout)) .ToArray(); var connectionNotToExpire = allConnections[allConnections.Length / 2].ConnectionId; @@ -216,22 +216,17 @@ public void Constructor_should_throw_when_exceptionHandler_is_null() [Theory] [ParameterAttributeData] - public void AcquireConnection_should_throw_an_InvalidOperationException_if_not_initialized( + public async Task AcquireConnection_should_throw_an_InvalidOperationException_if_not_initialized( [Values(false, true)] bool async) { _capturedEvents.Clear(); - Action act; - if (async) - { - act = () => _subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => _subject.AcquireConnection(CancellationToken.None); - } - act.ShouldThrow(); + var exception = async ? + await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => _subject.AcquireConnection(OperationCancellationContext.NoTimeout)); + + exception.Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); var connectionPoolCheckingOutConnectionFailedEvent = _capturedEvents.Next(); var e = connectionPoolCheckingOutConnectionFailedEvent.Should().BeOfType().Subject; @@ -241,24 +236,19 @@ public void AcquireConnection_should_throw_an_InvalidOperationException_if_not_i [Theory] [ParameterAttributeData] - public void AcquireConnection_should_throw_an_ObjectDisposedException_after_disposing( + public async Task AcquireConnection_should_throw_an_ObjectDisposedException_after_disposing( [Values(false, true)] bool async) { _capturedEvents.Clear(); _subject.Dispose(); - Action act; - if (async) - { - act = () => _subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => _subject.AcquireConnection(CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => _subject.AcquireConnection(OperationCancellationContext.NoTimeout)); + + exception.Should().BeOfType(); - act.ShouldThrow(); _capturedEvents.Next().Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); @@ -270,22 +260,16 @@ public void AcquireConnection_should_throw_an_ObjectDisposedException_after_disp [Theory] [ParameterAttributeData] - public void AcquireConnection_should_return_a_connection( + public async Task AcquireConnection_should_return_a_connection( [Values(false, true)] bool async) { InitializeAndWait(); _capturedEvents.Clear(); - IConnectionHandle connection; - if (async) - { - connection = _subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - connection = _subject.AcquireConnection(CancellationToken.None); - } + var connection = async ? + await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : + _subject.AcquireConnection(OperationCancellationContext.NoTimeout); connection.Should().NotBeNull(); _subject.AvailableCount.Should().Be(_settings.MaxConnections - 1); @@ -345,27 +329,18 @@ public async Task AcquireConnection_should_invoke_error_handling_before_releasin subject.Initialize(); subject.SetReady(); - try - { - if (async) - { - _ = await subject.AcquireConnectionAsync(default); - } - else - { - _ = subject.AcquireConnection(default); - } - } - catch (MongoConnectionException) - { - subject.AvailableCount.Should().Be(maxConnections); - mockConnectionExceptionHandler.Verify(handler => handler.HandleExceptionOnOpen(exception), Times.Once); - } + var resultException = async ? + await Record.ExceptionAsync(() => subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.AcquireConnection(OperationCancellationContext.NoTimeout)); + + resultException.Should().BeOfType(); + subject.AvailableCount.Should().Be(maxConnections); + mockConnectionExceptionHandler.Verify(handler => handler.HandleExceptionOnOpen(exception), Times.Once); } [Theory] [ParameterAttributeData] - internal void AcquireConnection_should_track_checked_out_reasons( + internal async Task AcquireConnection_should_track_checked_out_reasons( [Values(CheckOutReason.Cursor, CheckOutReason.Transaction)] CheckOutReason reason, [Values(1, 3, 5)] int attempts, [Values(false, true)] bool async) @@ -390,15 +365,9 @@ internal void AcquireConnection_should_track_checked_out_reasons( List connections = new(); for (int attempt = 1; attempt <= attempts; attempt++) { - IConnectionHandle connection; - if (async) - { - connection = subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - connection = subject.AcquireConnection(CancellationToken.None); - } + var connection = async ? + await subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : + subject.AcquireConnection(OperationCancellationContext.NoTimeout); ((ICheckOutReasonTracker)connection).SetCheckOutReasonIfNotAlreadySet(reason); connections.Add(connection); @@ -448,7 +417,7 @@ IEnumerable GetEnumItemsExcept(CheckOutReason reason) [Theory] [ParameterAttributeData] - public void AcquireConnection_should_increase_count_up_to_the_max_number_of_connections( + public async Task AcquireConnection_should_increase_count_up_to_the_max_number_of_connections( [Values(false, true)] bool async) { @@ -459,15 +428,9 @@ public void AcquireConnection_should_increase_count_up_to_the_max_number_of_conn for (int i = 0; i < _settings.MaxConnections; i++) { - IConnection connection; - if (async) - { - connection = _subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - connection = _subject.AcquireConnection(CancellationToken.None); - } + var connection = async ? + await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : + _subject.AcquireConnection(OperationCancellationContext.NoTimeout); connections.Add(connection); } @@ -494,21 +457,15 @@ public void AcquireConnection_should_increase_count_up_to_the_max_number_of_conn [Theory] [ParameterAttributeData] - public void AcquiredConnection_should_return_connections_to_the_pool_when_disposed( + public async Task AcquiredConnection_should_return_connections_to_the_pool_when_disposed( [Values(false, true)] bool async) { InitializeAndWait(); - IConnectionHandle connection; - if (async) - { - connection = _subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - connection = _subject.AcquireConnection(CancellationToken.None); - } + var connection = async ? + await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : + _subject.AcquireConnection(OperationCancellationContext.NoTimeout); _capturedEvents.Clear(); @@ -523,7 +480,7 @@ public void AcquiredConnection_should_return_connections_to_the_pool_when_dispos [Theory] [ParameterAttributeData] - public void AcquiredConnection_should_not_return_connections_to_the_pool_when_disposed_and_expired( + public async Task AcquiredConnection_should_not_return_connections_to_the_pool_when_disposed_and_expired( [Values(false, true)] bool async) { @@ -538,15 +495,9 @@ public void AcquiredConnection_should_not_return_connections_to_the_pool_when_di InitializeAndWait(); - IConnectionHandle connection; - if (async) - { - connection = _subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - connection = _subject.AcquireConnection(CancellationToken.None); - } + var connection = async ? + await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : + _subject.AcquireConnection(OperationCancellationContext.NoTimeout); _capturedEvents.Clear(); @@ -566,7 +517,7 @@ public void AcquiredConnection_should_not_return_connections_to_the_pool_when_di [Theory] [ParameterAttributeData] - public void AcquireConnection_should_throw_a_TimeoutException_when_all_connections_are_checked_out( + public async Task AcquireConnection_should_throw_a_TimeoutException_when_all_connections_are_checked_out( [Values(false, true)] bool async) { @@ -574,30 +525,18 @@ public void AcquireConnection_should_throw_a_TimeoutException_when_all_connectio var connections = new List(); for (int i = 0; i < _settings.MaxConnections; i++) { - IConnection connection; - if (async) - { - connection = _subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - connection = _subject.AcquireConnection(CancellationToken.None); - } + var connection = async ? + await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : + _subject.AcquireConnection(OperationCancellationContext.NoTimeout); connections.Add(connection); } _capturedEvents.Clear(); - Action act; - if (async) - { - act = () => _subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => _subject.AcquireConnection(CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => _subject.AcquireConnection(OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); var connectionPoolCheckingOutConnectionFailedEvent = _capturedEvents.Next(); @@ -681,7 +620,6 @@ public void AcquireConnection_should_timeout_when_non_sufficient_reused_connecti // block further establishments blockEstablishmentEvent.Reset(); - var allConnections = new List(); var actualTimeouts = 0; var expectedTimeouts = maxAcquiringCount - maxConnecting; @@ -735,7 +673,7 @@ public void AcquireConnection_should_timeout_when_non_sufficient_reused_connecti [Theory] [ParameterAttributeData] - public void AcquiredConnection_should_not_throw_exceptions_when_disposed_after_the_pool_was_disposed( + public async Task AcquiredConnection_should_not_throw_exceptions_when_disposed_after_the_pool_was_disposed( [Values(false, true)] bool async) { @@ -744,13 +682,13 @@ public void AcquiredConnection_should_not_throw_exceptions_when_disposed_after_t IConnectionHandle connection2; if (async) { - connection1 = _subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); - connection2 = _subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); + connection1 = await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout); + connection2 = await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout); } else { - connection1 = _subject.AcquireConnection(CancellationToken.None); - connection2 = _subject.AcquireConnection(CancellationToken.None); + connection1 = _subject.AcquireConnection(OperationCancellationContext.NoTimeout); + connection2 = _subject.AcquireConnection(OperationCancellationContext.NoTimeout); } _capturedEvents.Clear(); @@ -916,22 +854,16 @@ public void Clear_should_throw_an_ObjectDisposedException_after_disposing() [Theory] [ParameterAttributeData] - public void Clear_should_cause_existing_connections_to_be_expired( + public async Task Clear_should_cause_existing_connections_to_be_expired( [Values(false, true)] bool async) { _subject.Initialize(); _subject.SetReady(); - IConnectionHandle connection; - if (async) - { - connection = _subject.AcquireConnectionAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - connection = _subject.AcquireConnection(CancellationToken.None); - } + var connection = async ? + await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : + _subject.AcquireConnection(OperationCancellationContext.NoTimeout); connection.IsExpired.Should().BeFalse(); _subject.Clear(closeInUseConnections: false); @@ -940,7 +872,7 @@ public void Clear_should_cause_existing_connections_to_be_expired( [Theory] [ParameterAttributeData] - public void Clear_with_serviceId_should_cause_only_expected_connections_to_be_expired( + public async Task Clear_with_serviceId_should_cause_only_expected_connections_to_be_expired( [Values(false, true)] bool async) { var serviceId = ObjectId.GenerateNewId(); @@ -970,7 +902,9 @@ public void Clear_with_serviceId_should_cause_only_expected_connections_to_be_ex subject.Initialize(); subject.SetReady(); - var connection = AcquireConnection(subject, async); + var connection = async ? + await subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : + subject.AcquireConnection(OperationCancellationContext.NoTimeout); connection.IsExpired.Should().BeFalse(); var randomServiceId = ObjectId.GenerateNewId(); @@ -1686,13 +1620,13 @@ private IConnection AcquireConnection(ExclusiveConnectionPool subject, bool asyn if (async) { return subject - .AcquireConnectionAsync(CancellationToken.None) + .AcquireConnectionAsync(OperationCancellationContext.NoTimeout) .GetAwaiter() .GetResult(); } else { - return subject.AcquireConnection(CancellationToken.None); + return subject.AcquireConnection(OperationCancellationContext.NoTimeout); } } diff --git a/tests/MongoDB.Driver.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs b/tests/MongoDB.Driver.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs index 4e8a23a13fb..5fdf7dfbd83 100644 --- a/tests/MongoDB.Driver.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs @@ -168,7 +168,7 @@ public void Stop_should_trigger_immediate_maintenance_call( IConnection acquiredConnection = null; if (checkOutConnection) { - acquiredConnection = pool.AcquireConnection(CancellationToken.None); + acquiredConnection = pool.AcquireConnection(OperationCancellationContext.NoTimeout); acquiredConnection.ConnectionId.LongLocalValue.Should().Be(1); } @@ -178,7 +178,7 @@ public void Stop_should_trigger_immediate_maintenance_call( var requestInPlayTimeout = TimeSpan.FromMilliseconds(100); if (!closeInUseConnection && checkOutConnection) { - // connection in progress should be not touched + // connection in progress should be not touched Thread.Sleep(requestInPlayTimeout); } else diff --git a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs index bdf4438a008..8c6276c517b 100644 --- a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs @@ -75,7 +75,7 @@ public void Ensure_command_network_error_before_handshake_is_correctly_handled([ // The next hello or legacy hello response will be delayed because the waiting in the mock.Callbacks cluster.Initialize(); - var selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint1), CancellationToken.None); + var selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint1), OperationCancellationContext.NoTimeout); initialSelectedEndpoint = selectedServer.EndPoint; initialSelectedEndpoint.Should().Be(__endPoint1); @@ -86,11 +86,11 @@ public void Ensure_command_network_error_before_handshake_is_correctly_handled([ Exception exception; if (async) { - exception = Record.Exception(() => selectedServer.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult()); + exception = Record.Exception(() => selectedServer.GetChannelAsync(OperationCancellationContext.NoTimeout).GetAwaiter().GetResult()); } else { - exception = Record.Exception(() => selectedServer.GetChannel(CancellationToken.None)); + exception = Record.Exception(() => selectedServer.GetChannel(OperationCancellationContext.NoTimeout)); } var e = exception.Should().BeOfType().Subject; @@ -107,7 +107,7 @@ public void Ensure_command_network_error_before_handshake_is_correctly_handled([ } // ensure that a new server can be selected - selectedServer = cluster.SelectServer(WritableServerSelector.Instance, CancellationToken.None); + selectedServer = cluster.SelectServer(WritableServerSelector.Instance, OperationCancellationContext.NoTimeout); // ensure that the selected server is not the same as the initial selectedServer.EndPoint.Should().Be(__endPoint2); @@ -187,11 +187,11 @@ void SetupConnectionPool(Mock mockConnectionPool, IConnectionHa { var dnsException = CreateDnsException(connection.ConnectionId, from: "pool"); mockConnectionPool - .Setup(c => c.AcquireConnection(It.IsAny())) + .Setup(c => c.AcquireConnection(It.IsAny())) .Callback(() => exceptionHandlerProvider().HandleExceptionOnOpen(dnsException)) .Throws(dnsException); // throw command dns exception mockConnectionPool - .Setup(c => c.AcquireConnectionAsync(It.IsAny())) + .Setup(c => c.AcquireConnectionAsync(It.IsAny())) .Callback(() => exceptionHandlerProvider().HandleExceptionOnOpen(dnsException)) .Throws(dnsException); // throw command dns exception } diff --git a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs index 2a2a3f024d2..2a1badc0078 100644 --- a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs @@ -96,7 +96,7 @@ public async Task RapidHeartbeatTimerCallback_should_ignore_reentrant_calls() cluster.Initialize(); // Trigger Cluster._rapidHeartbeatTimer - var _ = cluster.SelectServerAsync(CreateWritableServerAndEndPointSelector(__endPoint1), CancellationToken.None); + _ = cluster.SelectServerAsync(CreateWritableServerAndEndPointSelector(__endPoint1), OperationCancellationContext.NoTimeout); // Wait for all heartbeats to complete await Task.WhenAny(allHeartbeatsReceived.Task, Task.Delay(1000)); @@ -142,13 +142,13 @@ public async Task Ensure_no_deadlock_after_primary_update() server.DescriptionChanged += ProcessServerDescriptionChanged; } - var selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint1), CancellationToken.None); + var selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint1), OperationCancellationContext.NoTimeout); initialSelectedEndpoint = selectedServer.EndPoint; initialSelectedEndpoint.Should().Be(__endPoint1); // Change primary currentPrimaries.Add(__serverId2); - selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint2), CancellationToken.None); + selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint2), OperationCancellationContext.NoTimeout); selectedServer.EndPoint.Should().Be(__endPoint2); // Ensure stalling happened @@ -198,10 +198,10 @@ void SetupConnection(Mock mockConnectionHandle, ServerId serv void SetupConnectionPool(Mock mockConnectionPool, IConnectionHandle connection) { mockConnectionPool - .Setup(c => c.AcquireConnection(It.IsAny())) + .Setup(c => c.AcquireConnection(It.IsAny())) .Returns(connection); mockConnectionPool - .Setup(c => c.AcquireConnectionAsync(It.IsAny())) + .Setup(c => c.AcquireConnectionAsync(It.IsAny())) .Returns(Task.FromResult(connection)); } diff --git a/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntergationTests.cs b/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntergationTests.cs index d8a6095aaf1..8295981ee28 100644 --- a/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntergationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntergationTests.cs @@ -15,7 +15,6 @@ using System; using System.Collections.Generic; -using System.Threading; using FluentAssertions; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -615,11 +614,11 @@ private BulkWriteOperationResult CreateAndRunBulkOperation(RetryableWriteContext if (async) { - return bulkInsertOperation.ExecuteAsync(context, CancellationToken.None).GetAwaiter().GetResult(); + return bulkInsertOperation.ExecuteAsync(context, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult(); } else { - return bulkInsertOperation.Execute(context, CancellationToken.None); + return bulkInsertOperation.Execute(context, OperationCancellationContext.NoTimeout); } } @@ -635,19 +634,19 @@ private IAsyncCursor CreateAndRunFindOperation(RetryableReadContex if (async) { - return findOperation.ExecuteAsync(context, CancellationToken.None).GetAwaiter().GetResult(); + return findOperation.ExecuteAsync(context, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult(); } else { - return findOperation.Execute(context, CancellationToken.None); + return findOperation.Execute(context, OperationCancellationContext.NoTimeout); } } private RetryableReadContext CreateRetryableReadContext(IReadBindingHandle readBindingHandle, bool async) { return async - ? RetryableReadContext.CreateAsync(readBindingHandle, retryRequested: false, CancellationToken.None).GetAwaiter().GetResult() - : RetryableReadContext.Create(readBindingHandle, retryRequested: false, CancellationToken.None); + ? RetryableReadContext.CreateAsync(readBindingHandle, retryRequested: false, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult() + : RetryableReadContext.Create(readBindingHandle, retryRequested: false, OperationCancellationContext.NoTimeout); } private DisposableBindingBundle CreateReadBindingsAndRetryableReadContext(IClusterInternal cluster, ICoreSessionHandle sessionHandle, bool async) @@ -663,8 +662,8 @@ private DisposableBindingBundle Create private RetryableWriteContext CreateRetryableWriteContext(IReadWriteBindingHandle readWriteBindingHandle, bool async) { return async - ? RetryableWriteContext.CreateAsync(readWriteBindingHandle, retryRequested: false, CancellationToken.None).GetAwaiter().GetResult() - : RetryableWriteContext.Create(readWriteBindingHandle, retryRequested: false, CancellationToken.None); + ? RetryableWriteContext.CreateAsync(readWriteBindingHandle, retryRequested: false, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult() + : RetryableWriteContext.Create(readWriteBindingHandle, retryRequested: false, OperationCancellationContext.NoTimeout); } private DisposableBindingBundle CreateReadWriteBindingsAndRetryableWriteContext(IClusterInternal cluster, ICoreSessionHandle sessionHandle, bool async) diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/AggregateOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/AggregateOperationTests.cs index 9e20b7d8fa0..cf3cc8b3206 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/AggregateOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/AggregateOperationTests.cs @@ -592,16 +592,7 @@ public void Execute_should_throw_when_binding_is_null( { var subject = new AggregateOperation(_collectionNamespace, __pipeline, __resultSerializer, _messageEncoderSettings); - Exception exception; - if (async) - { - exception = Record.Exception(() => subject.ExecuteAsync(binding: null, cancellationToken: CancellationToken.None).GetAwaiter().GetResult()); - } - else - { - exception = Record.Exception(() => subject.Execute(binding: null, cancellationToken: CancellationToken.None)); - } - + var exception = Record.Exception(() => ExecuteOperation(subject, binding: null, async: async)); var argumentNullException = exception.Should().BeOfType().Subject; argumentNullException.ParamName.Should().Be("binding"); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorTests.cs index 1f5be9d301d..04100a17888 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorTests.cs @@ -328,7 +328,7 @@ public void Dispose_should_be_shielded_from_exceptions() { var mockChannelSource = new Mock(); mockChannelSource - .Setup(c => c.GetChannel(It.IsAny())) + .Setup(c => c.GetChannel(It.IsAny())) .Throws(); var subject = CreateSubject(cursorId: 1, channelSource: Optional.Create(mockChannelSource.Object)); @@ -341,7 +341,7 @@ public void Dispose_should_dispose_channel_source_when_cursor_was_not_closed_by_ { var mockChannelSource = new Mock(); mockChannelSource - .Setup(c => c.GetChannel(It.IsAny())) + .Setup(c => c.GetChannel(It.IsAny())) .Throws(); var subject = CreateSubject(cursorId: 1, channelSource: Optional.Create(mockChannelSource.Object)); @@ -385,7 +385,7 @@ public void Dispose_should_not_call_close_cursors_for_zero_cursor_id() var mockChannelSource = new Mock(); mockChannelSource - .Setup(c => c.GetChannel(It.IsAny())) + .Setup(c => c.GetChannel(It.IsAny())) .Returns(mockChannelHandle.Object); var subject = CreateSubject(cursorId: 0, channelSource: Optional.Create(mockChannelSource.Object)); @@ -409,8 +409,6 @@ public void GetMore_should_use_same_session( var collectionNamespace = new CollectionNamespace(databaseNamespace, "collection"); var cursorId = 1; var subject = CreateSubject(collectionNamespace: collectionNamespace, cursorId: cursorId, channelSource: Optional.Create(channelSource)); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; var connectionDescription = CreateConnectionDescriptionSupportingSession(); mockChannelSource.SetupGet(m => m.Session).Returns(session); @@ -427,11 +425,11 @@ public void GetMore_should_use_same_session( } }; - subject.MoveNext(cancellationToken); // skip empty first batch + subject.MoveNext(CancellationToken.None); // skip empty first batch var sameSessionWasUsed = false; if (async) { - mockChannelSource.Setup(m => m.GetChannelAsync(cancellationToken)).Returns(Task.FromResult(channel)); + mockChannelSource.Setup(m => m.GetChannelAsync(It.IsAny())).Returns(Task.FromResult(channel)); mockChannel .Setup(m => m.CommandAsync( session, @@ -445,15 +443,15 @@ public void GetMore_should_use_same_session( CommandResponseHandling.Return, It.IsAny>(), It.IsAny(), - cancellationToken)) + It.IsAny())) .Callback(() => sameSessionWasUsed = true) .Returns(Task.FromResult(secondBatch)); - subject.MoveNextAsync(cancellationToken).GetAwaiter().GetResult(); + subject.MoveNextAsync(CancellationToken.None).GetAwaiter().GetResult(); } else { - mockChannelSource.Setup(m => m.GetChannel(cancellationToken)).Returns(channel); + mockChannelSource.Setup(m => m.GetChannel(It.IsAny())).Returns(channel); mockChannel .Setup(m => m.Command( session, @@ -467,29 +465,17 @@ public void GetMore_should_use_same_session( CommandResponseHandling.Return, It.IsAny>(), It.IsAny(), - cancellationToken)) + It.IsAny())) .Callback(() => sameSessionWasUsed = true) .Returns(secondBatch); - subject.MoveNext(cancellationToken); + subject.MoveNext(CancellationToken.None); } sameSessionWasUsed.Should().BeTrue(); } // private methods - private void Close(AsyncCursor asyncCursor, bool async, CancellationToken cancellationToken) - { - if (async) - { - asyncCursor.CloseAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - asyncCursor.Close(cancellationToken); - } - } - private ConnectionDescription CreateConnectionDescriptionSupportingSession(int maxWireVersion = WireVersion.Server36) { var clusterId = new ClusterId(1); @@ -529,18 +515,6 @@ private AsyncCursor CreateSubject( maxTime.WithDefault(null)); } - private bool MoveNext(IAsyncCursor asyncCursor, bool async, CancellationToken cancellationToken) - { - if (async) - { - return asyncCursor.MoveNextAsync(cancellationToken).GetAwaiter().GetResult(); - } - else - { - return asyncCursor.MoveNext(cancellationToken); - } - } - private void SetupChannelMocks(Mock mockChannelSource, Mock mockChannelHandle, bool async, string commandResult, int maxWireVersion = WireVersion.Server36, bool isChannelExpired = false) { SetupChannelMocks(mockChannelSource, mockChannelHandle, async, BsonDocument.Parse(commandResult), maxWireVersion, isChannelExpired); @@ -563,7 +537,7 @@ private void SetupChannelMocks(Mock mockChannelSource, Mock c.GetChannelAsync(It.IsAny())) + .Setup(c => c.GetChannelAsync(It.IsAny())) .ReturnsAsync(mockChannelHandle.Object); mockChannelHandle @@ -590,7 +564,7 @@ private void SetupChannelMocks(Mock mockChannelSource, Mock c.GetChannel(It.IsAny())) + .Setup(c => c.GetChannel(It.IsAny())) .Returns(mockChannelHandle.Object); mockChannelHandle @@ -676,19 +650,18 @@ public void Session_reference_count_should_be_decremented_as_soon_as_possible(in Insert(documents); _session.ReferenceCount().Should().Be(1); - var cancellationToken = CancellationToken.None; using (var binding = new ReadPreferenceBinding(CoreTestConfiguration.Cluster, ReadPreference.Primary, _session.Fork())) - using (var channelSource = (ChannelSourceHandle)binding.GetReadChannelSource(cancellationToken)) - using (var channel = channelSource.GetChannel(cancellationToken)) + using (var channelSource = (ChannelSourceHandle)binding.GetReadChannelSource(OperationCancellationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationCancellationContext.NoTimeout)) { var query = new BsonDocument(); long cursorId; - var firstBatch = GetFirstBatch(channel, query, batchSize, cancellationToken, out cursorId); + var firstBatch = GetFirstBatch(channel, query, batchSize, CancellationToken.None, out cursorId); using (var cursor = new AsyncCursor(channelSource, _collectionNamespace, comment: null, firstBatch, cursorId, batchSize, null, BsonDocumentSerializer.Instance, new MessageEncoderSettings())) { AssertExpectedSessionReferenceCount(_session, cursor); - while (cursor.MoveNext(cancellationToken)) + while (cursor.MoveNext(CancellationToken.None)) { AssertExpectedSessionReferenceCount(_session, cursor); } @@ -738,31 +711,6 @@ private IReadOnlyList GetFirstBatchUsingFindCommand(IChannelHandle cursorId = cursor["id"].ToInt64(); return firstBatch; } - - private IReadOnlyList GetFirstBatchUsingQueryMessage(IChannelHandle channel, BsonDocument query, int batchSize, CancellationToken cancellationToken, out long cursorId) - { -#pragma warning disable 618 - var result = channel.Query( - _collectionNamespace, - query, - null, // fields - NoOpElementNameValidator.Instance, - 0, // skip - batchSize, - false, // secondaryOk - false, // partialOk - false, // noCursorTimeout - false, // oplogReplay - false, // tailableCursor - false, // awaitData - BsonDocumentSerializer.Instance, - _messageEncoderSettings, - cancellationToken); -#pragma warning restore 618 - - cursorId = result.CursorId; - return result.Documents; - } } internal static class AsyncCursorReflector diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/BulkMixedWriteOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/BulkMixedWriteOperationTests.cs index fc223f8ab02..a1a899584e8 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/BulkMixedWriteOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/BulkMixedWriteOperationTests.cs @@ -1376,8 +1376,8 @@ public void Execute_unacknowledged_with_an_error_in_the_first_batch_and_ordered_ }; using (var readWriteBinding = CreateReadWriteBinding(useImplicitSession: true)) - using (var channelSource = readWriteBinding.GetWriteChannelSource(CancellationToken.None)) - using (var channel = channelSource.GetChannel(CancellationToken.None)) + using (var channelSource = readWriteBinding.GetWriteChannelSource(OperationCancellationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationCancellationContext.NoTimeout)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, readWriteBinding.Session.Fork())) { var result = ExecuteOperation(subject, channelBinding, async); @@ -1423,8 +1423,8 @@ public void Execute_unacknowledged_with_an_error_in_the_first_batch_and_ordered_ }; using (var readWriteBinding = CreateReadWriteBinding(useImplicitSession: true)) - using (var channelSource = readWriteBinding.GetWriteChannelSource(CancellationToken.None)) - using (var channel = channelSource.GetChannel(CancellationToken.None)) + using (var channelSource = readWriteBinding.GetWriteChannelSource(OperationCancellationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationCancellationContext.NoTimeout)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, readWriteBinding.Session.Fork())) { var result = ExecuteOperation(subject, channelBinding, async); @@ -1464,8 +1464,8 @@ public void Execute_unacknowledged_with_an_error_in_the_second_batch_and_ordered }; using (var readWriteBinding = CreateReadWriteBinding(useImplicitSession: true)) - using (var channelSource = readWriteBinding.GetWriteChannelSource(CancellationToken.None)) - using (var channel = channelSource.GetChannel(CancellationToken.None)) + using (var channelSource = readWriteBinding.GetWriteChannelSource(OperationCancellationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationCancellationContext.NoTimeout)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, readWriteBinding.Session.Fork())) { var result = ExecuteOperation(subject, channelBinding, async); @@ -1505,8 +1505,8 @@ public void Execute_unacknowledged_with_an_error_in_the_second_batch_and_ordered }; using (var readWriteBinding = CreateReadWriteBinding(useImplicitSession: true)) - using (var channelSource = readWriteBinding.GetWriteChannelSource(CancellationToken.None)) - using (var channel = channelSource.GetChannel(CancellationToken.None)) + using (var channelSource = readWriteBinding.GetWriteChannelSource(OperationCancellationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationCancellationContext.NoTimeout)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, readWriteBinding.Session.Fork())) { var result = ExecuteOperation(subject, channelBinding, async); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs index f2661693749..78854425a89 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs @@ -435,8 +435,6 @@ public void MoveNext_should_call_Resume_after_resumable_exception( var mockBinding = new Mock(); var mockOperation = new Mock>(); var subject = CreateSubject(cursor: mockCursor.Object, binding: mockBinding.Object, changeStreamOperation: mockOperation.Object); - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; var resumableException = CoreExceptionHelper.CreateException(resumableExceptionType); var mockResumedCursor = CreateMockCursor(); @@ -444,34 +442,34 @@ public void MoveNext_should_call_Resume_after_resumable_exception( var resumeToken = BsonDocument.Parse("{ resumeToken : 1 }"); var firstDocument = BsonDocument.Parse("{ _id : { resumeToken : 1 }, operationType : \"insert\", ns : { db : \"db\", coll : \"coll\" }, documentKey : { _id : 1 }, fullDocument : { _id : 1 } }"); var firstBatch = new[] { ToRawDocument(firstDocument) }; - mockCursor.Setup(c => c.MoveNext(cancellationToken)).Returns(true); + mockCursor.Setup(c => c.MoveNext(It.IsAny())).Returns(true); mockCursor.SetupGet(c => c.Current).Returns(firstBatch); - subject.MoveNext(cancellationToken); + subject.MoveNext(CancellationToken.None); bool result; if (async) { - mockCursor.Setup(c => c.MoveNextAsync(cancellationToken)).Returns(CreateFaultedTask(resumableException)); - mockOperation.Setup(o => o.ResumeAsync(mockBinding.Object, cancellationToken)).Returns(Task.FromResult(mockResumedCursor.Object)); - mockResumedCursor.Setup(c => c.MoveNextAsync(cancellationToken)).Returns(Task.FromResult(expectedResult)); + mockCursor.Setup(c => c.MoveNextAsync(It.IsAny())).Returns(CreateFaultedTask(resumableException)); + mockOperation.Setup(o => o.ResumeAsync(mockBinding.Object, It.IsAny())).Returns(Task.FromResult(mockResumedCursor.Object)); + mockResumedCursor.Setup(c => c.MoveNextAsync(It.IsAny())).Returns(Task.FromResult(expectedResult)); - result = subject.MoveNextAsync(cancellationToken).GetAwaiter().GetResult(); + result = subject.MoveNextAsync(It.IsAny()).GetAwaiter().GetResult(); - mockCursor.Verify(c => c.MoveNextAsync(cancellationToken), Times.Once); - mockOperation.Verify(o => o.ResumeAsync(mockBinding.Object, cancellationToken), Times.Once); - mockResumedCursor.Verify(c => c.MoveNextAsync(cancellationToken), Times.Once); + mockCursor.Verify(c => c.MoveNextAsync(It.IsAny()), Times.Once); + mockOperation.Verify(o => o.ResumeAsync(mockBinding.Object, It.IsAny()), Times.Once); + mockResumedCursor.Verify(c => c.MoveNextAsync(It.IsAny()), Times.Once); } else { - mockCursor.Setup(c => c.MoveNext(cancellationToken)).Throws(resumableException); - mockOperation.Setup(o => o.Resume(mockBinding.Object, cancellationToken)).Returns(mockResumedCursor.Object); - mockResumedCursor.Setup(c => c.MoveNext(cancellationToken)).Returns(expectedResult); + mockCursor.Setup(c => c.MoveNext(It.IsAny())).Throws(resumableException); + mockOperation.Setup(o => o.Resume(mockBinding.Object, It.IsAny())).Returns(mockResumedCursor.Object); + mockResumedCursor.Setup(c => c.MoveNext(It.IsAny())).Returns(expectedResult); - result = subject.MoveNext(cancellationToken); + result = subject.MoveNext(It.IsAny()); - mockCursor.Verify(c => c.MoveNext(cancellationToken), Times.Exactly(2)); - mockOperation.Verify(o => o.Resume(mockBinding.Object, cancellationToken), Times.Once); - mockResumedCursor.Verify(c => c.MoveNext(cancellationToken), Times.Once); + mockCursor.Verify(c => c.MoveNext(It.IsAny()), Times.Exactly(2)); + mockOperation.Verify(o => o.Resume(mockBinding.Object, It.IsAny()), Times.Once); + mockResumedCursor.Verify(c => c.MoveNext(It.IsAny()), Times.Once); } result.Should().Be(expectedResult); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamOperationTests.cs index b368fdea6a2..394685a8807 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamOperationTests.cs @@ -636,15 +636,7 @@ public void Execute_should_throw_when_binding_does_not_implement_IReadBindingHan var subject = CreateSubject(); var binding = new Mock().Object; - Exception exception; - if (async) - { - exception = Record.Exception(() => subject.ExecuteAsync(binding, CancellationToken.None).GetAwaiter().GetResult()); - } - else - { - exception = Record.Exception(() => subject.Execute(binding, CancellationToken.None)); - } + var exception = Record.Exception(() => ExecuteOperation(subject, binding, async)); var argumentException = exception.Should().BeOfType().Subject; argumentException.ParamName.Should().Be("binding"); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs index 18c67618a5c..48a11919dd3 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Bson; @@ -70,8 +69,8 @@ public async Task Enumerating_operations_should_be_stopped_when_error([Values(fa var subject = new CompositeWriteOperation((healthyOperation1.Object, IsMainOperation: false), (faultyOperation2.Object, IsMainOperation: false), (healthyOperation3.Object, IsMainOperation: true)); var resultedException = async - ? await Record.ExceptionAsync(() => subject.ExecuteAsync(Mock.Of(), CancellationToken.None)) - : Record.Exception(() => subject.Execute(Mock.Of(), CancellationToken.None)); + ? await Record.ExceptionAsync(() => subject.ExecuteAsync(Mock.Of(), OperationCancellationContext.NoTimeout)) + : Record.Exception(() => subject.Execute(Mock.Of(), OperationCancellationContext.NoTimeout)); resultedException.Should().Be(testException); @@ -93,8 +92,8 @@ public void Enumerating_operations_should_return_result_of_main_operation([Value var subject = new CompositeWriteOperation((operation1.Object, IsMainOperation: false), (operation2.Object, IsMainOperation: true), (operation3.Object, IsMainOperation: false)); var result = async - ? subject.ExecuteAsync(Mock.Of(), CancellationToken.None).GetAwaiter().GetResult() - : subject.Execute(Mock.Of(), CancellationToken.None); + ? subject.ExecuteAsync(Mock.Of(), OperationCancellationContext.NoTimeout).GetAwaiter().GetResult() + : subject.Execute(Mock.Of(), OperationCancellationContext.NoTimeout); result.Should().Be(operation2Result); @@ -108,10 +107,10 @@ private Mock> CreateFaultyOperation(Exception test { var mockedOperation = new Mock>(); mockedOperation - .Setup(c => c.Execute(It.IsAny(), It.IsAny())) + .Setup(c => c.Execute(It.IsAny(), It.IsAny())) .Throws(testException); mockedOperation - .Setup(c => c.ExecuteAsync(It.IsAny(), It.IsAny())) + .Setup(c => c.ExecuteAsync(It.IsAny(), It.IsAny())) .Throws(testException); return mockedOperation; } @@ -120,10 +119,10 @@ private Mock> CreateHealthyOperation(BsonDocument { var mockedOperation = new Mock>(); mockedOperation - .Setup(c => c.Execute(It.IsAny(), It.IsAny())) + .Setup(c => c.Execute(It.IsAny(), It.IsAny())) .Returns(response); mockedOperation - .Setup(c => c.ExecuteAsync(It.IsAny(), It.IsAny())) + .Setup(c => c.ExecuteAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(response); return mockedOperation; } @@ -132,11 +131,11 @@ private void VeryfyOperation(Mock> mockedOperation { if (async) { - mockedOperation.Verify(c => c.ExecuteAsync(It.IsAny(), It.IsAny()), hasBeenCalled ? Times.Once : Times.Never); + mockedOperation.Verify(c => c.ExecuteAsync(It.IsAny(), It.IsAny()), hasBeenCalled ? Times.Once : Times.Never); } else { - mockedOperation.Verify(c => c.Execute(It.IsAny(), It.IsAny()), hasBeenCalled ? Times.Once : Times.Never); + mockedOperation.Verify(c => c.Execute(It.IsAny(), It.IsAny()), hasBeenCalled ? Times.Once : Times.Never); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs index 3ef1da35313..90d11362d80 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs @@ -1031,11 +1031,11 @@ private BsonDocument ExecuteOperation(CreateCollectionOperation subject, IWriteB { if (async) { - return subject.ExecuteAsync(binding, CancellationToken.None).GetAwaiter().GetResult(); + return subject.ExecuteAsync(binding, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult(); } else { - return subject.Execute(binding, CancellationToken.None); + return subject.Execute(binding, OperationCancellationContext.NoTimeout); } } @@ -1045,7 +1045,7 @@ private BsonDocument GetCollectionInfo(IReadBinding binding) { Filter = new BsonDocument("name", _collectionNamespace.CollectionName) }; - return listCollectionsOperation.Execute(binding, CancellationToken.None).Single(); + return listCollectionsOperation.Execute(binding, OperationCancellationContext.NoTimeout).Single(); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs index ef72d20e5fa..681b2bad18b 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs @@ -331,7 +331,7 @@ private BsonDocument GetViewInfo(IReadBinding binding, string viewName) { Filter = new BsonDocument("name", viewName) }; - return listCollectionsOperation.Execute(binding, CancellationToken.None).Single(); + return listCollectionsOperation.Execute(binding, OperationCancellationContext.NoTimeout).Single(); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/EvalOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/EvalOperationTests.cs index 64080a96efa..a66b02b2462 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/EvalOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/EvalOperationTests.cs @@ -304,11 +304,11 @@ private BsonValue ExecuteOperation(EvalOperation operation, IWriteBinding bindin { if (async) { - return operation.ExecuteAsync(binding, CancellationToken.None).GetAwaiter().GetResult(); + return operation.ExecuteAsync(binding, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult(); } else { - return operation.Execute(binding, CancellationToken.None); + return operation.Execute(binding, OperationCancellationContext.NoTimeout); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/GroupOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/GroupOperationTests.cs index 4a7d7d4de0a..5bcfde3d6d8 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/GroupOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/GroupOperationTests.cs @@ -510,17 +510,7 @@ public void Execute_should_throw_when_binding_is_null( { var subject = new GroupOperation(_collectionNamespace, _key, _initial, _reduceFunction, _filter, _messageEncoderSettings); - var exception = Record.Exception(() => - { - if (async) - { - subject.ExecuteAsync(null, CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - subject.Execute(null, CancellationToken.None); - } - }); + var exception = Record.Exception(() => ExecuteOperation(subject, binding: null, async)); var argumentNullException = exception.Should().BeOfType().Subject; argumentNullException.ParamName.Should().Be("binding"); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs b/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs index c90c70c6132..414e556fadf 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs @@ -142,7 +142,7 @@ private protected TResult ExecuteOperation(IReadOperation oper using (var binding = CreateReadBinding()) using (var bindingHandle = new ReadBindingHandle(binding)) { - return operation.Execute(bindingHandle, CancellationToken.None); + return operation.Execute(bindingHandle, OperationCancellationContext.NoTimeout); } } @@ -163,14 +163,9 @@ private protected async Task ExecuteOperationAsync(IReadOperat using (var binding = CreateReadBinding(cluster)) using (var bindingHandle = new ReadBindingHandle(binding)) { - if (async) - { - return operation.Execute(bindingHandle, CancellationToken.None); - } - else - { - return await operation.ExecuteAsync(bindingHandle, CancellationToken.None); - } + return async ? + await operation.ExecuteAsync(bindingHandle, OperationCancellationContext.NoTimeout) : + operation.Execute(bindingHandle, OperationCancellationContext.NoTimeout); } } @@ -178,11 +173,11 @@ private protected TResult ExecuteOperation(IReadOperation oper { if (async) { - return operation.ExecuteAsync(binding, CancellationToken.None).GetAwaiter().GetResult(); + return operation.ExecuteAsync(binding, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult(); } else { - return operation.Execute(binding, CancellationToken.None); + return operation.Execute(binding, OperationCancellationContext.NoTimeout); } } @@ -200,7 +195,7 @@ private protected TResult ExecuteOperationSync(IWriteOperation using (var binding = CreateReadWriteBinding(useImplicitSession)) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { - return operation.Execute(bindingHandle, CancellationToken.None); + return operation.Execute(bindingHandle, OperationCancellationContext.NoTimeout); } } @@ -220,11 +215,11 @@ private protected TResult ExecuteOperation(IWriteOperation ope { if (async) { - return operation.ExecuteAsync(binding, CancellationToken.None).GetAwaiter().GetResult(); + return operation.ExecuteAsync(binding, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult(); } else { - return operation.Execute(binding, CancellationToken.None); + return operation.Execute(binding, OperationCancellationContext.NoTimeout); } } @@ -239,7 +234,7 @@ private protected async Task ExecuteOperationAsync(IReadOperat private protected async Task ExecuteOperationAsync(IReadOperation operation, IReadBinding binding) { - return await operation.ExecuteAsync(binding, CancellationToken.None); + return await operation.ExecuteAsync(binding, OperationCancellationContext.NoTimeout); } private protected async Task ExecuteOperationAsync(IWriteOperation operation, bool useImplicitSession = false) @@ -247,7 +242,7 @@ private protected async Task ExecuteOperationAsync(IWriteOpera using (var binding = CreateReadWriteBinding(useImplicitSession)) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { - return await operation.ExecuteAsync(bindingHandle, CancellationToken.None); + return await operation.ExecuteAsync(bindingHandle, OperationCancellationContext.NoTimeout); } } @@ -258,18 +253,23 @@ private protected async Task ExecuteOperationAsync(IWriteOpera { if (async) { - return await operation.ExecuteAsync(bindingHandle, CancellationToken.None); + return await operation.ExecuteAsync(bindingHandle, OperationCancellationContext.NoTimeout); } else { - return operation.Execute(bindingHandle, CancellationToken.None); + return operation.Execute(bindingHandle, OperationCancellationContext.NoTimeout); } } } + private protected TResult ExecuteOperation(IWriteOperation operation, IWriteBinding binding, bool async) + => async ? + operation.ExecuteAsync(binding, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult() : + operation.Execute(binding, OperationCancellationContext.NoTimeout); + private protected async Task ExecuteOperationAsync(IWriteOperation operation, IWriteBinding binding) { - return await operation.ExecuteAsync(binding, CancellationToken.None); + return await operation.ExecuteAsync(binding, OperationCancellationContext.NoTimeout); } private protected void CreateIndexes(params CreateIndexRequest[] requests) @@ -542,8 +542,8 @@ private protected void VerifySessionIdWasSentWhenSupported(IWriteOperat } private protected void VerifySessionIdSending( - Func> executeAsync, - Func execute, + Func> executeAsync, + Func execute, Action assertResults, string commandName, bool async, @@ -555,16 +555,14 @@ private protected void VerifySessionIdSending( using (var session = CreateSession(cluster, useImplicitSession)) using (var binding = new WritableServerBinding(cluster, session.Fork())) { - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; Exception exception; if (async) { - exception = Record.Exception(() => executeAsync(binding, cancellationToken).GetAwaiter().GetResult()); + exception = Record.Exception(() => executeAsync(binding, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult()); } else { - exception = Record.Exception(() => execute(binding, cancellationToken)); + exception = Record.Exception(() => execute(binding, OperationCancellationContext.NoTimeout)); } assertResults(eventCapturer, session, exception); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/ReadCommandOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/ReadCommandOperationTests.cs index e66a2fa67d1..4ec60ee1931 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/ReadCommandOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/ReadCommandOperationTests.cs @@ -13,7 +13,6 @@ * limitations under the License. */ -using System; using System.Net; using System.Threading; using System.Threading.Tasks; @@ -33,7 +32,7 @@ namespace MongoDB.Driver.Core.Operations { - public class ReadCommandOperationTests + public class ReadCommandOperationTests : OperationTestBase { // public methods [Fact] @@ -91,14 +90,10 @@ public void Execute_should_call_channel_Command_with_unwrapped_command_when_wrap var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockReadBinding(readPreference, channelSource).Object; - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - BsonDocument result; + ExecuteOperation(subject, binding, async); if (async) { - result = subject.ExecuteAsync(binding, cancellationToken).GetAwaiter().GetResult(); - mockChannel.Verify( c => c.CommandAsync( binding.Session, @@ -112,13 +107,11 @@ public void Execute_should_call_channel_Command_with_unwrapped_command_when_wrap CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } else { - result = subject.Execute(binding, cancellationToken); - mockChannel.Verify( c => c.Command( binding.Session, @@ -132,7 +125,7 @@ public void Execute_should_call_channel_Command_with_unwrapped_command_when_wrap CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } } @@ -150,15 +143,11 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_additi var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockReadBinding(readPreference, channelSource).Object; - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; var additionalOptions = BsonDocument.Parse("{ $comment : \"comment\", additional : 1 }"); - BsonDocument result; + ExecuteOperation(subject, binding, async); if (async) { - result = subject.ExecuteAsync(binding, cancellationToken).GetAwaiter().GetResult(); - mockChannel.Verify( c => c.CommandAsync( binding.Session, @@ -172,13 +161,11 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_additi CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } else { - result = subject.Execute(binding, cancellationToken); - mockChannel.Verify( c => c.Command( binding.Session, @@ -192,7 +179,7 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_additi CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } } @@ -209,15 +196,11 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockReadBinding(readPreference, channelSource).Object; - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; var additionalOptions = BsonDocument.Parse("{ $comment : \"comment\" }"); - BsonDocument result; + ExecuteOperation(subject, binding, async); if (async) { - result = subject.ExecuteAsync(binding, cancellationToken).GetAwaiter().GetResult(); - mockChannel.Verify( c => c.CommandAsync( binding.Session, @@ -231,13 +214,11 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } else { - result = subject.Execute(binding, cancellationToken); - mockChannel.Verify( c => c.Command( binding.Session, @@ -251,7 +232,7 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } } @@ -269,15 +250,11 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_readPr var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockReadBinding(readPreference, channelSource).Object; - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; var additionalOptions = BsonDocument.Parse("{ $comment : \"comment\", additional : 1 }"); - BsonDocument result; + ExecuteOperation(subject, binding, async); if (async) { - result = subject.ExecuteAsync(binding, cancellationToken).GetAwaiter().GetResult(); - mockChannel.Verify( c => c.CommandAsync( binding.Session, @@ -291,13 +268,11 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_readPr CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } else { - result = subject.Execute(binding, cancellationToken); - mockChannel.Verify( c => c.Command( binding.Session, @@ -311,7 +286,7 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_readPr CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } } @@ -326,18 +301,15 @@ public void Execute_should_call_GetChannel_only_once([Values(false, true)] bool var mockChannel = CreateMockChannel(); var mockChannelSource = CreateMockChannelSource(serverDescription, mockChannel.Object); var binding = CreateMockReadBinding(readPreference, mockChannelSource.Object).Object; - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + ExecuteOperation(subject, binding, async); if (async) { - subject.ExecuteAsync(binding, cancellationToken).GetAwaiter().GetResult(); - mockChannelSource.Verify(c => c.GetChannelAsync(cancellationToken), Times.Once); + mockChannelSource.Verify(c => c.GetChannelAsync(It.IsAny()), Times.Once); } else { - subject.Execute(binding, cancellationToken); - mockChannelSource.Verify(c => c.GetChannel(cancellationToken), Times.Once); + mockChannelSource.Verify(c => c.GetChannel(It.IsAny()), Times.Once); } } @@ -348,8 +320,8 @@ private Mock CreateMockReadBinding(ReadPreference readPreference, var mockSession = new Mock(); mockBinding.SetupGet(b => b.ReadPreference).Returns(readPreference); mockBinding.SetupGet(b => b.Session).Returns(mockSession.Object); - mockBinding.Setup(b => b.GetReadChannelSource(It.IsAny())).Returns(channelSource); - mockBinding.Setup(b => b.GetReadChannelSourceAsync(It.IsAny())).Returns(Task.FromResult(channelSource)); + mockBinding.Setup(b => b.GetReadChannelSource(It.IsAny())).Returns(channelSource); + mockBinding.Setup(b => b.GetReadChannelSourceAsync(It.IsAny())).Returns(Task.FromResult(channelSource)); return mockBinding; } @@ -363,8 +335,8 @@ private Mock CreateMockChannelSource(ServerDescription ser { var mockChannelSource = new Mock(); mockChannelSource.SetupGet(s => s.ServerDescription).Returns(serverDescription); - mockChannelSource.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); - mockChannelSource.Setup(s => s.GetChannelAsync(It.IsAny())).Returns(Task.FromResult(channel)); + mockChannelSource.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); + mockChannelSource.Setup(s => s.GetChannelAsync(It.IsAny())).Returns(Task.FromResult(channel)); return mockChannelSource; } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs index 9dd51a1ec42..ae6a5e87ae1 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs @@ -98,7 +98,7 @@ private IWriteBinding CreateBinding(bool areRetryableWritesSupported, bool hasSe var session = CreateSession(hasSessionId, isInTransaction); var channelSource = CreateChannelSource(areRetryableWritesSupported); mockBinding.SetupGet(m => m.Session).Returns(session); - mockBinding.Setup(m => m.GetWriteChannelSource(CancellationToken.None)).Returns(channelSource); + mockBinding.Setup(m => m.GetWriteChannelSource(It.IsAny())).Returns(channelSource); return mockBinding.Object; } @@ -114,7 +114,7 @@ private IChannelSourceHandle CreateChannelSource(bool areRetryableWritesSupporte { var mockChannelSource = new Mock(); var channel = CreateChannel(areRetryableWritesSupported); - mockChannelSource.Setup(m => m.GetChannel(CancellationToken.None)).Returns(channel); + mockChannelSource.Setup(m => m.GetChannel(It.IsAny())).Returns(channel); return mockChannelSource.Object; } @@ -142,7 +142,7 @@ private ConnectionDescription CreateConnectionDescription(bool withLogicalSessio private RetryableWriteContext CreateContext(bool retryRequested, bool areRetryableWritesSupported, bool hasSessionId, bool isInTransaction) { var binding = CreateBinding(areRetryableWritesSupported, hasSessionId, isInTransaction); - return RetryableWriteContext.Create(binding, retryRequested, CancellationToken.None); + return RetryableWriteContext.Create(binding, retryRequested, OperationCancellationContext.NoTimeout); } private IRetryableWriteOperation CreateOperation(bool withWriteConcern, bool isAcknowledged) diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/WriteCommandOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/WriteCommandOperationTests.cs index 6da9926706f..4837ed67dee 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/WriteCommandOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/WriteCommandOperationTests.cs @@ -13,7 +13,6 @@ * limitations under the License. */ -using System; using System.Net; using System.Threading; using System.Threading.Tasks; @@ -33,7 +32,7 @@ namespace MongoDB.Driver.Core.Operations { - public class WriteCommandOperationTests + public class WriteCommandOperationTests : OperationTestBase { // public methods [Fact] @@ -65,14 +64,10 @@ public void Execute_should_call_channel_Command_with_unwrapped_command_when_wrap var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockWriteBinding(channelSource).Object; - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; - BsonDocument result; + ExecuteOperation(subject, binding, async); if (async) { - result = subject.ExecuteAsync(binding, cancellationToken).GetAwaiter().GetResult(); - mockChannel.Verify( c => c.CommandAsync( binding.Session, @@ -86,13 +81,11 @@ public void Execute_should_call_channel_Command_with_unwrapped_command_when_wrap CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } else { - result = subject.Execute(binding, cancellationToken); - mockChannel.Verify( c => c.Command( binding.Session, @@ -106,7 +99,7 @@ public void Execute_should_call_channel_Command_with_unwrapped_command_when_wrap CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } } @@ -122,15 +115,11 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_additi var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockWriteBinding(channelSource).Object; - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; var command = BsonDocument.Parse("{ command : 1 }"); - BsonDocument result; + ExecuteOperation(subject, binding, async); if (async) { - result = subject.ExecuteAsync(binding, cancellationToken).GetAwaiter().GetResult(); - mockChannel.Verify( c => c.CommandAsync( It.IsAny(), @@ -144,13 +133,11 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_additi CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } else { - result = subject.Execute(binding, cancellationToken); - mockChannel.Verify( c => c.Command( It.IsAny(), @@ -164,7 +151,7 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_additi CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } } @@ -180,15 +167,11 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen var mockChannel = CreateMockChannel(); var channelSource = CreateMockChannelSource(serverDescription, mockChannel.Object).Object; var binding = CreateMockWriteBinding(channelSource).Object; - using var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; var additionalOptions = BsonDocument.Parse("{ $comment : \"comment\" }"); - BsonDocument result; + ExecuteOperation(subject, binding, async); if (async) { - result = subject.ExecuteAsync(binding, cancellationToken).GetAwaiter().GetResult(); - mockChannel.Verify( c => c.CommandAsync( binding.Session, @@ -202,13 +185,11 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } else { - result = subject.Execute(binding, cancellationToken); - mockChannel.Verify( c => c.Command( binding.Session, @@ -222,7 +203,7 @@ public void Execute_should_call_channel_Command_with_wrapped_command_when_commen CommandResponseHandling.Return, subject.ResultSerializer, subject.MessageEncoderSettings, - cancellationToken), + It.IsAny()), Times.Once); } } @@ -233,8 +214,8 @@ private Mock CreateMockWriteBinding(IChannelSourceHandle channelS var mockBinding = new Mock(); var mockSession = new Mock(); mockBinding.SetupGet(b => b.Session).Returns(mockSession.Object); - mockBinding.Setup(b => b.GetWriteChannelSource(It.IsAny())).Returns(channelSource); - mockBinding.Setup(b => b.GetWriteChannelSourceAsync(It.IsAny())).Returns(Task.FromResult(channelSource)); + mockBinding.Setup(b => b.GetWriteChannelSource(It.IsAny())).Returns(channelSource); + mockBinding.Setup(b => b.GetWriteChannelSourceAsync(It.IsAny())).Returns(Task.FromResult(channelSource)); return mockBinding; } @@ -248,8 +229,8 @@ private Mock CreateMockChannelSource(ServerDescription ser { var mockChannelSource = new Mock(); mockChannelSource.SetupGet(s => s.ServerDescription).Returns(serverDescription); - mockChannelSource.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); - mockChannelSource.Setup(s => s.GetChannelAsync(It.IsAny())).Returns(Task.FromResult(channel)); + mockChannelSource.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); + mockChannelSource.Setup(s => s.GetChannelAsync(It.IsAny())).Returns(Task.FromResult(channel)); return mockChannelSource; } diff --git a/tests/MongoDB.Driver.Tests/Core/Servers/LoadBalancedServerTests.cs b/tests/MongoDB.Driver.Tests/Core/Servers/LoadBalancedServerTests.cs index 6a663956ebe..9b554bb75e9 100644 --- a/tests/MongoDB.Driver.Tests/Core/Servers/LoadBalancedServerTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Servers/LoadBalancedServerTests.cs @@ -57,12 +57,10 @@ public LoadBalancedTests(ITestOutputHelper output) : base(output) _clusterId = new ClusterId(); _endPoint = new DnsEndPoint("localhost", 27017); - var mockConnectionExceptionHandler = new Mock(); - _clusterClock = new Mock().Object; _mockConnectionPool = new Mock(); - _mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny())).Returns(new Mock().Object); - _mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny())).Returns(Task.FromResult(new Mock().Object)); + _mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny())).Returns(new Mock().Object); + _mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny())).Returns(Task.FromResult(new Mock().Object)); _mockConnectionPoolFactory = new Mock(); _mockConnectionPoolFactory .Setup(f => f.CreateConnectionPool(It.IsAny(), _endPoint, It.IsAny())) @@ -79,13 +77,13 @@ public LoadBalancedTests(ITestOutputHelper output) : base(output) [Theory] [ParameterAttributeData] - public void ChannelFork_should_not_affect_operations_count([Values(false, true)] bool async) + public async Task ChannelFork_should_not_affect_operations_count([Values(false, true)] bool async) { IClusterableServer server = SetupServer(false, false); var channel = async ? - server.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult() : - server.GetChannel(CancellationToken.None); + await server.GetChannelAsync(OperationCancellationContext.NoTimeout) : + server.GetChannel(OperationCancellationContext.NoTimeout); server.OutstandingOperationsCount.Should().Be(1); @@ -169,7 +167,7 @@ public void Dispose_should_dispose_the_server() [Theory] [ParameterAttributeData] - public void GetChannel_should_clear_connection_pool_when_opening_connection_throws_MongoAuthenticationException( + public async Task GetChannel_should_clear_connection_pool_when_opening_connection_throws_MongoAuthenticationException( [Values(false, true)] bool async) { var connectionId = new ConnectionId(new ServerId(_clusterId, _endPoint)); @@ -181,11 +179,11 @@ public void GetChannel_should_clear_connection_pool_when_opening_connection_thro var mockConnectionPool = new Mock(); var authenticationException = new MongoAuthenticationException(connectionId, "Invalid login.") { ServiceId = ObjectId.GenerateNewId() }; mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Callback(() => server.HandleExceptionOnOpen(authenticationException)) .Throws(authenticationException); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Callback(() => server.HandleExceptionOnOpen(authenticationException)) .Throws(authenticationException); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); @@ -205,17 +203,9 @@ public void GetChannel_should_clear_connection_pool_when_opening_connection_thro _eventLogger); server.Initialize(); - var exception = Record.Exception(() => - { - if (async) - { - server.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - server.GetChannel(CancellationToken.None); - } - }); + var exception = async ? + await Record.ExceptionAsync(() => server.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => server.GetChannel(OperationCancellationContext.NoTimeout)); exception.Should().BeOfType(); mockConnectionPool.Verify(p => p.Clear(It.IsAny()), Times.Once()); @@ -223,42 +213,28 @@ public void GetChannel_should_clear_connection_pool_when_opening_connection_thro [Theory] [ParameterAttributeData] - public void GetChannel_should_get_a_connection([Values(false, true)] bool async) + public async Task GetChannel_should_get_a_connection([Values(false, true)] bool async) { _subject.Initialize(); - IChannelHandle channel; - if (async) - { - channel = _subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - channel = _subject.GetChannel(CancellationToken.None); - } + var channel = async ? + await _subject.GetChannelAsync(OperationCancellationContext.NoTimeout) : + _subject.GetChannel(OperationCancellationContext.NoTimeout); channel.Should().NotBeNull(); } [Theory] [ParameterAttributeData] - public void GetChannel_should_not_increase_operations_count_on_exception( + public async Task GetChannel_should_not_increase_operations_count_on_exception( [Values(false, true)] bool async, [Values(false, true)] bool connectionOpenException) { IClusterableServer server = SetupServer(connectionOpenException, !connectionOpenException); - var exception = Record.Exception(() => - { - if (async) - { - server.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - server.GetChannel(CancellationToken.None); - } - }); + var exception = async ? + await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationCancellationContext.NoTimeout)); exception.Should().NotBeNull(); server.OutstandingOperationsCount.Should().Be(0); @@ -266,7 +242,7 @@ public void GetChannel_should_not_increase_operations_count_on_exception( [Theory] [ParameterAttributeData] - public void GetChannel_should_set_operations_count_correctly( + public async Task GetChannel_should_set_operations_count_correctly( [Values(false, true)] bool async, [Values(0, 1, 2, 10)] int operationsCount) { @@ -275,14 +251,10 @@ public void GetChannel_should_set_operations_count_correctly( var channels = new List(); for (int i = 0; i < operationsCount; i++) { - if (async) - { - channels.Add(server.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult()); - } - else - { - channels.Add(server.GetChannel(CancellationToken.None)); - } + var channel = async ? + await server.GetChannelAsync(OperationCancellationContext.NoTimeout) : + server.GetChannel(OperationCancellationContext.NoTimeout); + channels.Add(channel); } server.OutstandingOperationsCount.Should().Be(operationsCount); @@ -296,44 +268,32 @@ public void GetChannel_should_set_operations_count_correctly( [Theory] [ParameterAttributeData] - public void GetChannel_should_throw_when_not_initialized( + public async Task GetChannel_should_throw_when_not_initialized( [Values(false, true)] bool async) { - Exception exception; - if (async) - { - exception = Record.Exception(() => _subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult()); - } - else - { - exception = Record.Exception(() => _subject.GetChannel(CancellationToken.None)); - } + var exception = async ? + await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationCancellationContext.NoTimeout)); exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetChannel_should_throw_when_disposed([Values(false, true)] bool async) + public async Task GetChannel_should_throw_when_disposed([Values(false, true)] bool async) { _subject.Dispose(); - Exception exception; - if (async) - { - exception = Record.Exception(() => _subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult()); - } - else - { - exception = Record.Exception(() => _subject.GetChannel(CancellationToken.None)); - } + var exception = async ? + await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationCancellationContext.NoTimeout)); exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetChannel_should_not_update_topology_and_clear_connection_pool_on_MongoConnectionException( + public async Task GetChannel_should_not_update_topology_and_clear_connection_pool_on_MongoConnectionException( [Values("TimedOutSocketException", "NetworkUnreachableSocketException")] string errorType, [Values(false, true)] bool async) { @@ -363,18 +323,10 @@ public void GetChannel_should_not_update_topology_and_clear_connection_pool_on_M var subject = new LoadBalancedServer(_clusterId, _clusterClock, _settings, _endPoint, mockConnectionPoolFactory.Object, _serverApi, _eventLogger); subject.Initialize(); - IChannelHandle channel = null; - Exception exception; - if (async) - { - exception = Record.Exception(() => channel = subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult()); - } - else - { - exception = Record.Exception(() => channel = subject.GetChannel(CancellationToken.None)); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationCancellationContext.NoTimeout)); - channel.Should().BeNull(); exception.Should().Be(openConnectionException); subject.Description.Type.Should().Be(ServerType.LoadBalanced); subject.Description.ReasonChanged.Should().Be("Initialized"); @@ -434,30 +386,30 @@ private Server SetupServer(bool exceptionOnConnectionOpen, bool exceptionOnConne if (exceptionOnConnectionAcquire) { mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Throws(new TimeoutException("Timeout")); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Throws(new TimeoutException("Timeout")); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); } else if (exceptionOnConnectionOpen) { mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Throws(new MongoAuthenticationException(connectionId, "Invalid login.")); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Throws(new MongoAuthenticationException(connectionId, "Invalid login.")); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); } else { mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Returns(mockConnectionHandle.Object); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Returns(Task.FromResult(mockConnectionHandle.Object)); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); } diff --git a/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs b/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs index d0c56e46227..85c560d5dd3 100644 --- a/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs @@ -71,8 +71,8 @@ public ServerTests(ITestOutputHelper output) : base(output) _clusterClock = new Mock().Object; _directConnection = false; _mockConnectionPool = new Mock(); - _mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny())).Returns(new Mock().Object); - _mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny())).Returns(Task.FromResult(new Mock().Object)); + _mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny())).Returns(new Mock().Object); + _mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny())).Returns(Task.FromResult(new Mock().Object)); _mockConnectionPoolFactory = new Mock(); _mockConnectionPoolFactory .Setup(f => f.CreateConnectionPool(It.IsAny(), _endPoint, It.IsAny())) @@ -99,13 +99,13 @@ protected override void DisposeInternal() [Theory] [ParameterAttributeData] - public void ChannelFork_should_not_affect_operations_count([Values(false, true)] bool async) + public async Task ChannelFork_should_not_affect_operations_count([Values(false, true)] bool async) { IClusterableServer server = SetupServer(false, false); var channel = async ? - server.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult() : - server.GetChannel(CancellationToken.None); + await server.GetChannelAsync(OperationCancellationContext.NoTimeout) : + server.GetChannel(OperationCancellationContext.NoTimeout); server.OutstandingOperationsCount.Should().Be(1); @@ -200,12 +200,10 @@ public void Dispose_should_dispose_the_server() [Theory] [ParameterAttributeData] - public void GetChannel_should_clear_connection_pool_when_opening_connection_throws_MongoAuthenticationException( + public async Task GetChannel_should_clear_connection_pool_when_opening_connection_throws_MongoAuthenticationException( [Values(false, true)] bool async) { var connectionId = new ConnectionId(new ServerId(_clusterId, _endPoint)); - var mockConnectionHandle = new Mock(); - var mockConnectionPool = new Mock(); var mockConnectionPoolFactory = new Mock(); @@ -226,28 +224,20 @@ public void GetChannel_should_clear_connection_pool_when_opening_connection_thro var exceptionToThrow = new MongoAuthenticationException(connectionId, "Invalid login."); mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Callback(() => server.HandleExceptionOnOpen(exceptionToThrow)) .Throws(exceptionToThrow); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Callback(() => server.HandleExceptionOnOpen(exceptionToThrow)) .Throws(exceptionToThrow); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); server.Initialize(); - var exception = Record.Exception(() => - { - if (async) - { - server.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - server.GetChannel(CancellationToken.None); - } - }); + var exception = async ? + await Record.ExceptionAsync(() => server.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => server.GetChannel(OperationCancellationContext.NoTimeout)); exception.Should().BeOfType(); mockConnectionPool.Verify(p => p.Clear(It.IsAny()), Times.Once()); @@ -255,51 +245,38 @@ public void GetChannel_should_clear_connection_pool_when_opening_connection_thro [Theory] [ParameterAttributeData] - public void GetChannel_should_get_a_connection( + public async Task GetChannel_should_get_a_connection( [Values(false, true)] bool async) { _subject.Initialize(); - IChannelHandle channel; - if (async) - { - channel = _subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - channel = _subject.GetChannel(CancellationToken.None); - } + var channel = async ? + await _subject.GetChannelAsync(OperationCancellationContext.NoTimeout) : + _subject.GetChannel(OperationCancellationContext.NoTimeout); channel.Should().NotBeNull(); } [Theory] [ParameterAttributeData] - public void GetChannel_should_not_increase_operations_count_on_exception( + public async Task GetChannel_should_not_increase_operations_count_on_exception( [Values(false, true)] bool async, [Values(false, true)] bool connectionOpenException) { IClusterableServer server = SetupServer(connectionOpenException, !connectionOpenException); - _ = Record.Exception(() => - { - if (async) - { - server.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - server.GetChannel(CancellationToken.None); - } - }); + var exception = async ? + await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationCancellationContext.NoTimeout)); + exception.Should().NotBeNull(); server.OutstandingOperationsCount.Should().Be(0); } [Theory] [ParameterAttributeData] - public void GetChannel_should_set_operations_count_correctly( + public async Task GetChannel_should_set_operations_count_correctly( [Values(false, true)] bool async, [Values(0, 1, 2, 10)] int operationsCount) { @@ -308,14 +285,10 @@ public void GetChannel_should_set_operations_count_correctly( var channels = new List(); for (int i = 0; i < operationsCount; i++) { - if (async) - { - channels.Add(server.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult()); - } - else - { - channels.Add(server.GetChannel(CancellationToken.None)); - } + var channel = async ? + await server.GetChannelAsync(OperationCancellationContext.NoTimeout) : + server.GetChannel(OperationCancellationContext.NoTimeout); + channels.Add(channel); } server.OutstandingOperationsCount.Should().Be(operationsCount); @@ -329,46 +302,34 @@ public void GetChannel_should_set_operations_count_correctly( [Theory] [ParameterAttributeData] - public void GetChannel_should_throw_when_not_initialized( + public async Task GetChannel_should_throw_when_not_initialized( [Values(false, true)] bool async) { - Action act; - if (async) - { - act = () => _subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => _subject.GetChannel(CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetChannel_should_throw_when_disposed( + public async Task GetChannel_should_throw_when_disposed( [Values(false, true)] bool async) { _subject.Dispose(); - Action act; - if (async) - { - act = () => _subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult(); - } - else - { - act = () => _subject.GetChannel(CancellationToken.None); - } + var exception = async ? + await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationCancellationContext.NoTimeout)); - act.ShouldThrow(); + exception.Should().BeOfType(); } [Theory] [ParameterAttributeData] - public void GetChannel_should_update_topology_and_clear_connection_pool_on_network_error_or_timeout( + public async Task GetChannel_should_update_topology_and_clear_connection_pool_on_network_error_or_timeout( [Values("TimedOutSocketException", "NetworkUnreachableSocketException")] string errorType, [Values(false, true)] bool async) { @@ -406,18 +367,10 @@ public void GetChannel_should_update_topology_and_clear_connection_pool_on_netwo subject.Initialize(); connectionPool.SetReady(); - IChannelHandle channel = null; - Exception exception; - if (async) - { - exception = Record.Exception(() => channel = subject.GetChannelAsync(CancellationToken.None).GetAwaiter().GetResult()); - } - else - { - exception = Record.Exception(() => channel = subject.GetChannel(CancellationToken.None)); - } + var exception = async ? + await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationCancellationContext.NoTimeout)); - channel.Should().BeNull(); exception.Should().Be(openConnectionException); subject.Description.Type.Should().Be(ServerType.Unknown); subject.Description.ReasonChanged.Should().Contain("ChannelException during handshake"); @@ -449,8 +402,8 @@ public void HandleChannelException_should_update_topology_as_expected_on_network mockConnection.SetupGet(c => c.Description) .Returns(new ConnectionDescription(new ConnectionId(serverId, 0), helloResult)); var mockConnectionPool = new Mock(); - mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny())).Returns(mockConnection.Object); - mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny())).ReturnsAsync(mockConnection.Object); + mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny())).Returns(mockConnection.Object); + mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny())).ReturnsAsync(mockConnection.Object); var mockConnectionPoolFactory = new Mock(); mockConnectionPoolFactory .Setup(f => f.CreateConnectionPool(It.IsAny(), _endPoint, It.IsAny())) @@ -834,30 +787,30 @@ private Server SetupServer(bool exceptionOnConnectionOpen, bool exceptionOnConne if (exceptionOnConnectionAcquire) { mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Throws(new TimeoutException("Timeout")); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Throws(new TimeoutException("Timeout")); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); } else if (exceptionOnConnectionOpen) { mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Throws(new MongoAuthenticationException(connectionId, "Invalid login.")); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Throws(new MongoAuthenticationException(connectionId, "Invalid login.")); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); } else { mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Returns(mockConnectionHandle.Object); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Returns(Task.FromResult(mockConnectionHandle.Object)); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); } @@ -900,9 +853,9 @@ public void Command_should_send_the_greater_of_the_session_and_cluster_cluster_t using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer))) using (var session = cluster.StartSession()) { - var cancellationToken = CancellationToken.None; - var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, cancellationToken); - using (var channel = server.GetChannel(cancellationToken)) + var cancellationContext = OperationCancellationContext.NoTimeout; + var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, cancellationContext); + using (var channel = server.GetChannel(cancellationContext)) { session.AdvanceClusterTime(sessionClusterTime); server.ClusterClock.AdvanceClusterTime(clusterClusterTime); @@ -922,7 +875,7 @@ public void Command_should_send_the_greater_of_the_session_and_cluster_cluster_t CommandResponseHandling.Return, BsonDocumentSerializer.Instance, new MessageEncoderSettings(), - cancellationToken); + It.IsAny()); } catch (MongoCommandException ex) { @@ -948,9 +901,9 @@ public void Command_should_update_the_session_and_cluster_cluster_times() using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer))) using (var session = cluster.StartSession()) { - var cancellationToken = CancellationToken.None; - var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, cancellationToken); - using (var channel = server.GetChannel(cancellationToken)) + var cancellationContext = OperationCancellationContext.NoTimeout; + var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, cancellationContext); + using (var channel = server.GetChannel(cancellationContext)) { var command = BsonDocument.Parse("{ ping : 1 }"); channel.Command( @@ -965,7 +918,7 @@ public void Command_should_update_the_session_and_cluster_cluster_times() CommandResponseHandling.Return, BsonDocumentSerializer.Instance, new MessageEncoderSettings(), - cancellationToken); + It.IsAny()); } var commandSucceededEvent = eventCapturer.Next().Should().BeOfType().Subject; @@ -978,7 +931,7 @@ public void Command_should_update_the_session_and_cluster_cluster_times() [Theory] [ParameterAttributeData] - public void Command_should_use_serverApi([Values(false, true)] bool async) + public async Task Command_should_use_serverApi([Values(false, true)] bool async) { RequireServer.Check(); @@ -992,14 +945,14 @@ public void Command_should_use_serverApi([Values(false, true)] bool async) using (var cluster = CoreTestConfiguration.CreateCluster(builder)) using (var session = cluster.StartSession()) { - var cancellationToken = CancellationToken.None; - var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, cancellationToken); - using (var channel = server.GetChannel(cancellationToken)) + var cancellationContext = OperationCancellationContext.NoTimeout; + var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, cancellationContext); + using (var channel = server.GetChannel(cancellationContext)) { var command = BsonDocument.Parse("{ ping : 1 }"); if (async) { - channel + await channel .CommandAsync( session, ReadPreference.Primary, @@ -1012,9 +965,7 @@ public void Command_should_use_serverApi([Values(false, true)] bool async) CommandResponseHandling.Return, BsonDocumentSerializer.Instance, new MessageEncoderSettings(), - cancellationToken) - .GetAwaiter() - .GetResult(); + It.IsAny()); } else { @@ -1030,7 +981,7 @@ public void Command_should_use_serverApi([Values(false, true)] bool async) CommandResponseHandling.Return, BsonDocumentSerializer.Instance, new MessageEncoderSettings(), - cancellationToken); + It.IsAny()); } } } diff --git a/tests/MongoDB.Driver.Tests/Encryption/ClientEncryptionTests.cs b/tests/MongoDB.Driver.Tests/Encryption/ClientEncryptionTests.cs index 69cb78ed104..1cbb70f2b5d 100644 --- a/tests/MongoDB.Driver.Tests/Encryption/ClientEncryptionTests.cs +++ b/tests/MongoDB.Driver.Tests/Encryption/ClientEncryptionTests.cs @@ -137,14 +137,14 @@ public async Task CreateEncryptedCollection_should_handle_generated_key_when_sec var mockServer = new Mock(); mockServer.SetupGet(s => s.Description).Returns(serverDescription); var channel = Mock.Of(c => c.ConnectionDescription == new ConnectionDescription(new ConnectionId(serverId), new HelloResult(new BsonDocument("maxWireVersion", serverDescription.WireVersionRange.Max)))); - mockServer.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); - mockServer.Setup(s => s.GetChannelAsync(It.IsAny())).ReturnsAsync(channel); + mockServer.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); + mockServer.Setup(s => s.GetChannelAsync(It.IsAny())).ReturnsAsync(channel); mockCluster - .Setup(m => m.SelectServer(It.IsAny(), It.IsAny())) + .Setup(m => m.SelectServer(It.IsAny(), It.IsAny())) .Returns(mockServer.Object); mockCluster - .Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())) + .Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(mockServer.Object); var database = Mock.Of(d => @@ -226,14 +226,14 @@ public async Task CreateEncryptedCollection_should_handle_various_encryptedField var mockServer = new Mock(); mockServer.SetupGet(s => s.Description).Returns(serverDescription); var channel = Mock.Of(c => c.ConnectionDescription == new ConnectionDescription(new ConnectionId(serverId), new HelloResult(new BsonDocument("maxWireVersion", serverDescription.WireVersionRange.Max)))); - mockServer.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); - mockServer.Setup(s => s.GetChannelAsync(It.IsAny())).ReturnsAsync(channel); + mockServer.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); + mockServer.Setup(s => s.GetChannelAsync(It.IsAny())).ReturnsAsync(channel); mockCluster - .Setup(m => m.SelectServer(It.IsAny(), It.IsAny())) + .Setup(m => m.SelectServer(It.IsAny(), It.IsAny())) .Returns(mockServer.Object); mockCluster - .Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())) + .Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(mockServer.Object); var database = Mock.Of(d => diff --git a/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenConfigureFailPointTest.cs b/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenConfigureFailPointTest.cs index b3720607b1c..56cf3056691 100644 --- a/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenConfigureFailPointTest.cs +++ b/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenConfigureFailPointTest.cs @@ -52,7 +52,7 @@ protected virtual IServer GetFailPointServer() } var cluster = TestRunner.FailPointCluster; - return cluster.SelectServer(WritableServerSelector.Instance, CancellationToken.None); + return cluster.SelectServer(WritableServerSelector.Instance, OperationCancellationContext.NoTimeout); } protected async virtual Task GetFailPointServerAsync() @@ -63,7 +63,7 @@ protected async virtual Task GetFailPointServerAsync() } var cluster = TestRunner.FailPointCluster; - return await cluster.SelectServerAsync(WritableServerSelector.Instance, CancellationToken.None).ConfigureAwait(false); + return await cluster.SelectServerAsync(WritableServerSelector.Instance, OperationCancellationContext.NoTimeout).ConfigureAwait(false); } protected override void SetArgument(string name, BsonValue value) diff --git a/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenTargetedFailPointTest.cs b/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenTargetedFailPointTest.cs index 44f2e342395..97557930acc 100644 --- a/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenTargetedFailPointTest.cs +++ b/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenTargetedFailPointTest.cs @@ -15,7 +15,6 @@ using System.Collections.Generic; using System.Net; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using MongoDB.Driver.Core.Clusters.ServerSelectors; @@ -34,17 +33,17 @@ protected override IServer GetFailPointServer() { var pinnedServerEndpoint = GetPinnedServerEndpointAndAssertNotNull(); var pinnedServerSelector = CreateServerSelector(pinnedServerEndpoint); - return TestRunner.FailPointCluster.SelectServer(pinnedServerSelector, CancellationToken.None); + return TestRunner.FailPointCluster.SelectServer(pinnedServerSelector, OperationCancellationContext.NoTimeout); } protected async override Task GetFailPointServerAsync() { var pinnedServerEndpoint = GetPinnedServerEndpointAndAssertNotNull(); var pinnedServerSelector = CreateServerSelector(pinnedServerEndpoint); - return await TestRunner.FailPointCluster.SelectServerAsync(pinnedServerSelector, CancellationToken.None).ConfigureAwait(false); + return await TestRunner.FailPointCluster.SelectServerAsync(pinnedServerSelector, OperationCancellationContext.NoTimeout).ConfigureAwait(false); } - // private methods + // private methods private IServerSelector CreateServerSelector(EndPoint endpoint) { return new CompositeServerSelector(new IServerSelector[] diff --git a/tests/MongoDB.Driver.Tests/OperationCancellationContextTests.cs b/tests/MongoDB.Driver.Tests/OperationCancellationContextTests.cs new file mode 100644 index 00000000000..f75d8214127 --- /dev/null +++ b/tests/MongoDB.Driver.Tests/OperationCancellationContextTests.cs @@ -0,0 +1,133 @@ +/* Copyright 2010-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. + */ + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using FluentAssertions; +using Xunit; + +namespace MongoDB.Driver.Tests +{ + public class OperationCancellationContextTests + { + [Fact] + public void Constructor_should_initialize_properties() + { + var timeout = TimeSpan.FromSeconds(42); + using var cancellationTokenSource = new CancellationTokenSource(); + var cancellationToken = cancellationTokenSource.Token; + + var cancellationContext = new OperationCancellationContext(timeout, cancellationToken); + + cancellationContext.Timeout.Should().Be(timeout); + cancellationContext.CancellationToken.Should().Be(cancellationToken); + } + + [Fact] + public void Elapsed_should_return_elapsed_time() + { + var stopwatch = Stopwatch.StartNew(); + Thread.Sleep(10); + stopwatch.Stop(); + + var cancellationContext = new OperationCancellationContext(stopwatch, TimeSpan.Zero, CancellationToken.None); + + cancellationContext.Elapsed.Should().Be(stopwatch.Elapsed); + } + + [Fact] + public void RemainingTimeout_should_calculate() + { + var timeout = TimeSpan.FromMilliseconds(500); + var stopwatch = Stopwatch.StartNew(); + Thread.Sleep(10); + stopwatch.Stop(); + + var cancellationContext = new OperationCancellationContext(stopwatch, timeout, CancellationToken.None); + + cancellationContext.RemainingTimeout.Should().Be(timeout - stopwatch.Elapsed); + } + + [Fact] + public void RemainingTimeout_should_return_infinite_for_infinite_timeout() + { + var stopwatch = Stopwatch.StartNew(); + Thread.Sleep(10); + stopwatch.Stop(); + + var cancellationContext = new OperationCancellationContext(stopwatch, Timeout.InfiniteTimeSpan, CancellationToken.None); + + cancellationContext.RemainingTimeout.Should().Be(Timeout.InfiniteTimeSpan); + } + + [Fact] + public void RenainingTimeout_could_be_negative() + { + var timeout = TimeSpan.FromMilliseconds(5); + var stopwatch = Stopwatch.StartNew(); + Thread.Sleep(10); + stopwatch.Stop(); + + var cancellationContext = new OperationCancellationContext(stopwatch, timeout, CancellationToken.None); + + cancellationContext.RemainingTimeout.Should().Be(timeout - stopwatch.Elapsed); + } + + [Theory] + [MemberData(nameof(IsTimedOut_test_cases))] + public void IsTimedOut_should_return_expected_result(bool expected, TimeSpan timeout, TimeSpan waitTime) + { + var stopwatch = Stopwatch.StartNew(); + Thread.Sleep(waitTime); + stopwatch.Stop(); + + var cancellationContext = new OperationCancellationContext(stopwatch, timeout, CancellationToken.None); + var result = cancellationContext.IsTimedOut(); + + result.Should().Be(expected); + } + + public static IEnumerable IsTimedOut_test_cases = + [ + [false, Timeout.InfiniteTimeSpan, TimeSpan.FromMilliseconds(5)], + [false, TimeSpan.FromMilliseconds(50), TimeSpan.FromMilliseconds(5)], + [true, TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(10)], + ]; + + [Theory] + [MemberData(nameof(WithTimeout_test_cases))] + public void WithTimeout_should_calculate_proper_timeout(TimeSpan expected, TimeSpan originalTimeout, TimeSpan newTimeout) + { + var cancellationContext = new OperationCancellationContext(new Stopwatch(), originalTimeout, CancellationToken.None); + var resultContext = cancellationContext.WithTimeout(newTimeout); + + resultContext.Timeout.Should().Be(expected); + } + + public static IEnumerable WithTimeout_test_cases = + [ + [Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan], + [TimeSpan.FromMilliseconds(5), Timeout.InfiniteTimeSpan, TimeSpan.FromMilliseconds(5)], + [TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(5), Timeout.InfiniteTimeSpan], + [TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(10)], + [TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(5)], + ]; + + // TODO: Add tests for WaitTask and WaitTaskAsync. + } +} + diff --git a/tests/MongoDB.Driver.Tests/OperationExecutorTests.cs b/tests/MongoDB.Driver.Tests/OperationExecutorTests.cs index ef207d784f6..267d3db0620 100644 --- a/tests/MongoDB.Driver.Tests/OperationExecutorTests.cs +++ b/tests/MongoDB.Driver.Tests/OperationExecutorTests.cs @@ -31,7 +31,7 @@ public class OperationExecutorTests [Fact] public void StartImplicitSession_should_call_cluster_StartSession() { - var subject = CreateSubject(out var clusterMock, out _); + var subject = CreateSubject(out var clusterMock); subject.StartImplicitSession(); @@ -42,8 +42,8 @@ public void StartImplicitSession_should_call_cluster_StartSession() [ParameterAttributeData] public async Task ExecuteReadOperation_throws_on_null_operation([Values(true, false)] bool async) { - var subject = CreateSubject(out _, out _); - var options = new ReadOperationOptions(); + var subject = CreateSubject(out _); + var options = new ReadOperationOptions(Timeout.InfiniteTimeSpan); var session = Mock.Of(); var exception = async ? @@ -58,7 +58,7 @@ await Record.ExceptionAsync(() => subject.ExecuteReadOperationAsync(sess [ParameterAttributeData] public async Task ExecuteReadOperation_throws_on_null_options([Values(true, false)] bool async) { - var subject = CreateSubject(out _, out _); + var subject = CreateSubject(out _); var operation = Mock.Of>(); var session = Mock.Of(); @@ -74,9 +74,9 @@ await Record.ExceptionAsync(() => subject.ExecuteReadOperationAsync(session, ope [ParameterAttributeData] public async Task ExecuteReadOperation_throws_on_null_session([Values(true, false)] bool async) { - var subject = CreateSubject(out _, out _); + var subject = CreateSubject(out _); var operation = Mock.Of>(); - var options = new ReadOperationOptions(); + var options = new ReadOperationOptions(Timeout.InfiniteTimeSpan); var exception = async ? await Record.ExceptionAsync(() => subject.ExecuteReadOperationAsync(null, operation, options, true, CancellationToken.None)) : @@ -90,8 +90,8 @@ await Record.ExceptionAsync(() => subject.ExecuteReadOperationAsync(null, operat [ParameterAttributeData] public async Task ExecuteWriteOperation_throws_on_null_operation([Values(true, false)] bool async) { - var subject = CreateSubject(out _, out _); - var options = new WriteOperationOptions(); + var subject = CreateSubject(out _); + var options = new WriteOperationOptions(Timeout.InfiniteTimeSpan); var session = Mock.Of(); var exception = async ? @@ -106,7 +106,7 @@ await Record.ExceptionAsync(() => subject.ExecuteWriteOperationAsync(ses [ParameterAttributeData] public async Task ExecuteWriteOperation_throws_on_null_options([Values(true, false)] bool async) { - var subject = CreateSubject(out _, out _); + var subject = CreateSubject(out _); var operation = Mock.Of>(); var session = Mock.Of(); @@ -122,9 +122,9 @@ await Record.ExceptionAsync(() => subject.ExecuteWriteOperationAsync(session, op [ParameterAttributeData] public async Task ExecuteWriteOperation_throws_on_null_session([Values(true, false)] bool async) { - var subject = CreateSubject(out _, out _); + var subject = CreateSubject(out _); var operation = Mock.Of>(); - var options = new WriteOperationOptions(); + var options = new WriteOperationOptions(Timeout.InfiniteTimeSpan); var exception = async ? await Record.ExceptionAsync(() => subject.ExecuteWriteOperationAsync(null, operation, options, true, CancellationToken.None)) : @@ -134,23 +134,13 @@ await Record.ExceptionAsync(() => subject.ExecuteWriteOperationAsync(null, opera .Subject.ParamName.Should().Be("session"); } - private OperationExecutor CreateSubject(out Mock clusterMock, out Mock implicitSessionMock) + private OperationExecutor CreateSubject(out Mock clusterMock) { - implicitSessionMock = CreateCoreSessionMock(true); clusterMock = new Mock(); - clusterMock.Setup(c => c.StartSession(It.IsAny())).Returns(implicitSessionMock.Object); var clientMock = new Mock(); clientMock.SetupGet(c => c.Cluster).Returns(clusterMock.Object); return new OperationExecutor(clientMock.Object); } - - private static Mock CreateCoreSessionMock(bool isImplicit) - { - var sessionMock = new Mock(); - sessionMock.SetupGet(s => s.IsImplicit).Returns(isImplicit); - sessionMock.Setup(s => s.Fork()).Returns(() => CreateCoreSessionMock(isImplicit).Object); - return sessionMock; - } } } diff --git a/tests/MongoDB.Driver.Tests/ReadOperationOptionsTests.cs b/tests/MongoDB.Driver.Tests/ReadOperationOptionsTests.cs index 585b2e442ff..eab234fa94b 100644 --- a/tests/MongoDB.Driver.Tests/ReadOperationOptionsTests.cs +++ b/tests/MongoDB.Driver.Tests/ReadOperationOptionsTests.cs @@ -14,6 +14,7 @@ */ using System.Collections.Generic; +using System.Threading; using FluentAssertions; using MongoDB.Driver.Core.Bindings; using Moq; @@ -31,7 +32,7 @@ public void GetEffectiveReadPreferenceTests( ReadPreference defaultReadPreference, IClientSessionHandle session) { - var readOperationOptions = new ReadOperationOptions(explicitReadPreference, defaultReadPreference); + var readOperationOptions = new ReadOperationOptions(Timeout.InfiniteTimeSpan, explicitReadPreference, defaultReadPreference); var result = readOperationOptions.GetEffectiveReadPreference(session); result.Should().Be(expectedReadPreference); diff --git a/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs b/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs index b0f403147d0..348c63ad888 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs @@ -456,11 +456,11 @@ private protected FailPoint ConfigureFailPoint(BsonDocument test, IMongoClient c var serverAddress = EndPointHelper.Parse(settings.Server.ToString()); var selector = new EndPointServerSelector(serverAddress); - _failPointServer = cluster.SelectServer(selector, CancellationToken.None); + _failPointServer = cluster.SelectServer(selector, OperationCancellationContext.NoTimeout); } else { - _failPointServer = cluster.SelectServer(WritableServerSelector.Instance, CancellationToken.None); + _failPointServer = cluster.SelectServer(WritableServerSelector.Instance, OperationCancellationContext.NoTimeout); } var session = NoCoreSession.NewHandle(); diff --git a/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs index ceafb5aeae4..faa34393943 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs @@ -3245,7 +3245,7 @@ private void DropCollection(CollectionNamespace collectionNamespace, BsonDocumen using (var binding = new WritableServerBinding(_cluster, session.Fork())) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { - operation.Execute(bindingHandle, CancellationToken.None); + operation.Execute(bindingHandle, OperationCancellationContext.NoTimeout); } } diff --git a/tests/MongoDB.Driver.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs b/tests/MongoDB.Driver.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs index 626ef59450a..f606ae54c02 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs @@ -409,18 +409,9 @@ private void ExecuteCheckOut( void CheckOut(BsonDocument op, IConnectionPool cp, ConcurrentDictionary cm) { - IConnection conn; - if (async) - { - conn = cp - .AcquireConnectionAsync(CancellationToken.None) - .GetAwaiter() - .GetResult(); - } - else - { - conn = cp.AcquireConnection(CancellationToken.None); - } + var conn = async ? + cp.AcquireConnectionAsync(OperationCancellationContext.NoTimeout).GetAwaiter().GetResult() : + cp.AcquireConnection(OperationCancellationContext.NoTimeout); if (op.TryGetValue("label", out var label)) { @@ -680,7 +671,7 @@ private void ParseSettings( connectionIdLocalValueProvider: connectionIdProvider)) .Subscribe(eventCapturer)); - var server = cluster.SelectServer(WritableServerSelector.Instance, CancellationToken.None); + var server = cluster.SelectServer(WritableServerSelector.Instance, OperationCancellationContext.NoTimeout); connectionPool = server._connectionPool(); if (test.TryGetValue(Schema.Intergration.failPoint, out var failPointDocument)) @@ -738,7 +729,7 @@ o is ServerHeartbeatSucceededEvent || eventCapturer.WaitForOrThrowIfTimeout(events => events.Any(e => e is ConnectionPoolClearedEvent), TimeSpan.FromMilliseconds(500)); } - var failPointServer = CoreTestConfiguration.Cluster.SelectServer(new EndPointServerSelector(server.EndPoint), default); + var failPointServer = CoreTestConfiguration.Cluster.SelectServer(new EndPointServerSelector(server.EndPoint), OperationCancellationContext.NoTimeout); failPoint = FailPoint.Configure(failPointServer, NoCoreSession.NewHandle(), failPointDocument.AsBsonDocument, withAsync: async); if (resetPool) diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsProseTests.cs index f4aa9cc83ac..8cd6c28c06f 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsProseTests.cs @@ -79,7 +79,7 @@ public async Task PoolClearedError_read_retryablity_test([Values(true, false)] b .Capture() .CaptureCommandEvents("find"); - var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(failPointSelector, default); + var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(failPointSelector, OperationCancellationContext.NoTimeout); using var failPoint = FailPoint.Configure(failpointServer, NoCoreSession.NewHandle(), failPointCommand); using var client = CreateClient(settings, eventCapturer, heartbeatInterval); @@ -146,8 +146,8 @@ public void Sharded_cluster_retryable_reads_are_retried_on_different_mongos_if_a }, useMultipleShardRouters: true); - var failPointServer1 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), default); - var failPointServer2 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint), default); + var failPointServer1 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationCancellationContext.NoTimeout); + var failPointServer2 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint), OperationCancellationContext.NoTimeout); using var failPoint1 = FailPoint.Configure(failPointServer1, NoCoreSession.NewHandle(), failPointCommand); using var failPoint2 = FailPoint.Configure(failPointServer2, NoCoreSession.NewHandle(), failPointCommand); @@ -196,7 +196,7 @@ public void Sharded_cluster_retryable_reads_are_retried_on_same_mongos_if_no_oth }, useMultipleShardRouters: false); - var failPointServer = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), default); + var failPointServer = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationCancellationContext.NoTimeout); using var failPoint = FailPoint.Configure(failPointServer, NoCoreSession.NewHandle(), failPointCommand); diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/PoolClearRetryability.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/PoolClearRetryability.cs index 9054e532708..b1cfea8d653 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/PoolClearRetryability.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/PoolClearRetryability.cs @@ -28,7 +28,6 @@ using MongoDB.Driver.Core.Misc; using MongoDB.Driver.Core.TestHelpers; using MongoDB.Driver.Core.TestHelpers.XunitExtensions; -using MongoDB.Driver.TestHelpers; using MongoDB.TestHelpers.XunitExtensions; using Xunit; @@ -83,7 +82,7 @@ public async Task PoolClearedError_write_retryablity_test([Values(false, true)] .Capture() .CaptureCommandEvents("insert"); - var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(failPointSelector, default); + var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(failPointSelector, OperationCancellationContext.NoTimeout); using var failPoint = FailPoint.Configure(failpointServer, NoCoreSession.NewHandle(), failPointCommand); using var client = CreateClient(settings, eventCapturer, heartbeatInterval); diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/RetryWriteOnOtherMongos.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/RetryWriteOnOtherMongos.cs index 75f89943f40..8282c83e18a 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/RetryWriteOnOtherMongos.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/RetryWriteOnOtherMongos.cs @@ -61,8 +61,8 @@ public void Sharded_cluster_retryable_writes_are_retried_on_different_mongos_if_ }, useMultipleShardRouters: true); - var failPointServer1 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), default); - var failPointServer2 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint), default); + var failPointServer1 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationCancellationContext.NoTimeout); + var failPointServer2 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint), OperationCancellationContext.NoTimeout); using var failPoint1 = FailPoint.Configure(failPointServer1, NoCoreSession.NewHandle(), failPointCommand); using var failPoint2 = FailPoint.Configure(failPointServer2, NoCoreSession.NewHandle(), failPointCommand); @@ -112,7 +112,7 @@ public void Sharded_cluster_retryable_writes_are_retried_on_same_mongo_if_no_oth }, useMultipleShardRouters: false); - var failPointServer = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), default); + var failPointServer = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationCancellationContext.NoTimeout); using var failPoint = FailPoint.Configure(failPointServer, NoCoreSession.NewHandle(), failPointCommand); diff --git a/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringProseTests.cs index cebdf47395f..7bbd3e0a0c1 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringProseTests.cs @@ -165,7 +165,7 @@ public void Monitor_sleep_at_least_minHeartbeatFrequencyMS_between_checks() settings.ApplicationName = appName; settings.ServerSelectionTimeout = TimeSpan.FromSeconds(5); - var server = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(new EndPointServerSelector(new DnsEndPoint(serverAddress.Host, serverAddress.Port)), default); + var server = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(new EndPointServerSelector(new DnsEndPoint(serverAddress.Host, serverAddress.Port)), OperationCancellationContext.NoTimeout); using var failPoint = FailPoint.Configure(server, NoCoreSession.NewHandle(), failPointCommand); using var client = DriverTestConfiguration.CreateMongoClient(settings); @@ -220,7 +220,7 @@ public void RoundTimeTrip_test() { // Note that the Server Description Equality rule means that ServerDescriptionChangedEvents will not be published. // So we use reflection to obtain the latest RTT instead. - var server = client.GetClusterInternal().SelectServer(WritableServerSelector.Instance, CancellationToken.None); + var server = client.GetClusterInternal().SelectServer(WritableServerSelector.Instance, OperationCancellationContext.NoTimeout); var roundTripTimeMonitor = server._monitor()._roundTripTimeMonitor(); var expectedRoundTripTime = TimeSpan.FromMilliseconds(250); var timeout = TimeSpan.FromSeconds(30); // should not be reached without a driver bug @@ -273,7 +273,7 @@ public void ConnectionPool_cleared_on_failed_hello() eventsWaitTimeout); eventCapturer.Clear(); - var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(new EndPointServerSelector(new DnsEndPoint(serverAddress.Host, serverAddress.Port)), default); + var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(new EndPointServerSelector(new DnsEndPoint(serverAddress.Host, serverAddress.Port)), OperationCancellationContext.NoTimeout); using var failPoint = FailPoint.Configure(failpointServer, NoCoreSession.NewHandle(), failPointCommand); eventCapturer.WaitForEventOrThrowIfTimeout(eventsWaitTimeout); diff --git a/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs b/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs index 84abad019de..325ec91ddea 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs @@ -82,8 +82,8 @@ public void RunTestDefinition(JsonDrivenTestCase testCase) for (int i = 0; i < testData.iterations; i++) { var selectedServer = testData.async - ? cluster.SelectServerAsync(readPreferenceSelector, default).GetAwaiter().GetResult() - : cluster.SelectServer(readPreferenceSelector, default); + ? cluster.SelectServerAsync(readPreferenceSelector, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult() + : cluster.SelectServer(readPreferenceSelector, OperationCancellationContext.NoTimeout); selectionHistogram[selectedServer.ServerId]++; } @@ -125,7 +125,6 @@ private MultiServerCluster CreateAndSetupCluster(ClusterDescription clusterDescr serverDescriptionDisconnected = serverDescriptionDisconnected.With(replicaSetConfig: replicaSetConfig); } var serverDescriptionConnected = serverDescriptionDisconnected.With(state: ServerState.Connected); - var operationsCount = operationsCounts.Single(o => endpoint.ToString().EndsWith(o.address)); diff --git a/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedTargetedFailPointOperation.cs b/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedTargetedFailPointOperation.cs index a1ff0e272c3..cb48c2c0727 100644 --- a/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedTargetedFailPointOperation.cs +++ b/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedTargetedFailPointOperation.cs @@ -14,7 +14,6 @@ */ using System; -using System.Threading; using MongoDB.Bson; using MongoDB.Driver.Core.Bindings; using MongoDB.Driver.Core.Clusters.ServerSelectors; @@ -53,7 +52,7 @@ public void Execute() _entityMap.RegisterForDispose(client); var cluster = client.GetClusterInternal(); - var server = cluster.SelectServer(new EndPointServerSelector(pinnedServer), CancellationToken.None); + var server = cluster.SelectServer(new EndPointServerSelector(pinnedServer), OperationCancellationContext.NoTimeout); var session = NoCoreSession.NewHandle(); From 6f38b2afba541291c74ec01f794281c102424ee3 Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Fri, 6 Jun 2025 14:03:23 -0700 Subject: [PATCH 02/13] Rename OperationCancellationContext to OperationContext --- .../Core/Bindings/ChannelChannelSource.cs | 4 +- .../Core/Bindings/ChannelReadBinding.cs | 12 +- .../Core/Bindings/ChannelReadWriteBinding.cs | 40 +-- .../Core/Bindings/ChannelSourceHandle.cs | 8 +- .../Bindings/ChannelSourceReadWriteBinding.cs | 40 +-- .../Core/Bindings/CoreSession.cs | 16 +- src/MongoDB.Driver/Core/Bindings/IBinding.cs | 24 +- .../Core/Bindings/IChannelSource.cs | 4 +- .../Core/Bindings/ReadBindingHandle.cs | 16 +- .../Core/Bindings/ReadPreferenceBinding.cs | 16 +- .../Core/Bindings/ReadWriteBindingHandle.cs | 48 ++-- .../Core/Bindings/ServerChannelSource.cs | 8 +- .../Core/Bindings/SingleServerReadBinding.cs | 12 +- .../Bindings/SingleServerReadWriteBinding.cs | 40 +-- .../Core/Bindings/WritableServerBinding.cs | 48 ++-- src/MongoDB.Driver/Core/Clusters/Cluster.cs | 32 +-- src/MongoDB.Driver/Core/Clusters/ICluster.cs | 4 +- .../Core/Clusters/IClusterExtensions.cs | 12 +- .../Core/Clusters/LoadBalancedCluster.cs | 12 +- .../ExclusiveConnectionPool.Helpers.cs | 110 ++++---- .../ExclusiveConnectionPool.cs | 12 +- .../Core/ConnectionPools/IConnectionPool.cs | 4 +- .../Core/ConnectionPools/MaintenanceHelper.cs | 6 +- src/MongoDB.Driver/Core/Misc/Feature.cs | 12 +- .../Core/Operations/AggregateOperation.cs | 20 +- .../AggregateToCollectionOperation.cs | 16 +- .../Core/Operations/AsyncCursor.cs | 16 +- .../Operations/BulkMixedWriteOperation.cs | 20 +- .../BulkUnmixedWriteOperationBase.cs | 36 +-- .../Core/Operations/ChangeStreamCursor.cs | 8 +- .../Core/Operations/ChangeStreamOperation.cs | 36 +-- .../Operations/ClientBulkWriteOperation.cs | 18 +- .../Core/Operations/CommandOperationBase.cs | 12 +- .../Operations/CompositeWriteOperation.cs | 8 +- .../Operations/CountDocumentsOperation.cs | 12 +- .../Core/Operations/CountOperation.cs | 20 +- .../Operations/CreateCollectionOperation.cs | 16 +- .../Core/Operations/CreateIndexesOperation.cs | 16 +- .../CreateSearchIndexesOperation.cs | 16 +- .../Core/Operations/CreateViewOperation.cs | 17 +- .../Operations/DatabaseExistsOperation.cs | 12 +- .../Core/Operations/DistinctOperation.cs | 12 +- .../Operations/DropCollectionOperation.cs | 16 +- .../Core/Operations/DropDatabaseOperation.cs | 16 +- .../Core/Operations/DropIndexOperation.cs | 16 +- .../Operations/DropSearchIndexOperation.cs | 16 +- .../Operations/EndTransactionOperation.cs | 24 +- .../EstimatedDocumentCountOperation.cs | 12 +- .../Core/Operations/EvalOperation.cs | 8 +- .../Operations/FindAndModifyOperationBase.cs | 24 +- .../Core/Operations/FindOperation.cs | 20 +- .../Core/Operations/GroupOperation.cs | 16 +- .../Core/Operations/IOperation.cs | 8 +- .../Core/Operations/IRetryableOperation.cs | 16 +- .../Operations/ListCollectionsOperation.cs | 20 +- .../Core/Operations/ListDatabasesOperation.cs | 8 +- .../Core/Operations/ListIndexesOperation.cs | 12 +- .../ListIndexesUsingCommandOperation.cs | 20 +- .../Core/Operations/MapReduceOperation.cs | 16 +- .../MapReduceOutputToCollectionOperation.cs | 16 +- .../Operations/OperationExtensionMethods.cs | 16 +- .../Core/Operations/ReadCommandOperation.cs | 28 +- .../Operations/RenameCollectionOperation.cs | 16 +- .../Core/Operations/RetryableReadContext.cs | 28 +- .../RetryableReadOperationExecutor.cs | 36 +-- .../RetryableWriteCommandOperationBase.cs | 28 +- .../Core/Operations/RetryableWriteContext.cs | 28 +- .../RetryableWriteOperationExecutor.cs | 36 +-- .../Operations/UpdateSearchIndexOperation.cs | 16 +- .../Core/Operations/WriteCommandOperation.cs | 12 +- src/MongoDB.Driver/Core/Servers/IServer.cs | 4 +- src/MongoDB.Driver/Core/Servers/Server.cs | 8 +- src/MongoDB.Driver/GridFS/GridFSBucket.cs | 266 +++++++++--------- .../GridFS/GridFSForwardOnlyDownloadStream.cs | 8 +- .../GridFS/GridFSForwardOnlyUploadStream.cs | 8 +- .../GridFS/GridFSSeekableDownloadStream.cs | 8 +- ...ellationContext.cs => OperationContext.cs} | 12 +- src/MongoDB.Driver/OperationOptionsBase.cs | 2 +- .../Core/CoreTestConfiguration.cs | 12 +- .../Core/FailPoint.cs | 4 +- .../Core/MockClusterableServerFactory.cs | 6 +- .../DriverTestConfiguration.cs | 4 +- .../AuthenticationTests.cs | 4 +- tests/MongoDB.Driver.Tests/ClusterTests.cs | 4 +- .../Bindings/ChannelChannelSourceTests.cs | 8 +- .../Core/Bindings/ChannelReadBindingTests.cs | 8 +- .../Bindings/ChannelReadWriteBindingTests.cs | 16 +- .../Core/Bindings/ChannelSourceHandleTests.cs | 12 +- .../ChannelSourceReadWriteBindingTests.cs | 16 +- .../Core/Bindings/ReadBindingHandleTests.cs | 12 +- .../Bindings/ReadPreferenceBindingTests.cs | 24 +- .../Bindings/ReadWriteBindingHandleTests.cs | 24 +- .../Core/Bindings/ServerChannelSourceTests.cs | 12 +- .../Bindings/SingleServerReadBindingTests.cs | 8 +- .../SingleServerReadWriteBindingTests.cs | 16 +- .../Bindings/WritableServerBindingTests.cs | 56 ++-- .../Core/Clusters/ClusterTests.cs | 56 ++-- .../Core/Clusters/LoadBalancedClusterTests.cs | 10 +- .../ExclusiveConnectionPoolTests.cs | 62 ++-- .../ConnectionPools/MaintenanceHelperTests.cs | 2 +- .../Core/Jira/CSharp3173Tests.cs | 12 +- .../Core/Jira/CSharp3302Tests.cs | 10 +- .../Core/LoadBalancingIntergationTests.cs | 16 +- .../Core/Operations/AsyncCursorTests.cs | 18 +- .../BulkMixedWriteOperationTests.cs | 16 +- .../Operations/ChangeStreamCursorTests.cs | 8 +- .../CompositeWriteOperationTests.cs | 20 +- .../CreateCollectionOperationTests.cs | 6 +- .../Operations/CreateViewOperationTests.cs | 2 +- .../Core/Operations/EvalOperationTests.cs | 4 +- .../Core/Operations/OperationTestBase.cs | 38 +-- .../Operations/ReadCommandOperationTests.cs | 12 +- .../RetryableWriteOperationExecutorTests.cs | 6 +- .../Operations/WriteCommandOperationTests.cs | 8 +- .../Core/Servers/LoadBalancedServerTests.cs | 52 ++-- .../Core/Servers/ServerTests.cs | 71 +++-- .../Encryption/ClientEncryptionTests.cs | 16 +- .../JsonDrivenConfigureFailPointTest.cs | 4 +- .../JsonDrivenTargetedFailPointTest.cs | 4 +- ...ntextTests.cs => OperationContextTests.cs} | 32 +-- .../MongoClientJsonDrivenTestRunnerBase.cs | 4 +- .../prose-tests/ClientEncryptionProseTests.cs | 2 +- ...onnectionMonitoringAndPoolingTestRunner.cs | 8 +- .../RetryableReadsProseTests.cs | 8 +- .../prose-tests/PoolClearRetryability.cs | 2 +- .../prose-tests/RetryWriteOnOtherMongos.cs | 6 +- .../ServerDiscoveryAndMonitoringProseTests.cs | 6 +- .../server-selection/InWindowTestRunner.cs | 4 +- .../UnifiedTargetedFailPointOperation.cs | 2 +- 129 files changed, 1233 insertions(+), 1235 deletions(-) rename src/MongoDB.Driver/{OperationCancellationContext.cs => OperationContext.cs} (84%) rename tests/MongoDB.Driver.Tests/{OperationCancellationContextTests.cs => OperationContextTests.cs} (70%) diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs b/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs index 324b49200c0..f48a8038428 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelChannelSource.cs @@ -63,13 +63,13 @@ public void Dispose() } } - public IChannelHandle GetChannel(OperationCancellationContext cancellationContext) + public IChannelHandle GetChannel(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelHelper(); } - public Task GetChannelAsync(OperationCancellationContext cancellationContext) + public Task GetChannelAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelHelper()); diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs b/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs index 8d755cc0f61..e03789a95c0 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs @@ -57,26 +57,26 @@ public void Dispose() } } - public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { ThrowIfDisposed(); return GetReadChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetReadChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetReadChannelSource(cancellationContext); + return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetReadChannelSourceAsync(cancellationContext); + return GetReadChannelSourceAsync(operationContext); } private IChannelSourceHandle GetReadChannelSourceHelper() diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs b/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs index 3d04c9d7b09..70c1150156c 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs @@ -55,68 +55,68 @@ public void Dispose() } } - public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetReadChannelSource(cancellationContext); + return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetReadChannelSourceAsync(cancellationContext); + return GetReadChannelSourceAsync(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetWriteChannelSource(cancellationContext); + return GetWriteChannelSource(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSource(cancellationContext); // ignore mayUseSecondary + return GetWriteChannelSource(operationContext); // ignore mayUseSecondary } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSource(mayUseSecondary, cancellationContext); + return GetWriteChannelSource(mayUseSecondary, operationContext); } - public Task GetWriteChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetWriteChannelSourceAsync(cancellationContext); + return GetWriteChannelSourceAsync(operationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSourceAsync(cancellationContext); // ignore mayUseSecondary + return GetWriteChannelSourceAsync(operationContext); // ignore mayUseSecondary } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSourceAsync(mayUseSecondary, cancellationContext); + return GetWriteChannelSourceAsync(mayUseSecondary, operationContext); } private IChannelSourceHandle GetChannelSourceHelper() diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs b/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs index 8bc8674cfd4..3b08ff9da33 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelSourceHandle.cs @@ -54,16 +54,16 @@ public ICoreSessionHandle Session } // methods - public IChannelHandle GetChannel(OperationCancellationContext cancellationContext) + public IChannelHandle GetChannel(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetChannel(cancellationContext); + return _reference.Instance.GetChannel(operationContext); } - public Task GetChannelAsync(OperationCancellationContext cancellationContext) + public Task GetChannelAsync(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetChannelAsync(cancellationContext); + return _reference.Instance.GetChannelAsync(operationContext); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelSourceReadWriteBinding.cs b/src/MongoDB.Driver/Core/Bindings/ChannelSourceReadWriteBinding.cs index 38f92f7a000..078f1530cdc 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelSourceReadWriteBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelSourceReadWriteBinding.cs @@ -45,68 +45,68 @@ public ICoreSessionHandle Session get { return _session; } } - public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetReadChannelSource(cancellationContext); + return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetReadChannelSourceAsync(cancellationContext); + return GetReadChannelSourceAsync(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetWriteChannelSource(cancellationContext); + return GetWriteChannelSource(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSource(cancellationContext); // ignore mayUseSecondary + return GetWriteChannelSource(operationContext); // ignore mayUseSecondary } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSource(mayUseSecondary, cancellationContext); + return GetWriteChannelSource(mayUseSecondary, operationContext); } - public Task GetWriteChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetWriteChannelSourceAsync(cancellationContext); + return GetWriteChannelSourceAsync(operationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSourceAsync(cancellationContext); // ignore mayUseSecondary + return GetWriteChannelSourceAsync(operationContext); // ignore mayUseSecondary } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSourceAsync(mayUseSecondary, cancellationContext); + return GetWriteChannelSourceAsync(mayUseSecondary, operationContext); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/CoreSession.cs b/src/MongoDB.Driver/Core/Bindings/CoreSession.cs index 5adaab71b65..6ae7382d91c 100644 --- a/src/MongoDB.Driver/Core/Bindings/CoreSession.cs +++ b/src/MongoDB.Driver/Core/Bindings/CoreSession.cs @@ -146,7 +146,7 @@ public bool IsInTransaction EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationCancellationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { if (_currentTransaction.IsEmpty) @@ -197,7 +197,7 @@ public bool IsInTransaction EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationCancellationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { if (_currentTransaction.IsEmpty) @@ -297,7 +297,7 @@ public long AdvanceTransactionNumber() EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationCancellationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { _isCommitTransactionInProgress = true; @@ -334,7 +334,7 @@ public long AdvanceTransactionNumber() EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationCancellationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { _isCommitTransactionInProgress = true; @@ -545,21 +545,21 @@ private void EnsureTransactionsAreSupported() } } - private TResult ExecuteEndTransactionOnPrimary(IReadOperation operation, OperationCancellationContext operationCancellationContext) + private TResult ExecuteEndTransactionOnPrimary(IReadOperation operation, OperationContext operationContext) { using (var sessionHandle = new NonDisposingCoreSessionHandle(this)) using (var binding = ChannelPinningHelper.CreateReadWriteBinding(_cluster, sessionHandle)) { - return operation.Execute(binding, operationCancellationContext); + return operation.Execute(binding, operationContext); } } - private async Task ExecuteEndTransactionOnPrimaryAsync(IReadOperation operation, OperationCancellationContext operationCancellationContext) + private async Task ExecuteEndTransactionOnPrimaryAsync(IReadOperation operation, OperationContext operationContext) { using (var sessionHandle = new NonDisposingCoreSessionHandle(this)) using (var binding = ChannelPinningHelper.CreateReadWriteBinding(_cluster, sessionHandle)) { - return await operation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Bindings/IBinding.cs b/src/MongoDB.Driver/Core/Bindings/IBinding.cs index f174d3fbe0f..e8bdc177210 100644 --- a/src/MongoDB.Driver/Core/Bindings/IBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/IBinding.cs @@ -30,24 +30,24 @@ internal interface IReadBinding : IBinding { ReadPreference ReadPreference { get; } - IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationToken); - Task GetReadChannelSourceAsync(OperationCancellationContext cancellationToken); + IChannelSourceHandle GetReadChannelSource(OperationContext operationContext); + Task GetReadChannelSourceAsync(OperationContext operationContext); - IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationToken); - Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationToken); + IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext); + Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext); } internal interface IWriteBinding : IBinding { - IChannelSourceHandle GetWriteChannelSource(OperationCancellationContext cancellationToken); - IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationToken); - IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationToken); - IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationToken); + IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext); + IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext); + IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext); + IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext); - Task GetWriteChannelSourceAsync(OperationCancellationContext cancellationToken); - Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationToken); - Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationToken); - Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationToken); + Task GetWriteChannelSourceAsync(OperationContext operationContext); + Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext); + Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext); + Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext); } internal interface IReadWriteBinding : IReadBinding, IWriteBinding diff --git a/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs b/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs index 4b7e6dfaff6..c9bd90ec61b 100644 --- a/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs +++ b/src/MongoDB.Driver/Core/Bindings/IChannelSource.cs @@ -25,8 +25,8 @@ internal interface IChannelSource : IDisposable ServerDescription ServerDescription { get; } ICoreSessionHandle Session { get; } - IChannelHandle GetChannel(OperationCancellationContext cancellationContext); - Task GetChannelAsync(OperationCancellationContext cancellationContext); + IChannelHandle GetChannel(OperationContext operationContext); + Task GetChannelAsync(OperationContext operationContext); } internal interface IChannelSourceHandle : IChannelSource diff --git a/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs b/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs index d1ce34fff88..5807898c6e9 100644 --- a/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs +++ b/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs @@ -46,28 +46,28 @@ public ICoreSessionHandle Session get { return _reference.Instance.Session; } } - public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(cancellationContext); + return _reference.Instance.GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(cancellationContext); + return _reference.Instance.GetReadChannelSourceAsync(operationContext); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(deprioritizedServers, cancellationContext); + return _reference.Instance.GetReadChannelSource(deprioritizedServers, operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(deprioritizedServers, cancellationContext); + return _reference.Instance.GetReadChannelSourceAsync(deprioritizedServers, operationContext); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs b/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs index a91bc35151c..0e7a0892529 100644 --- a/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs @@ -51,27 +51,27 @@ public ICoreSessionHandle Session get { return _session; } } - public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { - return GetReadChannelSource(null, cancellationContext); + return GetReadChannelSource(null, operationContext); } - public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { - return GetReadChannelSourceAsync(null, cancellationContext); + return GetReadChannelSourceAsync(null, operationContext); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(_session, _serverSelector, deprioritizedServers, cancellationContext); + var server = _cluster.SelectServerAndPinIfNeeded(_session, _serverSelector, deprioritizedServers, operationContext); return GetChannelSourceHelper(server); } - public async Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public async Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, _serverSelector, deprioritizedServers, cancellationContext).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, _serverSelector, deprioritizedServers, operationContext).ConfigureAwait(false); return GetChannelSourceHelper(server); } diff --git a/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs b/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs index 34cbc5eae7d..7d24474f394 100644 --- a/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs +++ b/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs @@ -46,76 +46,76 @@ public ICoreSessionHandle Session get { return _reference.Instance.Session; } } - public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(cancellationContext); + return _reference.Instance.GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(cancellationContext); + return _reference.Instance.GetReadChannelSourceAsync(operationContext); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(deprioritizedServers, cancellationContext); + return _reference.Instance.GetReadChannelSource(deprioritizedServers, operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(deprioritizedServers, cancellationContext); + return _reference.Instance.GetReadChannelSourceAsync(deprioritizedServers, operationContext); } - public IChannelSourceHandle GetWriteChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(cancellationContext); + return _reference.Instance.GetWriteChannelSource(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(deprioritizedServers, cancellationContext); + return _reference.Instance.GetWriteChannelSource(deprioritizedServers, operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(mayUseSecondary, cancellationContext); + return _reference.Instance.GetWriteChannelSource(mayUseSecondary, operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(deprioritizedServers, mayUseSecondary, cancellationContext); + return _reference.Instance.GetWriteChannelSource(deprioritizedServers, mayUseSecondary, operationContext); } - public Task GetWriteChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(cancellationContext); + return _reference.Instance.GetWriteChannelSourceAsync(operationContext); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(deprioritizedServers, cancellationContext); + return _reference.Instance.GetWriteChannelSourceAsync(deprioritizedServers, operationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(mayUseSecondary, cancellationContext); + return _reference.Instance.GetWriteChannelSourceAsync(mayUseSecondary, operationContext); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(deprioritizedServers, mayUseSecondary, cancellationContext); + return _reference.Instance.GetWriteChannelSourceAsync(deprioritizedServers, mayUseSecondary, operationContext); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs b/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs index 5f52bc702e3..c5fbc55cea1 100644 --- a/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs +++ b/src/MongoDB.Driver/Core/Bindings/ServerChannelSource.cs @@ -60,16 +60,16 @@ public void Dispose() } } - public IChannelHandle GetChannel(OperationCancellationContext cancellationContext) + public IChannelHandle GetChannel(OperationContext operationContext) { ThrowIfDisposed(); - return _server.GetChannel(cancellationContext); + return _server.GetChannel(operationContext); } - public Task GetChannelAsync(OperationCancellationContext cancellationContext) + public Task GetChannelAsync(OperationContext operationContext) { ThrowIfDisposed(); - return _server.GetChannelAsync(cancellationContext); + return _server.GetChannelAsync(operationContext); } private void ThrowIfDisposed() diff --git a/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs b/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs index 8d760aa9f0c..21eb3db1875 100644 --- a/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs @@ -48,26 +48,26 @@ public ICoreSessionHandle Session get { return _session; } } - public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetReadChannelSource(cancellationContext); + return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetReadChannelSourceAsync(cancellationContext); + return GetReadChannelSourceAsync(operationContext); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs b/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs index 4604a2322a2..a9ebfd21cf7 100644 --- a/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs @@ -52,68 +52,68 @@ public void Dispose() } } - public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetReadChannelSource(cancellationContext); + return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetReadChannelSourceAsync(cancellationContext); + return GetReadChannelSourceAsync(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) { ThrowIfDisposed(); return GetChannelSourceHelper(); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetWriteChannelSource(cancellationContext); + return GetWriteChannelSource(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSource(cancellationContext); // ignore mayUseSecondary + return GetWriteChannelSource(operationContext); // ignore mayUseSecondary } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSource(mayUseSecondary, cancellationContext); + return GetWriteChannelSource(mayUseSecondary, operationContext); } - public Task GetWriteChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext) { ThrowIfDisposed(); return Task.FromResult(GetChannelSourceHelper()); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { - return GetWriteChannelSourceAsync(cancellationContext); + return GetWriteChannelSourceAsync(operationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSourceAsync(cancellationContext); // ignore mayUseSecondary + return GetWriteChannelSourceAsync(operationContext); // ignore mayUseSecondary } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSourceAsync(mayUseSecondary, cancellationContext); + return GetWriteChannelSourceAsync(mayUseSecondary, operationContext); } private IChannelSourceHandle GetChannelSourceHelper() diff --git a/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs b/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs index 8295484bf5d..afb68fc1741 100644 --- a/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs @@ -47,48 +47,48 @@ public ICoreSessionHandle Session get { return _session; } } - public IChannelSourceHandle GetReadChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { - return GetReadChannelSource(null, cancellationContext); + return GetReadChannelSource(null, operationContext); } - public Task GetReadChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext) { - return GetReadChannelSourceAsync(null, cancellationContext); + return GetReadChannelSourceAsync(null, operationContext); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationContext); + var server = _cluster.SelectServerAndPinIfNeeded(_session, WritableServerSelector.Instance, deprioritizedServers, operationContext); return CreateServerChannelSource(server); } - public async Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public async Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationContext).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, WritableServerSelector.Instance, deprioritizedServers, operationContext).ConfigureAwait(false); return CreateServerChannelSource(server); } - public IChannelSourceHandle GetWriteChannelSource(OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) { - return GetWriteChannelSource(deprioritizedServers: null, cancellationContext); + return GetWriteChannelSource(deprioritizedServers: null, operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationContext); + var server = _cluster.SelectServerAndPinIfNeeded(_session, WritableServerSelector.Instance, deprioritizedServers, operationContext); return CreateServerChannelSource(server); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSource(null, mayUseSecondary, cancellationContext); + return GetWriteChannelSource(null, mayUseSecondary, operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { if (IsSessionPinnedToServer()) { @@ -101,28 +101,28 @@ public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection GetWriteChannelSourceAsync(OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext) { - return GetWriteChannelSourceAsync(deprioritizedServers: null, cancellationContext); + return GetWriteChannelSourceAsync(deprioritizedServers: null, operationContext); } - public async Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationCancellationContext cancellationContext) + public async Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, WritableServerSelector.Instance, deprioritizedServers, cancellationContext).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, WritableServerSelector.Instance, deprioritizedServers, operationContext).ConfigureAwait(false); return CreateServerChannelSource(server); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { - return GetWriteChannelSourceAsync(null, mayUseSecondary, cancellationContext); + return GetWriteChannelSourceAsync(null, mayUseSecondary, operationContext); } - public async Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationCancellationContext cancellationContext) + public async Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) { if (IsSessionPinnedToServer()) { @@ -135,7 +135,7 @@ public async Task GetWriteChannelSourceAsync(IReadOnlyColl ? new CompositeServerSelector(new IServerSelector[] { new PriorityServerSelector(deprioritizedServers), writableServerSelector }) : writableServerSelector; - var server = await _cluster.SelectServerAsync(selector, cancellationContext).ConfigureAwait(false); + var server = await _cluster.SelectServerAsync(selector, operationContext).ConfigureAwait(false); return CreateServerChannelSource(server); } diff --git a/src/MongoDB.Driver/Core/Clusters/Cluster.cs b/src/MongoDB.Driver/Core/Clusters/Cluster.cs index f7bf3869f52..352b9c9c188 100644 --- a/src/MongoDB.Driver/Core/Clusters/Cluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/Cluster.cs @@ -216,13 +216,13 @@ protected void OnDescriptionChanged(ClusterDescription oldDescription, ClusterDe DescriptionChanged?.Invoke(this, new ClusterDescriptionChangedEventArgs(oldDescription, newDescription)); } - public IServer SelectServer(IServerSelector selector, OperationCancellationContext cancellationContext) + public IServer SelectServer(IServerSelector selector, OperationContext operationContext) { ThrowIfDisposedOrNotOpen(); Ensure.IsNotNull(selector, nameof(selector)); - Ensure.IsNotNull(cancellationContext, nameof(cancellationContext)); + Ensure.IsNotNull(operationContext, nameof(operationContext)); - var serverSelectionCancellationContext = cancellationContext.WithTimeout(Settings.ServerSelectionTimeout); + var serverSelectionCancellationContext = operationContext.WithTimeout(Settings.ServerSelectionTimeout); using (var helper = new SelectServerHelper(this, selector)) { @@ -255,13 +255,13 @@ public IServer SelectServer(IServerSelector selector, OperationCancellationConte } } - public async Task SelectServerAsync(IServerSelector selector, OperationCancellationContext cancellationContext) + public async Task SelectServerAsync(IServerSelector selector, OperationContext operationContext) { ThrowIfDisposedOrNotOpen(); Ensure.IsNotNull(selector, nameof(selector)); - Ensure.IsNotNull(cancellationContext, nameof(cancellationContext)); + Ensure.IsNotNull(operationContext, nameof(operationContext)); - var serverSelectionCancellationContext = cancellationContext.WithTimeout(Settings.ServerSelectionTimeout); + var serverSelectionCancellationContext = operationContext.WithTimeout(Settings.ServerSelectionTimeout); using (var helper = new SelectServerHelper(this, selector)) { @@ -413,7 +413,7 @@ public void HandleException(Exception exception) EventContext.OperationName)); } - public IServer SelectServer(OperationCancellationContext cancellationContext) + public IServer SelectServer(OperationContext operationContext) { var clusterDescription = _cluster._descriptionWithChangedTaskCompletionSource; _descriptionChangedTask = clusterDescription.Changed; @@ -465,7 +465,7 @@ public IServer SelectServer(OperationCancellationContext cancellationContext) _description, _selector, selectedServer.Description, - cancellationContext.Elapsed, + operationContext.Elapsed, EventContext.OperationId, EventContext.OperationName)); } @@ -473,26 +473,26 @@ public IServer SelectServer(OperationCancellationContext cancellationContext) return selectedServer; } - public void WaitForDescriptionChanged(OperationCancellationContext cancellationContext) + public void WaitForDescriptionChanged(OperationContext operationContext) { - EnsureEnteredServerSelectionQueue(cancellationContext); - cancellationContext.WaitTask(DescriptionChangedTask); + EnsureEnteredServerSelectionQueue(operationContext); + operationContext.WaitTask(DescriptionChangedTask); } - public Task WaitForDescriptionChangedAsync(OperationCancellationContext cancellationContext) + public Task WaitForDescriptionChangedAsync(OperationContext operationContext) { - EnsureEnteredServerSelectionQueue(cancellationContext); - return cancellationContext.WaitTaskAsync(DescriptionChangedTask); + EnsureEnteredServerSelectionQueue(operationContext); + return operationContext.WaitTaskAsync(DescriptionChangedTask); } - private void EnsureEnteredServerSelectionQueue(OperationCancellationContext cancellationContext) + private void EnsureEnteredServerSelectionQueue(OperationContext operationContext) { if (_serverSelectionWaitQueueEntered) { return; } - _cluster.EnterServerSelectionWaitQueue(_selector, _description, EventContext.OperationId, cancellationContext.RemainingTimeout); + _cluster.EnterServerSelectionWaitQueue(_selector, _description, EventContext.OperationId, operationContext.RemainingTimeout); _serverSelectionWaitQueueEntered = true; } diff --git a/src/MongoDB.Driver/Core/Clusters/ICluster.cs b/src/MongoDB.Driver/Core/Clusters/ICluster.cs index 88ca766c310..8ab47f5cdbb 100644 --- a/src/MongoDB.Driver/Core/Clusters/ICluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/ICluster.cs @@ -61,8 +61,8 @@ internal interface IClusterInternal : ICluster void Initialize(); - IServer SelectServer(IServerSelector selector, OperationCancellationContext cancellationContext); - Task SelectServerAsync(IServerSelector selector, OperationCancellationContext cancellationContext); + IServer SelectServer(IServerSelector selector, OperationContext operationContext); + Task SelectServerAsync(IServerSelector selector, OperationContext operationContext); ICoreSessionHandle StartSession(CoreSessionOptions options = null); } diff --git a/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs b/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs index 025d8346486..c0de1fd5155 100644 --- a/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs +++ b/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs @@ -28,7 +28,7 @@ public static IServer SelectServerAndPinIfNeeded( ICoreSessionHandle session, IServerSelector selector, IReadOnlyCollection deprioritizedServers, - OperationCancellationContext cancellationContext) + OperationContext operationContext) { var pinnedServer = GetPinnedServerIfValid(cluster, session); if (pinnedServer != null) @@ -40,9 +40,9 @@ public static IServer SelectServerAndPinIfNeeded( ? new CompositeServerSelector(new[] { new PriorityServerSelector(deprioritizedServers), selector }) : selector; - // Server selection also updates the cluster type, allowing us to to determine if the server + // Server selection also updates the cluster type, allowing us to determine if the server // should be pinned. - var server = cluster.SelectServer(selector, cancellationContext); + var server = cluster.SelectServer(selector, operationContext); PinServerIfNeeded(cluster, session, server); return server; } @@ -52,7 +52,7 @@ public static async Task SelectServerAndPinIfNeededAsync( ICoreSessionHandle session, IServerSelector selector, IReadOnlyCollection deprioritizedServers, - OperationCancellationContext cancellationContext) + OperationContext operationContext) { var pinnedServer = GetPinnedServerIfValid(cluster, session); if (pinnedServer != null) @@ -64,9 +64,9 @@ public static async Task SelectServerAndPinIfNeededAsync( ? new CompositeServerSelector(new[] { new PriorityServerSelector(deprioritizedServers), selector }) : selector; - // Server selection also updates the cluster type, allowing us to to determine if the server + // Server selection also updates the cluster type, allowing us to determine if the server // should be pinned. - var server = await cluster.SelectServerAsync(selector, cancellationContext).ConfigureAwait(false); + var server = await cluster.SelectServerAsync(selector, operationContext).ConfigureAwait(false); PinServerIfNeeded(cluster, session, server); return server; diff --git a/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs b/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs index 59b51e5c204..21cbae7de89 100644 --- a/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs @@ -170,13 +170,13 @@ public void Initialize() } } - public IServer SelectServer(IServerSelector selector, OperationCancellationContext cancellationContext) + public IServer SelectServer(IServerSelector selector, OperationContext operationContext) { Ensure.IsNotNull(selector, nameof(selector)); - Ensure.IsNotNull(cancellationContext, nameof(cancellationContext)); + Ensure.IsNotNull(operationContext, nameof(operationContext)); ThrowIfDisposed(); - var serverSelectionCancellationContext = cancellationContext.WithTimeout(_settings.ServerSelectionTimeout); + var serverSelectionCancellationContext = operationContext.WithTimeout(_settings.ServerSelectionTimeout); _serverSelectionEventLogger.LogAndPublish(new ClusterSelectingServerEvent( _description, @@ -208,13 +208,13 @@ public IServer SelectServer(IServerSelector selector, OperationCancellationConte throw new InvalidOperationException("The server must be created before usage."); // should not be reached } - public async Task SelectServerAsync(IServerSelector selector, OperationCancellationContext cancellationContext) + public async Task SelectServerAsync(IServerSelector selector, OperationContext operationContext) { Ensure.IsNotNull(selector, nameof(selector)); - Ensure.IsNotNull(cancellationContext, nameof(cancellationContext)); + Ensure.IsNotNull(operationContext, nameof(operationContext)); ThrowIfDisposed(); - var serverSelectionCancellationContext = cancellationContext.WithTimeout(_settings.ServerSelectionTimeout); + var serverSelectionCancellationContext = operationContext.WithTimeout(_settings.ServerSelectionTimeout); _serverSelectionEventLogger.LogAndPublish(new ClusterSelectingServerEvent( _description, diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs index 932b4c118d7..9812a89ce01 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs @@ -33,7 +33,7 @@ namespace MongoDB.Driver.Core.ConnectionPools internal sealed partial class ExclusiveConnectionPool { // private methods - private Exception CreateTimeoutException(OperationCancellationContext cancellationContext, string message) + private Exception CreateTimeoutException(OperationContext operationContext, string message) { var checkOutsForCursorCount = _checkOutReasonCounter.GetCheckOutsCount(CheckOutReason.Cursor); var checkOutsForTransactionCount = _checkOutReasonCounter.GetCheckOutsCount(CheckOutReason.Transaction); @@ -47,7 +47,7 @@ private Exception CreateTimeoutException(OperationCancellationContext cancellati var checkOutsForOtherCount = checkOutsCount - checkOutsForCursorCount - checkOutsForTransactionCount; message = - $"Timed out after {cancellationContext.Elapsed.TotalMilliseconds}ms waiting for a connection from the connection pool. " + + $"Timed out after {operationContext.Elapsed.TotalMilliseconds}ms waiting for a connection from the connection pool. " + $"maxPoolSize: {maxPoolSize}, " + $"connections in use by cursors: {checkOutsForCursorCount}, " + $"connections in use by transactions: {checkOutsForTransactionCount}, " + @@ -176,60 +176,60 @@ public AcquireConnectionHelper(ExclusiveConnectionPool pool) _pool = pool; } - public IConnectionHandle AcquireConnection(OperationCancellationContext cancellationContext) + public IConnectionHandle AcquireConnection(OperationContext operationContext) { try { StartCheckingOut(); - _poolQueueWaitResult = _pool._maxConnectionsQueue.WaitSignaled(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken); + _poolQueueWaitResult = _pool._maxConnectionsQueue.WaitSignaled(operationContext.RemainingTimeout, operationContext.CancellationToken); if (_poolQueueWaitResult == SemaphoreSlimSignalable.SemaphoreWaitResult.Entered) { PooledConnection pooledConnection; - EnsureTimeout(cancellationContext); + EnsureTimeout(operationContext); using (var connectionCreator = new ConnectionCreator(_pool)) { - pooledConnection = connectionCreator.CreateOpenedOrReuse(cancellationContext); + pooledConnection = connectionCreator.CreateOpenedOrReuse(operationContext); } - return EndCheckingOut(pooledConnection, cancellationContext); + return EndCheckingOut(pooledConnection, operationContext); } - throw CreateException(cancellationContext); + throw CreateException(operationContext); } catch (Exception ex) { - HandleException(ex, cancellationContext.Elapsed); + HandleException(ex, operationContext.Elapsed); throw; } } - public async Task AcquireConnectionAsync(OperationCancellationContext cancellationContext) + public async Task AcquireConnectionAsync(OperationContext operationContext) { try { StartCheckingOut(); - _poolQueueWaitResult = await _pool._maxConnectionsQueue.WaitSignaledAsync(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken).ConfigureAwait(false); + _poolQueueWaitResult = await _pool._maxConnectionsQueue.WaitSignaledAsync(operationContext.RemainingTimeout, operationContext.CancellationToken).ConfigureAwait(false); if (_poolQueueWaitResult == SemaphoreSlimSignalable.SemaphoreWaitResult.Entered) { PooledConnection pooledConnection; - EnsureTimeout(cancellationContext); + EnsureTimeout(operationContext); using (var connectionCreator = new ConnectionCreator(_pool)) { - pooledConnection = await connectionCreator.CreateOpenedOrReuseAsync(cancellationContext).ConfigureAwait(false); + pooledConnection = await connectionCreator.CreateOpenedOrReuseAsync(operationContext).ConfigureAwait(false); } - return EndCheckingOut(pooledConnection, cancellationContext); + return EndCheckingOut(pooledConnection, operationContext); } - throw CreateException(cancellationContext); + throw CreateException(operationContext); } catch (Exception ex) { - HandleException(ex, cancellationContext.Elapsed); + HandleException(ex, operationContext.Elapsed); throw; } } @@ -281,12 +281,12 @@ private void StartCheckingOut() AcquireWaitQueueSlot(); } - private IConnectionHandle EndCheckingOut(PooledConnection pooledConnection, OperationCancellationContext cancellationContext) + private IConnectionHandle EndCheckingOut(PooledConnection pooledConnection, OperationContext operationContext) { var reference = new ReferenceCounted(pooledConnection, _pool.ReleaseConnection); var connectionHandle = new AcquiredConnection(_pool, reference); - _pool._eventLogger.LogAndPublish(new ConnectionPoolCheckedOutConnectionEvent(connectionHandle.ConnectionId, cancellationContext.Elapsed, EventContext.OperationId)); + _pool._eventLogger.LogAndPublish(new ConnectionPoolCheckedOutConnectionEvent(connectionHandle.ConnectionId, operationContext.Elapsed, EventContext.OperationId)); // no need to release the semaphore _poolQueueWaitResult = SemaphoreSlimSignalable.SemaphoreWaitResult.None; @@ -294,21 +294,21 @@ private IConnectionHandle EndCheckingOut(PooledConnection pooledConnection, Oper return connectionHandle; } - private void EnsureTimeout(OperationCancellationContext cancellationContext) + private void EnsureTimeout(OperationContext operationContext) { - if (cancellationContext.IsTimedOut()) + if (operationContext.IsTimedOut()) { - throw _pool.CreateTimeoutException(cancellationContext, $"Timed out waiting for a connection after {cancellationContext.Elapsed.TotalMilliseconds}ms."); + throw _pool.CreateTimeoutException(operationContext, $"Timed out waiting for a connection after {operationContext.Elapsed.TotalMilliseconds}ms."); } } - private Exception CreateException(OperationCancellationContext cancellationContext) => + private Exception CreateException(OperationContext operationContext) => _poolQueueWaitResult switch { SemaphoreSlimSignalable.SemaphoreWaitResult.Signaled => MongoConnectionPoolPausedException.ForConnectionPool(_pool._endPoint), SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => - _pool.CreateTimeoutException(cancellationContext, $"Timed out waiting for a connection after {cancellationContext.Elapsed.TotalMilliseconds}ms."), + _pool.CreateTimeoutException(operationContext, $"Timed out waiting for a connection after {operationContext.Elapsed.TotalMilliseconds}ms."), // should not be reached _ => new InvalidOperationException($"Invalid {_poolQueueWaitResult}.") }; @@ -844,19 +844,19 @@ public ConnectionCreator(ExclusiveConnectionPool pool) _disposeConnection = true; } - public PooledConnection CreateOpened(OperationCancellationContext cancellationContext) + public PooledConnection CreateOpened(OperationContext operationContext) { try { - _connectingWaitStatus = _pool._maxConnectingQueue.Wait(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken); + _connectingWaitStatus = _pool._maxConnectingQueue.Wait(operationContext.RemainingTimeout, operationContext.CancellationToken); _pool._poolState.ThrowIfNotReady(); if (_connectingWaitStatus == SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut) { - _pool.CreateTimeoutException(cancellationContext, $"Timed out waiting for in connecting queue after {cancellationContext.Elapsed.TotalMilliseconds}ms."); + _pool.CreateTimeoutException(operationContext, $"Timed out waiting for in connecting queue after {operationContext.Elapsed.TotalMilliseconds}ms."); } - return CreateOpenedInternal(cancellationContext); + return CreateOpenedInternal(operationContext); } catch (Exception ex) { @@ -865,7 +865,7 @@ public PooledConnection CreateOpened(OperationCancellationContext cancellationCo } } - public PooledConnection CreateOpenedOrReuse(OperationCancellationContext cancellationContext) + public PooledConnection CreateOpenedOrReuse(OperationContext operationContext) { try { @@ -879,19 +879,19 @@ public PooledConnection CreateOpenedOrReuse(OperationCancellationContext cancell // Entered: The request was successfully fulfilled, and a connection establishment can start // Signaled: The request was interrupted because Connection was return to pool and can be reused // Timeout: The request was timed out after WaitQueueTimeout period. - _connectingWaitStatus = _pool._maxConnectingQueue.WaitSignaled(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken); + _connectingWaitStatus = _pool._maxConnectingQueue.WaitSignaled(operationContext.RemainingTimeout, operationContext.CancellationToken); connection = _connectingWaitStatus switch { SemaphoreSlimSignalable.SemaphoreWaitResult.Signaled => _pool._connectionHolder.Acquire(), - SemaphoreSlimSignalable.SemaphoreWaitResult.Entered => CreateOpenedInternal(cancellationContext), - SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(cancellationContext), + SemaphoreSlimSignalable.SemaphoreWaitResult.Entered => CreateOpenedInternal(operationContext), + SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(operationContext), _ => throw new InvalidOperationException($"Invalid wait result {_connectingWaitStatus}") }; - if (connection == null && cancellationContext.IsTimedOut()) + if (connection == null && operationContext.IsTimedOut()) { - throw CreateTimeoutException(cancellationContext); + throw CreateTimeoutException(operationContext); } } @@ -904,7 +904,7 @@ public PooledConnection CreateOpenedOrReuse(OperationCancellationContext cancell } } - public async Task CreateOpenedOrReuseAsync(OperationCancellationContext cancellationContext) + public async Task CreateOpenedOrReuseAsync(OperationContext operationContext) { try { @@ -918,19 +918,19 @@ public async Task CreateOpenedOrReuseAsync(OperationCancellati // Entered: The request was successfully fulfilled, and a connection establishment can start // Signaled: The request was interrupted because Connection was return to pool and can be reused // Timeout: The request was timed out after WaitQueueTimeout period. - _connectingWaitStatus = await _pool._maxConnectingQueue.WaitSignaledAsync(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken).ConfigureAwait(false); + _connectingWaitStatus = await _pool._maxConnectingQueue.WaitSignaledAsync(operationContext.RemainingTimeout, operationContext.CancellationToken).ConfigureAwait(false); connection = _connectingWaitStatus switch { SemaphoreSlimSignalable.SemaphoreWaitResult.Signaled => _pool._connectionHolder.Acquire(), - SemaphoreSlimSignalable.SemaphoreWaitResult.Entered => await CreateOpenedInternalAsync(cancellationContext).ConfigureAwait(false), - SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(cancellationContext), + SemaphoreSlimSignalable.SemaphoreWaitResult.Entered => await CreateOpenedInternalAsync(operationContext).ConfigureAwait(false), + SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(operationContext), _ => throw new InvalidOperationException($"Invalid wait result {_connectingWaitStatus}") }; - if (connection == null && cancellationContext.IsTimedOut()) + if (connection == null && operationContext.IsTimedOut()) { - throw CreateTimeoutException(cancellationContext); + throw CreateTimeoutException(operationContext); } } @@ -958,36 +958,36 @@ public void Dispose() } // private methods - private PooledConnection CreateOpenedInternal(OperationCancellationContext cancellationContext) + private PooledConnection CreateOpenedInternal(OperationContext operationContext) { - StartCreating(cancellationContext); + StartCreating(operationContext); // TODO: CSOT add support of CSOT timeout in connection open code too. - _connection.Open(cancellationContext.CancellationToken); + _connection.Open(operationContext.CancellationToken); - FinishCreating(_connection.Description, cancellationContext); + FinishCreating(_connection.Description, operationContext); return _connection; } - private async Task CreateOpenedInternalAsync(OperationCancellationContext cancellationContext) + private async Task CreateOpenedInternalAsync(OperationContext operationContext) { - StartCreating(cancellationContext); + StartCreating(operationContext); // TODO: CSOT add support of CSOT timeout in connection open code too. - await _connection.OpenAsync(cancellationContext.CancellationToken).ConfigureAwait(false); + await _connection.OpenAsync(operationContext.CancellationToken).ConfigureAwait(false); - FinishCreating(_connection.Description, cancellationContext); + FinishCreating(_connection.Description, operationContext); return _connection; } - private void StartCreating(OperationCancellationContext cancellationContext) + private void StartCreating(OperationContext operationContext) { _pool._eventLogger.LogAndPublish(new ConnectionPoolAddingConnectionEvent(_pool._serverId, EventContext.OperationId)); - cancellationContext.CancellationToken.ThrowIfCancellationRequested(); - if (cancellationContext.IsTimedOut()) + operationContext.CancellationToken.ThrowIfCancellationRequested(); + if (operationContext.IsTimedOut()) { throw new TimeoutException(); } @@ -995,19 +995,19 @@ private void StartCreating(OperationCancellationContext cancellationContext) _connection = _pool.CreateNewConnection(); } - private void FinishCreating(ConnectionDescription description, OperationCancellationContext cancellationContext) + private void FinishCreating(ConnectionDescription description, OperationContext operationContext) { - _pool._eventLogger.LogAndPublish(new ConnectionPoolAddedConnectionEvent(_connection.ConnectionId, cancellationContext.Elapsed, EventContext.OperationId)); + _pool._eventLogger.LogAndPublish(new ConnectionPoolAddedConnectionEvent(_connection.ConnectionId, operationContext.Elapsed, EventContext.OperationId)); // Only if reached this stage, connection should not be disposed _disposeConnection = false; _pool._serviceStates.IncrementConnectionCount(description?.ServiceId); } - private Exception CreateTimeoutException(OperationCancellationContext cancellationContext) + private Exception CreateTimeoutException(OperationContext operationContext) { - var message = $"Timed out waiting in connecting queue after {cancellationContext.Elapsed.TotalMilliseconds}ms."; - return _pool.CreateTimeoutException(cancellationContext, message); + var message = $"Timed out waiting in connecting queue after {operationContext.Elapsed.TotalMilliseconds}ms."; + return _pool.CreateTimeoutException(operationContext, message); } } } diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.cs index 0dc075b603e..7489d714081 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.cs @@ -139,18 +139,18 @@ public int UsedCount internal ListConnectionHolder ConnectionHolder => _connectionHolder; // public methods - public IConnectionHandle AcquireConnection(OperationCancellationContext cancellationContext) + public IConnectionHandle AcquireConnection(OperationContext operationContext) { - cancellationContext = cancellationContext.WithTimeout(Settings.WaitQueueTimeout); + operationContext = operationContext.WithTimeout(Settings.WaitQueueTimeout); using var helper = new AcquireConnectionHelper(this); - return helper.AcquireConnection(cancellationContext); + return helper.AcquireConnection(operationContext); } - public async Task AcquireConnectionAsync(OperationCancellationContext cancellationContext) + public async Task AcquireConnectionAsync(OperationContext operationContext) { - cancellationContext = cancellationContext.WithTimeout(Settings.WaitQueueTimeout); + operationContext = operationContext.WithTimeout(Settings.WaitQueueTimeout); using var helper = new AcquireConnectionHelper(this); - return await helper.AcquireConnectionAsync(cancellationContext).ConfigureAwait(false); + return await helper.AcquireConnectionAsync(operationContext).ConfigureAwait(false); } public void Clear(bool closeInUseConnections = false) diff --git a/src/MongoDB.Driver/Core/ConnectionPools/IConnectionPool.cs b/src/MongoDB.Driver/Core/ConnectionPools/IConnectionPool.cs index 583e717dada..599185c797a 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/IConnectionPool.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/IConnectionPool.cs @@ -26,8 +26,8 @@ internal interface IConnectionPool : IDisposable int Generation { get; } ServerId ServerId { get; } - IConnectionHandle AcquireConnection(OperationCancellationContext cancellationContext); - Task AcquireConnectionAsync(OperationCancellationContext cancellationContext); + IConnectionHandle AcquireConnection(OperationContext operationContext); + Task AcquireConnectionAsync(OperationContext operationContext); void Clear(bool closeInUseConnections = false); void Clear(ObjectId serviceId); int GetGeneration(ObjectId? serviceId); diff --git a/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs b/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs index 91a4b6d405e..78ac0a55931 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs @@ -117,8 +117,8 @@ private void EnsureMinSize(CancellationToken cancellationToken) { using (var poolAwaiter = _connectionPool.CreateMaxConnectionsAwaiter()) { - var cancellationContext = new OperationCancellationContext(TimeSpan.FromMilliseconds(20), cancellationToken); - var entered = poolAwaiter.WaitSignaled(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken); + var operationContext = new OperationContext(TimeSpan.FromMilliseconds(20), cancellationToken); + var entered = poolAwaiter.WaitSignaled(operationContext.RemainingTimeout, operationContext.CancellationToken); if (!entered) { return; @@ -126,7 +126,7 @@ private void EnsureMinSize(CancellationToken cancellationToken) using (var connectionCreator = new ConnectionCreator(_connectionPool)) { - var connection = connectionCreator.CreateOpened(cancellationContext); + var connection = connectionCreator.CreateOpened(operationContext); _connectionPool.ConnectionHolder.Return(connection); } } diff --git a/src/MongoDB.Driver/Core/Misc/Feature.cs b/src/MongoDB.Driver/Core/Misc/Feature.cs index cfcfb59dd98..c3da1d48ffd 100644 --- a/src/MongoDB.Driver/Core/Misc/Feature.cs +++ b/src/MongoDB.Driver/Core/Misc/Feature.cs @@ -566,10 +566,10 @@ public void ThrowIfNotSupported(IMongoClient client, CancellationToken cancellat { var cluster = client.GetClusterInternal(); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, NoCoreSession.NewHandle()))) - using (var channelSource = binding.GetWriteChannelSource(operationCancellationContext)) - using (var channel = channelSource.GetChannel(operationCancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) { // Use WireVersion from a connection since server level value may be null ThrowIfNotSupported(channel.ConnectionDescription.MaxWireVersion); @@ -585,10 +585,10 @@ public async Task ThrowIfNotSupportedAsync(IMongoClient client, CancellationToke { var cluster = client.GetClusterInternal(); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, NoCoreSession.NewHandle()))) - using (var channelSource = await binding.GetWriteChannelSourceAsync(operationCancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(operationCancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) { // Use WireVersion from a connection since server level value may be null ThrowIfNotSupported(channel.ConnectionDescription.MaxWireVersion); diff --git a/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs b/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs index bd575f7bff5..01608902b97 100644 --- a/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs @@ -269,19 +269,19 @@ public bool? UseCursor // methods /// - public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) { - return Execute(context, cancellationContext); + return Execute(context, operationContext); } } /// - public IAsyncCursor Execute(RetryableReadContext context, OperationCancellationContext cancellationContext) + public IAsyncCursor Execute(RetryableReadContext context, OperationContext operationContext) { Ensure.IsNotNull(context, nameof(context)); EnsureIsReadOnlyPipeline(); @@ -289,7 +289,7 @@ public IAsyncCursor Execute(RetryableReadContext context, OperationCanc using (EventContext.BeginOperation()) { var operation = CreateOperation(context); - var result = operation.Execute(context, cancellationContext); + var result = operation.Execute(context, operationContext); context.ChannelSource.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); @@ -298,19 +298,19 @@ public IAsyncCursor Execute(RetryableReadContext context, OperationCanc } /// - public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + return await ExecuteAsync(context, operationContext).ConfigureAwait(false); } } /// - public async Task> ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(RetryableReadContext context, OperationContext operationContext) { Ensure.IsNotNull(context, nameof(context)); EnsureIsReadOnlyPipeline(); @@ -318,7 +318,7 @@ public async Task> ExecuteAsync(RetryableReadContext conte using (EventContext.BeginOperation()) { var operation = CreateOperation(context); - var result = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); context.ChannelSource.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); diff --git a/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs index db3c4e455a2..76108a15a04 100644 --- a/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs @@ -147,33 +147,33 @@ public WriteConcern WriteConcern set { _writeConcern = value; } } - public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); var mayUseSecondary = new MayUseSecondary(_readPreference); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(mayUseSecondary, cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(mayUseSecondary, operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, mayUseSecondary.EffectiveReadPreference); - return operation.Execute(channelBinding, cancellationContext); + return operation.Execute(channelBinding, operationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); var mayUseSecondary = new MayUseSecondary(_readPreference); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(mayUseSecondary, cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(mayUseSecondary, operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, mayUseSecondary.EffectiveReadPreference); - return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs b/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs index 769d6f6aaaf..57712fd29ea 100644 --- a/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs +++ b/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs @@ -410,9 +410,9 @@ private void DisposeChannelSourceIfNoLongerNeeded() private CursorBatch GetNextBatch(CancellationToken cancellationToken) { // TODO: CSOT implement proper way to obtain the operationCancellationContext - var cancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) - using (var channel = _channelSource.GetChannel(cancellationContext)) + using (var channel = _channelSource.GetChannel(operationContext)) { return ExecuteGetMoreCommand(channel, cancellationToken); } @@ -421,9 +421,9 @@ private CursorBatch GetNextBatch(CancellationToken cancellationToken) private async Task> GetNextBatchAsync(CancellationToken cancellationToken) { // TODO: CSOT implement proper way to obtain the operationCancellationContext - var cancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) - using (var channel = await _channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await _channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) { return await ExecuteGetMoreCommandAsync(channel, cancellationToken).ConfigureAwait(false); } @@ -437,10 +437,10 @@ private bool IsMongoCursorNotFoundException(MongoCommandException exception) private void KillCursors(CancellationToken cancellationToken) { // TODO: CSOT implement proper way to obtain the operationCancellationContext - var cancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) using (EventContext.BeginKillCursors(_collectionNamespace)) - using (var channel = _channelSource.GetChannel(cancellationContext.WithTimeout(TimeSpan.FromSeconds(10)))) + using (var channel = _channelSource.GetChannel(operationContext.WithTimeout(TimeSpan.FromSeconds(10)))) { if (!channel.Connection.IsExpired) { @@ -452,10 +452,10 @@ private void KillCursors(CancellationToken cancellationToken) private async Task KillCursorsAsync(CancellationToken cancellationToken) { // TODO: CSOT implement proper way to obtain the operationCancellationContext - var cancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) using (EventContext.BeginKillCursors(_collectionNamespace)) - using (var channel = await _channelSource.GetChannelAsync(cancellationContext.WithTimeout(TimeSpan.FromSeconds(10))).ConfigureAwait(false)) + using (var channel = await _channelSource.GetChannelAsync(operationContext.WithTimeout(TimeSpan.FromSeconds(10))).ConfigureAwait(false)) { if (!channel.Connection.IsExpired) { diff --git a/src/MongoDB.Driver/Core/Operations/BulkMixedWriteOperation.cs b/src/MongoDB.Driver/Core/Operations/BulkMixedWriteOperation.cs index 24c8832c1cc..34a71dbea11 100644 --- a/src/MongoDB.Driver/Core/Operations/BulkMixedWriteOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/BulkMixedWriteOperation.cs @@ -136,33 +136,33 @@ public WriteConcern WriteConcern set { _writeConcern = Ensure.IsNotNull(value, nameof(value)); } } - public BulkWriteOperationResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BulkWriteOperationResult Execute(IWriteBinding binding, OperationContext operationContext) { using (BeginOperation()) - using (var context = RetryableWriteContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableWriteContext.Create(binding, _retryRequested, operationContext)) { EnsureHintIsSupportedIfAnyRequestHasHint(); context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); var helper = new BatchHelper(_requests, _isOrdered, _writeConcern); foreach (var batch in helper.GetBatches()) { - batch.Result = ExecuteBatch(context, batch, cancellationContext); + batch.Result = ExecuteBatch(context, batch, operationContext); } return helper.GetFinalResultOrThrow(context.Channel.ConnectionDescription.ConnectionId); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { using (BeginOperation()) - using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) { EnsureHintIsSupportedIfAnyRequestHasHint(); context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); var helper = new BatchHelper(_requests, _isOrdered, _writeConcern); foreach (var batch in helper.GetBatches()) { - batch.Result = await ExecuteBatchAsync(context, batch, cancellationContext).ConfigureAwait(false); + batch.Result = await ExecuteBatchAsync(context, batch, operationContext).ConfigureAwait(false); } return helper.GetFinalResultOrThrow(context.Channel.ConnectionDescription.ConnectionId); } @@ -241,14 +241,14 @@ private void EnsureHintIsSupportedIfAnyRequestHasHint() } } - private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch batch, OperationCancellationContext cancellationContext) + private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch batch, OperationContext operationContext) { BulkWriteOperationResult result; MongoBulkWriteOperationException exception = null; try { var operation = CreateUnmixedBatchOperation(batch); - result = operation.Execute(context, cancellationContext); + result = operation.Execute(context, operationContext); } catch (MongoBulkWriteOperationException ex) { @@ -259,14 +259,14 @@ private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch b return BulkWriteBatchResult.Create(result, exception, batch.IndexMap); } - private async Task ExecuteBatchAsync(RetryableWriteContext context, Batch batch, OperationCancellationContext cancellationContext) + private async Task ExecuteBatchAsync(RetryableWriteContext context, Batch batch, OperationContext operationContext) { BulkWriteOperationResult result; MongoBulkWriteOperationException exception = null; try { var operation = CreateUnmixedBatchOperation(batch); - result = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + result = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); } catch (MongoBulkWriteOperationException ex) { diff --git a/src/MongoDB.Driver/Core/Operations/BulkUnmixedWriteOperationBase.cs b/src/MongoDB.Driver/Core/Operations/BulkUnmixedWriteOperationBase.cs index 4f9d2b34b70..57169f8b665 100644 --- a/src/MongoDB.Driver/Core/Operations/BulkUnmixedWriteOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/BulkUnmixedWriteOperationBase.cs @@ -119,37 +119,37 @@ public WriteConcern WriteConcern } // public methods - public BulkWriteOperationResult Execute(RetryableWriteContext context, OperationCancellationContext cancellationContext) + public BulkWriteOperationResult Execute(RetryableWriteContext context, OperationContext operationContext) { EnsureHintIsSupportedIfAnyRequestHasHint(); - return ExecuteBatches(context, cancellationContext); + return ExecuteBatches(context, operationContext); } - public BulkWriteOperationResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BulkWriteOperationResult Execute(IWriteBinding binding, OperationContext operationContext) { using (BeginOperation()) - using (var context = RetryableWriteContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableWriteContext.Create(binding, _retryRequested, operationContext)) { context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); - return Execute(context, cancellationContext); + return Execute(context, operationContext); } } - public Task ExecuteAsync(RetryableWriteContext context, OperationCancellationContext cancellationContext) + public Task ExecuteAsync(RetryableWriteContext context, OperationContext operationContext) { EnsureHintIsSupportedIfAnyRequestHasHint(); - return ExecuteBatchesAsync(context, cancellationContext); + return ExecuteBatchesAsync(context, operationContext); } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { using (BeginOperation()) - using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) { context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); - return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + return await ExecuteAsync(context, operationContext).ConfigureAwait(false); } } @@ -189,14 +189,14 @@ private void EnsureHintIsSupportedIfAnyRequestHasHint() } } - private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch batch, OperationCancellationContext cancellationContext) + private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch batch, OperationContext operationContext) { var operation = CreateBatchOperation(batch); BsonDocument operationResult; MongoWriteConcernException writeConcernException = null; try { - operationResult = RetryableWriteOperationExecutor.Execute(operation, context, cancellationContext); + operationResult = RetryableWriteOperationExecutor.Execute(operation, context, operationContext); } catch (MongoWriteConcernException exception) when (exception.IsWriteConcernErrorOnly()) { @@ -207,14 +207,14 @@ private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch b return CreateBatchResult(batch, operationResult, writeConcernException); } - private async Task ExecuteBatchAsync(RetryableWriteContext context, Batch batch, OperationCancellationContext cancellationContext) + private async Task ExecuteBatchAsync(RetryableWriteContext context, Batch batch, OperationContext operationContext) { var operation = CreateBatchOperation(batch); BsonDocument operationResult; MongoWriteConcernException writeConcernException = null; try { - operationResult = await RetryableWriteOperationExecutor.ExecuteAsync(operation, context, cancellationContext).ConfigureAwait(false); + operationResult = await RetryableWriteOperationExecutor.ExecuteAsync(operation, context, operationContext).ConfigureAwait(false); } catch (MongoWriteConcernException exception) when (exception.IsWriteConcernErrorOnly()) { @@ -225,22 +225,22 @@ private async Task ExecuteBatchAsync(RetryableWriteContext return CreateBatchResult(batch, operationResult, writeConcernException); } - private BulkWriteOperationResult ExecuteBatches(RetryableWriteContext context, OperationCancellationContext cancellationContext) + private BulkWriteOperationResult ExecuteBatches(RetryableWriteContext context, OperationContext operationContext) { var helper = new BatchHelper(_requests, _writeConcern, _isOrdered); foreach (var batch in helper.GetBatches()) { - batch.Result = ExecuteBatch(context, batch, cancellationContext); + batch.Result = ExecuteBatch(context, batch, operationContext); } return helper.CreateFinalResultOrThrow(context.Channel); } - private async Task ExecuteBatchesAsync(RetryableWriteContext context, OperationCancellationContext cancellationContext) + private async Task ExecuteBatchesAsync(RetryableWriteContext context, OperationContext operationContext) { var helper = new BatchHelper(_requests, _writeConcern, _isOrdered); foreach (var batch in helper.GetBatches()) { - batch.Result = await ExecuteBatchAsync(context, batch, cancellationContext).ConfigureAwait(false); + batch.Result = await ExecuteBatchAsync(context, batch, operationContext).ConfigureAwait(false); } return helper.CreateFinalResultOrThrow(context.Channel); } diff --git a/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs b/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs index c73c4f36252..e33a4f95c56 100644 --- a/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs +++ b/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs @@ -262,16 +262,16 @@ private IAsyncCursor Resume(CancellationToken cancellationToken { ReconfigureOperationResumeValues(); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); - return _changeStreamOperation.Resume(_binding, operationCancellationContext); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + return _changeStreamOperation.Resume(_binding, operationContext); } private async Task> ResumeAsync(CancellationToken cancellationToken) { ReconfigureOperationResumeValues(); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); - return await _changeStreamOperation.ResumeAsync(_binding, operationCancellationContext).ConfigureAwait(false); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + return await _changeStreamOperation.ResumeAsync(_binding, operationContext).ConfigureAwait(false); } internal struct ResumeValues diff --git a/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs b/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs index 8dd08e0024a..32bbb7091ce 100644 --- a/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs @@ -33,8 +33,8 @@ internal interface IChangeStreamOperation : IReadOperation Resume(IReadBinding binding, OperationCancellationContext cancellationContext); - Task> ResumeAsync(IReadBinding binding, OperationCancellationContext cancellationContext); + IAsyncCursor Resume(IReadBinding binding, OperationContext operationContext); + Task> ResumeAsync(IReadBinding binding, OperationContext operationContext); } internal sealed class ChangeStreamOperation : IChangeStreamOperation @@ -249,7 +249,7 @@ public BsonTimestamp StartAtOperationTime // public methods /// - public IChangeStreamCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public IChangeStreamCursor Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); var bindingHandle = binding as IReadBindingHandle; @@ -261,9 +261,9 @@ public IChangeStreamCursor Execute(IReadBinding binding, OperationCance IAsyncCursor cursor; ICursorBatchInfo cursorBatchInfo; BsonTimestamp initialOperationTime; - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) { - cursor = ExecuteAggregateOperation(context, cancellationContext); + cursor = ExecuteAggregateOperation(context, operationContext); cursorBatchInfo = (ICursorBatchInfo)cursor; initialOperationTime = GetInitialOperationTimeIfRequired(context, cursorBatchInfo); @@ -284,7 +284,7 @@ public IChangeStreamCursor Execute(IReadBinding binding, OperationCance } /// - public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); var bindingHandle = binding as IReadBindingHandle; @@ -296,9 +296,9 @@ public async Task> ExecuteAsync(IReadBinding bindin IAsyncCursor cursor; ICursorBatchInfo cursorBatchInfo; BsonTimestamp initialOperationTime; - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) { - cursor = await ExecuteAggregateOperationAsync(context, cancellationContext).ConfigureAwait(false); + cursor = await ExecuteAggregateOperationAsync(context, operationContext).ConfigureAwait(false); cursorBatchInfo = (ICursorBatchInfo)cursor; initialOperationTime = GetInitialOperationTimeIfRequired(context, cursorBatchInfo); @@ -319,20 +319,20 @@ public async Task> ExecuteAsync(IReadBinding bindin } /// - public IAsyncCursor Resume(IReadBinding binding, OperationCancellationContext cancellationContext) + public IAsyncCursor Resume(IReadBinding binding, OperationContext operationContext) { - using (var context = RetryableReadContext.Create(binding, retryRequested: false, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, retryRequested: false, operationContext)) { - return ExecuteAggregateOperation(context, cancellationContext); + return ExecuteAggregateOperation(context, operationContext); } } /// - public async Task> ResumeAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task> ResumeAsync(IReadBinding binding, OperationContext operationContext) { - using (var context = await RetryableReadContext.CreateAsync(binding, retryRequested: false, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, retryRequested: false, operationContext).ConfigureAwait(false)) { - return await ExecuteAggregateOperationAsync(context, cancellationContext).ConfigureAwait(false); + return await ExecuteAggregateOperationAsync(context, operationContext).ConfigureAwait(false); } } @@ -391,16 +391,16 @@ private List CreateCombinedPipeline(BsonDocument changeStreamStage return combinedPipeline; } - private IAsyncCursor ExecuteAggregateOperation(RetryableReadContext context, OperationCancellationContext cancellationContext) + private IAsyncCursor ExecuteAggregateOperation(RetryableReadContext context, OperationContext operationContext) { var aggregateOperation = CreateAggregateOperation(); - return aggregateOperation.Execute(context, cancellationContext); + return aggregateOperation.Execute(context, operationContext); } - private Task> ExecuteAggregateOperationAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) + private Task> ExecuteAggregateOperationAsync(RetryableReadContext context, OperationContext operationContext) { var aggregateOperation = CreateAggregateOperation(); - return aggregateOperation.ExecuteAsync(context, cancellationContext); + return aggregateOperation.ExecuteAsync(context, operationContext); } private BsonDocument GetInitialPostBatchResumeTokenIfRequired(ICursorBatchInfo cursorBatchInfo) diff --git a/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs b/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs index e6dfbc20191..f738de2aac2 100644 --- a/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs @@ -88,17 +88,17 @@ protected override IEnumerable CreateCommandPayl return new[] { payload }; } - public new ClientBulkWriteResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public new ClientBulkWriteResult Execute(IWriteBinding binding, OperationContext operationContext) { using var operation = BeginOperation(); var bulkWriteResults = new BulkWriteRawResult(); while (true) { - using var context = RetryableWriteContext.Create(binding, GetEffectiveRetryRequested(), cancellationContext); + using var context = RetryableWriteContext.Create(binding, GetEffectiveRetryRequested(), operationContext); BsonDocument serverResponse = null; try { - serverResponse = base.Execute(context, cancellationContext); + serverResponse = base.Execute(context, operationContext); } catch (MongoWriteConcernException concernException) { @@ -123,7 +123,8 @@ protected override IEnumerable CreateCommandPayl { try { - while (individualResults.MoveNext(cancellationContext.CancellationToken)) + // TODO: CSOT implement a way to support timeout in cursor methods + while (individualResults.MoveNext(operationContext.CancellationToken)) { PopulateIndividualResponses(individualResults.Current, bulkWriteResults); } @@ -145,17 +146,17 @@ protected override IEnumerable CreateCommandPayl } } - public new async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public new async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { using var operation = BeginOperation(); var bulkWriteResults = new BulkWriteRawResult(); while (true) { - using var context = RetryableWriteContext.Create(binding, GetEffectiveRetryRequested(), cancellationContext); + using var context = RetryableWriteContext.Create(binding, GetEffectiveRetryRequested(), operationContext); BsonDocument serverResponse = null; try { - serverResponse = await base.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + serverResponse = await base.ExecuteAsync(context, operationContext).ConfigureAwait(false); } catch (MongoWriteConcernException concernException) { @@ -180,7 +181,8 @@ protected override IEnumerable CreateCommandPayl { try { - while (await individualResults.MoveNextAsync(cancellationContext.CancellationToken).ConfigureAwait(false)) + // TODO: CSOT implement a way to support timeout in cursor methods + while (await individualResults.MoveNextAsync(operationContext.CancellationToken).ConfigureAwait(false)) { PopulateIndividualResponses(individualResults.Current, bulkWriteResults); } diff --git a/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs b/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs index 35bb200e2f7..cd602ae27f6 100644 --- a/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs @@ -108,11 +108,11 @@ protected TCommandResult ExecuteProtocol( IChannelSource channelSource, ICoreSessionHandle session, ReadPreference readPreference, - OperationCancellationContext cancellationContext) + OperationContext operationContext) { - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channel = channelSource.GetChannel(operationContext)) { - return ExecuteProtocol(channel, session, readPreference, cancellationContext.CancellationToken); + return ExecuteProtocol(channel, session, readPreference, operationContext.CancellationToken); } } @@ -139,11 +139,11 @@ protected async Task ExecuteProtocolAsync( IChannelSource channelSource, ICoreSessionHandle session, ReadPreference readPreference, - OperationCancellationContext cancellationContext) + OperationContext operationContext) { - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) { - return await ExecuteProtocolAsync(channel, session, readPreference, cancellationContext.CancellationToken).ConfigureAwait(false); + return await ExecuteProtocolAsync(channel, session, readPreference, operationContext.CancellationToken).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/CompositeWriteOperation.cs b/src/MongoDB.Driver/Core/Operations/CompositeWriteOperation.cs index 71caa80e40e..5669ca36fb9 100644 --- a/src/MongoDB.Driver/Core/Operations/CompositeWriteOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CompositeWriteOperation.cs @@ -31,12 +31,12 @@ public CompositeWriteOperation(params (IWriteOperation, bool IsMainOper Ensure.That(operations.Count(o => o.IsMainOperation) == 1, message: $"{nameof(CompositeWriteOperation)} must have a single main operation."); } - public TResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public TResult Execute(IWriteBinding binding, OperationContext operationContext) { TResult result = default; foreach (var operationInfo in _operations) { - var itemResult = operationInfo.Operation.Execute(binding, cancellationContext); + var itemResult = operationInfo.Operation.Execute(binding, operationContext); if (operationInfo.IsMainOperation) { result = itemResult; @@ -46,12 +46,12 @@ public TResult Execute(IWriteBinding binding, OperationCancellationContext cance return result; } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { TResult result = default; foreach (var operationInfo in _operations) { - var itemResult = await operationInfo.Operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); + var itemResult = await operationInfo.Operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); if (operationInfo.IsMainOperation) { result = itemResult; diff --git a/src/MongoDB.Driver/Core/Operations/CountDocumentsOperation.cs b/src/MongoDB.Driver/Core/Operations/CountDocumentsOperation.cs index eb88438ba10..1cc5b12e1f1 100644 --- a/src/MongoDB.Driver/Core/Operations/CountDocumentsOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CountDocumentsOperation.cs @@ -109,28 +109,28 @@ public long? Skip set { _skip = value; } } - public long Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public long Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var cursor = operation.Execute(binding, cancellationContext); - var result = cursor.ToList(cancellationContext.CancellationToken); + var cursor = operation.Execute(binding, operationContext); + var result = cursor.ToList(operationContext.CancellationToken); return ExtractCountFromResult(result); } } - public async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var cursor = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); - var result = await cursor.ToListAsync(cancellationContext.CancellationToken).ConfigureAwait(false); + var cursor = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + var result = await cursor.ToListAsync(operationContext.CancellationToken).ConfigureAwait(false); return ExtractCountFromResult(result); } } diff --git a/src/MongoDB.Driver/Core/Operations/CountOperation.cs b/src/MongoDB.Driver/Core/Operations/CountOperation.cs index b7ea4a668ae..4b75810956f 100644 --- a/src/MongoDB.Driver/Core/Operations/CountOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CountOperation.cs @@ -126,39 +126,39 @@ public BsonDocument CreateCommand(ConnectionDescription connectionDescription, I }; } - public long Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public long Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) { - return Execute(context, cancellationContext); + return Execute(context, operationContext); } } - public long Execute(RetryableReadContext context, OperationCancellationContext cancellationContext) + public long Execute(RetryableReadContext context, OperationContext operationContext) { var operation = CreateOperation(context); - var document = operation.Execute(context, cancellationContext); + var document = operation.Execute(context, operationContext); return document["n"].ToInt64(); } - public async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + return await ExecuteAsync(context, operationContext).ConfigureAwait(false); } } - public async Task ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(RetryableReadContext context, OperationContext operationContext) { var operation = CreateOperation(context); - var document = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + var document = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); return document["n"].ToInt64(); } diff --git a/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs index bf36d7e5a53..d32486a6180 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs @@ -273,36 +273,36 @@ internal BsonDocument CreateCommand(ICoreSessionHandle session) } } - public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) { EnsureServerIsValid(channel.ConnectionDescription.MaxWireVersion); using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); - return operation.Execute(channelBinding, cancellationContext); + return operation.Execute(channelBinding, operationContext); } } } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) { EnsureServerIsValid(channel.ConnectionDescription.MaxWireVersion); using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); - return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs index 4d8789ee80d..29d4d5ee56d 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs @@ -86,27 +86,27 @@ public TimeSpan? MaxTime set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); } } - public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return operation.Execute(channelBinding, cancellationContext); + return operation.Execute(channelBinding, operationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs index 1de7d07b176..d7eeb1db48a 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs @@ -54,28 +54,28 @@ public CreateSearchIndexesOperation( // public methods /// - public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { using (EventContext.BeginOperation("createSearchIndexes")) - using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return operation.Execute(channelBinding, cancellationContext); + return operation.Execute(channelBinding, operationContext); } } /// - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { using (EventContext.BeginOperation("createSearchIndexes")) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs index da19474048f..24e553618fa 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs @@ -15,7 +15,6 @@ using System.Collections.Generic; using System.Linq; -using System.Threading; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Serializers; @@ -87,29 +86,29 @@ public WriteConcern WriteConcern set { _writeConcern = value; } } - public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return operation.Execute(channelBinding, cancellationContext); + return operation.Execute(channelBinding, operationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/DatabaseExistsOperation.cs b/src/MongoDB.Driver/Core/Operations/DatabaseExistsOperation.cs index 6f09f0a1caa..e1f86ef6cf9 100644 --- a/src/MongoDB.Driver/Core/Operations/DatabaseExistsOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DatabaseExistsOperation.cs @@ -49,23 +49,23 @@ public bool RetryRequested set { _retryRequested = value; } } - public bool Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public bool Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = operation.Execute(binding, cancellationContext); + var result = operation.Execute(binding, operationContext); // TODO: CSOT find a way to apply CSOT timeout to ToList as well. - var list = result.ToList(cancellationContext.CancellationToken); + var list = result.ToList(operationContext.CancellationToken); return list.Any(x => x["name"] == _databaseNamespace.DatabaseName); } - public async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); // TODO: CSOT find a way to apply CSOT timeout to ToList as well. - var list = await result.ToListAsync(cancellationContext.CancellationToken).ConfigureAwait(false); + var list = await result.ToListAsync(operationContext.CancellationToken).ConfigureAwait(false); return list.Any(x => x["name"] == _databaseNamespace.DatabaseName); } diff --git a/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs b/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs index cabd2e2d56b..6c5e41867a6 100644 --- a/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs @@ -104,15 +104,15 @@ public IBsonSerializer ValueSerializer get { return _valueSerializer; } } - public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) { var operation = CreateOperation(context); - var result = operation.Execute(context, cancellationContext); + var result = operation.Execute(context, operationContext); binding.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); @@ -120,15 +120,15 @@ public IAsyncCursor Execute(IReadBinding binding, OperationCancellationC } } - public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) { var operation = CreateOperation(context); - var result = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); binding.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); diff --git a/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs index e4af7f3a7c6..33a312c913d 100644 --- a/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs @@ -95,20 +95,20 @@ public WriteConcern WriteConcern set { _writeConcern = value; } } - public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); BsonDocument result; try { - result = operation.Execute(channelBinding, cancellationContext); + result = operation.Execute(channelBinding, operationContext); } catch (MongoCommandException ex) { @@ -122,20 +122,20 @@ public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext } } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); BsonDocument result; try { - result = await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + result = await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } catch (MongoCommandException ex) { diff --git a/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs b/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs index 1a566015e2b..2afd2ad3b84 100644 --- a/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs @@ -64,31 +64,31 @@ public BsonDocument CreateCommand(ICoreSessionHandle session) }; } - public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); - return operation.Execute(channelBinding, cancellationContext); + return operation.Execute(channelBinding, operationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); - return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs index 193fb301ad4..c895a2e1378 100644 --- a/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs @@ -97,20 +97,20 @@ public BsonDocument CreateCommand(ICoreSessionHandle session) }; } - public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); BsonDocument result; try { - result = operation.Execute(channelBinding, cancellationContext); + result = operation.Execute(channelBinding, operationContext); } catch (MongoCommandException ex) { @@ -124,20 +124,20 @@ public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext } } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); BsonDocument result; try { - result = await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + result = await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } catch (MongoCommandException ex) { diff --git a/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs index c8364680c2e..71630d365cc 100644 --- a/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs @@ -62,20 +62,20 @@ private WriteCommandOperation CreateOperation() => new(_collectionNamespace.DatabaseNamespace, CreateCommand(), BsonDocumentSerializer.Instance, _messageEncoderSettings); /// - public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation("dropSearchIndex")) - using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); try { - return operation.Execute(channelBinding, cancellationContext); + return operation.Execute(channelBinding, operationContext); } catch (MongoCommandException ex) when (ShouldIgnoreException(ex)) { @@ -85,20 +85,20 @@ public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext } /// - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation("dropSearchIndex")) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); try { - return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } catch (MongoCommandException ex) when (ShouldIgnoreException(ex)) { diff --git a/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs b/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs index 346e9d22e1b..6e75367053b 100644 --- a/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs @@ -50,29 +50,29 @@ public MessageEncoderSettings MessageEncoderSettings protected abstract string CommandName { get; } - public virtual BsonDocument Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public virtual BsonDocument Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetReadChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetReadChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return operation.Execute(channelBinding, cancellationContext); + return operation.Execute(channelBinding, operationContext); } } - public virtual async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public virtual async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = await binding.GetReadChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetReadChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } } @@ -133,11 +133,11 @@ public TimeSpan? MaxCommitTime protected override string CommandName => "commitTransaction"; - public override BsonDocument Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public override BsonDocument Execute(IReadBinding binding, OperationContext operationContext) { try { - return base.Execute(binding, cancellationContext); + return base.Execute(binding, operationContext); } catch (MongoException exception) when (ShouldReplaceTransientTransactionErrorWithUnknownTransactionCommitResult(exception)) { @@ -146,11 +146,11 @@ public override BsonDocument Execute(IReadBinding binding, OperationCancellation } } - public override async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public override async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) { try { - return await base.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); + return await base.ExecuteAsync(binding, operationContext).ConfigureAwait(false); } catch (MongoException exception) when (ShouldReplaceTransientTransactionErrorWithUnknownTransactionCommitResult(exception)) { diff --git a/src/MongoDB.Driver/Core/Operations/EstimatedDocumentCountOperation.cs b/src/MongoDB.Driver/Core/Operations/EstimatedDocumentCountOperation.cs index 4dc34ecbb04..7c0701af038 100644 --- a/src/MongoDB.Driver/Core/Operations/EstimatedDocumentCountOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/EstimatedDocumentCountOperation.cs @@ -66,29 +66,29 @@ public bool RetryRequested set => _retryRequested = value; } - public long Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public long Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) { var operation = CreateCountOperation(); - return operation.Execute(context, cancellationContext); + return operation.Execute(context, operationContext); } } - public async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) { var operation = CreateCountOperation(); - return await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/EvalOperation.cs b/src/MongoDB.Driver/Core/Operations/EvalOperation.cs index a1eb93ea1bb..9ae4d6721c3 100644 --- a/src/MongoDB.Driver/Core/Operations/EvalOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/EvalOperation.cs @@ -87,19 +87,19 @@ public BsonDocument CreateCommand() }; } - public BsonValue Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonValue Execute(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = operation.Execute(binding, cancellationContext); + var result = operation.Execute(binding, operationContext); return result["retval"]; } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); return result["retval"]; } diff --git a/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs b/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs index 12c6835a0b6..7c36451db12 100644 --- a/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs @@ -84,39 +84,39 @@ public bool RetryRequested set { _retryRequested = value; } } - public TResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public TResult Execute(IWriteBinding binding, OperationContext operationContext) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.Execute(this, binding, _retryRequested, cancellationContext); + return RetryableWriteOperationExecutor.Execute(this, binding, _retryRequested, operationContext); } } - public TResult Execute(RetryableWriteContext context, OperationCancellationContext cancellationContext) + public TResult Execute(RetryableWriteContext context, OperationContext operationContext) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.Execute(this, context, cancellationContext); + return RetryableWriteOperationExecutor.Execute(this, context, operationContext); } } - public Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.ExecuteAsync(this, binding, _retryRequested, cancellationContext); + return RetryableWriteOperationExecutor.ExecuteAsync(this, binding, _retryRequested, operationContext); } } - public Task ExecuteAsync(RetryableWriteContext context, OperationCancellationContext cancellationContext) + public Task ExecuteAsync(RetryableWriteContext context, OperationContext operationContext) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.ExecuteAsync(this, context, cancellationContext); + return RetryableWriteOperationExecutor.ExecuteAsync(this, context, operationContext); } } - public TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext) + public TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, OperationContext operationContext) { var binding = context.Binding; var channelSource = context.ChannelSource; @@ -125,14 +125,14 @@ public TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, transactionNumber); - using (var rawBsonDocument = operation.Execute(channelBinding, cancellationContext)) + using (var rawBsonDocument = operation.Execute(channelBinding, operationContext)) { return ProcessCommandResult(channel.ConnectionDescription.ConnectionId, rawBsonDocument); } } } - public async Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext) + public async Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, OperationContext operationContext) { var binding = context.Binding; var channelSource = context.ChannelSource; @@ -141,7 +141,7 @@ public async Task ExecuteAttemptAsync(RetryableWriteContext context, in using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, transactionNumber); - using (var rawBsonDocument = await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false)) + using (var rawBsonDocument = await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false)) { return ProcessCommandResult(channel.ConnectionDescription.ConnectionId, rawBsonDocument); } diff --git a/src/MongoDB.Driver/Core/Operations/FindOperation.cs b/src/MongoDB.Driver/Core/Operations/FindOperation.cs index 593cfdcfc3a..4302f3b1767 100644 --- a/src/MongoDB.Driver/Core/Operations/FindOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/FindOperation.cs @@ -291,48 +291,48 @@ public BsonDocument CreateCommand(ConnectionDescription connectionDescription, I }; } - public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) { - return Execute(context, cancellationContext); + return Execute(context, operationContext); } } - public IAsyncCursor Execute(RetryableReadContext context, OperationCancellationContext cancellationContext) + public IAsyncCursor Execute(RetryableReadContext context, OperationContext operationContext) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginFind(_batchSize, _limit)) { var operation = CreateOperation(context); - var commandResult = operation.Execute(context, cancellationContext); + var commandResult = operation.Execute(context, operationContext); return CreateCursor(context.ChannelSource, context.Channel, commandResult); } } - public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + return await ExecuteAsync(context, operationContext).ConfigureAwait(false); } } - public async Task> ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(RetryableReadContext context, OperationContext operationContext) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginFind(_batchSize, _limit)) { var operation = CreateOperation(context); - var commandResult = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + var commandResult = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); return CreateCursor(context.ChannelSource, context.Channel, commandResult); } } diff --git a/src/MongoDB.Driver/Core/Operations/GroupOperation.cs b/src/MongoDB.Driver/Core/Operations/GroupOperation.cs index aa1f1e54f6c..a54b7e1b51f 100644 --- a/src/MongoDB.Driver/Core/Operations/GroupOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/GroupOperation.cs @@ -138,27 +138,27 @@ public BsonDocument CreateCommand() }; } - public IEnumerable Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public IEnumerable Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetReadChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetReadChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(); - return operation.Execute(channelBinding, cancellationContext); + return operation.Execute(channelBinding, operationContext); } } - public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = await binding.GetReadChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetReadChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(); - return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/IOperation.cs b/src/MongoDB.Driver/Core/Operations/IOperation.cs index cfc7c79e6f6..8cebc23ff53 100644 --- a/src/MongoDB.Driver/Core/Operations/IOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/IOperation.cs @@ -20,13 +20,13 @@ namespace MongoDB.Driver.Core.Operations { internal interface IReadOperation { - TResult Execute(IReadBinding binding, OperationCancellationContext cancellationContext); - Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext); + TResult Execute(IReadBinding binding, OperationContext operationContext); + Task ExecuteAsync(IReadBinding binding, OperationContext operationContext); } internal interface IWriteOperation { - TResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext); - Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext); + TResult Execute(IWriteBinding binding, OperationContext operationContext); + Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext); } } diff --git a/src/MongoDB.Driver/Core/Operations/IRetryableOperation.cs b/src/MongoDB.Driver/Core/Operations/IRetryableOperation.cs index 7bb816915e9..0f0a222ea7f 100644 --- a/src/MongoDB.Driver/Core/Operations/IRetryableOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/IRetryableOperation.cs @@ -19,27 +19,27 @@ namespace MongoDB.Driver.Core.Operations { internal interface IExecutableInRetryableReadContext { - TResult Execute(RetryableReadContext context, OperationCancellationContext cancellationContext); - Task ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext); + TResult Execute(RetryableReadContext context, OperationContext operationContext); + Task ExecuteAsync(RetryableReadContext context, OperationContext operationContext); } internal interface IExecutableInRetryableWriteContext { - TResult Execute(RetryableWriteContext context, OperationCancellationContext cancellationContext); - Task ExecuteAsync(RetryableWriteContext context, OperationCancellationContext cancellationContext); + TResult Execute(RetryableWriteContext context, OperationContext operationContext); + Task ExecuteAsync(RetryableWriteContext context, OperationContext operationContext); } internal interface IRetryableReadOperation : IExecutableInRetryableReadContext { - TResult ExecuteAttempt(RetryableReadContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext); - Task ExecuteAttemptAsync(RetryableReadContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext); + TResult ExecuteAttempt(RetryableReadContext context, int attempt, long? transactionNumber, OperationContext operationContext); + Task ExecuteAttemptAsync(RetryableReadContext context, int attempt, long? transactionNumber, OperationContext operationContext); } internal interface IRetryableWriteOperation : IExecutableInRetryableWriteContext { WriteConcern WriteConcern { get; } - TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext); - Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext); + TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, OperationContext operationContext); + Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, OperationContext operationContext); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs b/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs index d0d06bd20fe..adf8ab855ba 100644 --- a/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs @@ -90,52 +90,52 @@ public bool RetryRequested set => _retryRequested = value; } - public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) { - return Execute(context, cancellationContext); + return Execute(context, operationContext); } } } - public IAsyncCursor Execute(RetryableReadContext context, OperationCancellationContext cancellationContext) + public IAsyncCursor Execute(RetryableReadContext context, OperationContext operationContext) { Ensure.IsNotNull(context, nameof(context)); using (BeginOperation()) { var operation = CreateOperation(); - var result = operation.Execute(context, cancellationContext); + var result = operation.Execute(context, operationContext); return CreateCursor(context.ChannelSource, context.Channel, result); } } - public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + return await ExecuteAsync(context, operationContext).ConfigureAwait(false); } } } - public async Task> ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(RetryableReadContext context, OperationContext operationContext) { Ensure.IsNotNull(context, nameof(context)); using (BeginOperation()) { var operation = CreateOperation(); - var result = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); return CreateCursor(context.ChannelSource, context.Channel, result); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs b/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs index 16f88eea2ca..a5b6c63c486 100644 --- a/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs @@ -86,26 +86,26 @@ public BsonDocument CreateCommand() }; } - public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var reply = operation.Execute(binding, cancellationContext); + var reply = operation.Execute(binding, operationContext); return CreateCursor(reply); } } - public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var reply = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); + var reply = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); return CreateCursor(reply); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs index d03b2b4addb..23d357d0392 100644 --- a/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs @@ -67,27 +67,27 @@ public bool RetryRequested set => _retryRequested = value; } - public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) { var operation = CreateOperation(); - return operation.Execute(context, cancellationContext); + return operation.Execute(context, operationContext); } } - public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) { var operation = CreateOperation(); - return await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs index 9a52a5890e3..a90021db9fc 100644 --- a/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs @@ -69,17 +69,17 @@ public bool RetryRequested set => _retryRequested = value; } - public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) { - return Execute(context, cancellationContext); + return Execute(context, operationContext); } } - public IAsyncCursor Execute(RetryableReadContext context, OperationCancellationContext cancellationContext) + public IAsyncCursor Execute(RetryableReadContext context, OperationContext operationContext) { Ensure.IsNotNull(context, nameof(context)); @@ -88,7 +88,7 @@ public IAsyncCursor Execute(RetryableReadContext context, Operatio var operation = CreateOperation(); try { - var result = operation.Execute(context, cancellationContext); + var result = operation.Execute(context, operationContext); return CreateCursor(context.ChannelSource, context.Channel, result); } catch (MongoCommandException ex) when (IsCollectionNotFoundException(ex)) @@ -98,17 +98,17 @@ public IAsyncCursor Execute(RetryableReadContext context, Operatio } } - public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + return await ExecuteAsync(context, operationContext).ConfigureAwait(false); } } - public async Task> ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(RetryableReadContext context, OperationContext operationContext) { Ensure.IsNotNull(context, nameof(context)); @@ -117,7 +117,7 @@ public async Task> ExecuteAsync(RetryableReadContext var operation = CreateOperation(); try { - var result = await operation.ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); return CreateCursor(context.ChannelSource, context.Channel, result); } catch (MongoCommandException ex) when (IsCollectionNotFoundException(ex)) diff --git a/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs b/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs index 439021408fa..29589106fff 100644 --- a/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs @@ -87,31 +87,31 @@ protected override BsonDocument CreateOutputOptions() } /// - public IAsyncCursor Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetReadChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetReadChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - var result = operation.Execute(channelBinding, cancellationContext); + var result = operation.Execute(channelBinding, operationContext); return new SingleBatchAsyncCursor(result); } } /// - public async Task> ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = await binding.GetReadChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetReadChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - var result = await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); return new SingleBatchAsyncCursor(result); } } diff --git a/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs index 1ebcd51bab9..39973e361d9 100644 --- a/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs @@ -169,30 +169,30 @@ protected override BsonDocument CreateOutputOptions() } /// - public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return operation.Execute(channelBinding, cancellationContext); + return operation.Execute(channelBinding, operationContext); } } /// - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/OperationExtensionMethods.cs b/src/MongoDB.Driver/Core/Operations/OperationExtensionMethods.cs index d9a29fa2cd8..9368a870b89 100644 --- a/src/MongoDB.Driver/Core/Operations/OperationExtensionMethods.cs +++ b/src/MongoDB.Driver/Core/Operations/OperationExtensionMethods.cs @@ -26,12 +26,12 @@ public static TResult Execute( IChannelSourceHandle channelSource, ReadPreference readPreference, ICoreSessionHandle session, - OperationCancellationContext cancellationContext) + OperationContext operationContext) { Ensure.IsNotNull(operation, nameof(operation)); using (var readBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), readPreference, session.Fork())) { - return operation.Execute(readBinding, cancellationContext); + return operation.Execute(readBinding, operationContext); } } @@ -39,12 +39,12 @@ public static TResult Execute( this IWriteOperation operation, IChannelSourceHandle channelSource, ICoreSessionHandle session, - OperationCancellationContext cancellationContext) + OperationContext operationContext) { Ensure.IsNotNull(operation, nameof(operation)); using (var writeBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), ReadPreference.Primary, session.Fork())) { - return operation.Execute(writeBinding, cancellationContext); + return operation.Execute(writeBinding, operationContext); } } @@ -53,12 +53,12 @@ public static async Task ExecuteAsync( IChannelSourceHandle channelSource, ReadPreference readPreference, ICoreSessionHandle session, - OperationCancellationContext cancellationContext) + OperationContext operationContext) { Ensure.IsNotNull(operation, nameof(operation)); using (var readBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), readPreference, session.Fork())) { - return await operation.ExecuteAsync(readBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(readBinding, operationContext).ConfigureAwait(false); } } @@ -66,12 +66,12 @@ public static async Task ExecuteAsync( this IWriteOperation operation, IChannelSourceHandle channelSource, ICoreSessionHandle session, - OperationCancellationContext cancellationContext) + OperationContext operationContext) { Ensure.IsNotNull(operation, nameof(operation)); using (var writeBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), ReadPreference.Primary, session.Fork())) { - return await operation.ExecuteAsync(writeBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(writeBinding, operationContext).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs index d857aac7205..67e31222fb7 100644 --- a/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs @@ -42,54 +42,54 @@ public bool RetryRequested set => _retryRequested = value; } - public TCommandResult Execute(IReadBinding binding, OperationCancellationContext cancellationContext) + public TCommandResult Execute(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = RetryableReadContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) { - return Execute(context, cancellationContext); + return Execute(context, operationContext); } } - public TCommandResult Execute(RetryableReadContext context, OperationCancellationContext cancellationContext) + public TCommandResult Execute(RetryableReadContext context, OperationContext operationContext) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginOperation()) { - return RetryableReadOperationExecutor.Execute(this, context, cancellationContext); + return RetryableReadOperationExecutor.Execute(this, context, operationContext); } } - public async Task ExecuteAsync(IReadBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + return await ExecuteAsync(context, operationContext).ConfigureAwait(false); } } - public async Task ExecuteAsync(RetryableReadContext context, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(RetryableReadContext context, OperationContext operationContext) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginOperation()) { - return await RetryableReadOperationExecutor.ExecuteAsync(this, context, cancellationContext).ConfigureAwait(false); + return await RetryableReadOperationExecutor.ExecuteAsync(this, context, operationContext).ConfigureAwait(false); } } - public TCommandResult ExecuteAttempt(RetryableReadContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext) + public TCommandResult ExecuteAttempt(RetryableReadContext context, int attempt, long? transactionNumber, OperationContext operationContext) { - return ExecuteProtocol(context.Channel, context.Binding.Session, context.Binding.ReadPreference, cancellationContext.CancellationToken); + return ExecuteProtocol(context.Channel, context.Binding.Session, context.Binding.ReadPreference, operationContext.CancellationToken); } - public Task ExecuteAttemptAsync(RetryableReadContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext) + public Task ExecuteAttemptAsync(RetryableReadContext context, int attempt, long? transactionNumber, OperationContext operationContext) { - return ExecuteProtocolAsync(context.Channel, context.Binding.Session, context.Binding.ReadPreference, cancellationContext.CancellationToken); + return ExecuteProtocolAsync(context.Channel, context.Binding.Session, context.Binding.ReadPreference, operationContext.CancellationToken); } } } diff --git a/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs index d6d116c4790..69677409b5d 100644 --- a/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs @@ -82,31 +82,31 @@ public BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescript }; } - public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return operation.Execute(channelBinding, cancellationContext); + return operation.Execute(channelBinding, operationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs b/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs index 2e4b6c5c336..9921dd38b2f 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs @@ -24,12 +24,12 @@ internal sealed class RetryableReadContext : IDisposable { #region static - public static RetryableReadContext Create(IReadBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) + public static RetryableReadContext Create(IReadBinding binding, bool retryRequested, OperationContext operationContext) { var context = new RetryableReadContext(binding, retryRequested); try { - context.Initialize(cancellationContext); + context.Initialize(operationContext); ChannelPinningHelper.PinChannellIfRequired( context.ChannelSource, @@ -45,12 +45,12 @@ public static RetryableReadContext Create(IReadBinding binding, bool retryReques } } - public static async Task CreateAsync(IReadBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) + public static async Task CreateAsync(IReadBinding binding, bool retryRequested, OperationContext operationContext) { var context = new RetryableReadContext(binding, retryRequested); try { - await context.InitializeAsync(cancellationContext).ConfigureAwait(false); + await context.InitializeAsync(operationContext).ConfigureAwait(false); ChannelPinningHelper.PinChannellIfRequired( context.ChannelSource, @@ -112,33 +112,33 @@ public void ReplaceChannelSource(IChannelSourceHandle channelSource) _channel = null; } - private void Initialize(OperationCancellationContext cancellationContext) + private void Initialize(OperationContext operationContext) { - _channelSource = _binding.GetReadChannelSource(cancellationContext); + _channelSource = _binding.GetReadChannelSource(operationContext); try { - _channel = _channelSource.GetChannel(cancellationContext); + _channel = _channelSource.GetChannel(operationContext); } catch (Exception ex) when (RetryableReadOperationExecutor.ShouldConnectionAcquireBeRetried(this, ex)) { - ReplaceChannelSource(_binding.GetReadChannelSource(cancellationContext)); - ReplaceChannel(_channelSource.GetChannel(cancellationContext)); + ReplaceChannelSource(_binding.GetReadChannelSource(operationContext)); + ReplaceChannel(_channelSource.GetChannel(operationContext)); } } - private async Task InitializeAsync(OperationCancellationContext cancellationContext) + private async Task InitializeAsync(OperationContext operationContext) { - _channelSource = await _binding.GetReadChannelSourceAsync(cancellationContext).ConfigureAwait(false); + _channelSource = await _binding.GetReadChannelSourceAsync(operationContext).ConfigureAwait(false); try { - _channel = await _channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false); + _channel = await _channelSource.GetChannelAsync(operationContext).ConfigureAwait(false); } catch (Exception ex) when (RetryableReadOperationExecutor.ShouldConnectionAcquireBeRetried(this, ex)) { - ReplaceChannelSource(await _binding.GetReadChannelSourceAsync(cancellationContext).ConfigureAwait(false)); - ReplaceChannel(await _channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)); + ReplaceChannelSource(await _binding.GetReadChannelSourceAsync(operationContext).ConfigureAwait(false)); + ReplaceChannel(await _channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)); } } } diff --git a/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs b/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs index 534360ad6cc..76354e1413d 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs @@ -22,25 +22,25 @@ namespace MongoDB.Driver.Core.Operations internal static class RetryableReadOperationExecutor { // public static methods - public static TResult Execute(IRetryableReadOperation operation, IReadBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) + public static TResult Execute(IRetryableReadOperation operation, IReadBinding binding, bool retryRequested, OperationContext operationContext) { - using (var context = RetryableReadContext.Create(binding, retryRequested, cancellationContext)) + using (var context = RetryableReadContext.Create(binding, retryRequested, operationContext)) { - return Execute(operation, context, cancellationContext); + return Execute(operation, context, operationContext); } } - public static TResult Execute(IRetryableReadOperation operation, RetryableReadContext context, OperationCancellationContext cancellationContext) + public static TResult Execute(IRetryableReadOperation operation, RetryableReadContext context, OperationContext operationContext) { if (!ShouldReadBeRetried(context)) { - return operation.ExecuteAttempt(context, attempt: 1, transactionNumber: null, cancellationContext); + return operation.ExecuteAttempt(context, attempt: 1, transactionNumber: null, operationContext); } Exception originalException; try { - return operation.ExecuteAttempt(context, attempt: 1, transactionNumber: null, cancellationContext); + return operation.ExecuteAttempt(context, attempt: 1, transactionNumber: null, operationContext); } catch (Exception ex) when (RetryabilityHelper.IsRetryableReadException(ex)) @@ -50,8 +50,8 @@ public static TResult Execute(IRetryableReadOperation operatio try { - context.ReplaceChannelSource(context.Binding.GetReadChannelSource(new[] { context.ChannelSource.ServerDescription }, cancellationContext)); - context.ReplaceChannel(context.ChannelSource.GetChannel(cancellationContext)); + context.ReplaceChannelSource(context.Binding.GetReadChannelSource(new[] { context.ChannelSource.ServerDescription }, operationContext)); + context.ReplaceChannel(context.ChannelSource.GetChannel(operationContext)); } catch { @@ -60,7 +60,7 @@ public static TResult Execute(IRetryableReadOperation operatio try { - return operation.ExecuteAttempt(context, attempt: 2, transactionNumber: null, cancellationContext); + return operation.ExecuteAttempt(context, attempt: 2, transactionNumber: null, operationContext); } catch (Exception ex) when (ShouldThrowOriginalException(ex)) { @@ -68,25 +68,25 @@ public static TResult Execute(IRetryableReadOperation operatio } } - public static async Task ExecuteAsync(IRetryableReadOperation operation, IReadBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) + public static async Task ExecuteAsync(IRetryableReadOperation operation, IReadBinding binding, bool retryRequested, OperationContext operationContext) { - using (var context = await RetryableReadContext.CreateAsync(binding, retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(binding, retryRequested, operationContext).ConfigureAwait(false)) { - return await ExecuteAsync(operation, context, cancellationContext).ConfigureAwait(false); + return await ExecuteAsync(operation, context, operationContext).ConfigureAwait(false); } } - public static async Task ExecuteAsync(IRetryableReadOperation operation, RetryableReadContext context, OperationCancellationContext cancellationContext) + public static async Task ExecuteAsync(IRetryableReadOperation operation, RetryableReadContext context, OperationContext operationContext) { if (!ShouldReadBeRetried(context)) { - return await operation.ExecuteAttemptAsync(context, attempt: 1, transactionNumber: null, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(context, attempt: 1, transactionNumber: null, operationContext).ConfigureAwait(false); } Exception originalException; try { - return await operation.ExecuteAttemptAsync(context, attempt: 1, transactionNumber: null, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(context, attempt: 1, transactionNumber: null, operationContext).ConfigureAwait(false); } catch (Exception ex) when (RetryabilityHelper.IsRetryableReadException(ex)) { @@ -95,8 +95,8 @@ public static async Task ExecuteAsync(IRetryableReadOperation< try { - context.ReplaceChannelSource(context.Binding.GetReadChannelSource(new[] { context.ChannelSource.ServerDescription }, cancellationContext)); - context.ReplaceChannel(context.ChannelSource.GetChannel(cancellationContext)); + context.ReplaceChannelSource(context.Binding.GetReadChannelSource(new[] { context.ChannelSource.ServerDescription }, operationContext)); + context.ReplaceChannel(context.ChannelSource.GetChannel(operationContext)); } catch { @@ -105,7 +105,7 @@ public static async Task ExecuteAsync(IRetryableReadOperation< try { - return await operation.ExecuteAttemptAsync(context, attempt: 2, transactionNumber: null, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(context, attempt: 2, transactionNumber: null, operationContext).ConfigureAwait(false); } catch (Exception ex) when (ShouldThrowOriginalException(ex)) { diff --git a/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs b/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs index 89e106ccacd..5ff3185d9b3 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs @@ -86,33 +86,33 @@ public WriteConcern WriteConcern set { _writeConcern = value; } } - public virtual BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public virtual BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { - using (var context = RetryableWriteContext.Create(binding, _retryRequested, cancellationContext)) + using (var context = RetryableWriteContext.Create(binding, _retryRequested, operationContext)) { - return Execute(context, cancellationContext); + return Execute(context, operationContext); } } - public virtual BsonDocument Execute(RetryableWriteContext context, OperationCancellationContext cancellationContext) + public virtual BsonDocument Execute(RetryableWriteContext context, OperationContext operationContext) { - return RetryableWriteOperationExecutor.Execute(this, context, cancellationContext); + return RetryableWriteOperationExecutor.Execute(this, context, operationContext); } - public virtual async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public virtual async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { - using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) { - return await ExecuteAsync(context, cancellationContext).ConfigureAwait(false); + return await ExecuteAsync(context, operationContext).ConfigureAwait(false); } } - public virtual Task ExecuteAsync(RetryableWriteContext context, OperationCancellationContext cancellationContext) + public virtual Task ExecuteAsync(RetryableWriteContext context, OperationContext operationContext) { - return RetryableWriteOperationExecutor.ExecuteAsync(this, context, cancellationContext); + return RetryableWriteOperationExecutor.ExecuteAsync(this, context, operationContext); } - public BsonDocument ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext) + public BsonDocument ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, OperationContext operationContext) { var args = GetCommandArgs(context, attempt, transactionNumber); // TODO: CSOT implement timeout in Command Execution @@ -128,10 +128,10 @@ public BsonDocument ExecuteAttempt(RetryableWriteContext context, int attempt, l args.ResponseHandling, BsonDocumentSerializer.Instance, args.MessageEncoderSettings, - cancellationContext.CancellationToken); + operationContext.CancellationToken); } - public Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, OperationCancellationContext cancellationContext) + public Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, OperationContext operationContext) { var args = GetCommandArgs(context, attempt, transactionNumber); // TODO: CSOT implement timeout in Command Execution @@ -147,7 +147,7 @@ public Task ExecuteAttemptAsync(RetryableWriteContext context, int args.ResponseHandling, BsonDocumentSerializer.Instance, args.MessageEncoderSettings, - cancellationContext.CancellationToken); + operationContext.CancellationToken); } protected abstract BsonDocument CreateCommand(ICoreSessionHandle session, int attempt, long? transactionNumber); diff --git a/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs b/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs index 656db3c9d7a..d4b69a5261d 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs @@ -26,12 +26,12 @@ internal sealed class RetryableWriteContext : IDisposable { #region static - public static RetryableWriteContext Create(IWriteBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) + public static RetryableWriteContext Create(IWriteBinding binding, bool retryRequested, OperationContext operationContext) { var context = new RetryableWriteContext(binding, retryRequested); try { - context.Initialize(cancellationContext); + context.Initialize(operationContext); ChannelPinningHelper.PinChannellIfRequired( context.ChannelSource, @@ -47,12 +47,12 @@ public static RetryableWriteContext Create(IWriteBinding binding, bool retryRequ } } - public static async Task CreateAsync(IWriteBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) + public static async Task CreateAsync(IWriteBinding binding, bool retryRequested, OperationContext operationContext) { var context = new RetryableWriteContext(binding, retryRequested); try { - await context.InitializeAsync(cancellationContext).ConfigureAwait(false); + await context.InitializeAsync(operationContext).ConfigureAwait(false); ChannelPinningHelper.PinChannellIfRequired( context.ChannelSource, @@ -125,35 +125,35 @@ public void ReplaceChannelSource(IChannelSourceHandle channelSource) _channel = null; } - private void Initialize(OperationCancellationContext cancellationContext) + private void Initialize(OperationContext operationContext) { - _channelSource = _binding.GetWriteChannelSource(cancellationContext); + _channelSource = _binding.GetWriteChannelSource(operationContext); var serverDescription = _channelSource.ServerDescription; try { - _channel = _channelSource.GetChannel(cancellationContext); + _channel = _channelSource.GetChannel(operationContext); } catch (Exception ex) when (RetryableWriteOperationExecutor.ShouldConnectionAcquireBeRetried(this, serverDescription, ex)) { - ReplaceChannelSource(_binding.GetWriteChannelSource(cancellationContext)); - ReplaceChannel(_channelSource.GetChannel(cancellationContext)); + ReplaceChannelSource(_binding.GetWriteChannelSource(operationContext)); + ReplaceChannel(_channelSource.GetChannel(operationContext)); } } - private async Task InitializeAsync(OperationCancellationContext cancellationContext) + private async Task InitializeAsync(OperationContext operationContext) { - _channelSource = await _binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false); + _channelSource = await _binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false); var serverDescription = _channelSource.ServerDescription; try { - _channel = await _channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false); + _channel = await _channelSource.GetChannelAsync(operationContext).ConfigureAwait(false); } catch (Exception ex) when (RetryableWriteOperationExecutor.ShouldConnectionAcquireBeRetried(this, serverDescription, ex)) { - ReplaceChannelSource(await _binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)); - ReplaceChannel(await _channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)); + ReplaceChannelSource(await _binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)); + ReplaceChannel(await _channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)); } } } diff --git a/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs b/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs index d6773a8c342..6f5d01ebfef 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs @@ -24,26 +24,26 @@ namespace MongoDB.Driver.Core.Operations internal static class RetryableWriteOperationExecutor { // public static methods - public static TResult Execute(IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) + public static TResult Execute(IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested, OperationContext operationContext) { - using (var context = RetryableWriteContext.Create(binding, retryRequested, cancellationContext)) + using (var context = RetryableWriteContext.Create(binding, retryRequested, operationContext)) { - return Execute(operation, context, cancellationContext); + return Execute(operation, context, operationContext); } } - public static TResult Execute(IRetryableWriteOperation operation, RetryableWriteContext context, OperationCancellationContext cancellationContext) + public static TResult Execute(IRetryableWriteOperation operation, RetryableWriteContext context, OperationContext operationContext) { if (!AreRetriesAllowed(operation, context)) { - return operation.ExecuteAttempt(context, 1, null, cancellationContext); + return operation.ExecuteAttempt(context, 1, null, operationContext); } var transactionNumber = context.Binding.Session.AdvanceTransactionNumber(); Exception originalException; try { - return operation.ExecuteAttempt(context, 1, transactionNumber, cancellationContext); + return operation.ExecuteAttempt(context, 1, transactionNumber, operationContext); } catch (Exception ex) when (RetryabilityHelper.IsRetryableWriteException(ex)) { @@ -52,8 +52,8 @@ public static TResult Execute(IRetryableWriteOperation operati try { - context.ReplaceChannelSource(context.Binding.GetWriteChannelSource(new[] { context.ChannelSource.ServerDescription }, cancellationContext)); - context.ReplaceChannel(context.ChannelSource.GetChannel(cancellationContext)); + context.ReplaceChannelSource(context.Binding.GetWriteChannelSource(new[] { context.ChannelSource.ServerDescription }, operationContext)); + context.ReplaceChannel(context.ChannelSource.GetChannel(operationContext)); } catch { @@ -67,7 +67,7 @@ public static TResult Execute(IRetryableWriteOperation operati try { - return operation.ExecuteAttempt(context, 2, transactionNumber, cancellationContext); + return operation.ExecuteAttempt(context, 2, transactionNumber, operationContext); } catch (Exception ex) when (ShouldThrowOriginalException(ex)) { @@ -75,26 +75,26 @@ public static TResult Execute(IRetryableWriteOperation operati } } - public async static Task ExecuteAsync(IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested, OperationCancellationContext cancellationContext) + public async static Task ExecuteAsync(IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested, OperationContext operationContext) { - using (var context = await RetryableWriteContext.CreateAsync(binding, retryRequested, cancellationContext).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(binding, retryRequested, operationContext).ConfigureAwait(false)) { - return await ExecuteAsync(operation, context, cancellationContext).ConfigureAwait(false); + return await ExecuteAsync(operation, context, operationContext).ConfigureAwait(false); } } - public static async Task ExecuteAsync(IRetryableWriteOperation operation, RetryableWriteContext context, OperationCancellationContext cancellationContext) + public static async Task ExecuteAsync(IRetryableWriteOperation operation, RetryableWriteContext context, OperationContext operationContext) { if (!AreRetriesAllowed(operation, context)) { - return await operation.ExecuteAttemptAsync(context, 1, null, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(context, 1, null, operationContext).ConfigureAwait(false); } var transactionNumber = context.Binding.Session.AdvanceTransactionNumber(); Exception originalException; try { - return await operation.ExecuteAttemptAsync(context, 1, transactionNumber, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(context, 1, transactionNumber, operationContext).ConfigureAwait(false); } catch (Exception ex) when (RetryabilityHelper.IsRetryableWriteException(ex)) { @@ -103,8 +103,8 @@ public static async Task ExecuteAsync(IRetryableWriteOperation try { - context.ReplaceChannelSource(await context.Binding.GetWriteChannelSourceAsync(new[] { context.ChannelSource.ServerDescription }, cancellationContext).ConfigureAwait(false)); - context.ReplaceChannel(await context.ChannelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)); + context.ReplaceChannelSource(await context.Binding.GetWriteChannelSourceAsync(new[] { context.ChannelSource.ServerDescription }, operationContext).ConfigureAwait(false)); + context.ReplaceChannel(await context.ChannelSource.GetChannelAsync(operationContext).ConfigureAwait(false)); } catch { @@ -118,7 +118,7 @@ public static async Task ExecuteAsync(IRetryableWriteOperation try { - return await operation.ExecuteAttemptAsync(context, 2, transactionNumber, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(context, 2, transactionNumber, operationContext).ConfigureAwait(false); } catch (Exception ex) when (ShouldThrowOriginalException(ex)) { diff --git a/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs index de907057525..ef06bd5d506 100644 --- a/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs @@ -43,27 +43,27 @@ public UpdateSearchIndexOperation( _messageEncoderSettings = Ensure.IsNotNull(messageEncoderSettings, nameof(messageEncoderSettings)); } - public BsonDocument Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) { using (EventContext.BeginOperation("updateSearchIndex")) - using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) - using (var channel = channelSource.GetChannel(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) + using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return operation.Execute(channelBinding, cancellationContext); + return operation.Execute(channelBinding, operationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { using (EventContext.BeginOperation("updateSearchIndex")) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) - using (var channel = await channelSource.GetChannelAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) + using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return await operation.ExecuteAsync(channelBinding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs index 0fc7eff2138..a6cfaa792f0 100644 --- a/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs @@ -38,25 +38,25 @@ public ReadPreference ReadPreference set => _readPreference = Ensure.IsNotNull(value, nameof(value)); } - public TCommandResult Execute(IWriteBinding binding, OperationCancellationContext cancellationContext) + public TCommandResult Execute(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(cancellationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext)) { - return ExecuteProtocol(channelSource, binding.Session, _readPreference, cancellationContext); + return ExecuteProtocol(channelSource, binding.Session, _readPreference, operationContext); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationCancellationContext cancellationContext) + public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(cancellationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) { - return await ExecuteProtocolAsync(channelSource, binding.Session, _readPreference, cancellationContext).ConfigureAwait(false); + return await ExecuteProtocolAsync(channelSource, binding.Session, _readPreference, operationContext).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/Core/Servers/IServer.cs b/src/MongoDB.Driver/Core/Servers/IServer.cs index 7078d39b1b8..da1e6f49138 100644 --- a/src/MongoDB.Driver/Core/Servers/IServer.cs +++ b/src/MongoDB.Driver/Core/Servers/IServer.cs @@ -29,8 +29,8 @@ internal interface IServer EndPoint EndPoint { get; } ServerId ServerId { get; } - IChannelHandle GetChannel(OperationCancellationContext cancellationContext); - Task GetChannelAsync(OperationCancellationContext cancellationContext); + IChannelHandle GetChannel(OperationContext operationContext); + Task GetChannelAsync(OperationContext operationContext); } internal interface IClusterableServer : IServer, IDisposable diff --git a/src/MongoDB.Driver/Core/Servers/Server.cs b/src/MongoDB.Driver/Core/Servers/Server.cs index 9727fdcde79..fa93175f1c0 100644 --- a/src/MongoDB.Driver/Core/Servers/Server.cs +++ b/src/MongoDB.Driver/Core/Servers/Server.cs @@ -107,7 +107,7 @@ public void Dispose() public void HandleExceptionOnOpen(Exception exception) => HandleBeforeHandshakeCompletesException(exception); - public IChannelHandle GetChannel(OperationCancellationContext cancellationContext) + public IChannelHandle GetChannel(OperationContext operationContext) { ThrowIfNotOpen(); @@ -115,7 +115,7 @@ public IChannelHandle GetChannel(OperationCancellationContext cancellationContex { Interlocked.Increment(ref _outstandingOperationsCount); - var connection = _connectionPool.AcquireConnection(cancellationContext); + var connection = _connectionPool.AcquireConnection(operationContext); return new ServerChannel(this, connection); } catch @@ -126,14 +126,14 @@ public IChannelHandle GetChannel(OperationCancellationContext cancellationContex } } - public async Task GetChannelAsync(OperationCancellationContext cancellationContext) + public async Task GetChannelAsync(OperationContext operationContext) { ThrowIfNotOpen(); try { Interlocked.Increment(ref _outstandingOperationsCount); - var connection = await _connectionPool.AcquireConnectionAsync(cancellationContext).ConfigureAwait(false); + var connection = await _connectionPool.AcquireConnectionAsync(operationContext).ConfigureAwait(false); return new ServerChannel(this, connection); } catch diff --git a/src/MongoDB.Driver/GridFS/GridFSBucket.cs b/src/MongoDB.Driver/GridFS/GridFSBucket.cs index b30af6a5991..bb0cff5c5ce 100644 --- a/src/MongoDB.Driver/GridFS/GridFSBucket.cs +++ b/src/MongoDB.Driver/GridFS/GridFSBucket.cs @@ -84,14 +84,14 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); - using (var binding = GetSingleServerReadWriteBinding(operationCancellationContext)) + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + using (var binding = GetSingleServerReadWriteBinding(operationContext)) { var filesCollectionDeleteOperation = CreateDeleteFileOperation(id); - var filesCollectionDeleteResult = filesCollectionDeleteOperation.Execute(binding, operationCancellationContext); + var filesCollectionDeleteResult = filesCollectionDeleteOperation.Execute(binding, operationContext); var chunksDeleteOperation = CreateDeleteChunksOperation(id); - chunksDeleteOperation.Execute(binding, operationCancellationContext); + chunksDeleteOperation.Execute(binding, operationContext); if (filesCollectionDeleteResult.DeletedCount == 0) { @@ -105,14 +105,14 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); - using (var binding = await GetSingleServerReadWriteBindingAsync(operationCancellationContext).ConfigureAwait(false)) + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) { var filesCollectionDeleteOperation = CreateDeleteFileOperation(id); - var filesCollectionDeleteResult = await filesCollectionDeleteOperation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); + var filesCollectionDeleteResult = await filesCollectionDeleteOperation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); var chunksDeleteOperation = CreateDeleteChunksOperation(id); - await chunksDeleteOperation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); + await chunksDeleteOperation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); if (filesCollectionDeleteResult.DeletedCount == 0) { @@ -126,11 +126,11 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = GetSingleServerReadBinding(operationCancellationContext)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfo(binding, id, operationCancellationContext); + var fileInfo = GetFileInfo(binding, id, operationContext); return DownloadAsBytesHelper(binding, fileInfo, options, cancellationToken); } } @@ -140,11 +140,11 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoAsync(binding, id, operationCancellationContext).ConfigureAwait(false); + var fileInfo = await GetFileInfoAsync(binding, id, operationContext).ConfigureAwait(false); return await DownloadAsBytesHelperAsync(binding, fileInfo, options, cancellationToken).ConfigureAwait(false); } } @@ -154,12 +154,12 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filename, nameof(filename)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = GetSingleServerReadBinding(operationCancellationContext)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfoByName(binding, filename, options.Revision, operationCancellationContext); + var fileInfo = GetFileInfoByName(binding, filename, options.Revision, operationContext); return DownloadAsBytesHelper(binding, fileInfo, options, cancellationToken); } } @@ -169,12 +169,12 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filename, nameof(filename)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, operationCancellationContext).ConfigureAwait(false); + var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, operationContext).ConfigureAwait(false); return await DownloadAsBytesHelperAsync(binding, fileInfo, options, cancellationToken).ConfigureAwait(false); } } @@ -185,11 +185,11 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(destination, nameof(destination)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = GetSingleServerReadBinding(operationCancellationContext)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfo(binding, id, operationCancellationContext); + var fileInfo = GetFileInfo(binding, id, operationContext); DownloadToStreamHelper(binding, fileInfo, destination, options, cancellationToken); } } @@ -200,11 +200,11 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(destination, nameof(destination)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoAsync(binding, id, operationCancellationContext).ConfigureAwait(false); + var fileInfo = await GetFileInfoAsync(binding, id, operationContext).ConfigureAwait(false); await DownloadToStreamHelperAsync(binding, fileInfo, destination, options, cancellationToken).ConfigureAwait(false); } } @@ -215,12 +215,12 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(destination, nameof(destination)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = GetSingleServerReadBinding(operationCancellationContext)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfoByName(binding, filename, options.Revision, operationCancellationContext); + var fileInfo = GetFileInfoByName(binding, filename, options.Revision, operationContext); DownloadToStreamHelper(binding, fileInfo, destination, options, cancellationToken); } } @@ -231,12 +231,12 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(destination, nameof(destination)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, operationCancellationContext).ConfigureAwait(false); + var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, operationContext).ConfigureAwait(false); await DownloadToStreamHelperAsync(binding, fileInfo, destination, options, cancellationToken).ConfigureAwait(false); } } @@ -245,18 +245,18 @@ public ImmutableGridFSBucketOptions Options public void Drop(CancellationToken cancellationToken = default(CancellationToken)) { // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); var filesCollectionNamespace = this.GetFilesCollectionNamespace(); var chunksCollectionNamespace = this.GetChunksCollectionNamespace(); var messageEncoderSettings = this.GetMessageEncoderSettings(); - using (var binding = GetSingleServerReadWriteBinding(operationCancellationContext)) + using (var binding = GetSingleServerReadWriteBinding(operationContext)) { var filesCollectionDropOperation = CreateDropCollectionOperation(filesCollectionNamespace, messageEncoderSettings); - filesCollectionDropOperation.Execute(binding, operationCancellationContext); + filesCollectionDropOperation.Execute(binding, operationContext); var chunksCollectionDropOperation = CreateDropCollectionOperation(chunksCollectionNamespace, messageEncoderSettings); - chunksCollectionDropOperation.Execute(binding, operationCancellationContext); + chunksCollectionDropOperation.Execute(binding, operationContext); } } @@ -264,18 +264,18 @@ public ImmutableGridFSBucketOptions Options public async Task DropAsync(CancellationToken cancellationToken = default(CancellationToken)) { // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); var filesCollectionNamespace = this.GetFilesCollectionNamespace(); var chunksCollectionNamespace = this.GetChunksCollectionNamespace(); var messageEncoderSettings = this.GetMessageEncoderSettings(); - using (var binding = await GetSingleServerReadWriteBindingAsync(operationCancellationContext).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) { var filesCollectionDropOperation = CreateDropCollectionOperation(filesCollectionNamespace, messageEncoderSettings); - await filesCollectionDropOperation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); + await filesCollectionDropOperation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); var chunksCollectionDropOperation = CreateDropCollectionOperation(chunksCollectionNamespace, messageEncoderSettings); - await chunksCollectionDropOperation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); + await chunksCollectionDropOperation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); } } @@ -284,14 +284,14 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filter, nameof(filter)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSFindOptions(); var translationOptions = _database.Client.Settings.TranslationOptions; var operation = CreateFindOperation(filter, options, translationOptions); - using (var binding = GetSingleServerReadBinding(operationCancellationContext)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - return operation.Execute(binding, operationCancellationContext); + return operation.Execute(binding, operationContext); } } @@ -300,14 +300,14 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filter, nameof(filter)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSFindOptions(); var translationOptions = _database.Client.Settings.TranslationOptions; var operation = CreateFindOperation(filter, options, translationOptions); - using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - return await operation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); } } @@ -316,11 +316,11 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = GetSingleServerReadBinding(operationCancellationContext)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfo(binding, id, operationCancellationContext); + var fileInfo = GetFileInfo(binding, id, operationContext); return CreateDownloadStream(binding.Fork(), fileInfo, options, cancellationToken); } } @@ -330,11 +330,11 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); - using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoAsync(binding, id, operationCancellationContext).ConfigureAwait(false); + var fileInfo = await GetFileInfoAsync(binding, id, operationContext).ConfigureAwait(false); return CreateDownloadStream(binding.Fork(), fileInfo, options, cancellationToken); } } @@ -344,12 +344,12 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filename, nameof(filename)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = GetSingleServerReadBinding(operationCancellationContext)) + using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfoByName(binding, filename, options.Revision, operationCancellationContext); + var fileInfo = GetFileInfoByName(binding, filename, options.Revision, operationContext); return CreateDownloadStream(binding.Fork(), fileInfo, options); } } @@ -359,12 +359,12 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filename, nameof(filename)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); - using (var binding = await GetSingleServerReadBindingAsync(operationCancellationContext).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, operationCancellationContext).ConfigureAwait(false); + var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, operationContext).ConfigureAwait(false); return CreateDownloadStream(binding.Fork(), fileInfo, options); } } @@ -375,12 +375,12 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(filename, nameof(filename)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); - using (var binding = GetSingleServerReadWriteBinding(operationCancellationContext)) + using (var binding = GetSingleServerReadWriteBinding(operationContext)) { - EnsureIndexes(binding, operationCancellationContext); + EnsureIndexes(binding, operationContext); return CreateUploadStream(binding, id, filename, options); } } @@ -391,12 +391,12 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(filename, nameof(filename)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); - using (var binding = await GetSingleServerReadWriteBindingAsync(operationCancellationContext).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) { - await EnsureIndexesAsync(binding, operationCancellationContext).ConfigureAwait(false); + await EnsureIndexesAsync(binding, operationContext).ConfigureAwait(false); return CreateUploadStream(binding, id, filename, options); } } @@ -407,11 +407,11 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(newFilename, nameof(newFilename)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); var renameOperation = CreateRenameOperation(id, newFilename); - using (var binding = GetSingleServerReadWriteBinding(operationCancellationContext)) + using (var binding = GetSingleServerReadWriteBinding(operationContext)) { - var result = renameOperation.Execute(binding, operationCancellationContext); + var result = renameOperation.Execute(binding, operationContext); if (result.IsModifiedCountAvailable && result.ModifiedCount == 0) { @@ -426,11 +426,11 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(newFilename, nameof(newFilename)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); var renameOperation = CreateRenameOperation(id, newFilename); - using (var binding = await GetSingleServerReadWriteBindingAsync(operationCancellationContext).ConfigureAwait(false)) + using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) { - var result = await renameOperation.ExecuteAsync(binding, operationCancellationContext).ConfigureAwait(false); + var result = await renameOperation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); if (result.IsModifiedCountAvailable && result.ModifiedCount == 0) { @@ -446,7 +446,7 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(source, nameof(source)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); using (var sourceStream = new MemoryStream(source)) @@ -462,7 +462,7 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(source, nameof(source)); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); using (var sourceStream = new MemoryStream(source)) @@ -570,28 +570,28 @@ private bool ChunksCollectionIndexesExist(List indexes) return IndexExists(indexes, key); } - private bool ChunksCollectionIndexesExist(IReadBindingHandle binding, OperationCancellationContext cancellationContext) + private bool ChunksCollectionIndexesExist(IReadBindingHandle binding, OperationContext operationContext) { - var indexes = ListIndexes(binding, this.GetChunksCollectionNamespace(), cancellationContext); + var indexes = ListIndexes(binding, this.GetChunksCollectionNamespace(), operationContext); return ChunksCollectionIndexesExist(indexes); } - private async Task ChunksCollectionIndexesExistAsync(IReadBindingHandle binding, OperationCancellationContext cancellationContext) + private async Task ChunksCollectionIndexesExistAsync(IReadBindingHandle binding, OperationContext operationContext) { - var indexes = await ListIndexesAsync(binding, this.GetChunksCollectionNamespace(), cancellationContext).ConfigureAwait(false); + var indexes = await ListIndexesAsync(binding, this.GetChunksCollectionNamespace(), operationContext).ConfigureAwait(false); return ChunksCollectionIndexesExist(indexes); } - private void CreateChunksCollectionIndexes(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) + private void CreateChunksCollectionIndexes(IReadWriteBindingHandle binding, OperationContext operationContext) { var operation = CreateCreateChunksCollectionIndexesOperation(); - operation.Execute(binding, cancellationContext); + operation.Execute(binding, operationContext); } - private async Task CreateChunksCollectionIndexesAsync(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) + private async Task CreateChunksCollectionIndexesAsync(IReadWriteBindingHandle binding, OperationContext operationContext) { var operation = CreateCreateChunksCollectionIndexesOperation(); - await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); + await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); } internal CreateIndexesOperation CreateCreateChunksCollectionIndexesOperation() @@ -656,16 +656,16 @@ private BulkMixedWriteOperation CreateDeleteFileOperation(TFileId id) this.GetMessageEncoderSettings()); } - private void CreateFilesCollectionIndexes(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) + private void CreateFilesCollectionIndexes(IReadWriteBindingHandle binding, OperationContext operationContext) { var operation = CreateCreateFilesCollectionIndexesOperation(); - operation.Execute(binding, cancellationContext); + operation.Execute(binding, operationContext); } - private async Task CreateFilesCollectionIndexesAsync(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) + private async Task CreateFilesCollectionIndexesAsync(IReadWriteBindingHandle binding, OperationContext operationContext) { var operation = CreateCreateFilesCollectionIndexesOperation(); - await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); + await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); } private FindOperation> CreateFindOperation( @@ -858,23 +858,23 @@ private GridFSUploadStream CreateUploadStream(IReadWriteBindingHandle b } } - private void EnsureIndexes(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) + private void EnsureIndexes(IReadWriteBindingHandle binding, OperationContext operationContext) { - _ensureIndexesSemaphore.Wait(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken); + _ensureIndexesSemaphore.Wait(operationContext.RemainingTimeout, operationContext.CancellationToken); try { if (!_ensureIndexesDone) { - var isFilesCollectionEmpty = IsFilesCollectionEmpty(binding, cancellationContext); + var isFilesCollectionEmpty = IsFilesCollectionEmpty(binding, operationContext); if (isFilesCollectionEmpty) { - if (!FilesCollectionIndexesExist(binding, cancellationContext)) + if (!FilesCollectionIndexesExist(binding, operationContext)) { - CreateFilesCollectionIndexes(binding, cancellationContext); + CreateFilesCollectionIndexes(binding, operationContext); } - if (!ChunksCollectionIndexesExist(binding, cancellationContext)) + if (!ChunksCollectionIndexesExist(binding, operationContext)) { - CreateChunksCollectionIndexes(binding, cancellationContext); + CreateChunksCollectionIndexes(binding, operationContext); } } @@ -887,23 +887,23 @@ private void EnsureIndexes(IReadWriteBindingHandle binding, OperationCancellatio } } - private async Task EnsureIndexesAsync(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) + private async Task EnsureIndexesAsync(IReadWriteBindingHandle binding, OperationContext operationContext) { - await _ensureIndexesSemaphore.WaitAsync(cancellationContext.RemainingTimeout, cancellationContext.CancellationToken).ConfigureAwait(false); + await _ensureIndexesSemaphore.WaitAsync(operationContext.RemainingTimeout, operationContext.CancellationToken).ConfigureAwait(false); try { if (!_ensureIndexesDone) { - var isFilesCollectionEmpty = await IsFilesCollectionEmptyAsync(binding, cancellationContext).ConfigureAwait(false); + var isFilesCollectionEmpty = await IsFilesCollectionEmptyAsync(binding, operationContext).ConfigureAwait(false); if (isFilesCollectionEmpty) { - if (!(await FilesCollectionIndexesExistAsync(binding, cancellationContext).ConfigureAwait(false))) + if (!(await FilesCollectionIndexesExistAsync(binding, operationContext).ConfigureAwait(false))) { - await CreateFilesCollectionIndexesAsync(binding, cancellationContext).ConfigureAwait(false); + await CreateFilesCollectionIndexesAsync(binding, operationContext).ConfigureAwait(false); } - if (!(await ChunksCollectionIndexesExistAsync(binding, cancellationContext).ConfigureAwait(false))) + if (!(await ChunksCollectionIndexesExistAsync(binding, operationContext).ConfigureAwait(false))) { - await CreateChunksCollectionIndexesAsync(binding, cancellationContext).ConfigureAwait(false); + await CreateChunksCollectionIndexesAsync(binding, operationContext).ConfigureAwait(false); } } @@ -922,25 +922,25 @@ private bool FilesCollectionIndexesExist(List indexes) return IndexExists(indexes, key); } - private bool FilesCollectionIndexesExist(IReadBindingHandle binding, OperationCancellationContext cancellationContext) + private bool FilesCollectionIndexesExist(IReadBindingHandle binding, OperationContext operationContext) { - var indexes = ListIndexes(binding, this.GetFilesCollectionNamespace(), cancellationContext); + var indexes = ListIndexes(binding, this.GetFilesCollectionNamespace(), operationContext); return FilesCollectionIndexesExist(indexes); } - private async Task FilesCollectionIndexesExistAsync(IReadBindingHandle binding, OperationCancellationContext cancellationContext) + private async Task FilesCollectionIndexesExistAsync(IReadBindingHandle binding, OperationContext operationContext) { - var indexes = await ListIndexesAsync(binding, this.GetFilesCollectionNamespace(), cancellationContext).ConfigureAwait(false); + var indexes = await ListIndexesAsync(binding, this.GetFilesCollectionNamespace(), operationContext).ConfigureAwait(false); return FilesCollectionIndexesExist(indexes); } - private GridFSFileInfo GetFileInfo(IReadBindingHandle binding, TFileId id, OperationCancellationContext cancellationContext) + private GridFSFileInfo GetFileInfo(IReadBindingHandle binding, TFileId id, OperationContext operationContext) { var operation = CreateGetFileInfoOperation(id); - using (var cursor = operation.Execute(binding, cancellationContext)) + using (var cursor = operation.Execute(binding, operationContext)) { // TODO: CSOT add a way to propagate cancellationContext into cursor methods. - var fileInfo = cursor.FirstOrDefault(cancellationContext.CancellationToken); + var fileInfo = cursor.FirstOrDefault(operationContext.CancellationToken); if (fileInfo == null) { throw new GridFSFileNotFoundException(_idSerializationInfo.SerializeValue(id)); @@ -949,13 +949,13 @@ private GridFSFileInfo GetFileInfo(IReadBindingHandle binding, TFileId } } - private async Task> GetFileInfoAsync(IReadBindingHandle binding, TFileId id, OperationCancellationContext cancellationContext) + private async Task> GetFileInfoAsync(IReadBindingHandle binding, TFileId id, OperationContext operationContext) { var operation = CreateGetFileInfoOperation(id); - using (var cursor = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false)) { // TODO: CSOT add a way to propagate cancellationContext into cursor methods. - var fileInfo = await cursor.FirstOrDefaultAsync(cancellationContext.CancellationToken).ConfigureAwait(false); + var fileInfo = await cursor.FirstOrDefaultAsync(operationContext.CancellationToken).ConfigureAwait(false); if (fileInfo == null) { throw new GridFSFileNotFoundException(_idSerializationInfo.SerializeValue(id)); @@ -964,13 +964,13 @@ private async Task> GetFileInfoAsync(IReadBindingHandle } } - private GridFSFileInfo GetFileInfoByName(IReadBindingHandle binding, string filename, int revision, OperationCancellationContext cancellationContext) + private GridFSFileInfo GetFileInfoByName(IReadBindingHandle binding, string filename, int revision, OperationContext operationContext) { var operation = CreateGetFileInfoByNameOperation(filename, revision); - using (var cursor = operation.Execute(binding, cancellationContext)) + using (var cursor = operation.Execute(binding, operationContext)) { // TODO: CSOT add a way to propagate cancellationContext into cursor methods. - var fileInfo = cursor.FirstOrDefault(cancellationContext.CancellationToken); + var fileInfo = cursor.FirstOrDefault(operationContext.CancellationToken); if (fileInfo == null) { throw new GridFSFileNotFoundException(filename, revision); @@ -979,13 +979,13 @@ private GridFSFileInfo GetFileInfoByName(IReadBindingHandle binding, st } } - private async Task> GetFileInfoByNameAsync(IReadBindingHandle binding, string filename, int revision, OperationCancellationContext cancellationContext) + private async Task> GetFileInfoByNameAsync(IReadBindingHandle binding, string filename, int revision, OperationContext operationContext) { var operation = CreateGetFileInfoByNameOperation(filename, revision); - using (var cursor = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false)) { // TODO: CSOT add a way to propagate cancellationContext into cursor methods. - var fileInfo = await cursor.FirstOrDefaultAsync(cancellationContext.CancellationToken).ConfigureAwait(false); + var fileInfo = await cursor.FirstOrDefaultAsync(operationContext.CancellationToken).ConfigureAwait(false); if (fileInfo == null) { throw new GridFSFileNotFoundException(filename, revision); @@ -999,36 +999,36 @@ private ReadConcern GetReadConcern() return _options.ReadConcern ?? _database.Settings.ReadConcern; } - private IReadBindingHandle GetSingleServerReadBinding(OperationCancellationContext cancellationContext) + private IReadBindingHandle GetSingleServerReadBinding(OperationContext operationContext) { var readPreference = _options.ReadPreference ?? _database.Settings.ReadPreference; var selector = new ReadPreferenceServerSelector(readPreference); - var server = _cluster.SelectServer(selector, cancellationContext); + var server = _cluster.SelectServer(selector, operationContext); var binding = new SingleServerReadBinding(server, readPreference, NoCoreSession.NewHandle()); return new ReadBindingHandle(binding); } - private async Task GetSingleServerReadBindingAsync(OperationCancellationContext cancellationContext) + private async Task GetSingleServerReadBindingAsync(OperationContext operationContext) { var readPreference = _options.ReadPreference ?? _database.Settings.ReadPreference; var selector = new ReadPreferenceServerSelector(readPreference); - var server = await _cluster.SelectServerAsync(selector, cancellationContext).ConfigureAwait(false); + var server = await _cluster.SelectServerAsync(selector, operationContext).ConfigureAwait(false); var binding = new SingleServerReadBinding(server, readPreference, NoCoreSession.NewHandle()); return new ReadBindingHandle(binding); } - private IReadWriteBindingHandle GetSingleServerReadWriteBinding(OperationCancellationContext cancellationContext) + private IReadWriteBindingHandle GetSingleServerReadWriteBinding(OperationContext operationContext) { var selector = WritableServerSelector.Instance; - var server = _cluster.SelectServer(selector, cancellationContext); + var server = _cluster.SelectServer(selector, operationContext); var binding = new SingleServerReadWriteBinding(server, NoCoreSession.NewHandle()); return new ReadWriteBindingHandle(binding); } - private async Task GetSingleServerReadWriteBindingAsync(OperationCancellationContext cancellationContext) + private async Task GetSingleServerReadWriteBindingAsync(OperationContext operationContext) { var selector = WritableServerSelector.Instance; - var server = await _cluster.SelectServerAsync(selector, cancellationContext).ConfigureAwait(false); + var server = await _cluster.SelectServerAsync(selector, operationContext).ConfigureAwait(false); var binding = new SingleServerReadWriteBinding(server, NoCoreSession.NewHandle()); return new ReadWriteBindingHandle(binding); } @@ -1045,39 +1045,39 @@ private bool IndexExists(List indexes, BsonDocument key) return false; } - private bool IsFilesCollectionEmpty(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) + private bool IsFilesCollectionEmpty(IReadWriteBindingHandle binding, OperationContext operationContext) { var operation = CreateIsFilesCollectionEmptyOperation(); - using (var cursor = operation.Execute(binding, cancellationContext)) + using (var cursor = operation.Execute(binding, operationContext)) { // TODO: CSOT add a way to propagate cancellationContext into cursor methods. - var firstOrDefault = cursor.FirstOrDefault(cancellationContext.CancellationToken); + var firstOrDefault = cursor.FirstOrDefault(operationContext.CancellationToken); return firstOrDefault == null; } } - private async Task IsFilesCollectionEmptyAsync(IReadWriteBindingHandle binding, OperationCancellationContext cancellationContext) + private async Task IsFilesCollectionEmptyAsync(IReadWriteBindingHandle binding, OperationContext operationContext) { var operation = CreateIsFilesCollectionEmptyOperation(); - using (var cursor = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false)) { // TODO: CSOT add a way to propagate cancellationContext into cursor methods. - var firstOrDefault = await cursor.FirstOrDefaultAsync(cancellationContext.CancellationToken).ConfigureAwait(false); + var firstOrDefault = await cursor.FirstOrDefaultAsync(operationContext.CancellationToken).ConfigureAwait(false); return firstOrDefault == null; } } - private List ListIndexes(IReadBinding binding, CollectionNamespace collectionNamespace, OperationCancellationContext cancellationContext) + private List ListIndexes(IReadBinding binding, CollectionNamespace collectionNamespace, OperationContext operationContext) { var operation = CreateListIndexesOperation(collectionNamespace); - return operation.Execute(binding, cancellationContext).ToList(); + return operation.Execute(binding, operationContext).ToList(); } - private async Task> ListIndexesAsync(IReadBinding binding, CollectionNamespace collectionNamespace, OperationCancellationContext cancellationContext) + private async Task> ListIndexesAsync(IReadBinding binding, CollectionNamespace collectionNamespace, OperationContext operationContext) { var operation = CreateListIndexesOperation(collectionNamespace); - var cursor = await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); - return await cursor.ToListAsync(cancellationContext.CancellationToken).ConfigureAwait(false); + var cursor = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + return await cursor.ToListAsync(operationContext.CancellationToken).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs index 932784461d2..a73ab856d25 100644 --- a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs +++ b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs @@ -197,8 +197,8 @@ private void GetFirstBatch(CancellationToken cancellationToken) { var operation = CreateFirstBatchOperation(); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); - _cursor = operation.Execute(Binding, operationCancellationContext); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + _cursor = operation.Execute(Binding, operationContext); GetNextBatch(cancellationToken); } @@ -206,8 +206,8 @@ private async Task GetFirstBatchAsync(CancellationToken cancellationToken) { var operation = CreateFirstBatchOperation(); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); - _cursor = await operation.ExecuteAsync(Binding, operationCancellationContext).ConfigureAwait(false); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + _cursor = await operation.ExecuteAsync(Binding, operationContext).ConfigureAwait(false); await GetNextBatchAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs index b09060c4d98..92f08860940 100644 --- a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs +++ b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs @@ -123,8 +123,8 @@ public override long Position var operation = CreateAbortOperation(); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); - operation.Execute(_binding, operationCancellationContext); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + operation.Execute(_binding, operationContext); } public override async Task AbortAsync(CancellationToken cancellationToken = default(CancellationToken)) @@ -138,8 +138,8 @@ public override long Position var operation = CreateAbortOperation(); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); - await operation.ExecuteAsync(_binding, operationCancellationContext).ConfigureAwait(false); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + await operation.ExecuteAsync(_binding, operationContext).ConfigureAwait(false); } public override void Close(CancellationToken cancellationToken) diff --git a/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs b/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs index 2cdc932daa1..fd0786d8f80 100644 --- a/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs +++ b/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs @@ -173,8 +173,8 @@ private void GetChunk(long n, CancellationToken cancellationToken) { var operation = CreateGetChunkOperation(n); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); - using (var cursor = operation.Execute(Binding, operationCancellationContext)) + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + using (var cursor = operation.Execute(Binding, operationContext)) { var documents = cursor.ToList(); _chunk = GetChunkHelper(n, documents); @@ -186,8 +186,8 @@ private async Task GetChunkAsync(long n, CancellationToken cancellationToken) { var operation = CreateGetChunkOperation(n); // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationToken); - using (var cursor = await operation.ExecuteAsync(Binding, operationCancellationContext).ConfigureAwait(false)) + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + using (var cursor = await operation.ExecuteAsync(Binding, operationContext).ConfigureAwait(false)) { var documents = await cursor.ToListAsync().ConfigureAwait(false); _chunk = GetChunkHelper(n, documents); diff --git a/src/MongoDB.Driver/OperationCancellationContext.cs b/src/MongoDB.Driver/OperationContext.cs similarity index 84% rename from src/MongoDB.Driver/OperationCancellationContext.cs rename to src/MongoDB.Driver/OperationContext.cs index 31883afae1c..7f60da95e4b 100644 --- a/src/MongoDB.Driver/OperationCancellationContext.cs +++ b/src/MongoDB.Driver/OperationContext.cs @@ -21,19 +21,19 @@ namespace MongoDB.Driver { - internal sealed class OperationCancellationContext + internal sealed class OperationContext { // TODO: this static field is temporary here and will be removed in a future PRs in scope of CSOT. - public static readonly OperationCancellationContext NoTimeout = new(System.Threading.Timeout.InfiniteTimeSpan, CancellationToken.None); + public static readonly OperationContext NoTimeout = new(System.Threading.Timeout.InfiniteTimeSpan, CancellationToken.None); private readonly Stopwatch _stopwatch; - public OperationCancellationContext(TimeSpan timeout, CancellationToken cancellationToken) + public OperationContext(TimeSpan timeout, CancellationToken cancellationToken) : this(Stopwatch.StartNew(), timeout, cancellationToken) { } - internal OperationCancellationContext(Stopwatch stopwatch, TimeSpan timeout, CancellationToken cancellationToken) + internal OperationContext(Stopwatch stopwatch, TimeSpan timeout, CancellationToken cancellationToken) { _stopwatch = stopwatch; Timeout = timeout; @@ -70,7 +70,7 @@ public bool IsTimedOut() return remainingTimeout < TimeSpan.Zero; } - public OperationCancellationContext WithTimeout(TimeSpan timeout) + public OperationContext WithTimeout(TimeSpan timeout) { var remainingTimeout = RemainingTimeout; if (timeout == System.Threading.Timeout.InfiniteTimeSpan) @@ -82,7 +82,7 @@ public OperationCancellationContext WithTimeout(TimeSpan timeout) timeout = remainingTimeout; } - return new OperationCancellationContext(timeout, CancellationToken); + return new OperationContext(timeout, CancellationToken); } public void WaitTask(Task task) diff --git a/src/MongoDB.Driver/OperationOptionsBase.cs b/src/MongoDB.Driver/OperationOptionsBase.cs index e270f2c0efd..17f17ef4b81 100644 --- a/src/MongoDB.Driver/OperationOptionsBase.cs +++ b/src/MongoDB.Driver/OperationOptionsBase.cs @@ -20,7 +20,7 @@ namespace MongoDB.Driver { internal abstract record OperationOptionsBase(TimeSpan Timeout) { - public OperationCancellationContext CreateCancellationContext(CancellationToken cancellationToken) + public OperationContext CreateCancellationContext(CancellationToken cancellationToken) => new (Timeout, cancellationToken); } } diff --git a/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs b/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs index 6eef6a12246..f0b57b50756 100644 --- a/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs +++ b/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs @@ -314,7 +314,7 @@ private static int GetMaxWireVersion() { var command = new BsonDocument("hello", 1); var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var response = operation.Execute(binding, OperationCancellationContext.NoTimeout); + var response = operation.Execute(binding, OperationContext.NoTimeout); return response["maxWireVersion"].AsInt32; } } @@ -326,7 +326,7 @@ private static SemanticVersion GetServerVersion() { var command = new BsonDocument("buildinfo", 1); var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var response = operation.Execute(binding, OperationCancellationContext.NoTimeout); + var response = operation.Execute(binding, OperationContext.NoTimeout); return SemanticVersion.Parse(response["version"].AsString); } } @@ -338,7 +338,7 @@ public static BsonDocument GetServerParameters() { var command = new BsonDocument("getParameter", new BsonString("*")); var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var serverParameters = operation.Execute(binding, OperationCancellationContext.NoTimeout); + var serverParameters = operation.Execute(binding, OperationContext.NoTimeout); return serverParameters; } @@ -404,7 +404,7 @@ private static void DropDatabase() using (var session = StartSession()) using (var binding = CreateReadWriteBinding(session)) { - operation.Execute(binding, OperationCancellationContext.NoTimeout); + operation.Execute(binding, OperationContext.NoTimeout); } } @@ -415,7 +415,7 @@ private static IEnumerable FindDocuments(IClusterInternal cluster, { var operation = new FindOperation(collectionNamespace, BsonDocumentSerializer.Instance, __messageEncoderSettings); - return operation.Execute(binding, OperationCancellationContext.NoTimeout).ToList(); + return operation.Execute(binding, OperationContext.NoTimeout).ToList(); } } @@ -495,7 +495,7 @@ string GetStorageEngineForCluster(IClusterInternal cluster) { var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var response = operation.Execute(binding, OperationCancellationContext.NoTimeout); + var response = operation.Execute(binding, OperationContext.NoTimeout); if (response.TryGetValue("storageEngine", out var storageEngine) && storageEngine.AsBsonDocument.TryGetValue("name", out var name)) { return name.AsString; diff --git a/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs b/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs index 0db72e6057f..17b8060310f 100644 --- a/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs +++ b/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs @@ -88,7 +88,7 @@ public static FailPoint ConfigureAlwaysOn(IClusterInternal cluster, ICoreSession private static IServer GetWriteableServer(IClusterInternal cluster) { var selector = WritableServerSelector.Instance; - return cluster.SelectServer(selector, OperationCancellationContext.NoTimeout); + return cluster.SelectServer(selector, OperationContext.NoTimeout); } private static void MakeFailPointApplicationNameTestableIfConfigured(BsonDocument command, bool async) @@ -186,7 +186,7 @@ private void ExecuteCommand(BsonDocument command, bool waitForConnected) BsonDocumentSerializer.Instance, new MessageEncoderSettings()); - operation.Execute(_binding, OperationCancellationContext.NoTimeout); + operation.Execute(_binding, OperationContext.NoTimeout); } } } diff --git a/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs b/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs index da1b0c0c330..9bc9a17f6a9 100644 --- a/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs +++ b/tests/MongoDB.Driver.TestHelpers/Core/MockClusterableServerFactory.cs @@ -93,11 +93,11 @@ public IClusterableServer CreateServer(ClusterType clusterType, ClusterId cluste mockConnectionPool.Setup(p => p.Generation).Returns(valueFunction: () => poolGeneration); Action acquireConnectionCallback = () => { connectionGeneration = poolGeneration; }; mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Callback(acquireConnectionCallback) .Returns(mockConnection.Object); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Callback(acquireConnectionCallback) .ReturnsAsync(mockConnection.Object); mockConnectionPool.Setup(p => p.Clear(It.IsAny())).Callback(() => { ++poolGeneration; }); @@ -186,7 +186,7 @@ public void PublishDescription(ServerDescription description) var maxWireVersion = description.MaxWireVersion; var server = (Server)result.Server; var helloResult = new HelloResult(new BsonDocument { { "compressors", new BsonArray() }, { "maxWireVersion", maxWireVersion } }); - var mockConnection = Mock.Get(server._connectionPool().AcquireConnection(OperationCancellationContext.NoTimeout)); + var mockConnection = Mock.Get(server._connectionPool().AcquireConnection(OperationContext.NoTimeout)); mockConnection.SetupGet(c => c.Description) .Returns(new ConnectionDescription(new ConnectionId(description.ServerId, 0), helloResult)); } diff --git a/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs b/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs index b357bac1522..4a266dbb70a 100644 --- a/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs +++ b/tests/MongoDB.Driver.TestHelpers/DriverTestConfiguration.cs @@ -197,8 +197,8 @@ public static ConnectionDescription GetConnectionDescription() { var cluster = Client.GetClusterInternal(); using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, NoCoreSession.NewHandle()))) - using (var channelSource = binding.GetWriteChannelSource(OperationCancellationContext.NoTimeout)) - using (var channel = channelSource.GetChannel(OperationCancellationContext.NoTimeout)) + using (var channelSource = binding.GetWriteChannelSource(OperationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationContext.NoTimeout)) { return channel.ConnectionDescription; } diff --git a/tests/MongoDB.Driver.Tests/AuthenticationTests.cs b/tests/MongoDB.Driver.Tests/AuthenticationTests.cs index acbec64b4be..3b866b4c14e 100644 --- a/tests/MongoDB.Driver.Tests/AuthenticationTests.cs +++ b/tests/MongoDB.Driver.Tests/AuthenticationTests.cs @@ -338,8 +338,8 @@ private void AssertAuthenticationSucceeds( speculativeAuthenticatationShouldSucceedIfPossible) { var serverSelector = new ReadPreferenceServerSelector(settings.ReadPreference); - var server = client.GetClusterInternal().SelectServer(serverSelector, OperationCancellationContext.NoTimeout); - var channel = server.GetChannel(OperationCancellationContext.NoTimeout); + var server = client.GetClusterInternal().SelectServer(serverSelector, OperationContext.NoTimeout); + var channel = server.GetChannel(OperationContext.NoTimeout); var helloResult = channel.ConnectionDescription.HelloResult; helloResult.SpeculativeAuthenticate.Should().NotBeNull(); } diff --git a/tests/MongoDB.Driver.Tests/ClusterTests.cs b/tests/MongoDB.Driver.Tests/ClusterTests.cs index f64a7c99b96..b13bdf52297 100644 --- a/tests/MongoDB.Driver.Tests/ClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/ClusterTests.cs @@ -100,8 +100,8 @@ public void SelectServer_loadbalancing_prose_test([Values(false, true)] bool asy var channels = new ConcurrentBag(); ThreadingUtilities.ExecuteOnNewThreads(threadsCount, i => { - channels.Add(slowServer.GetChannel(OperationCancellationContext.NoTimeout)); - channels.Add(fastServer.GetChannel(OperationCancellationContext.NoTimeout)); + channels.Add(slowServer.GetChannel(OperationContext.NoTimeout)); + channels.Add(fastServer.GetChannel(OperationContext.NoTimeout)); }); foreach (var channel in channels) diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelChannelSourceTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelChannelSourceTests.cs index 30257944773..650f074169d 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelChannelSourceTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelChannelSourceTests.cs @@ -149,8 +149,8 @@ public async Task GetChannel_should_return_expected_result( mockChannel.Setup(m => m.Fork()).Returns(expectedResult); var result = async ? - await subject.GetChannelAsync(OperationCancellationContext.NoTimeout) : - subject.GetChannel(OperationCancellationContext.NoTimeout); + await subject.GetChannelAsync(OperationContext.NoTimeout) : + subject.GetChannel(OperationContext.NoTimeout); result.Should().BeSameAs(expectedResult); mockChannel.Verify(m => m.Fork(), Times.Once); @@ -164,8 +164,8 @@ public async Task GetChannel_should_throw_when_disposed( var subject = CreateDisposedSubject(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadBindingTests.cs index 3360100430d..1d6f317e611 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadBindingTests.cs @@ -160,8 +160,8 @@ public async Task GetReadChannelSource_should_return_expected_result( mockSession.Setup(m => m.Fork()).Returns(forkedSession); var result = async ? - await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout) : - subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout) : + subject.GetReadChannelSource(OperationContext.NoTimeout); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); @@ -177,8 +177,8 @@ public async Task GetReadChannelSource_should_throw_when_disposed( { var subject = CreateDisposedSubject(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs index 9ae61ca3ff4..acc8fdfa4ad 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelReadWriteBindingTests.cs @@ -141,8 +141,8 @@ public async Task GetReadChannelSource_should_return_expected_result( mockSession.Setup(m => m.Fork()).Returns(forkedSession); var result = async ? - await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout) : - subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout) : + subject.GetReadChannelSource(OperationContext.NoTimeout); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); @@ -166,8 +166,8 @@ public async Task GetWriteChannelSource_should_return_expected_result( mockSession.Setup(m => m.Fork()).Returns(forkedSession); var result = async ? - await subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout) : - subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout) : + subject.GetWriteChannelSource(OperationContext.NoTimeout); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); @@ -183,8 +183,8 @@ public async Task GetReadChannelSource_should_throw_when_disposed( { var subject = CreateDisposedSubject(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); @@ -197,8 +197,8 @@ public async Task GetWriteChannelSource_should_throw_when_disposed( { var subject = CreateDisposedSubject(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetWriteChannelSource(OperationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceHandleTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceHandleTests.cs index 31af56c6576..37031583a76 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceHandleTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceHandleTests.cs @@ -62,8 +62,8 @@ public async Task GetChannel_should_throw_if_disposed( subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -78,15 +78,15 @@ public async Task GetChannel_should_delegate_to_reference( if (async) { - await subject.GetChannelAsync(OperationCancellationContext.NoTimeout); + await subject.GetChannelAsync(OperationContext.NoTimeout); - _mockChannelSource.Verify(s => s.GetChannelAsync(It.IsAny()), Times.Once); + _mockChannelSource.Verify(s => s.GetChannelAsync(It.IsAny()), Times.Once); } else { - subject.GetChannel(OperationCancellationContext.NoTimeout); + subject.GetChannel(OperationContext.NoTimeout); - _mockChannelSource.Verify(s => s.GetChannel(It.IsAny()), Times.Once); + _mockChannelSource.Verify(s => s.GetChannel(It.IsAny()), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceReadWriteBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceReadWriteBindingTests.cs index e9e6bc41a07..fbac6fc6c7b 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceReadWriteBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ChannelSourceReadWriteBindingTests.cs @@ -84,8 +84,8 @@ public async Task GetReadChannelSourceAsync_should_throw_if_disposed( subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -98,8 +98,8 @@ public async Task GetReadChannelSource_should_fork_the_channelSource( { var subject = new ChannelSourceReadWriteBinding(_mockChannelSource.Object, ReadPreference.Primary, NoCoreSession.NewHandle()); var result = async ? - await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout) : - subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout) : + subject.GetReadChannelSource(OperationContext.NoTimeout); _mockChannelSource.Verify(f => f.Fork(), Times.Once); } @@ -114,8 +114,8 @@ public async Task GetWriteChannelSource_should_throw_if_disposed( subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetWriteChannelSource(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -128,8 +128,8 @@ public async Task GetWriteChannelSource_should_fork_the_channelSource( { var subject = new ChannelSourceReadWriteBinding(_mockChannelSource.Object, ReadPreference.Primary, NoCoreSession.NewHandle()); var result = async ? - await subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout) : - subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout) : + subject.GetWriteChannelSource(OperationContext.NoTimeout); _mockChannelSource.Verify(f => f.Fork(), Times.Once); } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadBindingHandleTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadBindingHandleTests.cs index 6621a9699b0..070b01d7e48 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadBindingHandleTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadBindingHandleTests.cs @@ -59,8 +59,8 @@ public async Task GetReadChannelSource_should_throw_if_disposed( subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -75,15 +75,15 @@ public async Task GetReadChannelSource_should_delegate_to_reference( if (async) { - await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout); - _mockReadBinding.Verify(b => b.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout), Times.Once); + _mockReadBinding.Verify(b => b.GetReadChannelSourceAsync(OperationContext.NoTimeout), Times.Once); } else { - subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); + subject.GetReadChannelSource(OperationContext.NoTimeout); - _mockReadBinding.Verify(b => b.GetReadChannelSource(OperationCancellationContext.NoTimeout), Times.Once); + _mockReadBinding.Verify(b => b.GetReadChannelSource(OperationContext.NoTimeout), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs index 16db8d16877..82d016cd151 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs @@ -82,8 +82,8 @@ public async Task GetReadChannelSource_should_throw_if_disposed( subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -111,19 +111,19 @@ public async Task GetReadChannelSource_should_use_a_read_preference_server_selec if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); - await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), It.IsAny()), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), It.IsAny()), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); - subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); + subject.GetReadChannelSource(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.IsAny(), It.IsAny()), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.IsAny(), It.IsAny()), Times.Once); } } @@ -135,8 +135,8 @@ public async Task GetReadChannelSource_should_fork_the_session( var mockSession = new Mock(); var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary, mockSession.Object); var selectedServer = new Mock().Object; - _mockCluster.Setup(m => m.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); - _mockCluster.Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(m => m.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); + _mockCluster.Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); var forkedSession = new Mock().Object; mockSession.Setup(m => m.Fork()).Returns(forkedSession); @@ -153,8 +153,8 @@ public async Task GetReadChannelSource_should_fork_the_session( _mockCluster.SetupSequence(c => c.Description).Returns(initialClusterDescription).Returns(finalClusterDescription); var result = async ? - await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout) : - subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout) : + subject.GetReadChannelSource(OperationContext.NoTimeout); var handle = result.Should().BeOfType().Subject; var referenceCounted = handle._reference().Should().BeOfType>().Subject; diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadWriteBindingHandleTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadWriteBindingHandleTests.cs index 0a551419af5..7549be8c4c8 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadWriteBindingHandleTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadWriteBindingHandleTests.cs @@ -59,8 +59,8 @@ public async Task GetReadChannelSource_should_throw_if_disposed( subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -75,15 +75,15 @@ public async Task GetReadChannelSource_should_delegate_to_reference( if (async) { - await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout); - _mockReadWriteBinding.Verify(b => b.GetReadChannelSourceAsync(It.IsAny()), Times.Once); + _mockReadWriteBinding.Verify(b => b.GetReadChannelSourceAsync(It.IsAny()), Times.Once); } else { - subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); + subject.GetReadChannelSource(OperationContext.NoTimeout); - _mockReadWriteBinding.Verify(b => b.GetReadChannelSource(It.IsAny()), Times.Once); + _mockReadWriteBinding.Verify(b => b.GetReadChannelSource(It.IsAny()), Times.Once); } } @@ -97,8 +97,8 @@ public async Task GetWriteChannelSource_should_throw_if_disposed( subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetWriteChannelSource(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -113,15 +113,15 @@ public async Task GetWriteChannelSource_should_delegate_to_reference( if (async) { - await subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout); - _mockReadWriteBinding.Verify(b => b.GetWriteChannelSourceAsync(It.IsAny()), Times.Once); + _mockReadWriteBinding.Verify(b => b.GetWriteChannelSourceAsync(It.IsAny()), Times.Once); } else { - subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout); + subject.GetWriteChannelSource(OperationContext.NoTimeout); - _mockReadWriteBinding.Verify(b => b.GetWriteChannelSource(It.IsAny()), Times.Once); + _mockReadWriteBinding.Verify(b => b.GetWriteChannelSource(It.IsAny()), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ServerChannelSourceTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ServerChannelSourceTests.cs index 02631cf70b2..62bd5cfd535 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ServerChannelSourceTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ServerChannelSourceTests.cs @@ -90,8 +90,8 @@ public async Task GetChannel_should_throw_if_disposed( subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -107,15 +107,15 @@ public async Task GetChannel_should_get_connection_from_server( if (async) { - await subject.GetChannelAsync(OperationCancellationContext.NoTimeout); + await subject.GetChannelAsync(OperationContext.NoTimeout); - _mockServer.Verify(s => s.GetChannelAsync(It.IsAny()), Times.Once); + _mockServer.Verify(s => s.GetChannelAsync(It.IsAny()), Times.Once); } else { - subject.GetChannel(OperationCancellationContext.NoTimeout); + subject.GetChannel(OperationContext.NoTimeout); - _mockServer.Verify(s => s.GetChannel(It.IsAny()), Times.Once); + _mockServer.Verify(s => s.GetChannel(It.IsAny()), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadBindingTests.cs index cb9eaba20f1..ab0fae6858c 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadBindingTests.cs @@ -136,8 +136,8 @@ public async Task GetReadChannelSource_should_return_expected_result( mockSession.Setup(m => m.Fork()).Returns(forkedSession); var result = async ? - await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout) : - subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout) : + subject.GetReadChannelSource(OperationContext.NoTimeout); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); @@ -153,8 +153,8 @@ public async Task GetReadChannelSource_should_throw_when_disposed( var subject = CreateDisposedSubject(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs index 067554e8775..2efd25ca017 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/SingleServerReadWriteBindingTests.cs @@ -117,8 +117,8 @@ public async Task GetReadChannelSource_should_return_expected_result( mockSession.Setup(m => m.Fork()).Returns(forkedSession); var result = async ? - await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout) : - subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout) : + subject.GetReadChannelSource(OperationContext.NoTimeout); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); @@ -133,8 +133,8 @@ public async Task GetReadChannelSource_should_throw_when_disposed( { var subject = CreateDisposedSubject(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); @@ -151,8 +151,8 @@ public async Task GetWriteChannelSource_should_return_expected_result( mockSession.Setup(m => m.Fork()).Returns(forkedSession); var result = async ? - await subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout) : - subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout) : + subject.GetWriteChannelSource(OperationContext.NoTimeout); var newHandle = result.Should().BeOfType().Subject; var referenceCounted = newHandle._reference(); @@ -167,8 +167,8 @@ public async Task GetWriteChannelSource_should_throw_when_disposed( { var subject = CreateDisposedSubject(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); var e = exception.Should().BeOfType().Subject; e.ObjectName.Should().Be(subject.GetType().FullName); diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs index 5c7f2e49805..a65dd2f43e6 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs @@ -84,8 +84,8 @@ public async Task GetReadChannelSource_should_throw_if_disposed( subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetReadChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetReadChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetReadChannelSource(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -115,19 +115,19 @@ public async Task GetReadChannelSource_should_use_a_writable_server_selector_to_ if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), OperationCancellationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), OperationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); - await subject.GetReadChannelSourceAsync(OperationCancellationContext.NoTimeout); + await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), OperationCancellationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), OperationContext.NoTimeout), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), OperationCancellationContext.NoTimeout)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), OperationContext.NoTimeout)).Returns(selectedServer); - subject.GetReadChannelSource(OperationCancellationContext.NoTimeout); + subject.GetReadChannelSource(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.IsAny(), OperationCancellationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.IsAny(), OperationContext.NoTimeout), Times.Once); } } @@ -141,8 +141,8 @@ public async Task GetWriteChannelSource_should_throw_if_disposed( subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetWriteChannelSource(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -171,19 +171,19 @@ public async Task GetWriteChannelSourceAsync_should_use_a_writable_server_select if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), OperationCancellationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), OperationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); - await subject.GetWriteChannelSourceAsync(OperationCancellationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), OperationCancellationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), OperationContext.NoTimeout), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), OperationCancellationContext.NoTimeout)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), OperationContext.NoTimeout)).Returns(selectedServer); - subject.GetWriteChannelSource(OperationCancellationContext.NoTimeout); + subject.GetWriteChannelSource(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.IsAny(), OperationCancellationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.IsAny(), OperationContext.NoTimeout), Times.Once); } } @@ -212,19 +212,19 @@ public async Task GetWriteChannelSource_should_use_a_composite_server_selector_t if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), OperationCancellationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), OperationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); - await subject.GetWriteChannelSourceAsync(deprioritizedServers, OperationCancellationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(deprioritizedServers, OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), OperationCancellationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), OperationContext.NoTimeout), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), OperationCancellationContext.NoTimeout)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), OperationContext.NoTimeout)).Returns(selectedServer); - subject.GetWriteChannelSource(deprioritizedServers, OperationCancellationContext.NoTimeout); + subject.GetWriteChannelSource(deprioritizedServers, OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.Is(c => c.ToString().Contains("PriorityServerSelector")), OperationCancellationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.Is(c => c.ToString().Contains("PriorityServerSelector")), OperationContext.NoTimeout), Times.Once); } } @@ -256,19 +256,19 @@ public async Task GetWriteChannelSource_with_mayUseSecondary_should_pass_mayUseS if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), OperationCancellationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), OperationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); - await subject.GetWriteChannelSourceAsync(mayUseSecondary, OperationCancellationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(mayUseSecondary, OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.Is(s => s.MayUseSecondary == mayUseSecondary), OperationCancellationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.Is(s => s.MayUseSecondary == mayUseSecondary), OperationContext.NoTimeout), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), OperationCancellationContext.NoTimeout)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), OperationContext.NoTimeout)).Returns(selectedServer); - subject.GetWriteChannelSource(mayUseSecondary, OperationCancellationContext.NoTimeout); + subject.GetWriteChannelSource(mayUseSecondary, OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.Is(s => s.MayUseSecondary == mayUseSecondary), OperationCancellationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.Is(s => s.MayUseSecondary == mayUseSecondary), OperationContext.NoTimeout), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs b/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs index b30e9c2992c..26f042869e2 100644 --- a/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs @@ -128,8 +128,8 @@ public async Task SelectServer_should_throw_if_not_initialized( var subject = CreateSubject(); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(selector, OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(selector, OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -145,8 +145,8 @@ public async Task SelectServer_should_throw_if_disposed( subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(selector, OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(selector, OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -161,8 +161,8 @@ public async Task SelectServer_should_throw_if_serverSelector_is_null( subject.Initialize(); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(null, OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(null, OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(null, OperationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(null, OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -183,8 +183,8 @@ public async Task SelectServer_should_return_a_server_if_one_matches( var selector = new DelegateServerSelector((c, s) => s); var result = async ? - await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout) : - subject.SelectServer(selector, OperationCancellationContext.NoTimeout); + await subject.SelectServerAsync(selector, OperationContext.NoTimeout) : + subject.SelectServer(selector, OperationContext.NoTimeout); result.Should().NotBeNull(); @@ -213,8 +213,8 @@ public async Task SelectServer_should_return_second_server_if_first_cannot_be_fo var selector = new DelegateServerSelector((c, s) => s); var result = async ? - await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout) : - subject.SelectServer(selector, OperationCancellationContext.NoTimeout); + await subject.SelectServerAsync(selector, OperationContext.NoTimeout) : + subject.SelectServer(selector, OperationContext.NoTimeout); result.Should().NotBeNull(); @@ -241,8 +241,8 @@ public async Task SelectServer_should_throw_if_no_servers_match( var selector = new DelegateServerSelector((c, s) => Enumerable.Empty()); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(selector, OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(selector, OperationContext.NoTimeout)); exception.Should().BeOfType(); @@ -269,8 +269,8 @@ public async Task SelectServer_should_throw_if_the_matched_server_cannot_be_foun var selector = new DelegateServerSelector((c, s) => s); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(selector, OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(selector, OperationContext.NoTimeout)); exception.Should().BeOfType(); @@ -297,8 +297,8 @@ public async Task SelectServer_should_throw_if_any_servers_are_incompatible(int var selector = new DelegateServerSelector((c, s) => s); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(selector, OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(selector, OperationContext.NoTimeout)); exception.Should().BeOfType(); @@ -338,8 +338,8 @@ public async Task SelectServer_should_keep_trying_to_match_by_waiting_on_cluster var selector = new DelegateServerSelector((c, s) => s); var result = async ? - await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout) : - subject.SelectServer(selector, OperationCancellationContext.NoTimeout); + await subject.SelectServerAsync(selector, OperationContext.NoTimeout) : + subject.SelectServer(selector, OperationContext.NoTimeout); result.Should().NotBeNull(); @@ -377,8 +377,8 @@ public async Task SelectServer_should_ignore_deprioritized_servers_if_cluster_is _capturedEvents.Clear(); var result = async ? - await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout) : - subject.SelectServer(selector, OperationCancellationContext.NoTimeout); + await subject.SelectServerAsync(selector, OperationContext.NoTimeout) : + subject.SelectServer(selector, OperationContext.NoTimeout); result.Should().NotBeNull(); @@ -411,8 +411,8 @@ public async Task SelectServer_should_return_deprioritized_servers_if_no_other_s _capturedEvents.Clear(); var result = async ? - await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout) : - subject.SelectServer(selector, OperationCancellationContext.NoTimeout); + await subject.SelectServerAsync(selector, OperationContext.NoTimeout) : + subject.SelectServer(selector, OperationContext.NoTimeout); result.Should().NotBeNull(); @@ -492,8 +492,8 @@ public async Task SelectServer_should_apply_both_pre_and_post_server_selectors( _capturedEvents.Clear(); var result = async ? - await subject.SelectServerAsync(middleSelector, OperationCancellationContext.NoTimeout) : - subject.SelectServer(middleSelector, OperationCancellationContext.NoTimeout); + await subject.SelectServerAsync(middleSelector, OperationContext.NoTimeout) : + subject.SelectServer(middleSelector, OperationContext.NoTimeout); ((DnsEndPoint)result.EndPoint).Port.Should().Be(27020); _capturedEvents.Next().Should().BeOfType(); @@ -527,8 +527,8 @@ public async Task SelectServer_should_call_custom_selector( { var selector = new DelegateServerSelector((c, s) => s); var selectedServer = async ? - await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout): - subject.SelectServer(selector, OperationCancellationContext.NoTimeout); + await subject.SelectServerAsync(selector, OperationContext.NoTimeout): + subject.SelectServer(selector, OperationContext.NoTimeout); var selectedServerPort = ((DnsEndPoint)selectedServer.EndPoint).Port; selectedServerPort.Should().Be(27020); @@ -539,8 +539,8 @@ await subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout { var selector = new DelegateServerSelector((c, s) => new ServerDescription[0]); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(selector, OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(selector, OperationContext.NoTimeout)); exception.Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); diff --git a/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs b/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs index 4a2d865ed65..27e7537fe85 100644 --- a/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs @@ -328,8 +328,8 @@ public async Task SelectServer_should_return_expected_server( PublishDescription(_endPoint); var result = async ? - await subject.SelectServerAsync(Mock.Of(), OperationCancellationContext.NoTimeout) : - subject.SelectServer(Mock.Of(), OperationCancellationContext.NoTimeout); + await subject.SelectServerAsync(Mock.Of(), OperationContext.NoTimeout) : + subject.SelectServer(Mock.Of(), OperationContext.NoTimeout); result.EndPoint.Should().Be(_endPoint); } @@ -356,8 +356,8 @@ public async Task SelectServer_should_throw_server_selection_timeout_if_server_h } var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(Mock.Of(), OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(Mock.Of(), OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(Mock.Of(), OperationContext.NoTimeout)) : + Record.Exception(() => subject.SelectServer(Mock.Of(), OperationContext.NoTimeout)); var ex = exception.Should().BeOfType().Subject; ex.Message.Should().StartWith($"A timeout occurred after {serverSelectionTimeout.TotalMilliseconds}ms selecting a server. Client view of cluster state is "); @@ -387,7 +387,7 @@ public async Task SelectServer_should_be_cancelled_by_cancellationToken( Exception exception; using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(100))) { - var cancellationContext = new OperationCancellationContext(Timeout.InfiniteTimeSpan, cancellationTokenSource.Token); + var cancellationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationTokenSource.Token); exception = async ? await Record.ExceptionAsync(() => subject.SelectServerAsync(Mock.Of(), cancellationContext)) : Record.Exception(() => subject.SelectServer(Mock.Of(), cancellationContext)); diff --git a/tests/MongoDB.Driver.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs b/tests/MongoDB.Driver.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs index 5e2c0449e9b..e467384ef70 100644 --- a/tests/MongoDB.Driver.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/ConnectionPools/ExclusiveConnectionPoolTests.cs @@ -175,7 +175,7 @@ public void AcquireConnection_should_iterate_over_all_dormant_connections() // acquire all connections and return them var allConnections = Enumerable.Range(0, connectionsCount) - .Select(i => subject.AcquireConnection(OperationCancellationContext.NoTimeout)) + .Select(i => subject.AcquireConnection(OperationContext.NoTimeout)) .ToArray(); var connectionNotToExpire = allConnections[allConnections.Length / 2].ConnectionId; @@ -223,8 +223,8 @@ public async Task AcquireConnection_should_throw_an_InvalidOperationException_if _capturedEvents.Clear(); var exception = async ? - await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => _subject.AcquireConnection(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.AcquireConnection(OperationContext.NoTimeout)); exception.Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); @@ -244,8 +244,8 @@ public async Task AcquireConnection_should_throw_an_ObjectDisposedException_afte _subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => _subject.AcquireConnection(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.AcquireConnection(OperationContext.NoTimeout)); exception.Should().BeOfType(); @@ -268,8 +268,8 @@ public async Task AcquireConnection_should_return_a_connection( _capturedEvents.Clear(); var connection = async ? - await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : - _subject.AcquireConnection(OperationCancellationContext.NoTimeout); + await _subject.AcquireConnectionAsync(OperationContext.NoTimeout) : + _subject.AcquireConnection(OperationContext.NoTimeout); connection.Should().NotBeNull(); _subject.AvailableCount.Should().Be(_settings.MaxConnections - 1); @@ -330,8 +330,8 @@ public async Task AcquireConnection_should_invoke_error_handling_before_releasin subject.SetReady(); var resultException = async ? - await Record.ExceptionAsync(() => subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.AcquireConnection(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.AcquireConnectionAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.AcquireConnection(OperationContext.NoTimeout)); resultException.Should().BeOfType(); subject.AvailableCount.Should().Be(maxConnections); @@ -366,8 +366,8 @@ internal async Task AcquireConnection_should_track_checked_out_reasons( for (int attempt = 1; attempt <= attempts; attempt++) { var connection = async ? - await subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : - subject.AcquireConnection(OperationCancellationContext.NoTimeout); + await subject.AcquireConnectionAsync(OperationContext.NoTimeout) : + subject.AcquireConnection(OperationContext.NoTimeout); ((ICheckOutReasonTracker)connection).SetCheckOutReasonIfNotAlreadySet(reason); connections.Add(connection); @@ -429,8 +429,8 @@ public async Task AcquireConnection_should_increase_count_up_to_the_max_number_o for (int i = 0; i < _settings.MaxConnections; i++) { var connection = async ? - await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : - _subject.AcquireConnection(OperationCancellationContext.NoTimeout); + await _subject.AcquireConnectionAsync(OperationContext.NoTimeout) : + _subject.AcquireConnection(OperationContext.NoTimeout); connections.Add(connection); } @@ -464,8 +464,8 @@ public async Task AcquiredConnection_should_return_connections_to_the_pool_when_ InitializeAndWait(); var connection = async ? - await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : - _subject.AcquireConnection(OperationCancellationContext.NoTimeout); + await _subject.AcquireConnectionAsync(OperationContext.NoTimeout) : + _subject.AcquireConnection(OperationContext.NoTimeout); _capturedEvents.Clear(); @@ -496,8 +496,8 @@ public async Task AcquiredConnection_should_not_return_connections_to_the_pool_w InitializeAndWait(); var connection = async ? - await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : - _subject.AcquireConnection(OperationCancellationContext.NoTimeout); + await _subject.AcquireConnectionAsync(OperationContext.NoTimeout) : + _subject.AcquireConnection(OperationContext.NoTimeout); _capturedEvents.Clear(); @@ -526,15 +526,15 @@ public async Task AcquireConnection_should_throw_a_TimeoutException_when_all_con for (int i = 0; i < _settings.MaxConnections; i++) { var connection = async ? - await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : - _subject.AcquireConnection(OperationCancellationContext.NoTimeout); + await _subject.AcquireConnectionAsync(OperationContext.NoTimeout) : + _subject.AcquireConnection(OperationContext.NoTimeout); connections.Add(connection); } _capturedEvents.Clear(); var exception = async ? - await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => _subject.AcquireConnection(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.AcquireConnectionAsync(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.AcquireConnection(OperationContext.NoTimeout)); exception.Should().BeOfType(); @@ -682,13 +682,13 @@ public async Task AcquiredConnection_should_not_throw_exceptions_when_disposed_a IConnectionHandle connection2; if (async) { - connection1 = await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout); - connection2 = await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout); + connection1 = await _subject.AcquireConnectionAsync(OperationContext.NoTimeout); + connection2 = await _subject.AcquireConnectionAsync(OperationContext.NoTimeout); } else { - connection1 = _subject.AcquireConnection(OperationCancellationContext.NoTimeout); - connection2 = _subject.AcquireConnection(OperationCancellationContext.NoTimeout); + connection1 = _subject.AcquireConnection(OperationContext.NoTimeout); + connection2 = _subject.AcquireConnection(OperationContext.NoTimeout); } _capturedEvents.Clear(); @@ -862,8 +862,8 @@ public async Task Clear_should_cause_existing_connections_to_be_expired( _subject.SetReady(); var connection = async ? - await _subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : - _subject.AcquireConnection(OperationCancellationContext.NoTimeout); + await _subject.AcquireConnectionAsync(OperationContext.NoTimeout) : + _subject.AcquireConnection(OperationContext.NoTimeout); connection.IsExpired.Should().BeFalse(); _subject.Clear(closeInUseConnections: false); @@ -903,8 +903,8 @@ public async Task Clear_with_serviceId_should_cause_only_expected_connections_to subject.SetReady(); var connection = async ? - await subject.AcquireConnectionAsync(OperationCancellationContext.NoTimeout) : - subject.AcquireConnection(OperationCancellationContext.NoTimeout); + await subject.AcquireConnectionAsync(OperationContext.NoTimeout) : + subject.AcquireConnection(OperationContext.NoTimeout); connection.IsExpired.Should().BeFalse(); var randomServiceId = ObjectId.GenerateNewId(); @@ -1620,13 +1620,13 @@ private IConnection AcquireConnection(ExclusiveConnectionPool subject, bool asyn if (async) { return subject - .AcquireConnectionAsync(OperationCancellationContext.NoTimeout) + .AcquireConnectionAsync(OperationContext.NoTimeout) .GetAwaiter() .GetResult(); } else { - return subject.AcquireConnection(OperationCancellationContext.NoTimeout); + return subject.AcquireConnection(OperationContext.NoTimeout); } } diff --git a/tests/MongoDB.Driver.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs b/tests/MongoDB.Driver.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs index 5fdf7dfbd83..2b4970bd723 100644 --- a/tests/MongoDB.Driver.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/ConnectionPools/MaintenanceHelperTests.cs @@ -168,7 +168,7 @@ public void Stop_should_trigger_immediate_maintenance_call( IConnection acquiredConnection = null; if (checkOutConnection) { - acquiredConnection = pool.AcquireConnection(OperationCancellationContext.NoTimeout); + acquiredConnection = pool.AcquireConnection(OperationContext.NoTimeout); acquiredConnection.ConnectionId.LongLocalValue.Should().Be(1); } diff --git a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs index 8c6276c517b..ea31f3779d9 100644 --- a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs @@ -75,7 +75,7 @@ public void Ensure_command_network_error_before_handshake_is_correctly_handled([ // The next hello or legacy hello response will be delayed because the waiting in the mock.Callbacks cluster.Initialize(); - var selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint1), OperationCancellationContext.NoTimeout); + var selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint1), OperationContext.NoTimeout); initialSelectedEndpoint = selectedServer.EndPoint; initialSelectedEndpoint.Should().Be(__endPoint1); @@ -86,11 +86,11 @@ public void Ensure_command_network_error_before_handshake_is_correctly_handled([ Exception exception; if (async) { - exception = Record.Exception(() => selectedServer.GetChannelAsync(OperationCancellationContext.NoTimeout).GetAwaiter().GetResult()); + exception = Record.Exception(() => selectedServer.GetChannelAsync(OperationContext.NoTimeout).GetAwaiter().GetResult()); } else { - exception = Record.Exception(() => selectedServer.GetChannel(OperationCancellationContext.NoTimeout)); + exception = Record.Exception(() => selectedServer.GetChannel(OperationContext.NoTimeout)); } var e = exception.Should().BeOfType().Subject; @@ -107,7 +107,7 @@ public void Ensure_command_network_error_before_handshake_is_correctly_handled([ } // ensure that a new server can be selected - selectedServer = cluster.SelectServer(WritableServerSelector.Instance, OperationCancellationContext.NoTimeout); + selectedServer = cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); // ensure that the selected server is not the same as the initial selectedServer.EndPoint.Should().Be(__endPoint2); @@ -187,11 +187,11 @@ void SetupConnectionPool(Mock mockConnectionPool, IConnectionHa { var dnsException = CreateDnsException(connection.ConnectionId, from: "pool"); mockConnectionPool - .Setup(c => c.AcquireConnection(It.IsAny())) + .Setup(c => c.AcquireConnection(It.IsAny())) .Callback(() => exceptionHandlerProvider().HandleExceptionOnOpen(dnsException)) .Throws(dnsException); // throw command dns exception mockConnectionPool - .Setup(c => c.AcquireConnectionAsync(It.IsAny())) + .Setup(c => c.AcquireConnectionAsync(It.IsAny())) .Callback(() => exceptionHandlerProvider().HandleExceptionOnOpen(dnsException)) .Throws(dnsException); // throw command dns exception } diff --git a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs index 2a1badc0078..552e46170c4 100644 --- a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs @@ -96,7 +96,7 @@ public async Task RapidHeartbeatTimerCallback_should_ignore_reentrant_calls() cluster.Initialize(); // Trigger Cluster._rapidHeartbeatTimer - _ = cluster.SelectServerAsync(CreateWritableServerAndEndPointSelector(__endPoint1), OperationCancellationContext.NoTimeout); + _ = cluster.SelectServerAsync(CreateWritableServerAndEndPointSelector(__endPoint1), OperationContext.NoTimeout); // Wait for all heartbeats to complete await Task.WhenAny(allHeartbeatsReceived.Task, Task.Delay(1000)); @@ -142,13 +142,13 @@ public async Task Ensure_no_deadlock_after_primary_update() server.DescriptionChanged += ProcessServerDescriptionChanged; } - var selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint1), OperationCancellationContext.NoTimeout); + var selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint1), OperationContext.NoTimeout); initialSelectedEndpoint = selectedServer.EndPoint; initialSelectedEndpoint.Should().Be(__endPoint1); // Change primary currentPrimaries.Add(__serverId2); - selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint2), OperationCancellationContext.NoTimeout); + selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint2), OperationContext.NoTimeout); selectedServer.EndPoint.Should().Be(__endPoint2); // Ensure stalling happened @@ -198,10 +198,10 @@ void SetupConnection(Mock mockConnectionHandle, ServerId serv void SetupConnectionPool(Mock mockConnectionPool, IConnectionHandle connection) { mockConnectionPool - .Setup(c => c.AcquireConnection(It.IsAny())) + .Setup(c => c.AcquireConnection(It.IsAny())) .Returns(connection); mockConnectionPool - .Setup(c => c.AcquireConnectionAsync(It.IsAny())) + .Setup(c => c.AcquireConnectionAsync(It.IsAny())) .Returns(Task.FromResult(connection)); } diff --git a/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntergationTests.cs b/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntergationTests.cs index 8295981ee28..2c5dbba625f 100644 --- a/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntergationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntergationTests.cs @@ -614,11 +614,11 @@ private BulkWriteOperationResult CreateAndRunBulkOperation(RetryableWriteContext if (async) { - return bulkInsertOperation.ExecuteAsync(context, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult(); + return bulkInsertOperation.ExecuteAsync(context, OperationContext.NoTimeout).GetAwaiter().GetResult(); } else { - return bulkInsertOperation.Execute(context, OperationCancellationContext.NoTimeout); + return bulkInsertOperation.Execute(context, OperationContext.NoTimeout); } } @@ -634,19 +634,19 @@ private IAsyncCursor CreateAndRunFindOperation(RetryableReadContex if (async) { - return findOperation.ExecuteAsync(context, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult(); + return findOperation.ExecuteAsync(context, OperationContext.NoTimeout).GetAwaiter().GetResult(); } else { - return findOperation.Execute(context, OperationCancellationContext.NoTimeout); + return findOperation.Execute(context, OperationContext.NoTimeout); } } private RetryableReadContext CreateRetryableReadContext(IReadBindingHandle readBindingHandle, bool async) { return async - ? RetryableReadContext.CreateAsync(readBindingHandle, retryRequested: false, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult() - : RetryableReadContext.Create(readBindingHandle, retryRequested: false, OperationCancellationContext.NoTimeout); + ? RetryableReadContext.CreateAsync(readBindingHandle, retryRequested: false, OperationContext.NoTimeout).GetAwaiter().GetResult() + : RetryableReadContext.Create(readBindingHandle, retryRequested: false, OperationContext.NoTimeout); } private DisposableBindingBundle CreateReadBindingsAndRetryableReadContext(IClusterInternal cluster, ICoreSessionHandle sessionHandle, bool async) @@ -662,8 +662,8 @@ private DisposableBindingBundle Create private RetryableWriteContext CreateRetryableWriteContext(IReadWriteBindingHandle readWriteBindingHandle, bool async) { return async - ? RetryableWriteContext.CreateAsync(readWriteBindingHandle, retryRequested: false, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult() - : RetryableWriteContext.Create(readWriteBindingHandle, retryRequested: false, OperationCancellationContext.NoTimeout); + ? RetryableWriteContext.CreateAsync(readWriteBindingHandle, retryRequested: false, OperationContext.NoTimeout).GetAwaiter().GetResult() + : RetryableWriteContext.Create(readWriteBindingHandle, retryRequested: false, OperationContext.NoTimeout); } private DisposableBindingBundle CreateReadWriteBindingsAndRetryableWriteContext(IClusterInternal cluster, ICoreSessionHandle sessionHandle, bool async) diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorTests.cs index 04100a17888..a1b8943a276 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/AsyncCursorTests.cs @@ -328,7 +328,7 @@ public void Dispose_should_be_shielded_from_exceptions() { var mockChannelSource = new Mock(); mockChannelSource - .Setup(c => c.GetChannel(It.IsAny())) + .Setup(c => c.GetChannel(It.IsAny())) .Throws(); var subject = CreateSubject(cursorId: 1, channelSource: Optional.Create(mockChannelSource.Object)); @@ -341,7 +341,7 @@ public void Dispose_should_dispose_channel_source_when_cursor_was_not_closed_by_ { var mockChannelSource = new Mock(); mockChannelSource - .Setup(c => c.GetChannel(It.IsAny())) + .Setup(c => c.GetChannel(It.IsAny())) .Throws(); var subject = CreateSubject(cursorId: 1, channelSource: Optional.Create(mockChannelSource.Object)); @@ -385,7 +385,7 @@ public void Dispose_should_not_call_close_cursors_for_zero_cursor_id() var mockChannelSource = new Mock(); mockChannelSource - .Setup(c => c.GetChannel(It.IsAny())) + .Setup(c => c.GetChannel(It.IsAny())) .Returns(mockChannelHandle.Object); var subject = CreateSubject(cursorId: 0, channelSource: Optional.Create(mockChannelSource.Object)); @@ -429,7 +429,7 @@ public void GetMore_should_use_same_session( var sameSessionWasUsed = false; if (async) { - mockChannelSource.Setup(m => m.GetChannelAsync(It.IsAny())).Returns(Task.FromResult(channel)); + mockChannelSource.Setup(m => m.GetChannelAsync(It.IsAny())).Returns(Task.FromResult(channel)); mockChannel .Setup(m => m.CommandAsync( session, @@ -451,7 +451,7 @@ public void GetMore_should_use_same_session( } else { - mockChannelSource.Setup(m => m.GetChannel(It.IsAny())).Returns(channel); + mockChannelSource.Setup(m => m.GetChannel(It.IsAny())).Returns(channel); mockChannel .Setup(m => m.Command( session, @@ -537,7 +537,7 @@ private void SetupChannelMocks(Mock mockChannelSource, Mock c.GetChannelAsync(It.IsAny())) + .Setup(c => c.GetChannelAsync(It.IsAny())) .ReturnsAsync(mockChannelHandle.Object); mockChannelHandle @@ -564,7 +564,7 @@ private void SetupChannelMocks(Mock mockChannelSource, Mock c.GetChannel(It.IsAny())) + .Setup(c => c.GetChannel(It.IsAny())) .Returns(mockChannelHandle.Object); mockChannelHandle @@ -651,8 +651,8 @@ public void Session_reference_count_should_be_decremented_as_soon_as_possible(in _session.ReferenceCount().Should().Be(1); using (var binding = new ReadPreferenceBinding(CoreTestConfiguration.Cluster, ReadPreference.Primary, _session.Fork())) - using (var channelSource = (ChannelSourceHandle)binding.GetReadChannelSource(OperationCancellationContext.NoTimeout)) - using (var channel = channelSource.GetChannel(OperationCancellationContext.NoTimeout)) + using (var channelSource = (ChannelSourceHandle)binding.GetReadChannelSource(OperationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationContext.NoTimeout)) { var query = new BsonDocument(); long cursorId; diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/BulkMixedWriteOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/BulkMixedWriteOperationTests.cs index a1a899584e8..c14714121a3 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/BulkMixedWriteOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/BulkMixedWriteOperationTests.cs @@ -1376,8 +1376,8 @@ public void Execute_unacknowledged_with_an_error_in_the_first_batch_and_ordered_ }; using (var readWriteBinding = CreateReadWriteBinding(useImplicitSession: true)) - using (var channelSource = readWriteBinding.GetWriteChannelSource(OperationCancellationContext.NoTimeout)) - using (var channel = channelSource.GetChannel(OperationCancellationContext.NoTimeout)) + using (var channelSource = readWriteBinding.GetWriteChannelSource(OperationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationContext.NoTimeout)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, readWriteBinding.Session.Fork())) { var result = ExecuteOperation(subject, channelBinding, async); @@ -1423,8 +1423,8 @@ public void Execute_unacknowledged_with_an_error_in_the_first_batch_and_ordered_ }; using (var readWriteBinding = CreateReadWriteBinding(useImplicitSession: true)) - using (var channelSource = readWriteBinding.GetWriteChannelSource(OperationCancellationContext.NoTimeout)) - using (var channel = channelSource.GetChannel(OperationCancellationContext.NoTimeout)) + using (var channelSource = readWriteBinding.GetWriteChannelSource(OperationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationContext.NoTimeout)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, readWriteBinding.Session.Fork())) { var result = ExecuteOperation(subject, channelBinding, async); @@ -1464,8 +1464,8 @@ public void Execute_unacknowledged_with_an_error_in_the_second_batch_and_ordered }; using (var readWriteBinding = CreateReadWriteBinding(useImplicitSession: true)) - using (var channelSource = readWriteBinding.GetWriteChannelSource(OperationCancellationContext.NoTimeout)) - using (var channel = channelSource.GetChannel(OperationCancellationContext.NoTimeout)) + using (var channelSource = readWriteBinding.GetWriteChannelSource(OperationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationContext.NoTimeout)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, readWriteBinding.Session.Fork())) { var result = ExecuteOperation(subject, channelBinding, async); @@ -1505,8 +1505,8 @@ public void Execute_unacknowledged_with_an_error_in_the_second_batch_and_ordered }; using (var readWriteBinding = CreateReadWriteBinding(useImplicitSession: true)) - using (var channelSource = readWriteBinding.GetWriteChannelSource(OperationCancellationContext.NoTimeout)) - using (var channel = channelSource.GetChannel(OperationCancellationContext.NoTimeout)) + using (var channelSource = readWriteBinding.GetWriteChannelSource(OperationContext.NoTimeout)) + using (var channel = channelSource.GetChannel(OperationContext.NoTimeout)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, readWriteBinding.Session.Fork())) { var result = ExecuteOperation(subject, channelBinding, async); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs index 78854425a89..ff500312db1 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs @@ -450,25 +450,25 @@ public void MoveNext_should_call_Resume_after_resumable_exception( if (async) { mockCursor.Setup(c => c.MoveNextAsync(It.IsAny())).Returns(CreateFaultedTask(resumableException)); - mockOperation.Setup(o => o.ResumeAsync(mockBinding.Object, It.IsAny())).Returns(Task.FromResult(mockResumedCursor.Object)); + mockOperation.Setup(o => o.ResumeAsync(mockBinding.Object, It.IsAny())).Returns(Task.FromResult(mockResumedCursor.Object)); mockResumedCursor.Setup(c => c.MoveNextAsync(It.IsAny())).Returns(Task.FromResult(expectedResult)); result = subject.MoveNextAsync(It.IsAny()).GetAwaiter().GetResult(); mockCursor.Verify(c => c.MoveNextAsync(It.IsAny()), Times.Once); - mockOperation.Verify(o => o.ResumeAsync(mockBinding.Object, It.IsAny()), Times.Once); + mockOperation.Verify(o => o.ResumeAsync(mockBinding.Object, It.IsAny()), Times.Once); mockResumedCursor.Verify(c => c.MoveNextAsync(It.IsAny()), Times.Once); } else { mockCursor.Setup(c => c.MoveNext(It.IsAny())).Throws(resumableException); - mockOperation.Setup(o => o.Resume(mockBinding.Object, It.IsAny())).Returns(mockResumedCursor.Object); + mockOperation.Setup(o => o.Resume(mockBinding.Object, It.IsAny())).Returns(mockResumedCursor.Object); mockResumedCursor.Setup(c => c.MoveNext(It.IsAny())).Returns(expectedResult); result = subject.MoveNext(It.IsAny()); mockCursor.Verify(c => c.MoveNext(It.IsAny()), Times.Exactly(2)); - mockOperation.Verify(o => o.Resume(mockBinding.Object, It.IsAny()), Times.Once); + mockOperation.Verify(o => o.Resume(mockBinding.Object, It.IsAny()), Times.Once); mockResumedCursor.Verify(c => c.MoveNext(It.IsAny()), Times.Once); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs index 48a11919dd3..8b73a49ed7d 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs @@ -69,8 +69,8 @@ public async Task Enumerating_operations_should_be_stopped_when_error([Values(fa var subject = new CompositeWriteOperation((healthyOperation1.Object, IsMainOperation: false), (faultyOperation2.Object, IsMainOperation: false), (healthyOperation3.Object, IsMainOperation: true)); var resultedException = async - ? await Record.ExceptionAsync(() => subject.ExecuteAsync(Mock.Of(), OperationCancellationContext.NoTimeout)) - : Record.Exception(() => subject.Execute(Mock.Of(), OperationCancellationContext.NoTimeout)); + ? await Record.ExceptionAsync(() => subject.ExecuteAsync(Mock.Of(), OperationContext.NoTimeout)) + : Record.Exception(() => subject.Execute(Mock.Of(), OperationContext.NoTimeout)); resultedException.Should().Be(testException); @@ -92,8 +92,8 @@ public void Enumerating_operations_should_return_result_of_main_operation([Value var subject = new CompositeWriteOperation((operation1.Object, IsMainOperation: false), (operation2.Object, IsMainOperation: true), (operation3.Object, IsMainOperation: false)); var result = async - ? subject.ExecuteAsync(Mock.Of(), OperationCancellationContext.NoTimeout).GetAwaiter().GetResult() - : subject.Execute(Mock.Of(), OperationCancellationContext.NoTimeout); + ? subject.ExecuteAsync(Mock.Of(), OperationContext.NoTimeout).GetAwaiter().GetResult() + : subject.Execute(Mock.Of(), OperationContext.NoTimeout); result.Should().Be(operation2Result); @@ -107,10 +107,10 @@ private Mock> CreateFaultyOperation(Exception test { var mockedOperation = new Mock>(); mockedOperation - .Setup(c => c.Execute(It.IsAny(), It.IsAny())) + .Setup(c => c.Execute(It.IsAny(), It.IsAny())) .Throws(testException); mockedOperation - .Setup(c => c.ExecuteAsync(It.IsAny(), It.IsAny())) + .Setup(c => c.ExecuteAsync(It.IsAny(), It.IsAny())) .Throws(testException); return mockedOperation; } @@ -119,10 +119,10 @@ private Mock> CreateHealthyOperation(BsonDocument { var mockedOperation = new Mock>(); mockedOperation - .Setup(c => c.Execute(It.IsAny(), It.IsAny())) + .Setup(c => c.Execute(It.IsAny(), It.IsAny())) .Returns(response); mockedOperation - .Setup(c => c.ExecuteAsync(It.IsAny(), It.IsAny())) + .Setup(c => c.ExecuteAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(response); return mockedOperation; } @@ -131,11 +131,11 @@ private void VeryfyOperation(Mock> mockedOperation { if (async) { - mockedOperation.Verify(c => c.ExecuteAsync(It.IsAny(), It.IsAny()), hasBeenCalled ? Times.Once : Times.Never); + mockedOperation.Verify(c => c.ExecuteAsync(It.IsAny(), It.IsAny()), hasBeenCalled ? Times.Once : Times.Never); } else { - mockedOperation.Verify(c => c.Execute(It.IsAny(), It.IsAny()), hasBeenCalled ? Times.Once : Times.Never); + mockedOperation.Verify(c => c.Execute(It.IsAny(), It.IsAny()), hasBeenCalled ? Times.Once : Times.Never); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs index 90d11362d80..191ab5e3fd1 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs @@ -1031,11 +1031,11 @@ private BsonDocument ExecuteOperation(CreateCollectionOperation subject, IWriteB { if (async) { - return subject.ExecuteAsync(binding, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult(); + return subject.ExecuteAsync(binding, OperationContext.NoTimeout).GetAwaiter().GetResult(); } else { - return subject.Execute(binding, OperationCancellationContext.NoTimeout); + return subject.Execute(binding, OperationContext.NoTimeout); } } @@ -1045,7 +1045,7 @@ private BsonDocument GetCollectionInfo(IReadBinding binding) { Filter = new BsonDocument("name", _collectionNamespace.CollectionName) }; - return listCollectionsOperation.Execute(binding, OperationCancellationContext.NoTimeout).Single(); + return listCollectionsOperation.Execute(binding, OperationContext.NoTimeout).Single(); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs index 681b2bad18b..a30edfcc563 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs @@ -331,7 +331,7 @@ private BsonDocument GetViewInfo(IReadBinding binding, string viewName) { Filter = new BsonDocument("name", viewName) }; - return listCollectionsOperation.Execute(binding, OperationCancellationContext.NoTimeout).Single(); + return listCollectionsOperation.Execute(binding, OperationContext.NoTimeout).Single(); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/EvalOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/EvalOperationTests.cs index a66b02b2462..6ae0637b1ef 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/EvalOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/EvalOperationTests.cs @@ -304,11 +304,11 @@ private BsonValue ExecuteOperation(EvalOperation operation, IWriteBinding bindin { if (async) { - return operation.ExecuteAsync(binding, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult(); + return operation.ExecuteAsync(binding, OperationContext.NoTimeout).GetAwaiter().GetResult(); } else { - return operation.Execute(binding, OperationCancellationContext.NoTimeout); + return operation.Execute(binding, OperationContext.NoTimeout); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs b/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs index 414e556fadf..467575a7b67 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs @@ -142,7 +142,7 @@ private protected TResult ExecuteOperation(IReadOperation oper using (var binding = CreateReadBinding()) using (var bindingHandle = new ReadBindingHandle(binding)) { - return operation.Execute(bindingHandle, OperationCancellationContext.NoTimeout); + return operation.Execute(bindingHandle, OperationContext.NoTimeout); } } @@ -164,8 +164,8 @@ private protected async Task ExecuteOperationAsync(IReadOperat using (var bindingHandle = new ReadBindingHandle(binding)) { return async ? - await operation.ExecuteAsync(bindingHandle, OperationCancellationContext.NoTimeout) : - operation.Execute(bindingHandle, OperationCancellationContext.NoTimeout); + await operation.ExecuteAsync(bindingHandle, OperationContext.NoTimeout) : + operation.Execute(bindingHandle, OperationContext.NoTimeout); } } @@ -173,11 +173,11 @@ private protected TResult ExecuteOperation(IReadOperation oper { if (async) { - return operation.ExecuteAsync(binding, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult(); + return operation.ExecuteAsync(binding, OperationContext.NoTimeout).GetAwaiter().GetResult(); } else { - return operation.Execute(binding, OperationCancellationContext.NoTimeout); + return operation.Execute(binding, OperationContext.NoTimeout); } } @@ -195,7 +195,7 @@ private protected TResult ExecuteOperationSync(IWriteOperation using (var binding = CreateReadWriteBinding(useImplicitSession)) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { - return operation.Execute(bindingHandle, OperationCancellationContext.NoTimeout); + return operation.Execute(bindingHandle, OperationContext.NoTimeout); } } @@ -215,11 +215,11 @@ private protected TResult ExecuteOperation(IWriteOperation ope { if (async) { - return operation.ExecuteAsync(binding, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult(); + return operation.ExecuteAsync(binding, OperationContext.NoTimeout).GetAwaiter().GetResult(); } else { - return operation.Execute(binding, OperationCancellationContext.NoTimeout); + return operation.Execute(binding, OperationContext.NoTimeout); } } @@ -234,7 +234,7 @@ private protected async Task ExecuteOperationAsync(IReadOperat private protected async Task ExecuteOperationAsync(IReadOperation operation, IReadBinding binding) { - return await operation.ExecuteAsync(binding, OperationCancellationContext.NoTimeout); + return await operation.ExecuteAsync(binding, OperationContext.NoTimeout); } private protected async Task ExecuteOperationAsync(IWriteOperation operation, bool useImplicitSession = false) @@ -242,7 +242,7 @@ private protected async Task ExecuteOperationAsync(IWriteOpera using (var binding = CreateReadWriteBinding(useImplicitSession)) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { - return await operation.ExecuteAsync(bindingHandle, OperationCancellationContext.NoTimeout); + return await operation.ExecuteAsync(bindingHandle, OperationContext.NoTimeout); } } @@ -253,23 +253,23 @@ private protected async Task ExecuteOperationAsync(IWriteOpera { if (async) { - return await operation.ExecuteAsync(bindingHandle, OperationCancellationContext.NoTimeout); + return await operation.ExecuteAsync(bindingHandle, OperationContext.NoTimeout); } else { - return operation.Execute(bindingHandle, OperationCancellationContext.NoTimeout); + return operation.Execute(bindingHandle, OperationContext.NoTimeout); } } } private protected TResult ExecuteOperation(IWriteOperation operation, IWriteBinding binding, bool async) => async ? - operation.ExecuteAsync(binding, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult() : - operation.Execute(binding, OperationCancellationContext.NoTimeout); + operation.ExecuteAsync(binding, OperationContext.NoTimeout).GetAwaiter().GetResult() : + operation.Execute(binding, OperationContext.NoTimeout); private protected async Task ExecuteOperationAsync(IWriteOperation operation, IWriteBinding binding) { - return await operation.ExecuteAsync(binding, OperationCancellationContext.NoTimeout); + return await operation.ExecuteAsync(binding, OperationContext.NoTimeout); } private protected void CreateIndexes(params CreateIndexRequest[] requests) @@ -542,8 +542,8 @@ private protected void VerifySessionIdWasSentWhenSupported(IWriteOperat } private protected void VerifySessionIdSending( - Func> executeAsync, - Func execute, + Func> executeAsync, + Func execute, Action assertResults, string commandName, bool async, @@ -558,11 +558,11 @@ private protected void VerifySessionIdSending( Exception exception; if (async) { - exception = Record.Exception(() => executeAsync(binding, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult()); + exception = Record.Exception(() => executeAsync(binding, OperationContext.NoTimeout).GetAwaiter().GetResult()); } else { - exception = Record.Exception(() => execute(binding, OperationCancellationContext.NoTimeout)); + exception = Record.Exception(() => execute(binding, OperationContext.NoTimeout)); } assertResults(eventCapturer, session, exception); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/ReadCommandOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/ReadCommandOperationTests.cs index 4ec60ee1931..f866f268877 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/ReadCommandOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/ReadCommandOperationTests.cs @@ -305,11 +305,11 @@ public void Execute_should_call_GetChannel_only_once([Values(false, true)] bool ExecuteOperation(subject, binding, async); if (async) { - mockChannelSource.Verify(c => c.GetChannelAsync(It.IsAny()), Times.Once); + mockChannelSource.Verify(c => c.GetChannelAsync(It.IsAny()), Times.Once); } else { - mockChannelSource.Verify(c => c.GetChannel(It.IsAny()), Times.Once); + mockChannelSource.Verify(c => c.GetChannel(It.IsAny()), Times.Once); } } @@ -320,8 +320,8 @@ private Mock CreateMockReadBinding(ReadPreference readPreference, var mockSession = new Mock(); mockBinding.SetupGet(b => b.ReadPreference).Returns(readPreference); mockBinding.SetupGet(b => b.Session).Returns(mockSession.Object); - mockBinding.Setup(b => b.GetReadChannelSource(It.IsAny())).Returns(channelSource); - mockBinding.Setup(b => b.GetReadChannelSourceAsync(It.IsAny())).Returns(Task.FromResult(channelSource)); + mockBinding.Setup(b => b.GetReadChannelSource(It.IsAny())).Returns(channelSource); + mockBinding.Setup(b => b.GetReadChannelSourceAsync(It.IsAny())).Returns(Task.FromResult(channelSource)); return mockBinding; } @@ -335,8 +335,8 @@ private Mock CreateMockChannelSource(ServerDescription ser { var mockChannelSource = new Mock(); mockChannelSource.SetupGet(s => s.ServerDescription).Returns(serverDescription); - mockChannelSource.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); - mockChannelSource.Setup(s => s.GetChannelAsync(It.IsAny())).Returns(Task.FromResult(channel)); + mockChannelSource.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); + mockChannelSource.Setup(s => s.GetChannelAsync(It.IsAny())).Returns(Task.FromResult(channel)); return mockChannelSource; } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs index ae6a5e87ae1..f4ab46bce2e 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs @@ -98,7 +98,7 @@ private IWriteBinding CreateBinding(bool areRetryableWritesSupported, bool hasSe var session = CreateSession(hasSessionId, isInTransaction); var channelSource = CreateChannelSource(areRetryableWritesSupported); mockBinding.SetupGet(m => m.Session).Returns(session); - mockBinding.Setup(m => m.GetWriteChannelSource(It.IsAny())).Returns(channelSource); + mockBinding.Setup(m => m.GetWriteChannelSource(It.IsAny())).Returns(channelSource); return mockBinding.Object; } @@ -114,7 +114,7 @@ private IChannelSourceHandle CreateChannelSource(bool areRetryableWritesSupporte { var mockChannelSource = new Mock(); var channel = CreateChannel(areRetryableWritesSupported); - mockChannelSource.Setup(m => m.GetChannel(It.IsAny())).Returns(channel); + mockChannelSource.Setup(m => m.GetChannel(It.IsAny())).Returns(channel); return mockChannelSource.Object; } @@ -142,7 +142,7 @@ private ConnectionDescription CreateConnectionDescription(bool withLogicalSessio private RetryableWriteContext CreateContext(bool retryRequested, bool areRetryableWritesSupported, bool hasSessionId, bool isInTransaction) { var binding = CreateBinding(areRetryableWritesSupported, hasSessionId, isInTransaction); - return RetryableWriteContext.Create(binding, retryRequested, OperationCancellationContext.NoTimeout); + return RetryableWriteContext.Create(binding, retryRequested, OperationContext.NoTimeout); } private IRetryableWriteOperation CreateOperation(bool withWriteConcern, bool isAcknowledged) diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/WriteCommandOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/WriteCommandOperationTests.cs index 4837ed67dee..bc44255fa2c 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/WriteCommandOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/WriteCommandOperationTests.cs @@ -214,8 +214,8 @@ private Mock CreateMockWriteBinding(IChannelSourceHandle channelS var mockBinding = new Mock(); var mockSession = new Mock(); mockBinding.SetupGet(b => b.Session).Returns(mockSession.Object); - mockBinding.Setup(b => b.GetWriteChannelSource(It.IsAny())).Returns(channelSource); - mockBinding.Setup(b => b.GetWriteChannelSourceAsync(It.IsAny())).Returns(Task.FromResult(channelSource)); + mockBinding.Setup(b => b.GetWriteChannelSource(It.IsAny())).Returns(channelSource); + mockBinding.Setup(b => b.GetWriteChannelSourceAsync(It.IsAny())).Returns(Task.FromResult(channelSource)); return mockBinding; } @@ -229,8 +229,8 @@ private Mock CreateMockChannelSource(ServerDescription ser { var mockChannelSource = new Mock(); mockChannelSource.SetupGet(s => s.ServerDescription).Returns(serverDescription); - mockChannelSource.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); - mockChannelSource.Setup(s => s.GetChannelAsync(It.IsAny())).Returns(Task.FromResult(channel)); + mockChannelSource.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); + mockChannelSource.Setup(s => s.GetChannelAsync(It.IsAny())).Returns(Task.FromResult(channel)); return mockChannelSource; } diff --git a/tests/MongoDB.Driver.Tests/Core/Servers/LoadBalancedServerTests.cs b/tests/MongoDB.Driver.Tests/Core/Servers/LoadBalancedServerTests.cs index 9b554bb75e9..16709b65bf3 100644 --- a/tests/MongoDB.Driver.Tests/Core/Servers/LoadBalancedServerTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Servers/LoadBalancedServerTests.cs @@ -59,8 +59,8 @@ public LoadBalancedTests(ITestOutputHelper output) : base(output) _clusterClock = new Mock().Object; _mockConnectionPool = new Mock(); - _mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny())).Returns(new Mock().Object); - _mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny())).Returns(Task.FromResult(new Mock().Object)); + _mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny())).Returns(new Mock().Object); + _mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny())).Returns(Task.FromResult(new Mock().Object)); _mockConnectionPoolFactory = new Mock(); _mockConnectionPoolFactory .Setup(f => f.CreateConnectionPool(It.IsAny(), _endPoint, It.IsAny())) @@ -82,8 +82,8 @@ public async Task ChannelFork_should_not_affect_operations_count([Values(false, IClusterableServer server = SetupServer(false, false); var channel = async ? - await server.GetChannelAsync(OperationCancellationContext.NoTimeout) : - server.GetChannel(OperationCancellationContext.NoTimeout); + await server.GetChannelAsync(OperationContext.NoTimeout) : + server.GetChannel(OperationContext.NoTimeout); server.OutstandingOperationsCount.Should().Be(1); @@ -179,11 +179,11 @@ public async Task GetChannel_should_clear_connection_pool_when_opening_connectio var mockConnectionPool = new Mock(); var authenticationException = new MongoAuthenticationException(connectionId, "Invalid login.") { ServiceId = ObjectId.GenerateNewId() }; mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Callback(() => server.HandleExceptionOnOpen(authenticationException)) .Throws(authenticationException); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Callback(() => server.HandleExceptionOnOpen(authenticationException)) .Throws(authenticationException); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); @@ -204,8 +204,8 @@ public async Task GetChannel_should_clear_connection_pool_when_opening_connectio server.Initialize(); var exception = async ? - await Record.ExceptionAsync(() => server.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => server.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => server.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => server.GetChannel(OperationContext.NoTimeout)); exception.Should().BeOfType(); mockConnectionPool.Verify(p => p.Clear(It.IsAny()), Times.Once()); @@ -218,8 +218,8 @@ public async Task GetChannel_should_get_a_connection([Values(false, true)] bool _subject.Initialize(); var channel = async ? - await _subject.GetChannelAsync(OperationCancellationContext.NoTimeout) : - _subject.GetChannel(OperationCancellationContext.NoTimeout); + await _subject.GetChannelAsync(OperationContext.NoTimeout) : + _subject.GetChannel(OperationContext.NoTimeout); channel.Should().NotBeNull(); } @@ -233,8 +233,8 @@ public async Task GetChannel_should_not_increase_operations_count_on_exception( IClusterableServer server = SetupServer(connectionOpenException, !connectionOpenException); var exception = async ? - await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => _subject.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationContext.NoTimeout)); exception.Should().NotBeNull(); server.OutstandingOperationsCount.Should().Be(0); @@ -252,8 +252,8 @@ public async Task GetChannel_should_set_operations_count_correctly( for (int i = 0; i < operationsCount; i++) { var channel = async ? - await server.GetChannelAsync(OperationCancellationContext.NoTimeout) : - server.GetChannel(OperationCancellationContext.NoTimeout); + await server.GetChannelAsync(OperationContext.NoTimeout) : + server.GetChannel(OperationContext.NoTimeout); channels.Add(channel); } @@ -272,8 +272,8 @@ public async Task GetChannel_should_throw_when_not_initialized( [Values(false, true)] bool async) { var exception = async ? - await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => _subject.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -285,8 +285,8 @@ public async Task GetChannel_should_throw_when_disposed([Values(false, true)] bo _subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => _subject.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -324,8 +324,8 @@ public async Task GetChannel_should_not_update_topology_and_clear_connection_poo subject.Initialize(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationContext.NoTimeout)); exception.Should().Be(openConnectionException); subject.Description.Type.Should().Be(ServerType.LoadBalanced); @@ -386,30 +386,30 @@ private Server SetupServer(bool exceptionOnConnectionOpen, bool exceptionOnConne if (exceptionOnConnectionAcquire) { mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Throws(new TimeoutException("Timeout")); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Throws(new TimeoutException("Timeout")); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); } else if (exceptionOnConnectionOpen) { mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Throws(new MongoAuthenticationException(connectionId, "Invalid login.")); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Throws(new MongoAuthenticationException(connectionId, "Invalid login.")); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); } else { mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Returns(mockConnectionHandle.Object); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Returns(Task.FromResult(mockConnectionHandle.Object)); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); } diff --git a/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs b/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs index 85c560d5dd3..6f2778d71f4 100644 --- a/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs @@ -71,8 +71,8 @@ public ServerTests(ITestOutputHelper output) : base(output) _clusterClock = new Mock().Object; _directConnection = false; _mockConnectionPool = new Mock(); - _mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny())).Returns(new Mock().Object); - _mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny())).Returns(Task.FromResult(new Mock().Object)); + _mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny())).Returns(new Mock().Object); + _mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny())).Returns(Task.FromResult(new Mock().Object)); _mockConnectionPoolFactory = new Mock(); _mockConnectionPoolFactory .Setup(f => f.CreateConnectionPool(It.IsAny(), _endPoint, It.IsAny())) @@ -104,8 +104,8 @@ public async Task ChannelFork_should_not_affect_operations_count([Values(false, IClusterableServer server = SetupServer(false, false); var channel = async ? - await server.GetChannelAsync(OperationCancellationContext.NoTimeout) : - server.GetChannel(OperationCancellationContext.NoTimeout); + await server.GetChannelAsync(OperationContext.NoTimeout) : + server.GetChannel(OperationContext.NoTimeout); server.OutstandingOperationsCount.Should().Be(1); @@ -224,11 +224,11 @@ public async Task GetChannel_should_clear_connection_pool_when_opening_connectio var exceptionToThrow = new MongoAuthenticationException(connectionId, "Invalid login."); mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Callback(() => server.HandleExceptionOnOpen(exceptionToThrow)) .Throws(exceptionToThrow); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Callback(() => server.HandleExceptionOnOpen(exceptionToThrow)) .Throws(exceptionToThrow); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); @@ -236,8 +236,8 @@ public async Task GetChannel_should_clear_connection_pool_when_opening_connectio server.Initialize(); var exception = async ? - await Record.ExceptionAsync(() => server.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => server.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => server.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => server.GetChannel(OperationContext.NoTimeout)); exception.Should().BeOfType(); mockConnectionPool.Verify(p => p.Clear(It.IsAny()), Times.Once()); @@ -252,8 +252,8 @@ public async Task GetChannel_should_get_a_connection( _subject.Initialize(); var channel = async ? - await _subject.GetChannelAsync(OperationCancellationContext.NoTimeout) : - _subject.GetChannel(OperationCancellationContext.NoTimeout); + await _subject.GetChannelAsync(OperationContext.NoTimeout) : + _subject.GetChannel(OperationContext.NoTimeout); channel.Should().NotBeNull(); } @@ -267,8 +267,8 @@ public async Task GetChannel_should_not_increase_operations_count_on_exception( IClusterableServer server = SetupServer(connectionOpenException, !connectionOpenException); var exception = async ? - await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => _subject.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationContext.NoTimeout)); exception.Should().NotBeNull(); server.OutstandingOperationsCount.Should().Be(0); @@ -286,8 +286,8 @@ public async Task GetChannel_should_set_operations_count_correctly( for (int i = 0; i < operationsCount; i++) { var channel = async ? - await server.GetChannelAsync(OperationCancellationContext.NoTimeout) : - server.GetChannel(OperationCancellationContext.NoTimeout); + await server.GetChannelAsync(OperationContext.NoTimeout) : + server.GetChannel(OperationContext.NoTimeout); channels.Add(channel); } @@ -306,8 +306,8 @@ public async Task GetChannel_should_throw_when_not_initialized( [Values(false, true)] bool async) { var exception = async ? - await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => _subject.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -321,8 +321,8 @@ public async Task GetChannel_should_throw_when_disposed( _subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => _subject.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => _subject.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => _subject.GetChannel(OperationContext.NoTimeout)); exception.Should().BeOfType(); } @@ -368,8 +368,8 @@ public async Task GetChannel_should_update_topology_and_clear_connection_pool_on connectionPool.SetReady(); var exception = async ? - await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationCancellationContext.NoTimeout)) : - Record.Exception(() => subject.GetChannel(OperationCancellationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.GetChannelAsync(OperationContext.NoTimeout)) : + Record.Exception(() => subject.GetChannel(OperationContext.NoTimeout)); exception.Should().Be(openConnectionException); subject.Description.Type.Should().Be(ServerType.Unknown); @@ -402,8 +402,8 @@ public void HandleChannelException_should_update_topology_as_expected_on_network mockConnection.SetupGet(c => c.Description) .Returns(new ConnectionDescription(new ConnectionId(serverId, 0), helloResult)); var mockConnectionPool = new Mock(); - mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny())).Returns(mockConnection.Object); - mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny())).ReturnsAsync(mockConnection.Object); + mockConnectionPool.Setup(p => p.AcquireConnection(It.IsAny())).Returns(mockConnection.Object); + mockConnectionPool.Setup(p => p.AcquireConnectionAsync(It.IsAny())).ReturnsAsync(mockConnection.Object); var mockConnectionPoolFactory = new Mock(); mockConnectionPoolFactory .Setup(f => f.CreateConnectionPool(It.IsAny(), _endPoint, It.IsAny())) @@ -787,30 +787,30 @@ private Server SetupServer(bool exceptionOnConnectionOpen, bool exceptionOnConne if (exceptionOnConnectionAcquire) { mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Throws(new TimeoutException("Timeout")); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Throws(new TimeoutException("Timeout")); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); } else if (exceptionOnConnectionOpen) { mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Throws(new MongoAuthenticationException(connectionId, "Invalid login.")); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Throws(new MongoAuthenticationException(connectionId, "Invalid login.")); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); } else { mockConnectionPool - .Setup(p => p.AcquireConnection(It.IsAny())) + .Setup(p => p.AcquireConnection(It.IsAny())) .Returns(mockConnectionHandle.Object); mockConnectionPool - .Setup(p => p.AcquireConnectionAsync(It.IsAny())) + .Setup(p => p.AcquireConnectionAsync(It.IsAny())) .Returns(Task.FromResult(mockConnectionHandle.Object)); mockConnectionPool.Setup(p => p.Clear(It.IsAny())); } @@ -853,9 +853,8 @@ public void Command_should_send_the_greater_of_the_session_and_cluster_cluster_t using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer))) using (var session = cluster.StartSession()) { - var cancellationContext = OperationCancellationContext.NoTimeout; - var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, cancellationContext); - using (var channel = server.GetChannel(cancellationContext)) + var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); + using (var channel = server.GetChannel(OperationContext.NoTimeout)) { session.AdvanceClusterTime(sessionClusterTime); server.ClusterClock.AdvanceClusterTime(clusterClusterTime); @@ -901,9 +900,8 @@ public void Command_should_update_the_session_and_cluster_cluster_times() using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer))) using (var session = cluster.StartSession()) { - var cancellationContext = OperationCancellationContext.NoTimeout; - var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, cancellationContext); - using (var channel = server.GetChannel(cancellationContext)) + var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); + using (var channel = server.GetChannel(OperationContext.NoTimeout)) { var command = BsonDocument.Parse("{ ping : 1 }"); channel.Command( @@ -945,9 +943,8 @@ public async Task Command_should_use_serverApi([Values(false, true)] bool async) using (var cluster = CoreTestConfiguration.CreateCluster(builder)) using (var session = cluster.StartSession()) { - var cancellationContext = OperationCancellationContext.NoTimeout; - var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, cancellationContext); - using (var channel = server.GetChannel(cancellationContext)) + var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); + using (var channel = server.GetChannel(OperationContext.NoTimeout)) { var command = BsonDocument.Parse("{ ping : 1 }"); if (async) diff --git a/tests/MongoDB.Driver.Tests/Encryption/ClientEncryptionTests.cs b/tests/MongoDB.Driver.Tests/Encryption/ClientEncryptionTests.cs index 1cbb70f2b5d..f541233952f 100644 --- a/tests/MongoDB.Driver.Tests/Encryption/ClientEncryptionTests.cs +++ b/tests/MongoDB.Driver.Tests/Encryption/ClientEncryptionTests.cs @@ -137,14 +137,14 @@ public async Task CreateEncryptedCollection_should_handle_generated_key_when_sec var mockServer = new Mock(); mockServer.SetupGet(s => s.Description).Returns(serverDescription); var channel = Mock.Of(c => c.ConnectionDescription == new ConnectionDescription(new ConnectionId(serverId), new HelloResult(new BsonDocument("maxWireVersion", serverDescription.WireVersionRange.Max)))); - mockServer.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); - mockServer.Setup(s => s.GetChannelAsync(It.IsAny())).ReturnsAsync(channel); + mockServer.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); + mockServer.Setup(s => s.GetChannelAsync(It.IsAny())).ReturnsAsync(channel); mockCluster - .Setup(m => m.SelectServer(It.IsAny(), It.IsAny())) + .Setup(m => m.SelectServer(It.IsAny(), It.IsAny())) .Returns(mockServer.Object); mockCluster - .Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())) + .Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(mockServer.Object); var database = Mock.Of(d => @@ -226,14 +226,14 @@ public async Task CreateEncryptedCollection_should_handle_various_encryptedField var mockServer = new Mock(); mockServer.SetupGet(s => s.Description).Returns(serverDescription); var channel = Mock.Of(c => c.ConnectionDescription == new ConnectionDescription(new ConnectionId(serverId), new HelloResult(new BsonDocument("maxWireVersion", serverDescription.WireVersionRange.Max)))); - mockServer.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); - mockServer.Setup(s => s.GetChannelAsync(It.IsAny())).ReturnsAsync(channel); + mockServer.Setup(s => s.GetChannel(It.IsAny())).Returns(channel); + mockServer.Setup(s => s.GetChannelAsync(It.IsAny())).ReturnsAsync(channel); mockCluster - .Setup(m => m.SelectServer(It.IsAny(), It.IsAny())) + .Setup(m => m.SelectServer(It.IsAny(), It.IsAny())) .Returns(mockServer.Object); mockCluster - .Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())) + .Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(mockServer.Object); var database = Mock.Of(d => diff --git a/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenConfigureFailPointTest.cs b/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenConfigureFailPointTest.cs index 56cf3056691..72bf46cafc2 100644 --- a/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenConfigureFailPointTest.cs +++ b/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenConfigureFailPointTest.cs @@ -52,7 +52,7 @@ protected virtual IServer GetFailPointServer() } var cluster = TestRunner.FailPointCluster; - return cluster.SelectServer(WritableServerSelector.Instance, OperationCancellationContext.NoTimeout); + return cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); } protected async virtual Task GetFailPointServerAsync() @@ -63,7 +63,7 @@ protected async virtual Task GetFailPointServerAsync() } var cluster = TestRunner.FailPointCluster; - return await cluster.SelectServerAsync(WritableServerSelector.Instance, OperationCancellationContext.NoTimeout).ConfigureAwait(false); + return await cluster.SelectServerAsync(WritableServerSelector.Instance, OperationContext.NoTimeout).ConfigureAwait(false); } protected override void SetArgument(string name, BsonValue value) diff --git a/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenTargetedFailPointTest.cs b/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenTargetedFailPointTest.cs index 97557930acc..5e91ce740e6 100644 --- a/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenTargetedFailPointTest.cs +++ b/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenTargetedFailPointTest.cs @@ -33,14 +33,14 @@ protected override IServer GetFailPointServer() { var pinnedServerEndpoint = GetPinnedServerEndpointAndAssertNotNull(); var pinnedServerSelector = CreateServerSelector(pinnedServerEndpoint); - return TestRunner.FailPointCluster.SelectServer(pinnedServerSelector, OperationCancellationContext.NoTimeout); + return TestRunner.FailPointCluster.SelectServer(pinnedServerSelector, OperationContext.NoTimeout); } protected async override Task GetFailPointServerAsync() { var pinnedServerEndpoint = GetPinnedServerEndpointAndAssertNotNull(); var pinnedServerSelector = CreateServerSelector(pinnedServerEndpoint); - return await TestRunner.FailPointCluster.SelectServerAsync(pinnedServerSelector, OperationCancellationContext.NoTimeout).ConfigureAwait(false); + return await TestRunner.FailPointCluster.SelectServerAsync(pinnedServerSelector, OperationContext.NoTimeout).ConfigureAwait(false); } // private methods diff --git a/tests/MongoDB.Driver.Tests/OperationCancellationContextTests.cs b/tests/MongoDB.Driver.Tests/OperationContextTests.cs similarity index 70% rename from tests/MongoDB.Driver.Tests/OperationCancellationContextTests.cs rename to tests/MongoDB.Driver.Tests/OperationContextTests.cs index f75d8214127..8025b3f5acd 100644 --- a/tests/MongoDB.Driver.Tests/OperationCancellationContextTests.cs +++ b/tests/MongoDB.Driver.Tests/OperationContextTests.cs @@ -22,7 +22,7 @@ namespace MongoDB.Driver.Tests { - public class OperationCancellationContextTests + public class OperationContextTests { [Fact] public void Constructor_should_initialize_properties() @@ -31,10 +31,10 @@ public void Constructor_should_initialize_properties() using var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; - var cancellationContext = new OperationCancellationContext(timeout, cancellationToken); + var operationContext = new OperationContext(timeout, cancellationToken); - cancellationContext.Timeout.Should().Be(timeout); - cancellationContext.CancellationToken.Should().Be(cancellationToken); + operationContext.Timeout.Should().Be(timeout); + operationContext.CancellationToken.Should().Be(cancellationToken); } [Fact] @@ -44,9 +44,9 @@ public void Elapsed_should_return_elapsed_time() Thread.Sleep(10); stopwatch.Stop(); - var cancellationContext = new OperationCancellationContext(stopwatch, TimeSpan.Zero, CancellationToken.None); + var operationContext = new OperationContext(stopwatch, TimeSpan.Zero, CancellationToken.None); - cancellationContext.Elapsed.Should().Be(stopwatch.Elapsed); + operationContext.Elapsed.Should().Be(stopwatch.Elapsed); } [Fact] @@ -57,9 +57,9 @@ public void RemainingTimeout_should_calculate() Thread.Sleep(10); stopwatch.Stop(); - var cancellationContext = new OperationCancellationContext(stopwatch, timeout, CancellationToken.None); + var operationContext = new OperationContext(stopwatch, timeout, CancellationToken.None); - cancellationContext.RemainingTimeout.Should().Be(timeout - stopwatch.Elapsed); + operationContext.RemainingTimeout.Should().Be(timeout - stopwatch.Elapsed); } [Fact] @@ -69,9 +69,9 @@ public void RemainingTimeout_should_return_infinite_for_infinite_timeout() Thread.Sleep(10); stopwatch.Stop(); - var cancellationContext = new OperationCancellationContext(stopwatch, Timeout.InfiniteTimeSpan, CancellationToken.None); + var operationContext = new OperationContext(stopwatch, Timeout.InfiniteTimeSpan, CancellationToken.None); - cancellationContext.RemainingTimeout.Should().Be(Timeout.InfiniteTimeSpan); + operationContext.RemainingTimeout.Should().Be(Timeout.InfiniteTimeSpan); } [Fact] @@ -82,9 +82,9 @@ public void RenainingTimeout_could_be_negative() Thread.Sleep(10); stopwatch.Stop(); - var cancellationContext = new OperationCancellationContext(stopwatch, timeout, CancellationToken.None); + var operationContext = new OperationContext(stopwatch, timeout, CancellationToken.None); - cancellationContext.RemainingTimeout.Should().Be(timeout - stopwatch.Elapsed); + operationContext.RemainingTimeout.Should().Be(timeout - stopwatch.Elapsed); } [Theory] @@ -95,8 +95,8 @@ public void IsTimedOut_should_return_expected_result(bool expected, TimeSpan tim Thread.Sleep(waitTime); stopwatch.Stop(); - var cancellationContext = new OperationCancellationContext(stopwatch, timeout, CancellationToken.None); - var result = cancellationContext.IsTimedOut(); + var operationContext = new OperationContext(stopwatch, timeout, CancellationToken.None); + var result = operationContext.IsTimedOut(); result.Should().Be(expected); } @@ -112,8 +112,8 @@ public void IsTimedOut_should_return_expected_result(bool expected, TimeSpan tim [MemberData(nameof(WithTimeout_test_cases))] public void WithTimeout_should_calculate_proper_timeout(TimeSpan expected, TimeSpan originalTimeout, TimeSpan newTimeout) { - var cancellationContext = new OperationCancellationContext(new Stopwatch(), originalTimeout, CancellationToken.None); - var resultContext = cancellationContext.WithTimeout(newTimeout); + var operationContext = new OperationContext(new Stopwatch(), originalTimeout, CancellationToken.None); + var resultContext = operationContext.WithTimeout(newTimeout); resultContext.Timeout.Should().Be(expected); } diff --git a/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs b/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs index 348c63ad888..84cc0e77e89 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs @@ -456,11 +456,11 @@ private protected FailPoint ConfigureFailPoint(BsonDocument test, IMongoClient c var serverAddress = EndPointHelper.Parse(settings.Server.ToString()); var selector = new EndPointServerSelector(serverAddress); - _failPointServer = cluster.SelectServer(selector, OperationCancellationContext.NoTimeout); + _failPointServer = cluster.SelectServer(selector, OperationContext.NoTimeout); } else { - _failPointServer = cluster.SelectServer(WritableServerSelector.Instance, OperationCancellationContext.NoTimeout); + _failPointServer = cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); } var session = NoCoreSession.NewHandle(); diff --git a/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs index faa34393943..dc2dae7dc0a 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs @@ -3245,7 +3245,7 @@ private void DropCollection(CollectionNamespace collectionNamespace, BsonDocumen using (var binding = new WritableServerBinding(_cluster, session.Fork())) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { - operation.Execute(bindingHandle, OperationCancellationContext.NoTimeout); + operation.Execute(bindingHandle, OperationContext.NoTimeout); } } diff --git a/tests/MongoDB.Driver.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs b/tests/MongoDB.Driver.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs index f606ae54c02..17a2ef3d736 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs @@ -410,8 +410,8 @@ private void ExecuteCheckOut( void CheckOut(BsonDocument op, IConnectionPool cp, ConcurrentDictionary cm) { var conn = async ? - cp.AcquireConnectionAsync(OperationCancellationContext.NoTimeout).GetAwaiter().GetResult() : - cp.AcquireConnection(OperationCancellationContext.NoTimeout); + cp.AcquireConnectionAsync(OperationContext.NoTimeout).GetAwaiter().GetResult() : + cp.AcquireConnection(OperationContext.NoTimeout); if (op.TryGetValue("label", out var label)) { @@ -671,7 +671,7 @@ private void ParseSettings( connectionIdLocalValueProvider: connectionIdProvider)) .Subscribe(eventCapturer)); - var server = cluster.SelectServer(WritableServerSelector.Instance, OperationCancellationContext.NoTimeout); + var server = cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); connectionPool = server._connectionPool(); if (test.TryGetValue(Schema.Intergration.failPoint, out var failPointDocument)) @@ -729,7 +729,7 @@ o is ServerHeartbeatSucceededEvent || eventCapturer.WaitForOrThrowIfTimeout(events => events.Any(e => e is ConnectionPoolClearedEvent), TimeSpan.FromMilliseconds(500)); } - var failPointServer = CoreTestConfiguration.Cluster.SelectServer(new EndPointServerSelector(server.EndPoint), OperationCancellationContext.NoTimeout); + var failPointServer = CoreTestConfiguration.Cluster.SelectServer(new EndPointServerSelector(server.EndPoint), OperationContext.NoTimeout); failPoint = FailPoint.Configure(failPointServer, NoCoreSession.NewHandle(), failPointDocument.AsBsonDocument, withAsync: async); if (resetPool) diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsProseTests.cs index 8cd6c28c06f..3dba3140de5 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsProseTests.cs @@ -79,7 +79,7 @@ public async Task PoolClearedError_read_retryablity_test([Values(true, false)] b .Capture() .CaptureCommandEvents("find"); - var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(failPointSelector, OperationCancellationContext.NoTimeout); + var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(failPointSelector, OperationContext.NoTimeout); using var failPoint = FailPoint.Configure(failpointServer, NoCoreSession.NewHandle(), failPointCommand); using var client = CreateClient(settings, eventCapturer, heartbeatInterval); @@ -146,8 +146,8 @@ public void Sharded_cluster_retryable_reads_are_retried_on_different_mongos_if_a }, useMultipleShardRouters: true); - var failPointServer1 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationCancellationContext.NoTimeout); - var failPointServer2 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint), OperationCancellationContext.NoTimeout); + var failPointServer1 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationContext.NoTimeout); + var failPointServer2 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint), OperationContext.NoTimeout); using var failPoint1 = FailPoint.Configure(failPointServer1, NoCoreSession.NewHandle(), failPointCommand); using var failPoint2 = FailPoint.Configure(failPointServer2, NoCoreSession.NewHandle(), failPointCommand); @@ -196,7 +196,7 @@ public void Sharded_cluster_retryable_reads_are_retried_on_same_mongos_if_no_oth }, useMultipleShardRouters: false); - var failPointServer = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationCancellationContext.NoTimeout); + var failPointServer = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationContext.NoTimeout); using var failPoint = FailPoint.Configure(failPointServer, NoCoreSession.NewHandle(), failPointCommand); diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/PoolClearRetryability.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/PoolClearRetryability.cs index b1cfea8d653..c06bb59f57d 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/PoolClearRetryability.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/PoolClearRetryability.cs @@ -82,7 +82,7 @@ public async Task PoolClearedError_write_retryablity_test([Values(false, true)] .Capture() .CaptureCommandEvents("insert"); - var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(failPointSelector, OperationCancellationContext.NoTimeout); + var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(failPointSelector, OperationContext.NoTimeout); using var failPoint = FailPoint.Configure(failpointServer, NoCoreSession.NewHandle(), failPointCommand); using var client = CreateClient(settings, eventCapturer, heartbeatInterval); diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/RetryWriteOnOtherMongos.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/RetryWriteOnOtherMongos.cs index 8282c83e18a..bd3d834cb37 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/RetryWriteOnOtherMongos.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/RetryWriteOnOtherMongos.cs @@ -61,8 +61,8 @@ public void Sharded_cluster_retryable_writes_are_retried_on_different_mongos_if_ }, useMultipleShardRouters: true); - var failPointServer1 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationCancellationContext.NoTimeout); - var failPointServer2 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint), OperationCancellationContext.NoTimeout); + var failPointServer1 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationContext.NoTimeout); + var failPointServer2 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint), OperationContext.NoTimeout); using var failPoint1 = FailPoint.Configure(failPointServer1, NoCoreSession.NewHandle(), failPointCommand); using var failPoint2 = FailPoint.Configure(failPointServer2, NoCoreSession.NewHandle(), failPointCommand); @@ -112,7 +112,7 @@ public void Sharded_cluster_retryable_writes_are_retried_on_same_mongo_if_no_oth }, useMultipleShardRouters: false); - var failPointServer = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationCancellationContext.NoTimeout); + var failPointServer = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationContext.NoTimeout); using var failPoint = FailPoint.Configure(failPointServer, NoCoreSession.NewHandle(), failPointCommand); diff --git a/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringProseTests.cs index 7bbd3e0a0c1..6ce8ddd9a6b 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringProseTests.cs @@ -165,7 +165,7 @@ public void Monitor_sleep_at_least_minHeartbeatFrequencyMS_between_checks() settings.ApplicationName = appName; settings.ServerSelectionTimeout = TimeSpan.FromSeconds(5); - var server = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(new EndPointServerSelector(new DnsEndPoint(serverAddress.Host, serverAddress.Port)), OperationCancellationContext.NoTimeout); + var server = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(new EndPointServerSelector(new DnsEndPoint(serverAddress.Host, serverAddress.Port)), OperationContext.NoTimeout); using var failPoint = FailPoint.Configure(server, NoCoreSession.NewHandle(), failPointCommand); using var client = DriverTestConfiguration.CreateMongoClient(settings); @@ -220,7 +220,7 @@ public void RoundTimeTrip_test() { // Note that the Server Description Equality rule means that ServerDescriptionChangedEvents will not be published. // So we use reflection to obtain the latest RTT instead. - var server = client.GetClusterInternal().SelectServer(WritableServerSelector.Instance, OperationCancellationContext.NoTimeout); + var server = client.GetClusterInternal().SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); var roundTripTimeMonitor = server._monitor()._roundTripTimeMonitor(); var expectedRoundTripTime = TimeSpan.FromMilliseconds(250); var timeout = TimeSpan.FromSeconds(30); // should not be reached without a driver bug @@ -273,7 +273,7 @@ public void ConnectionPool_cleared_on_failed_hello() eventsWaitTimeout); eventCapturer.Clear(); - var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(new EndPointServerSelector(new DnsEndPoint(serverAddress.Host, serverAddress.Port)), OperationCancellationContext.NoTimeout); + var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(new EndPointServerSelector(new DnsEndPoint(serverAddress.Host, serverAddress.Port)), OperationContext.NoTimeout); using var failPoint = FailPoint.Configure(failpointServer, NoCoreSession.NewHandle(), failPointCommand); eventCapturer.WaitForEventOrThrowIfTimeout(eventsWaitTimeout); diff --git a/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs b/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs index 325ec91ddea..e8e394e3aba 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs @@ -82,8 +82,8 @@ public void RunTestDefinition(JsonDrivenTestCase testCase) for (int i = 0; i < testData.iterations; i++) { var selectedServer = testData.async - ? cluster.SelectServerAsync(readPreferenceSelector, OperationCancellationContext.NoTimeout).GetAwaiter().GetResult() - : cluster.SelectServer(readPreferenceSelector, OperationCancellationContext.NoTimeout); + ? cluster.SelectServerAsync(readPreferenceSelector, OperationContext.NoTimeout).GetAwaiter().GetResult() + : cluster.SelectServer(readPreferenceSelector, OperationContext.NoTimeout); selectionHistogram[selectedServer.ServerId]++; } diff --git a/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedTargetedFailPointOperation.cs b/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedTargetedFailPointOperation.cs index cb48c2c0727..ba65dd7fc59 100644 --- a/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedTargetedFailPointOperation.cs +++ b/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedTargetedFailPointOperation.cs @@ -52,7 +52,7 @@ public void Execute() _entityMap.RegisterForDispose(client); var cluster = client.GetClusterInternal(); - var server = cluster.SelectServer(new EndPointServerSelector(pinnedServer), OperationCancellationContext.NoTimeout); + var server = cluster.SelectServer(new EndPointServerSelector(pinnedServer), OperationContext.NoTimeout); var session = NoCoreSession.NewHandle(); From b819cc7beabaf66a0040fb6c132740dba26a4d6d Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Fri, 6 Jun 2025 17:03:15 -0700 Subject: [PATCH 03/13] PR --- src/MongoDB.Driver/OperationContext.cs | 18 +++++++++++------- .../OperationContextTests.cs | 10 ++++++++++ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/src/MongoDB.Driver/OperationContext.cs b/src/MongoDB.Driver/OperationContext.cs index 7f60da95e4b..7f57ff52526 100644 --- a/src/MongoDB.Driver/OperationContext.cs +++ b/src/MongoDB.Driver/OperationContext.cs @@ -17,7 +17,6 @@ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; -using MongoDB.Driver.Core.Misc; namespace MongoDB.Driver { @@ -26,8 +25,6 @@ internal sealed class OperationContext // TODO: this static field is temporary here and will be removed in a future PRs in scope of CSOT. public static readonly OperationContext NoTimeout = new(System.Threading.Timeout.InfiniteTimeSpan, CancellationToken.None); - private readonly Stopwatch _stopwatch; - public OperationContext(TimeSpan timeout, CancellationToken cancellationToken) : this(Stopwatch.StartNew(), timeout, cancellationToken) { @@ -35,17 +32,19 @@ public OperationContext(TimeSpan timeout, CancellationToken cancellationToken) internal OperationContext(Stopwatch stopwatch, TimeSpan timeout, CancellationToken cancellationToken) { - _stopwatch = stopwatch; + Stopwatch = stopwatch; Timeout = timeout; CancellationToken = cancellationToken; } public CancellationToken CancellationToken { get; } - public TimeSpan Elapsed => _stopwatch.Elapsed; + public TimeSpan Elapsed => Stopwatch.Elapsed; public TimeSpan Timeout { get; } + public OperationContext ParentContext { get; private init; } + public TimeSpan RemainingTimeout { get @@ -55,10 +54,12 @@ public TimeSpan RemainingTimeout return System.Threading.Timeout.InfiniteTimeSpan; } - return Timeout - _stopwatch.Elapsed; + return Timeout - Elapsed; } } + private Stopwatch Stopwatch { get; } + public bool IsTimedOut() { var remainingTimeout = RemainingTimeout; @@ -82,7 +83,10 @@ public OperationContext WithTimeout(TimeSpan timeout) timeout = remainingTimeout; } - return new OperationContext(timeout, CancellationToken); + return new OperationContext(timeout, CancellationToken) + { + ParentContext = this + }; } public void WaitTask(Task task) diff --git a/tests/MongoDB.Driver.Tests/OperationContextTests.cs b/tests/MongoDB.Driver.Tests/OperationContextTests.cs index 8025b3f5acd..aae2fd23774 100644 --- a/tests/MongoDB.Driver.Tests/OperationContextTests.cs +++ b/tests/MongoDB.Driver.Tests/OperationContextTests.cs @@ -35,6 +35,7 @@ public void Constructor_should_initialize_properties() operationContext.Timeout.Should().Be(timeout); operationContext.CancellationToken.Should().Be(cancellationToken); + operationContext.ParentContext.Should().BeNull(); } [Fact] @@ -127,6 +128,15 @@ public void WithTimeout_should_calculate_proper_timeout(TimeSpan expected, TimeS [TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(5)], ]; + [Fact] + public void WithTimeout_should_set_ParentContext() + { + var operationContext = new OperationContext(new Stopwatch(), Timeout.InfiniteTimeSpan, CancellationToken.None); + var resultContext = operationContext.WithTimeout(TimeSpan.FromSeconds(10)); + + resultContext.ParentContext.Should().Be(operationContext); + } + // TODO: Add tests for WaitTask and WaitTaskAsync. } } From fa4b6d3f1ef4a9d904ada542167f96fede12f80d Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Fri, 6 Jun 2025 17:54:31 -0700 Subject: [PATCH 04/13] pr --- src/MongoDB.Driver/OperationContext.cs | 36 +++++- .../OperationContextTests.cs | 103 +++++++++++++++++- 2 files changed, 134 insertions(+), 5 deletions(-) diff --git a/src/MongoDB.Driver/OperationContext.cs b/src/MongoDB.Driver/OperationContext.cs index 7f57ff52526..9233d7711ef 100644 --- a/src/MongoDB.Driver/OperationContext.cs +++ b/src/MongoDB.Driver/OperationContext.cs @@ -17,6 +17,9 @@ using System.Diagnostics; using System.Threading; using System.Threading.Tasks; +#if !NET6_0_OR_GREATER +using MongoDB.Driver.Core.Misc; +#endif namespace MongoDB.Driver { @@ -91,22 +94,47 @@ public OperationContext WithTimeout(TimeSpan timeout) public void WaitTask(Task task) { + if (task.IsCompleted) + { + task.GetAwaiter().GetResult(); // re-throws exception if any + return; + } + var timeout = RemainingTimeout; - if (timeout < TimeSpan.Zero) + if (timeout != System.Threading.Timeout.InfiniteTimeSpan && timeout < TimeSpan.Zero) { throw new TimeoutException(); } - if (!task.Wait((int)timeout.TotalMilliseconds, CancellationToken)) + try { - throw new TimeoutException(); + if (!task.Wait((int)timeout.TotalMilliseconds, CancellationToken)) + { + CancellationToken.ThrowIfCancellationRequested(); + throw new TimeoutException(); + } + } + catch (AggregateException e) + { + if (e.InnerExceptions.Count == 1) + { + throw e.InnerExceptions[0]; + } + + throw; } } public async Task WaitTaskAsync(Task task) { + if (task.IsCompleted) + { + await task.ConfigureAwait(false); // re-throws exception if any + return; + } + var timeout = RemainingTimeout; - if (timeout < TimeSpan.Zero) + if (timeout != System.Threading.Timeout.InfiniteTimeSpan && timeout < TimeSpan.Zero) { throw new TimeoutException(); } diff --git a/tests/MongoDB.Driver.Tests/OperationContextTests.cs b/tests/MongoDB.Driver.Tests/OperationContextTests.cs index aae2fd23774..3063d3c89d7 100644 --- a/tests/MongoDB.Driver.Tests/OperationContextTests.cs +++ b/tests/MongoDB.Driver.Tests/OperationContextTests.cs @@ -17,7 +17,9 @@ using System.Collections.Generic; using System.Diagnostics; using System.Threading; +using System.Threading.Tasks; using FluentAssertions; +using MongoDB.TestHelpers.XunitExtensions; using Xunit; namespace MongoDB.Driver.Tests @@ -137,7 +139,106 @@ public void WithTimeout_should_set_ParentContext() resultContext.ParentContext.Should().Be(operationContext); } - // TODO: Add tests for WaitTask and WaitTaskAsync. + [Theory] + [ParameterAttributeData] + public async Task Wait_should_throw_if_context_is_timedout([Values(true, false)] bool async) + { + var taskCompletionSource = new TaskCompletionSource(); + var operationContext = new OperationContext(TimeSpan.FromMilliseconds(10), CancellationToken.None); + Thread.Sleep(20); + + var exception = async ? + await Record.ExceptionAsync(() => operationContext.WaitTaskAsync(taskCompletionSource.Task)) : + Record.Exception(() => operationContext.WaitTask(taskCompletionSource.Task)); + + exception.Should().BeOfType(); + } + + [Theory] + [ParameterAttributeData] + public async Task Wait_should_throw_if_context_is_cancelled([Values(true, false)] bool async) + { + var taskCompletionSource = new TaskCompletionSource(); + var cancellationTokenSource = new CancellationTokenSource(); + cancellationTokenSource.Cancel(); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationTokenSource.Token); + + var exception = async ? + await Record.ExceptionAsync(() => operationContext.WaitTaskAsync(taskCompletionSource.Task)) : + Record.Exception(() => operationContext.WaitTask(taskCompletionSource.Task)); + + exception.Should().BeOfType(); + } + + [Theory] + [ParameterAttributeData] + public async Task Wait_should_rethrow_on_failed_task([Values(true, false)] bool async) + { + var ex = new InvalidOperationException(); + var task = Task.FromException(ex); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, CancellationToken.None); + + var exception = async ? + await Record.ExceptionAsync(() => operationContext.WaitTaskAsync(task)) : + Record.Exception(() => operationContext.WaitTask(task)); + + exception.Should().Be(ex); + } + + [Theory] + [ParameterAttributeData] + public async Task Wait_should_rethrow_on_failed_promise_task([Values(true, false)] bool async) + { + var ex = new InvalidOperationException("Ups!"); + var taskCompletionSource = new TaskCompletionSource(); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, CancellationToken.None); + + var task = Task.Run(async () => + { + if (async) + { + await operationContext.WaitTaskAsync(taskCompletionSource.Task); + } + else + { + operationContext.WaitTask(taskCompletionSource.Task); + } + }); + Thread.Sleep(20); + taskCompletionSource.SetException(ex); + + var exception = await Record.ExceptionAsync(() => task); + exception.Should().Be(ex); + } + + [Theory] + [ParameterAttributeData] + public async Task Wait_should_throw_on_timeout([Values(true, false)] bool async) + { + var taskCompletionSource = new TaskCompletionSource(); + var operationContext = new OperationContext(TimeSpan.FromMilliseconds(20), CancellationToken.None); + + var exception = async ? + await Record.ExceptionAsync(() => operationContext.WaitTaskAsync(taskCompletionSource.Task)) : + Record.Exception(() => operationContext.WaitTask(taskCompletionSource.Task)); + + exception.Should().BeOfType(); + } + + [Theory] + [ParameterAttributeData] + public async Task Wait_should_not_throw_on_resolved_task_with_timedout_context([Values(true, false)] bool async) + { + var task = Task.FromResult(42); + var operationContext = new OperationContext(TimeSpan.FromMilliseconds(10), CancellationToken.None); + Thread.Sleep(20); + + var exception = async ? + await Record.ExceptionAsync(() => operationContext.WaitTaskAsync(task)) : + Record.Exception(() => operationContext.WaitTask(task)); + + exception.Should().BeNull(); + } } } From da1d2126fa15752d856c2b7f711f9238b83399a7 Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Mon, 9 Jun 2025 13:48:38 -0700 Subject: [PATCH 05/13] pr --- src/MongoDB.Driver/Core/Clusters/Cluster.cs | 12 +++---- .../Core/Clusters/LoadBalancedCluster.cs | 12 +++---- .../ExclusiveConnectionPool.Helpers.cs | 32 +++++++++---------- src/MongoDB.Driver/OperationContext.cs | 3 +- .../OperationContextTests.cs | 3 +- 5 files changed, 32 insertions(+), 30 deletions(-) diff --git a/src/MongoDB.Driver/Core/Clusters/Cluster.cs b/src/MongoDB.Driver/Core/Clusters/Cluster.cs index 352b9c9c188..a5f93f79837 100644 --- a/src/MongoDB.Driver/Core/Clusters/Cluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/Cluster.cs @@ -222,7 +222,7 @@ public IServer SelectServer(IServerSelector selector, OperationContext operation Ensure.IsNotNull(selector, nameof(selector)); Ensure.IsNotNull(operationContext, nameof(operationContext)); - var serverSelectionCancellationContext = operationContext.WithTimeout(Settings.ServerSelectionTimeout); + var serverSelectionOperationContext = operationContext.WithTimeout(Settings.ServerSelectionTimeout); using (var helper = new SelectServerHelper(this, selector)) { @@ -230,13 +230,13 @@ public IServer SelectServer(IServerSelector selector, OperationContext operation { while (true) { - var server = helper.SelectServer(serverSelectionCancellationContext); + var server = helper.SelectServer(serverSelectionOperationContext); if (server != null) { return server; } - helper.WaitForDescriptionChanged(serverSelectionCancellationContext); + helper.WaitForDescriptionChanged(serverSelectionOperationContext); } } catch (TimeoutException) @@ -261,7 +261,7 @@ public async Task SelectServerAsync(IServerSelector selector, Operation Ensure.IsNotNull(selector, nameof(selector)); Ensure.IsNotNull(operationContext, nameof(operationContext)); - var serverSelectionCancellationContext = operationContext.WithTimeout(Settings.ServerSelectionTimeout); + var serverSelectionOperationContext = operationContext.WithTimeout(Settings.ServerSelectionTimeout); using (var helper = new SelectServerHelper(this, selector)) { @@ -269,13 +269,13 @@ public async Task SelectServerAsync(IServerSelector selector, Operation { while (true) { - var server = helper.SelectServer(serverSelectionCancellationContext); + var server = helper.SelectServer(serverSelectionOperationContext); if (server != null) { return server; } - await helper.WaitForDescriptionChangedAsync(serverSelectionCancellationContext).ConfigureAwait(false); + await helper.WaitForDescriptionChangedAsync(serverSelectionOperationContext).ConfigureAwait(false); } } catch (TimeoutException) diff --git a/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs b/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs index 21cbae7de89..39ea5e9ec95 100644 --- a/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs @@ -176,7 +176,7 @@ public IServer SelectServer(IServerSelector selector, OperationContext operation Ensure.IsNotNull(operationContext, nameof(operationContext)); ThrowIfDisposed(); - var serverSelectionCancellationContext = operationContext.WithTimeout(_settings.ServerSelectionTimeout); + var serverSelectionOperationContext = operationContext.WithTimeout(_settings.ServerSelectionTimeout); _serverSelectionEventLogger.LogAndPublish(new ClusterSelectingServerEvent( _description, @@ -186,7 +186,7 @@ public IServer SelectServer(IServerSelector selector, OperationContext operation try { - serverSelectionCancellationContext.WaitTask(_serverReadyTaskCompletionSource.Task); + serverSelectionOperationContext.WaitTask(_serverReadyTaskCompletionSource.Task); } catch (TimeoutException) { @@ -199,7 +199,7 @@ public IServer SelectServer(IServerSelector selector, OperationContext operation _description, selector, _server.Description, - serverSelectionCancellationContext.Elapsed, + serverSelectionOperationContext.Elapsed, null, EventContext.OperationName)); } @@ -214,7 +214,7 @@ public async Task SelectServerAsync(IServerSelector selector, Operation Ensure.IsNotNull(operationContext, nameof(operationContext)); ThrowIfDisposed(); - var serverSelectionCancellationContext = operationContext.WithTimeout(_settings.ServerSelectionTimeout); + var serverSelectionOperationContext = operationContext.WithTimeout(_settings.ServerSelectionTimeout); _serverSelectionEventLogger.LogAndPublish(new ClusterSelectingServerEvent( _description, @@ -224,7 +224,7 @@ public async Task SelectServerAsync(IServerSelector selector, Operation try { - await serverSelectionCancellationContext.WaitTaskAsync(_serverReadyTaskCompletionSource.Task).ConfigureAwait(false); + await serverSelectionOperationContext.WaitTaskAsync(_serverReadyTaskCompletionSource.Task).ConfigureAwait(false); } catch (TimeoutException) { @@ -237,7 +237,7 @@ public async Task SelectServerAsync(IServerSelector selector, Operation _description, selector, _server.Description, - serverSelectionCancellationContext.Elapsed, + serverSelectionOperationContext.Elapsed, null, EventContext.OperationName)); } diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs index 9812a89ce01..d6d76a47a5b 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs @@ -33,7 +33,7 @@ namespace MongoDB.Driver.Core.ConnectionPools internal sealed partial class ExclusiveConnectionPool { // private methods - private Exception CreateTimeoutException(OperationContext operationContext, string message) + private Exception CreateTimeoutException(TimeSpan elapsed, string message) { var checkOutsForCursorCount = _checkOutReasonCounter.GetCheckOutsCount(CheckOutReason.Cursor); var checkOutsForTransactionCount = _checkOutReasonCounter.GetCheckOutsCount(CheckOutReason.Transaction); @@ -47,7 +47,7 @@ private Exception CreateTimeoutException(OperationContext operationContext, stri var checkOutsForOtherCount = checkOutsCount - checkOutsForCursorCount - checkOutsForTransactionCount; message = - $"Timed out after {operationContext.Elapsed.TotalMilliseconds}ms waiting for a connection from the connection pool. " + + $"Timed out after {elapsed.TotalMilliseconds}ms waiting for a connection from the connection pool. " + $"maxPoolSize: {maxPoolSize}, " + $"connections in use by cursors: {checkOutsForCursorCount}, " + $"connections in use by transactions: {checkOutsForTransactionCount}, " + @@ -296,9 +296,9 @@ private IConnectionHandle EndCheckingOut(PooledConnection pooledConnection, Oper private void EnsureTimeout(OperationContext operationContext) { - if (operationContext.IsTimedOut()) + if (operationContext.IsTimedOut(out var elapsed)) { - throw _pool.CreateTimeoutException(operationContext, $"Timed out waiting for a connection after {operationContext.Elapsed.TotalMilliseconds}ms."); + throw _pool.CreateTimeoutException(elapsed, $"Timed out waiting for a connection after {elapsed.TotalMilliseconds}ms."); } } @@ -308,7 +308,7 @@ private Exception CreateException(OperationContext operationContext) => SemaphoreSlimSignalable.SemaphoreWaitResult.Signaled => MongoConnectionPoolPausedException.ForConnectionPool(_pool._endPoint), SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => - _pool.CreateTimeoutException(operationContext, $"Timed out waiting for a connection after {operationContext.Elapsed.TotalMilliseconds}ms."), + _pool.CreateTimeoutException(operationContext.Elapsed, $"Timed out waiting for a connection after {operationContext.Elapsed.TotalMilliseconds}ms."), // should not be reached _ => new InvalidOperationException($"Invalid {_poolQueueWaitResult}.") }; @@ -853,7 +853,7 @@ public PooledConnection CreateOpened(OperationContext operationContext) if (_connectingWaitStatus == SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut) { - _pool.CreateTimeoutException(operationContext, $"Timed out waiting for in connecting queue after {operationContext.Elapsed.TotalMilliseconds}ms."); + _pool.CreateTimeoutException(operationContext.Elapsed, $"Timed out waiting for in connecting queue after {operationContext.Elapsed.TotalMilliseconds}ms."); } return CreateOpenedInternal(operationContext); @@ -885,13 +885,13 @@ public PooledConnection CreateOpenedOrReuse(OperationContext operationContext) { SemaphoreSlimSignalable.SemaphoreWaitResult.Signaled => _pool._connectionHolder.Acquire(), SemaphoreSlimSignalable.SemaphoreWaitResult.Entered => CreateOpenedInternal(operationContext), - SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(operationContext), + SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(operationContext.Elapsed), _ => throw new InvalidOperationException($"Invalid wait result {_connectingWaitStatus}") }; - if (connection == null && operationContext.IsTimedOut()) + if (connection == null && operationContext.IsTimedOut(out var elapsed)) { - throw CreateTimeoutException(operationContext); + throw CreateTimeoutException(elapsed); } } @@ -924,13 +924,13 @@ public async Task CreateOpenedOrReuseAsync(OperationContext op { SemaphoreSlimSignalable.SemaphoreWaitResult.Signaled => _pool._connectionHolder.Acquire(), SemaphoreSlimSignalable.SemaphoreWaitResult.Entered => await CreateOpenedInternalAsync(operationContext).ConfigureAwait(false), - SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(operationContext), + SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(operationContext.Elapsed), _ => throw new InvalidOperationException($"Invalid wait result {_connectingWaitStatus}") }; - if (connection == null && operationContext.IsTimedOut()) + if (connection == null && operationContext.IsTimedOut(out var elapsed)) { - throw CreateTimeoutException(operationContext); + throw CreateTimeoutException(elapsed); } } @@ -987,7 +987,7 @@ private void StartCreating(OperationContext operationContext) _pool._eventLogger.LogAndPublish(new ConnectionPoolAddingConnectionEvent(_pool._serverId, EventContext.OperationId)); operationContext.CancellationToken.ThrowIfCancellationRequested(); - if (operationContext.IsTimedOut()) + if (operationContext.IsTimedOut(out _)) { throw new TimeoutException(); } @@ -1004,10 +1004,10 @@ private void FinishCreating(ConnectionDescription description, OperationContext _pool._serviceStates.IncrementConnectionCount(description?.ServiceId); } - private Exception CreateTimeoutException(OperationContext operationContext) + private Exception CreateTimeoutException(TimeSpan elapsed) { - var message = $"Timed out waiting in connecting queue after {operationContext.Elapsed.TotalMilliseconds}ms."; - return _pool.CreateTimeoutException(operationContext, message); + var message = $"Timed out waiting in connecting queue after {elapsed.TotalMilliseconds}ms."; + return _pool.CreateTimeoutException(elapsed, message); } } } diff --git a/src/MongoDB.Driver/OperationContext.cs b/src/MongoDB.Driver/OperationContext.cs index 9233d7711ef..ddfff2e42f9 100644 --- a/src/MongoDB.Driver/OperationContext.cs +++ b/src/MongoDB.Driver/OperationContext.cs @@ -63,8 +63,9 @@ public TimeSpan RemainingTimeout private Stopwatch Stopwatch { get; } - public bool IsTimedOut() + public bool IsTimedOut(out TimeSpan elapsed) { + elapsed = Elapsed; var remainingTimeout = RemainingTimeout; if (remainingTimeout == System.Threading.Timeout.InfiniteTimeSpan) { diff --git a/tests/MongoDB.Driver.Tests/OperationContextTests.cs b/tests/MongoDB.Driver.Tests/OperationContextTests.cs index 3063d3c89d7..061288fab75 100644 --- a/tests/MongoDB.Driver.Tests/OperationContextTests.cs +++ b/tests/MongoDB.Driver.Tests/OperationContextTests.cs @@ -99,9 +99,10 @@ public void IsTimedOut_should_return_expected_result(bool expected, TimeSpan tim stopwatch.Stop(); var operationContext = new OperationContext(stopwatch, timeout, CancellationToken.None); - var result = operationContext.IsTimedOut(); + var result = operationContext.IsTimedOut(out var elapsed); result.Should().Be(expected); + elapsed.Should().Be(stopwatch.Elapsed); } public static IEnumerable IsTimedOut_test_cases = From d80fa50a8e582d1ff1168f399492ad177671f55a Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Tue, 10 Jun 2025 11:38:37 -0700 Subject: [PATCH 06/13] PR --- .../Core/Bindings/ChannelReadBinding.cs | 4 +- .../Core/Bindings/ChannelReadWriteBinding.cs | 20 +- .../Bindings/ChannelSourceReadWriteBinding.cs | 20 +- .../Core/Bindings/CoreSession.cs | 40 ++-- src/MongoDB.Driver/Core/Bindings/IBinding.cs | 16 +- .../Core/Bindings/ReadBindingHandle.cs | 8 +- .../Core/Bindings/ReadPreferenceBinding.cs | 12 +- .../Core/Bindings/ReadWriteBindingHandle.cs | 32 +-- .../Core/Bindings/SingleServerReadBinding.cs | 4 +- .../Bindings/SingleServerReadWriteBinding.cs | 20 +- .../Core/Bindings/WritableServerBinding.cs | 40 ++-- src/MongoDB.Driver/Core/Clusters/Cluster.cs | 4 +- src/MongoDB.Driver/Core/Clusters/ICluster.cs | 4 +- .../Core/Clusters/IClusterExtensions.cs | 12 +- .../Core/Clusters/LoadBalancedCluster.cs | 4 +- .../ExclusiveConnectionPool.Helpers.cs | 12 +- src/MongoDB.Driver/Core/Misc/Feature.cs | 4 +- .../Core/Operations/AggregateOperation.cs | 20 +- .../AggregateToCollectionOperation.cs | 12 +- .../Core/Operations/AsyncCursor.cs | 8 +- .../Operations/BulkMixedWriteOperation.cs | 20 +- .../BulkUnmixedWriteOperationBase.cs | 36 ++-- .../Core/Operations/ChangeStreamCursor.cs | 8 +- .../Core/Operations/ChangeStreamOperation.cs | 36 ++-- .../Operations/ClientBulkWriteOperation.cs | 12 +- .../Core/Operations/CommandOperationBase.cs | 8 +- .../Operations/CompositeWriteOperation.cs | 8 +- .../Operations/CountDocumentsOperation.cs | 8 +- .../Core/Operations/CountOperation.cs | 20 +- .../Operations/CreateCollectionOperation.cs | 8 +- .../Core/Operations/CreateIndexesOperation.cs | 8 +- .../CreateSearchIndexesOperation.cs | 8 +- .../Core/Operations/CreateViewOperation.cs | 8 +- .../Operations/DatabaseExistsOperation.cs | 8 +- .../Core/Operations/DistinctOperation.cs | 12 +- .../Operations/DropCollectionOperation.cs | 8 +- .../Core/Operations/DropDatabaseOperation.cs | 8 +- .../Core/Operations/DropIndexOperation.cs | 8 +- .../Operations/DropSearchIndexOperation.cs | 8 +- .../Operations/EndTransactionOperation.cs | 16 +- .../EstimatedDocumentCountOperation.cs | 12 +- .../Core/Operations/EvalOperation.cs | 8 +- .../Operations/FindAndModifyOperationBase.cs | 24 +-- .../Core/Operations/FindOperation.cs | 20 +- .../Core/Operations/GroupOperation.cs | 8 +- .../Core/Operations/IOperation.cs | 8 +- .../Core/Operations/IRetryableOperation.cs | 16 +- .../Operations/ListCollectionsOperation.cs | 20 +- .../Core/Operations/ListDatabasesOperation.cs | 8 +- .../Core/Operations/ListIndexesOperation.cs | 12 +- .../ListIndexesUsingCommandOperation.cs | 20 +- .../Core/Operations/MapReduceOperation.cs | 8 +- .../MapReduceOutputToCollectionOperation.cs | 8 +- .../Operations/OperationExtensionMethods.cs | 24 +-- .../Core/Operations/ReadCommandOperation.cs | 24 +-- .../Operations/RenameCollectionOperation.cs | 8 +- .../Core/Operations/RetryableReadContext.cs | 4 +- .../RetryableReadOperationExecutor.cs | 32 +-- .../RetryableWriteCommandOperationBase.cs | 24 +-- .../Core/Operations/RetryableWriteContext.cs | 4 +- .../RetryableWriteOperationExecutor.cs | 32 +-- .../Operations/UpdateSearchIndexOperation.cs | 8 +- .../Core/Operations/WriteCommandOperation.cs | 8 +- src/MongoDB.Driver/GridFS/GridFSBucket.cs | 196 +++++++++--------- .../GridFS/GridFSForwardOnlyDownloadStream.cs | 8 +- .../GridFS/GridFSForwardOnlyUploadStream.cs | 8 +- .../GridFS/GridFSSeekableDownloadStream.cs | 8 +- src/MongoDB.Driver/OperationExecutor.cs | 8 +- .../Core/CoreTestConfiguration.cs | 12 +- .../Core/FailPoint.cs | 4 +- .../AuthenticationTests.cs | 2 +- tests/MongoDB.Driver.Tests/ClusterTests.cs | 4 +- .../Bindings/ReadPreferenceBindingTests.cs | 12 +- .../Bindings/WritableServerBindingTests.cs | 40 ++-- .../Core/Clusters/ClusterTests.cs | 56 ++--- .../Core/Clusters/LoadBalancedClusterTests.cs | 12 +- .../Core/Jira/CSharp3173Tests.cs | 4 +- .../Core/Jira/CSharp3302Tests.cs | 6 +- .../Core/LoadBalancingIntergationTests.cs | 16 +- .../Operations/ChangeStreamCursorTests.cs | 8 +- .../CompositeWriteOperationTests.cs | 20 +- .../CreateCollectionOperationTests.cs | 6 +- .../Operations/CreateViewOperationTests.cs | 2 +- .../Core/Operations/EvalOperationTests.cs | 4 +- .../Core/Operations/OperationTestBase.cs | 42 ++-- .../RetryableWriteOperationExecutorTests.cs | 2 +- .../Core/Servers/ServerTests.cs | 6 +- .../Encryption/ClientEncryptionTests.cs | 8 +- .../JsonDrivenConfigureFailPointTest.cs | 4 +- .../JsonDrivenTargetedFailPointTest.cs | 4 +- .../MongoClientJsonDrivenTestRunnerBase.cs | 4 +- .../prose-tests/ClientEncryptionProseTests.cs | 2 +- ...onnectionMonitoringAndPoolingTestRunner.cs | 4 +- .../RetryableReadsProseTests.cs | 8 +- .../prose-tests/PoolClearRetryability.cs | 2 +- .../prose-tests/RetryWriteOnOtherMongos.cs | 6 +- .../ServerDiscoveryAndMonitoringProseTests.cs | 6 +- .../server-selection/InWindowTestRunner.cs | 4 +- .../UnifiedTargetedFailPointOperation.cs | 2 +- 99 files changed, 716 insertions(+), 716 deletions(-) diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs b/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs index e03789a95c0..63dab353cf4 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelReadBinding.cs @@ -69,12 +69,12 @@ public Task GetReadChannelSourceAsync(OperationContext ope return Task.FromResult(GetReadChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetReadChannelSourceAsync(operationContext); } diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs b/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs index 70c1150156c..17ae75966bc 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelReadWriteBinding.cs @@ -67,12 +67,12 @@ public Task GetReadChannelSourceAsync(OperationContext ope return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetReadChannelSourceAsync(operationContext); } @@ -83,19 +83,19 @@ public IChannelSourceHandle GetWriteChannelSource(OperationContext operationCont return GetChannelSourceHelper(); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetWriteChannelSource(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { return GetWriteChannelSource(operationContext); // ignore mayUseSecondary } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSource(mayUseSecondary, operationContext); + return GetWriteChannelSource(operationContext, mayUseSecondary); } public Task GetWriteChannelSourceAsync(OperationContext operationContext) @@ -104,19 +104,19 @@ public Task GetWriteChannelSourceAsync(OperationContext op return Task.FromResult(GetChannelSourceHelper()); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetWriteChannelSourceAsync(operationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { return GetWriteChannelSourceAsync(operationContext); // ignore mayUseSecondary } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSourceAsync(mayUseSecondary, operationContext); + return GetWriteChannelSourceAsync(operationContext, mayUseSecondary); } private IChannelSourceHandle GetChannelSourceHelper() diff --git a/src/MongoDB.Driver/Core/Bindings/ChannelSourceReadWriteBinding.cs b/src/MongoDB.Driver/Core/Bindings/ChannelSourceReadWriteBinding.cs index 078f1530cdc..e0c4772d23f 100644 --- a/src/MongoDB.Driver/Core/Bindings/ChannelSourceReadWriteBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ChannelSourceReadWriteBinding.cs @@ -57,12 +57,12 @@ public Task GetReadChannelSourceAsync(OperationContext ope return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetReadChannelSourceAsync(operationContext); } @@ -73,19 +73,19 @@ public IChannelSourceHandle GetWriteChannelSource(OperationContext operationCont return GetChannelSourceHelper(); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetWriteChannelSource(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { return GetWriteChannelSource(operationContext); // ignore mayUseSecondary } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSource(mayUseSecondary, operationContext); + return GetWriteChannelSource(operationContext, mayUseSecondary); } public Task GetWriteChannelSourceAsync(OperationContext operationContext) @@ -94,19 +94,19 @@ public Task GetWriteChannelSourceAsync(OperationContext op return Task.FromResult(GetChannelSourceHelper()); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetWriteChannelSourceAsync(operationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { return GetWriteChannelSourceAsync(operationContext); // ignore mayUseSecondary } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSourceAsync(mayUseSecondary, operationContext); + return GetWriteChannelSourceAsync(operationContext, mayUseSecondary); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/CoreSession.cs b/src/MongoDB.Driver/Core/Bindings/CoreSession.cs index 6ae7382d91c..073492ea4da 100644 --- a/src/MongoDB.Driver/Core/Bindings/CoreSession.cs +++ b/src/MongoDB.Driver/Core/Bindings/CoreSession.cs @@ -145,8 +145,8 @@ public bool IsInTransaction { EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + // TODO: CSOT implement proper way to obtain the operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { if (_currentTransaction.IsEmpty) @@ -157,7 +157,7 @@ public bool IsInTransaction try { var firstAttempt = CreateAbortTransactionOperation(); - ExecuteEndTransactionOnPrimary(firstAttempt, operationCancellationContext); + ExecuteEndTransactionOnPrimary(operationContext, firstAttempt); return; } catch (Exception exception) when (ShouldRetryEndTransactionException(exception)) @@ -175,7 +175,7 @@ public bool IsInTransaction try { var secondAttempt = CreateAbortTransactionOperation(); - ExecuteEndTransactionOnPrimary(secondAttempt, operationCancellationContext); + ExecuteEndTransactionOnPrimary(operationContext, secondAttempt); } catch { @@ -196,8 +196,8 @@ public bool IsInTransaction { EnsureAbortTransactionCanBeCalled(nameof(AbortTransaction)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + // TODO: CSOT implement proper way to obtain the operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { if (_currentTransaction.IsEmpty) @@ -208,7 +208,7 @@ public bool IsInTransaction try { var firstAttempt = CreateAbortTransactionOperation(); - await ExecuteEndTransactionOnPrimaryAsync(firstAttempt, operationCancellationContext).ConfigureAwait(false); + await ExecuteEndTransactionOnPrimaryAsync(operationContext, firstAttempt).ConfigureAwait(false); return; } catch (Exception exception) when (ShouldRetryEndTransactionException(exception)) @@ -226,7 +226,7 @@ public bool IsInTransaction try { var secondAttempt = CreateAbortTransactionOperation(); - await ExecuteEndTransactionOnPrimaryAsync(secondAttempt, operationCancellationContext).ConfigureAwait(false); + await ExecuteEndTransactionOnPrimaryAsync(operationContext, secondAttempt).ConfigureAwait(false); } catch { @@ -296,8 +296,8 @@ public long AdvanceTransactionNumber() { EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + // TODO: CSOT implement proper way to obtain the operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { _isCommitTransactionInProgress = true; @@ -309,7 +309,7 @@ public long AdvanceTransactionNumber() try { var firstAttempt = CreateCommitTransactionOperation(IsFirstCommitAttemptRetry()); - ExecuteEndTransactionOnPrimary(firstAttempt, operationCancellationContext); + ExecuteEndTransactionOnPrimary(operationContext, firstAttempt); return; } catch (Exception exception) when (ShouldRetryEndTransactionException(exception)) @@ -319,7 +319,7 @@ public long AdvanceTransactionNumber() } var secondAttempt = CreateCommitTransactionOperation(isCommitRetry: true); - ExecuteEndTransactionOnPrimary(secondAttempt, operationCancellationContext); + ExecuteEndTransactionOnPrimary(operationContext, secondAttempt); } finally { @@ -333,8 +333,8 @@ public long AdvanceTransactionNumber() { EnsureCommitTransactionCanBeCalled(nameof(CommitTransaction)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext - var operationCancellationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + // TODO: CSOT implement proper way to obtain the operationContext + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); try { _isCommitTransactionInProgress = true; @@ -346,7 +346,7 @@ public long AdvanceTransactionNumber() try { var firstAttempt = CreateCommitTransactionOperation(IsFirstCommitAttemptRetry()); - await ExecuteEndTransactionOnPrimaryAsync(firstAttempt, operationCancellationContext).ConfigureAwait(false); + await ExecuteEndTransactionOnPrimaryAsync(operationContext, firstAttempt).ConfigureAwait(false); return; } catch (Exception exception) when (ShouldRetryEndTransactionException(exception)) @@ -356,7 +356,7 @@ public long AdvanceTransactionNumber() } var secondAttempt = CreateCommitTransactionOperation(isCommitRetry: true); - await ExecuteEndTransactionOnPrimaryAsync(secondAttempt, operationCancellationContext).ConfigureAwait(false); + await ExecuteEndTransactionOnPrimaryAsync(operationContext, secondAttempt).ConfigureAwait(false); } finally { @@ -545,21 +545,21 @@ private void EnsureTransactionsAreSupported() } } - private TResult ExecuteEndTransactionOnPrimary(IReadOperation operation, OperationContext operationContext) + private TResult ExecuteEndTransactionOnPrimary(OperationContext operationContext, IReadOperation operation) { using (var sessionHandle = new NonDisposingCoreSessionHandle(this)) using (var binding = ChannelPinningHelper.CreateReadWriteBinding(_cluster, sessionHandle)) { - return operation.Execute(binding, operationContext); + return operation.Execute(operationContext, binding); } } - private async Task ExecuteEndTransactionOnPrimaryAsync(IReadOperation operation, OperationContext operationContext) + private async Task ExecuteEndTransactionOnPrimaryAsync(OperationContext operationContext, IReadOperation operation) { using (var sessionHandle = new NonDisposingCoreSessionHandle(this)) using (var binding = ChannelPinningHelper.CreateReadWriteBinding(_cluster, sessionHandle)) { - return await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Bindings/IBinding.cs b/src/MongoDB.Driver/Core/Bindings/IBinding.cs index e8bdc177210..275131043ba 100644 --- a/src/MongoDB.Driver/Core/Bindings/IBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/IBinding.cs @@ -33,21 +33,21 @@ internal interface IReadBinding : IBinding IChannelSourceHandle GetReadChannelSource(OperationContext operationContext); Task GetReadChannelSourceAsync(OperationContext operationContext); - IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext); - Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext); + IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers); + Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers); } internal interface IWriteBinding : IBinding { IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext); - IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext); - IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext); - IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext); + IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers); + IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary); + IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary); Task GetWriteChannelSourceAsync(OperationContext operationContext); - Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext); - Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext); - Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext); + Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers); + Task GetWriteChannelSourceAsync(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary); + Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary); } internal interface IReadWriteBinding : IReadBinding, IWriteBinding diff --git a/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs b/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs index 5807898c6e9..99dfa24212d 100644 --- a/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs +++ b/src/MongoDB.Driver/Core/Bindings/ReadBindingHandle.cs @@ -58,16 +58,16 @@ public Task GetReadChannelSourceAsync(OperationContext ope return _reference.Instance.GetReadChannelSourceAsync(operationContext); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(deprioritizedServers, operationContext); + return _reference.Instance.GetReadChannelSource(operationContext, deprioritizedServers); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(deprioritizedServers, operationContext); + return _reference.Instance.GetReadChannelSourceAsync(operationContext, deprioritizedServers); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs b/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs index 0e7a0892529..32106f0efcd 100644 --- a/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs @@ -53,25 +53,25 @@ public ICoreSessionHandle Session public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { - return GetReadChannelSource(null, operationContext); + return GetReadChannelSource(operationContext, null); } public Task GetReadChannelSourceAsync(OperationContext operationContext) { - return GetReadChannelSourceAsync(null, operationContext); + return GetReadChannelSourceAsync(operationContext, null); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(_session, _serverSelector, deprioritizedServers, operationContext); + var server = _cluster.SelectServerAndPinIfNeeded(operationContext, _session, _serverSelector, deprioritizedServers); return GetChannelSourceHelper(server); } - public async Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public async Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, _serverSelector, deprioritizedServers, operationContext).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(operationContext, _session, _serverSelector, deprioritizedServers).ConfigureAwait(false); return GetChannelSourceHelper(server); } diff --git a/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs b/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs index 7d24474f394..0409d3ae844 100644 --- a/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs +++ b/src/MongoDB.Driver/Core/Bindings/ReadWriteBindingHandle.cs @@ -58,16 +58,16 @@ public Task GetReadChannelSourceAsync(OperationContext ope return _reference.Instance.GetReadChannelSourceAsync(operationContext); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSource(deprioritizedServers, operationContext); + return _reference.Instance.GetReadChannelSource(operationContext, deprioritizedServers); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - return _reference.Instance.GetReadChannelSourceAsync(deprioritizedServers, operationContext); + return _reference.Instance.GetReadChannelSourceAsync(operationContext, deprioritizedServers); } public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) @@ -76,22 +76,22 @@ public IChannelSourceHandle GetWriteChannelSource(OperationContext operationCont return _reference.Instance.GetWriteChannelSource(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(deprioritizedServers, operationContext); + return _reference.Instance.GetWriteChannelSource(operationContext, deprioritizedServers); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(mayUseSecondary, operationContext); + return _reference.Instance.GetWriteChannelSource(operationContext, mayUseSecondary); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSource(deprioritizedServers, mayUseSecondary, operationContext); + return _reference.Instance.GetWriteChannelSource(operationContext, deprioritizedServers, mayUseSecondary); } public Task GetWriteChannelSourceAsync(OperationContext operationContext) @@ -100,22 +100,22 @@ public Task GetWriteChannelSourceAsync(OperationContext op return _reference.Instance.GetWriteChannelSourceAsync(operationContext); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(deprioritizedServers, operationContext); + return _reference.Instance.GetWriteChannelSourceAsync(operationContext, deprioritizedServers); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(mayUseSecondary, operationContext); + return _reference.Instance.GetWriteChannelSourceAsync(operationContext, mayUseSecondary); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { ThrowIfDisposed(); - return _reference.Instance.GetWriteChannelSourceAsync(deprioritizedServers, mayUseSecondary, operationContext); + return _reference.Instance.GetWriteChannelSourceAsync(operationContext, deprioritizedServers, mayUseSecondary); } public void Dispose() diff --git a/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs b/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs index 21eb3db1875..04a65fbd4b3 100644 --- a/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/SingleServerReadBinding.cs @@ -60,12 +60,12 @@ public Task GetReadChannelSourceAsync(OperationContext ope return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetReadChannelSourceAsync(operationContext); } diff --git a/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs b/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs index a9ebfd21cf7..5113baa09c0 100644 --- a/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/SingleServerReadWriteBinding.cs @@ -64,12 +64,12 @@ public Task GetReadChannelSourceAsync(OperationContext ope return Task.FromResult(GetChannelSourceHelper()); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetReadChannelSource(operationContext); } - public Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetReadChannelSourceAsync(operationContext); } @@ -80,19 +80,19 @@ public IChannelSourceHandle GetWriteChannelSource(OperationContext operationCont return GetChannelSourceHelper(); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetWriteChannelSource(operationContext); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { return GetWriteChannelSource(operationContext); // ignore mayUseSecondary } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSource(mayUseSecondary, operationContext); + return GetWriteChannelSource(operationContext, mayUseSecondary); } public Task GetWriteChannelSourceAsync(OperationContext operationContext) @@ -101,19 +101,19 @@ public Task GetWriteChannelSourceAsync(OperationContext op return Task.FromResult(GetChannelSourceHelper()); } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { return GetWriteChannelSourceAsync(operationContext); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { return GetWriteChannelSourceAsync(operationContext); // ignore mayUseSecondary } - public Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSourceAsync(mayUseSecondary, operationContext); + return GetWriteChannelSourceAsync(operationContext, mayUseSecondary); } private IChannelSourceHandle GetChannelSourceHelper() diff --git a/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs b/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs index afb68fc1741..764bdc0e0ae 100644 --- a/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs +++ b/src/MongoDB.Driver/Core/Bindings/WritableServerBinding.cs @@ -49,46 +49,46 @@ public ICoreSessionHandle Session public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { - return GetReadChannelSource(null, operationContext); + return GetReadChannelSource(operationContext, null); } public Task GetReadChannelSourceAsync(OperationContext operationContext) { - return GetReadChannelSourceAsync(null, operationContext); + return GetReadChannelSourceAsync(operationContext, null); } - public IChannelSourceHandle GetReadChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(_session, WritableServerSelector.Instance, deprioritizedServers, operationContext); + var server = _cluster.SelectServerAndPinIfNeeded(operationContext, _session, WritableServerSelector.Instance, deprioritizedServers); return CreateServerChannelSource(server); } - public async Task GetReadChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public async Task GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, WritableServerSelector.Instance, deprioritizedServers, operationContext).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(operationContext, _session, WritableServerSelector.Instance, deprioritizedServers).ConfigureAwait(false); return CreateServerChannelSource(server); } public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext) { - return GetWriteChannelSource(deprioritizedServers: null, operationContext); + return GetWriteChannelSource(operationContext, deprioritizedServers: null); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = _cluster.SelectServerAndPinIfNeeded(_session, WritableServerSelector.Instance, deprioritizedServers, operationContext); + var server = _cluster.SelectServerAndPinIfNeeded(operationContext, _session, WritableServerSelector.Instance, deprioritizedServers); return CreateServerChannelSource(server); } - public IChannelSourceHandle GetWriteChannelSource(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSource(null, mayUseSecondary, operationContext); + return GetWriteChannelSource(operationContext, null, mayUseSecondary); } - public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public IChannelSourceHandle GetWriteChannelSource(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { if (IsSessionPinnedToServer()) { @@ -101,28 +101,28 @@ public IChannelSourceHandle GetWriteChannelSource(IReadOnlyCollection GetWriteChannelSourceAsync(OperationContext operationContext) { - return GetWriteChannelSourceAsync(deprioritizedServers: null, operationContext); + return GetWriteChannelSourceAsync(operationContext, deprioritizedServers: null); } - public async Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, OperationContext operationContext) + public async Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers) { ThrowIfDisposed(); - var server = await _cluster.SelectServerAndPinIfNeededAsync(_session, WritableServerSelector.Instance, deprioritizedServers, operationContext).ConfigureAwait(false); + var server = await _cluster.SelectServerAndPinIfNeededAsync(operationContext, _session, WritableServerSelector.Instance, deprioritizedServers).ConfigureAwait(false); return CreateServerChannelSource(server); } - public Task GetWriteChannelSourceAsync(IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public Task GetWriteChannelSourceAsync(OperationContext operationContext, IMayUseSecondaryCriteria mayUseSecondary) { - return GetWriteChannelSourceAsync(null, mayUseSecondary, operationContext); + return GetWriteChannelSourceAsync(operationContext, null, mayUseSecondary); } - public async Task GetWriteChannelSourceAsync(IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary, OperationContext operationContext) + public async Task GetWriteChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection deprioritizedServers, IMayUseSecondaryCriteria mayUseSecondary) { if (IsSessionPinnedToServer()) { @@ -135,7 +135,7 @@ public async Task GetWriteChannelSourceAsync(IReadOnlyColl ? new CompositeServerSelector(new IServerSelector[] { new PriorityServerSelector(deprioritizedServers), writableServerSelector }) : writableServerSelector; - var server = await _cluster.SelectServerAsync(selector, operationContext).ConfigureAwait(false); + var server = await _cluster.SelectServerAsync(operationContext, selector).ConfigureAwait(false); return CreateServerChannelSource(server); } diff --git a/src/MongoDB.Driver/Core/Clusters/Cluster.cs b/src/MongoDB.Driver/Core/Clusters/Cluster.cs index a5f93f79837..00bda54accf 100644 --- a/src/MongoDB.Driver/Core/Clusters/Cluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/Cluster.cs @@ -216,7 +216,7 @@ protected void OnDescriptionChanged(ClusterDescription oldDescription, ClusterDe DescriptionChanged?.Invoke(this, new ClusterDescriptionChangedEventArgs(oldDescription, newDescription)); } - public IServer SelectServer(IServerSelector selector, OperationContext operationContext) + public IServer SelectServer(OperationContext operationContext, IServerSelector selector) { ThrowIfDisposedOrNotOpen(); Ensure.IsNotNull(selector, nameof(selector)); @@ -255,7 +255,7 @@ public IServer SelectServer(IServerSelector selector, OperationContext operation } } - public async Task SelectServerAsync(IServerSelector selector, OperationContext operationContext) + public async Task SelectServerAsync(OperationContext operationContext, IServerSelector selector) { ThrowIfDisposedOrNotOpen(); Ensure.IsNotNull(selector, nameof(selector)); diff --git a/src/MongoDB.Driver/Core/Clusters/ICluster.cs b/src/MongoDB.Driver/Core/Clusters/ICluster.cs index 8ab47f5cdbb..ea31d13bc12 100644 --- a/src/MongoDB.Driver/Core/Clusters/ICluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/ICluster.cs @@ -61,8 +61,8 @@ internal interface IClusterInternal : ICluster void Initialize(); - IServer SelectServer(IServerSelector selector, OperationContext operationContext); - Task SelectServerAsync(IServerSelector selector, OperationContext operationContext); + IServer SelectServer(OperationContext operationContext, IServerSelector selector); + Task SelectServerAsync(OperationContext operationContext, IServerSelector selector); ICoreSessionHandle StartSession(CoreSessionOptions options = null); } diff --git a/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs b/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs index c0de1fd5155..e8060a75a07 100644 --- a/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs +++ b/src/MongoDB.Driver/Core/Clusters/IClusterExtensions.cs @@ -25,10 +25,10 @@ internal static class IClusterExtensions { public static IServer SelectServerAndPinIfNeeded( this IClusterInternal cluster, + OperationContext operationContext, ICoreSessionHandle session, IServerSelector selector, - IReadOnlyCollection deprioritizedServers, - OperationContext operationContext) + IReadOnlyCollection deprioritizedServers) { var pinnedServer = GetPinnedServerIfValid(cluster, session); if (pinnedServer != null) @@ -42,17 +42,17 @@ public static IServer SelectServerAndPinIfNeeded( // Server selection also updates the cluster type, allowing us to determine if the server // should be pinned. - var server = cluster.SelectServer(selector, operationContext); + var server = cluster.SelectServer(operationContext, selector); PinServerIfNeeded(cluster, session, server); return server; } public static async Task SelectServerAndPinIfNeededAsync( this IClusterInternal cluster, + OperationContext operationContext, ICoreSessionHandle session, IServerSelector selector, - IReadOnlyCollection deprioritizedServers, - OperationContext operationContext) + IReadOnlyCollection deprioritizedServers) { var pinnedServer = GetPinnedServerIfValid(cluster, session); if (pinnedServer != null) @@ -66,7 +66,7 @@ public static async Task SelectServerAndPinIfNeededAsync( // Server selection also updates the cluster type, allowing us to determine if the server // should be pinned. - var server = await cluster.SelectServerAsync(selector, operationContext).ConfigureAwait(false); + var server = await cluster.SelectServerAsync(operationContext, selector).ConfigureAwait(false); PinServerIfNeeded(cluster, session, server); return server; diff --git a/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs b/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs index 39ea5e9ec95..75367a9dbf2 100644 --- a/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs @@ -170,7 +170,7 @@ public void Initialize() } } - public IServer SelectServer(IServerSelector selector, OperationContext operationContext) + public IServer SelectServer(OperationContext operationContext, IServerSelector selector) { Ensure.IsNotNull(selector, nameof(selector)); Ensure.IsNotNull(operationContext, nameof(operationContext)); @@ -208,7 +208,7 @@ public IServer SelectServer(IServerSelector selector, OperationContext operation throw new InvalidOperationException("The server must be created before usage."); // should not be reached } - public async Task SelectServerAsync(IServerSelector selector, OperationContext operationContext) + public async Task SelectServerAsync(OperationContext operationContext, IServerSelector selector) { Ensure.IsNotNull(selector, nameof(selector)); Ensure.IsNotNull(operationContext, nameof(operationContext)); diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs index d6d76a47a5b..1aa39584175 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs @@ -193,7 +193,7 @@ public IConnectionHandle AcquireConnection(OperationContext operationContext) pooledConnection = connectionCreator.CreateOpenedOrReuse(operationContext); } - return EndCheckingOut(pooledConnection, operationContext); + return EndCheckingOut(operationContext, pooledConnection); } throw CreateException(operationContext); @@ -222,7 +222,7 @@ public async Task AcquireConnectionAsync(OperationContext ope pooledConnection = await connectionCreator.CreateOpenedOrReuseAsync(operationContext).ConfigureAwait(false); } - return EndCheckingOut(pooledConnection, operationContext); + return EndCheckingOut(operationContext, pooledConnection); } throw CreateException(operationContext); @@ -281,7 +281,7 @@ private void StartCheckingOut() AcquireWaitQueueSlot(); } - private IConnectionHandle EndCheckingOut(PooledConnection pooledConnection, OperationContext operationContext) + private IConnectionHandle EndCheckingOut(OperationContext operationContext, PooledConnection pooledConnection) { var reference = new ReferenceCounted(pooledConnection, _pool.ReleaseConnection); var connectionHandle = new AcquiredConnection(_pool, reference); @@ -965,7 +965,7 @@ private PooledConnection CreateOpenedInternal(OperationContext operationContext) // TODO: CSOT add support of CSOT timeout in connection open code too. _connection.Open(operationContext.CancellationToken); - FinishCreating(_connection.Description, operationContext); + FinishCreating(operationContext, _connection.Description); return _connection; } @@ -977,7 +977,7 @@ private async Task CreateOpenedInternalAsync(OperationContext // TODO: CSOT add support of CSOT timeout in connection open code too. await _connection.OpenAsync(operationContext.CancellationToken).ConfigureAwait(false); - FinishCreating(_connection.Description, operationContext); + FinishCreating(operationContext, _connection.Description); return _connection; } @@ -995,7 +995,7 @@ private void StartCreating(OperationContext operationContext) _connection = _pool.CreateNewConnection(); } - private void FinishCreating(ConnectionDescription description, OperationContext operationContext) + private void FinishCreating(OperationContext operationContext, ConnectionDescription description) { _pool._eventLogger.LogAndPublish(new ConnectionPoolAddedConnectionEvent(_connection.ConnectionId, operationContext.Elapsed, EventContext.OperationId)); diff --git a/src/MongoDB.Driver/Core/Misc/Feature.cs b/src/MongoDB.Driver/Core/Misc/Feature.cs index c3da1d48ffd..762b7d0591e 100644 --- a/src/MongoDB.Driver/Core/Misc/Feature.cs +++ b/src/MongoDB.Driver/Core/Misc/Feature.cs @@ -565,7 +565,7 @@ internal int LastNotSupportedWireVersion public void ThrowIfNotSupported(IMongoClient client, CancellationToken cancellationToken = default) { var cluster = client.GetClusterInternal(); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, NoCoreSession.NewHandle()))) using (var channelSource = binding.GetWriteChannelSource(operationContext)) @@ -584,7 +584,7 @@ public void ThrowIfNotSupported(IMongoClient client, CancellationToken cancellat public async Task ThrowIfNotSupportedAsync(IMongoClient client, CancellationToken cancellationToken = default) { var cluster = client.GetClusterInternal(); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (var binding = new ReadWriteBindingHandle(new WritableServerBinding(cluster, NoCoreSession.NewHandle()))) using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) diff --git a/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs b/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs index 01608902b97..86eae237593 100644 --- a/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/AggregateOperation.cs @@ -269,19 +269,19 @@ public bool? UseCursor // methods /// - public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) + public IAsyncCursor Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, operationContext); + return Execute(operationContext, context); } } /// - public IAsyncCursor Execute(RetryableReadContext context, OperationContext operationContext) + public IAsyncCursor Execute(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); EnsureIsReadOnlyPipeline(); @@ -289,7 +289,7 @@ public IAsyncCursor Execute(RetryableReadContext context, OperationCont using (EventContext.BeginOperation()) { var operation = CreateOperation(context); - var result = operation.Execute(context, operationContext); + var result = operation.Execute(operationContext, context); context.ChannelSource.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); @@ -298,19 +298,19 @@ public IAsyncCursor Execute(RetryableReadContext context, OperationCont } /// - public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, operationContext).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } /// - public async Task> ExecuteAsync(RetryableReadContext context, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); EnsureIsReadOnlyPipeline(); @@ -318,7 +318,7 @@ public async Task> ExecuteAsync(RetryableReadContext conte using (EventContext.BeginOperation()) { var operation = CreateOperation(context); - var result = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); context.ChannelSource.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); diff --git a/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs index 76108a15a04..79c684d9752 100644 --- a/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/AggregateToCollectionOperation.cs @@ -147,33 +147,33 @@ public WriteConcern WriteConcern set { _writeConcern = value; } } - public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); var mayUseSecondary = new MayUseSecondary(_readPreference); using (BeginOperation()) - using (var channelSource = binding.GetWriteChannelSource(mayUseSecondary, operationContext)) + using (var channelSource = binding.GetWriteChannelSource(operationContext, mayUseSecondary)) using (var channel = channelSource.GetChannel(operationContext)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, mayUseSecondary.EffectiveReadPreference); - return operation.Execute(channelBinding, operationContext); + return operation.Execute(operationContext, channelBinding); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); var mayUseSecondary = new MayUseSecondary(_readPreference); using (BeginOperation()) - using (var channelSource = await binding.GetWriteChannelSourceAsync(mayUseSecondary, operationContext).ConfigureAwait(false)) + using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext, mayUseSecondary).ConfigureAwait(false)) using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, mayUseSecondary.EffectiveReadPreference); - return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs b/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs index 57712fd29ea..bb0b2daa92a 100644 --- a/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs +++ b/src/MongoDB.Driver/Core/Operations/AsyncCursor.cs @@ -409,7 +409,7 @@ private void DisposeChannelSourceIfNoLongerNeeded() private CursorBatch GetNextBatch(CancellationToken cancellationToken) { - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) using (var channel = _channelSource.GetChannel(operationContext)) @@ -420,7 +420,7 @@ private CursorBatch GetNextBatch(CancellationToken cancellationToken) private async Task> GetNextBatchAsync(CancellationToken cancellationToken) { - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) using (var channel = await _channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) @@ -436,7 +436,7 @@ private bool IsMongoCursorNotFoundException(MongoCommandException exception) private void KillCursors(CancellationToken cancellationToken) { - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) using (EventContext.BeginKillCursors(_collectionNamespace)) @@ -451,7 +451,7 @@ private void KillCursors(CancellationToken cancellationToken) private async Task KillCursorsAsync(CancellationToken cancellationToken) { - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (EventContext.BeginOperation(_operationId)) using (EventContext.BeginKillCursors(_collectionNamespace)) diff --git a/src/MongoDB.Driver/Core/Operations/BulkMixedWriteOperation.cs b/src/MongoDB.Driver/Core/Operations/BulkMixedWriteOperation.cs index 34a71dbea11..efe28a3f4af 100644 --- a/src/MongoDB.Driver/Core/Operations/BulkMixedWriteOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/BulkMixedWriteOperation.cs @@ -136,33 +136,33 @@ public WriteConcern WriteConcern set { _writeConcern = Ensure.IsNotNull(value, nameof(value)); } } - public BulkWriteOperationResult Execute(IWriteBinding binding, OperationContext operationContext) + public BulkWriteOperationResult Execute(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) - using (var context = RetryableWriteContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableWriteContext.Create(operationContext, binding, _retryRequested)) { EnsureHintIsSupportedIfAnyRequestHasHint(); context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); var helper = new BatchHelper(_requests, _isOrdered, _writeConcern); foreach (var batch in helper.GetBatches()) { - batch.Result = ExecuteBatch(context, batch, operationContext); + batch.Result = ExecuteBatch(operationContext, context, batch); } return helper.GetFinalResultOrThrow(context.Channel.ConnectionDescription.ConnectionId); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) - using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { EnsureHintIsSupportedIfAnyRequestHasHint(); context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); var helper = new BatchHelper(_requests, _isOrdered, _writeConcern); foreach (var batch in helper.GetBatches()) { - batch.Result = await ExecuteBatchAsync(context, batch, operationContext).ConfigureAwait(false); + batch.Result = await ExecuteBatchAsync(operationContext, context, batch).ConfigureAwait(false); } return helper.GetFinalResultOrThrow(context.Channel.ConnectionDescription.ConnectionId); } @@ -241,14 +241,14 @@ private void EnsureHintIsSupportedIfAnyRequestHasHint() } } - private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch batch, OperationContext operationContext) + private BulkWriteBatchResult ExecuteBatch(OperationContext operationContext, RetryableWriteContext context, Batch batch) { BulkWriteOperationResult result; MongoBulkWriteOperationException exception = null; try { var operation = CreateUnmixedBatchOperation(batch); - result = operation.Execute(context, operationContext); + result = operation.Execute(operationContext, context); } catch (MongoBulkWriteOperationException ex) { @@ -259,14 +259,14 @@ private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch b return BulkWriteBatchResult.Create(result, exception, batch.IndexMap); } - private async Task ExecuteBatchAsync(RetryableWriteContext context, Batch batch, OperationContext operationContext) + private async Task ExecuteBatchAsync(OperationContext operationContext, RetryableWriteContext context, Batch batch) { BulkWriteOperationResult result; MongoBulkWriteOperationException exception = null; try { var operation = CreateUnmixedBatchOperation(batch); - result = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); + result = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); } catch (MongoBulkWriteOperationException ex) { diff --git a/src/MongoDB.Driver/Core/Operations/BulkUnmixedWriteOperationBase.cs b/src/MongoDB.Driver/Core/Operations/BulkUnmixedWriteOperationBase.cs index 57169f8b665..03ad4ad3e3c 100644 --- a/src/MongoDB.Driver/Core/Operations/BulkUnmixedWriteOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/BulkUnmixedWriteOperationBase.cs @@ -119,37 +119,37 @@ public WriteConcern WriteConcern } // public methods - public BulkWriteOperationResult Execute(RetryableWriteContext context, OperationContext operationContext) + public BulkWriteOperationResult Execute(OperationContext operationContext, RetryableWriteContext context) { EnsureHintIsSupportedIfAnyRequestHasHint(); - return ExecuteBatches(context, operationContext); + return ExecuteBatches(operationContext, context); } - public BulkWriteOperationResult Execute(IWriteBinding binding, OperationContext operationContext) + public BulkWriteOperationResult Execute(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) - using (var context = RetryableWriteContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableWriteContext.Create(operationContext, binding, _retryRequested)) { context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); - return Execute(context, operationContext); + return Execute(operationContext, context); } } - public Task ExecuteAsync(RetryableWriteContext context, OperationContext operationContext) + public Task ExecuteAsync(OperationContext operationContext, RetryableWriteContext context) { EnsureHintIsSupportedIfAnyRequestHasHint(); - return ExecuteBatchesAsync(context, operationContext); + return ExecuteBatchesAsync(operationContext, context); } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) - using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { context.DisableRetriesIfAnyWriteRequestIsNotRetryable(_requests); - return await ExecuteAsync(context, operationContext).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } @@ -189,14 +189,14 @@ private void EnsureHintIsSupportedIfAnyRequestHasHint() } } - private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch batch, OperationContext operationContext) + private BulkWriteBatchResult ExecuteBatch(OperationContext operationContext, RetryableWriteContext context, Batch batch) { var operation = CreateBatchOperation(batch); BsonDocument operationResult; MongoWriteConcernException writeConcernException = null; try { - operationResult = RetryableWriteOperationExecutor.Execute(operation, context, operationContext); + operationResult = RetryableWriteOperationExecutor.Execute(operationContext, operation, context); } catch (MongoWriteConcernException exception) when (exception.IsWriteConcernErrorOnly()) { @@ -207,14 +207,14 @@ private BulkWriteBatchResult ExecuteBatch(RetryableWriteContext context, Batch b return CreateBatchResult(batch, operationResult, writeConcernException); } - private async Task ExecuteBatchAsync(RetryableWriteContext context, Batch batch, OperationContext operationContext) + private async Task ExecuteBatchAsync(OperationContext operationContext, RetryableWriteContext context, Batch batch) { var operation = CreateBatchOperation(batch); BsonDocument operationResult; MongoWriteConcernException writeConcernException = null; try { - operationResult = await RetryableWriteOperationExecutor.ExecuteAsync(operation, context, operationContext).ConfigureAwait(false); + operationResult = await RetryableWriteOperationExecutor.ExecuteAsync(operationContext, operation, context).ConfigureAwait(false); } catch (MongoWriteConcernException exception) when (exception.IsWriteConcernErrorOnly()) { @@ -225,22 +225,22 @@ private async Task ExecuteBatchAsync(RetryableWriteContext return CreateBatchResult(batch, operationResult, writeConcernException); } - private BulkWriteOperationResult ExecuteBatches(RetryableWriteContext context, OperationContext operationContext) + private BulkWriteOperationResult ExecuteBatches(OperationContext operationContext, RetryableWriteContext context) { var helper = new BatchHelper(_requests, _writeConcern, _isOrdered); foreach (var batch in helper.GetBatches()) { - batch.Result = ExecuteBatch(context, batch, operationContext); + batch.Result = ExecuteBatch(operationContext, context, batch); } return helper.CreateFinalResultOrThrow(context.Channel); } - private async Task ExecuteBatchesAsync(RetryableWriteContext context, OperationContext operationContext) + private async Task ExecuteBatchesAsync(OperationContext operationContext, RetryableWriteContext context) { var helper = new BatchHelper(_requests, _writeConcern, _isOrdered); foreach (var batch in helper.GetBatches()) { - batch.Result = await ExecuteBatchAsync(context, batch, operationContext).ConfigureAwait(false); + batch.Result = await ExecuteBatchAsync(operationContext, context, batch).ConfigureAwait(false); } return helper.CreateFinalResultOrThrow(context.Channel); } diff --git a/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs b/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs index e33a4f95c56..afd01623847 100644 --- a/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs +++ b/src/MongoDB.Driver/Core/Operations/ChangeStreamCursor.cs @@ -261,17 +261,17 @@ private void ReconfigureOperationResumeValues() private IAsyncCursor Resume(CancellationToken cancellationToken) { ReconfigureOperationResumeValues(); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); - return _changeStreamOperation.Resume(_binding, operationContext); + return _changeStreamOperation.Resume(operationContext, _binding); } private async Task> ResumeAsync(CancellationToken cancellationToken) { ReconfigureOperationResumeValues(); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); - return await _changeStreamOperation.ResumeAsync(_binding, operationContext).ConfigureAwait(false); + return await _changeStreamOperation.ResumeAsync(operationContext, _binding).ConfigureAwait(false); } internal struct ResumeValues diff --git a/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs b/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs index 32bbb7091ce..ed08f1c85e5 100644 --- a/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ChangeStreamOperation.cs @@ -33,8 +33,8 @@ internal interface IChangeStreamOperation : IReadOperation Resume(IReadBinding binding, OperationContext operationContext); - Task> ResumeAsync(IReadBinding binding, OperationContext operationContext); + IAsyncCursor Resume(OperationContext operationContext, IReadBinding binding); + Task> ResumeAsync(OperationContext operationContext, IReadBinding binding); } internal sealed class ChangeStreamOperation : IChangeStreamOperation @@ -249,7 +249,7 @@ public BsonTimestamp StartAtOperationTime // public methods /// - public IChangeStreamCursor Execute(IReadBinding binding, OperationContext operationContext) + public IChangeStreamCursor Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); var bindingHandle = binding as IReadBindingHandle; @@ -261,9 +261,9 @@ public IChangeStreamCursor Execute(IReadBinding binding, OperationConte IAsyncCursor cursor; ICursorBatchInfo cursorBatchInfo; BsonTimestamp initialOperationTime; - using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - cursor = ExecuteAggregateOperation(context, operationContext); + cursor = ExecuteAggregateOperation(operationContext, context); cursorBatchInfo = (ICursorBatchInfo)cursor; initialOperationTime = GetInitialOperationTimeIfRequired(context, cursorBatchInfo); @@ -284,7 +284,7 @@ public IChangeStreamCursor Execute(IReadBinding binding, OperationConte } /// - public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); var bindingHandle = binding as IReadBindingHandle; @@ -296,9 +296,9 @@ public async Task> ExecuteAsync(IReadBinding bindin IAsyncCursor cursor; ICursorBatchInfo cursorBatchInfo; BsonTimestamp initialOperationTime; - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - cursor = await ExecuteAggregateOperationAsync(context, operationContext).ConfigureAwait(false); + cursor = await ExecuteAggregateOperationAsync(operationContext, context).ConfigureAwait(false); cursorBatchInfo = (ICursorBatchInfo)cursor; initialOperationTime = GetInitialOperationTimeIfRequired(context, cursorBatchInfo); @@ -319,20 +319,20 @@ public async Task> ExecuteAsync(IReadBinding bindin } /// - public IAsyncCursor Resume(IReadBinding binding, OperationContext operationContext) + public IAsyncCursor Resume(OperationContext operationContext, IReadBinding binding) { - using (var context = RetryableReadContext.Create(binding, retryRequested: false, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, retryRequested: false)) { - return ExecuteAggregateOperation(context, operationContext); + return ExecuteAggregateOperation(operationContext, context); } } /// - public async Task> ResumeAsync(IReadBinding binding, OperationContext operationContext) + public async Task> ResumeAsync(OperationContext operationContext, IReadBinding binding) { - using (var context = await RetryableReadContext.CreateAsync(binding, retryRequested: false, operationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, retryRequested: false).ConfigureAwait(false)) { - return await ExecuteAggregateOperationAsync(context, operationContext).ConfigureAwait(false); + return await ExecuteAggregateOperationAsync(operationContext, context).ConfigureAwait(false); } } @@ -391,16 +391,16 @@ private List CreateCombinedPipeline(BsonDocument changeStreamStage return combinedPipeline; } - private IAsyncCursor ExecuteAggregateOperation(RetryableReadContext context, OperationContext operationContext) + private IAsyncCursor ExecuteAggregateOperation(OperationContext operationContext, RetryableReadContext context) { var aggregateOperation = CreateAggregateOperation(); - return aggregateOperation.Execute(context, operationContext); + return aggregateOperation.Execute(operationContext, context); } - private Task> ExecuteAggregateOperationAsync(RetryableReadContext context, OperationContext operationContext) + private Task> ExecuteAggregateOperationAsync(OperationContext operationContext, RetryableReadContext context) { var aggregateOperation = CreateAggregateOperation(); - return aggregateOperation.ExecuteAsync(context, operationContext); + return aggregateOperation.ExecuteAsync(operationContext, context); } private BsonDocument GetInitialPostBatchResumeTokenIfRequired(ICursorBatchInfo cursorBatchInfo) diff --git a/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs b/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs index f738de2aac2..2416fd0aff3 100644 --- a/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ClientBulkWriteOperation.cs @@ -88,17 +88,17 @@ protected override IEnumerable CreateCommandPayl return new[] { payload }; } - public new ClientBulkWriteResult Execute(IWriteBinding binding, OperationContext operationContext) + public new ClientBulkWriteResult Execute(OperationContext operationContext, IWriteBinding binding) { using var operation = BeginOperation(); var bulkWriteResults = new BulkWriteRawResult(); while (true) { - using var context = RetryableWriteContext.Create(binding, GetEffectiveRetryRequested(), operationContext); + using var context = RetryableWriteContext.Create(operationContext, binding, GetEffectiveRetryRequested()); BsonDocument serverResponse = null; try { - serverResponse = base.Execute(context, operationContext); + serverResponse = base.Execute(operationContext, context); } catch (MongoWriteConcernException concernException) { @@ -146,17 +146,17 @@ protected override IEnumerable CreateCommandPayl } } - public new async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public new async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { using var operation = BeginOperation(); var bulkWriteResults = new BulkWriteRawResult(); while (true) { - using var context = RetryableWriteContext.Create(binding, GetEffectiveRetryRequested(), operationContext); + using var context = RetryableWriteContext.Create(operationContext, binding, GetEffectiveRetryRequested()); BsonDocument serverResponse = null; try { - serverResponse = await base.ExecuteAsync(context, operationContext).ConfigureAwait(false); + serverResponse = await base.ExecuteAsync(operationContext, context).ConfigureAwait(false); } catch (MongoWriteConcernException concernException) { diff --git a/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs b/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs index cd602ae27f6..62eca2d6992 100644 --- a/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/CommandOperationBase.cs @@ -105,10 +105,10 @@ protected TCommandResult ExecuteProtocol(IChannelHandle channel, ICoreSessionHan } protected TCommandResult ExecuteProtocol( + OperationContext operationContext, IChannelSource channelSource, ICoreSessionHandle session, - ReadPreference readPreference, - OperationContext operationContext) + ReadPreference readPreference) { using (var channel = channelSource.GetChannel(operationContext)) { @@ -136,10 +136,10 @@ protected Task ExecuteProtocolAsync(IChannelHandle channel, ICor } protected async Task ExecuteProtocolAsync( + OperationContext operationContext, IChannelSource channelSource, ICoreSessionHandle session, - ReadPreference readPreference, - OperationContext operationContext) + ReadPreference readPreference) { using (var channel = await channelSource.GetChannelAsync(operationContext).ConfigureAwait(false)) { diff --git a/src/MongoDB.Driver/Core/Operations/CompositeWriteOperation.cs b/src/MongoDB.Driver/Core/Operations/CompositeWriteOperation.cs index 5669ca36fb9..68e6964d994 100644 --- a/src/MongoDB.Driver/Core/Operations/CompositeWriteOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CompositeWriteOperation.cs @@ -31,12 +31,12 @@ public CompositeWriteOperation(params (IWriteOperation, bool IsMainOper Ensure.That(operations.Count(o => o.IsMainOperation) == 1, message: $"{nameof(CompositeWriteOperation)} must have a single main operation."); } - public TResult Execute(IWriteBinding binding, OperationContext operationContext) + public TResult Execute(OperationContext operationContext, IWriteBinding binding) { TResult result = default; foreach (var operationInfo in _operations) { - var itemResult = operationInfo.Operation.Execute(binding, operationContext); + var itemResult = operationInfo.Operation.Execute(operationContext, binding); if (operationInfo.IsMainOperation) { result = itemResult; @@ -46,12 +46,12 @@ public TResult Execute(IWriteBinding binding, OperationContext operationContext) return result; } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { TResult result = default; foreach (var operationInfo in _operations) { - var itemResult = await operationInfo.Operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + var itemResult = await operationInfo.Operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); if (operationInfo.IsMainOperation) { result = itemResult; diff --git a/src/MongoDB.Driver/Core/Operations/CountDocumentsOperation.cs b/src/MongoDB.Driver/Core/Operations/CountDocumentsOperation.cs index 1cc5b12e1f1..6bcc00d33db 100644 --- a/src/MongoDB.Driver/Core/Operations/CountDocumentsOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CountDocumentsOperation.cs @@ -109,27 +109,27 @@ public long? Skip set { _skip = value; } } - public long Execute(IReadBinding binding, OperationContext operationContext) + public long Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var cursor = operation.Execute(binding, operationContext); + var cursor = operation.Execute(operationContext, binding); var result = cursor.ToList(operationContext.CancellationToken); return ExtractCountFromResult(result); } } - public async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var cursor = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + var cursor = await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); var result = await cursor.ToListAsync(operationContext.CancellationToken).ConfigureAwait(false); return ExtractCountFromResult(result); } diff --git a/src/MongoDB.Driver/Core/Operations/CountOperation.cs b/src/MongoDB.Driver/Core/Operations/CountOperation.cs index 4b75810956f..cd83e1d374d 100644 --- a/src/MongoDB.Driver/Core/Operations/CountOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CountOperation.cs @@ -126,39 +126,39 @@ public BsonDocument CreateCommand(ConnectionDescription connectionDescription, I }; } - public long Execute(IReadBinding binding, OperationContext operationContext) + public long Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, operationContext); + return Execute(operationContext, context); } } - public long Execute(RetryableReadContext context, OperationContext operationContext) + public long Execute(OperationContext operationContext, RetryableReadContext context) { var operation = CreateOperation(context); - var document = operation.Execute(context, operationContext); + var document = operation.Execute(operationContext, context); return document["n"].ToInt64(); } - public async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, operationContext).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } - public async Task ExecuteAsync(RetryableReadContext context, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, RetryableReadContext context) { var operation = CreateOperation(context); - var document = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); + var document = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); return document["n"].ToInt64(); } diff --git a/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs index d32486a6180..31b2f7be994 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateCollectionOperation.cs @@ -273,7 +273,7 @@ internal BsonDocument CreateCommand(ICoreSessionHandle session) } } - public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -285,12 +285,12 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); - return operation.Execute(channelBinding, operationContext); + return operation.Execute(operationContext, channelBinding); } } } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -302,7 +302,7 @@ public async Task ExecuteAsync(IWriteBinding binding, OperationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); - return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs index 29d4d5ee56d..f4e071950ad 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateIndexesOperation.cs @@ -86,7 +86,7 @@ public TimeSpan? MaxTime set { _maxTime = Ensure.IsNullOrInfiniteOrGreaterThanOrEqualToZero(value, nameof(value)); } } - public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) using (var channelSource = binding.GetWriteChannelSource(operationContext)) @@ -94,11 +94,11 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return operation.Execute(channelBinding, operationContext); + return operation.Execute(operationContext, channelBinding); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) @@ -106,7 +106,7 @@ public async Task ExecuteAsync(IWriteBinding binding, OperationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs index d7eeb1db48a..edc8ae04f77 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateSearchIndexesOperation.cs @@ -54,7 +54,7 @@ public CreateSearchIndexesOperation( // public methods /// - public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { using (EventContext.BeginOperation("createSearchIndexes")) using (var channelSource = binding.GetWriteChannelSource(operationContext)) @@ -62,12 +62,12 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return operation.Execute(channelBinding, operationContext); + return operation.Execute(operationContext, channelBinding); } } /// - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { using (EventContext.BeginOperation("createSearchIndexes")) using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) @@ -75,7 +75,7 @@ public async Task ExecuteAsync(IWriteBinding binding, OperationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs b/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs index 24e553618fa..64a5d954bc2 100644 --- a/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/CreateViewOperation.cs @@ -86,7 +86,7 @@ public WriteConcern WriteConcern set { _writeConcern = value; } } - public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -95,11 +95,11 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return operation.Execute(channelBinding, operationContext); + return operation.Execute(operationContext, channelBinding); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -108,7 +108,7 @@ public async Task ExecuteAsync(IWriteBinding binding, OperationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/DatabaseExistsOperation.cs b/src/MongoDB.Driver/Core/Operations/DatabaseExistsOperation.cs index e1f86ef6cf9..9b6f4cdca4d 100644 --- a/src/MongoDB.Driver/Core/Operations/DatabaseExistsOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DatabaseExistsOperation.cs @@ -49,21 +49,21 @@ public bool RetryRequested set { _retryRequested = value; } } - public bool Execute(IReadBinding binding, OperationContext operationContext) + public bool Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = operation.Execute(binding, operationContext); + var result = operation.Execute(operationContext, binding); // TODO: CSOT find a way to apply CSOT timeout to ToList as well. var list = result.ToList(operationContext.CancellationToken); return list.Any(x => x["name"] == _databaseNamespace.DatabaseName); } - public async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); // TODO: CSOT find a way to apply CSOT timeout to ToList as well. var list = await result.ToListAsync(operationContext.CancellationToken).ConfigureAwait(false); return list.Any(x => x["name"] == _databaseNamespace.DatabaseName); diff --git a/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs b/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs index 6c5e41867a6..0e25eb3d097 100644 --- a/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DistinctOperation.cs @@ -104,15 +104,15 @@ public IBsonSerializer ValueSerializer get { return _valueSerializer; } } - public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) + public IAsyncCursor Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { var operation = CreateOperation(context); - var result = operation.Execute(context, operationContext); + var result = operation.Execute(operationContext, context); binding.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); @@ -120,15 +120,15 @@ public IAsyncCursor Execute(IReadBinding binding, OperationContext opera } } - public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { var operation = CreateOperation(context); - var result = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); binding.Session.SetSnapshotTimeIfNeeded(result.AtClusterTime); diff --git a/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs index 33a312c913d..d667367575a 100644 --- a/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropCollectionOperation.cs @@ -95,7 +95,7 @@ public WriteConcern WriteConcern set { _writeConcern = value; } } - public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -108,7 +108,7 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon BsonDocument result; try { - result = operation.Execute(channelBinding, operationContext); + result = operation.Execute(operationContext, channelBinding); } catch (MongoCommandException ex) { @@ -122,7 +122,7 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon } } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -135,7 +135,7 @@ public async Task ExecuteAsync(IWriteBinding binding, OperationCon BsonDocument result; try { - result = await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + result = await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } catch (MongoCommandException ex) { diff --git a/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs b/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs index 2afd2ad3b84..39be674d49c 100644 --- a/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropDatabaseOperation.cs @@ -64,7 +64,7 @@ public BsonDocument CreateCommand(ICoreSessionHandle session) }; } - public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -74,11 +74,11 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); - return operation.Execute(channelBinding, operationContext); + return operation.Execute(operationContext, channelBinding); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -88,7 +88,7 @@ public async Task ExecuteAsync(IWriteBinding binding, OperationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session); - return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs index c895a2e1378..ef68ad071c5 100644 --- a/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropIndexOperation.cs @@ -97,7 +97,7 @@ public BsonDocument CreateCommand(ICoreSessionHandle session) }; } - public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -110,7 +110,7 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon BsonDocument result; try { - result = operation.Execute(channelBinding, operationContext); + result = operation.Execute(operationContext, channelBinding); } catch (MongoCommandException ex) { @@ -124,7 +124,7 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon } } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -137,7 +137,7 @@ public async Task ExecuteAsync(IWriteBinding binding, OperationCon BsonDocument result; try { - result = await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + result = await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } catch (MongoCommandException ex) { diff --git a/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs index 71630d365cc..aff890be381 100644 --- a/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/DropSearchIndexOperation.cs @@ -62,7 +62,7 @@ private WriteCommandOperation CreateOperation() => new(_collectionNamespace.DatabaseNamespace, CreateCommand(), BsonDocumentSerializer.Instance, _messageEncoderSettings); /// - public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -75,7 +75,7 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon try { - return operation.Execute(channelBinding, operationContext); + return operation.Execute(operationContext, channelBinding); } catch (MongoCommandException ex) when (ShouldIgnoreException(ex)) { @@ -85,7 +85,7 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon } /// - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -98,7 +98,7 @@ public async Task ExecuteAsync(IWriteBinding binding, OperationCon try { - return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } catch (MongoCommandException ex) when (ShouldIgnoreException(ex)) { diff --git a/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs b/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs index 6e75367053b..0544b2498c3 100644 --- a/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/EndTransactionOperation.cs @@ -50,7 +50,7 @@ public MessageEncoderSettings MessageEncoderSettings protected abstract string CommandName { get; } - public virtual BsonDocument Execute(IReadBinding binding, OperationContext operationContext) + public virtual BsonDocument Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -59,11 +59,11 @@ public virtual BsonDocument Execute(IReadBinding binding, OperationContext opera using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return operation.Execute(channelBinding, operationContext); + return operation.Execute(operationContext, channelBinding); } } - public virtual async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public virtual async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -72,7 +72,7 @@ public virtual async Task ExecuteAsync(IReadBinding binding, Opera using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } @@ -133,11 +133,11 @@ public TimeSpan? MaxCommitTime protected override string CommandName => "commitTransaction"; - public override BsonDocument Execute(IReadBinding binding, OperationContext operationContext) + public override BsonDocument Execute(OperationContext operationContext, IReadBinding binding) { try { - return base.Execute(binding, operationContext); + return base.Execute(operationContext, binding); } catch (MongoException exception) when (ShouldReplaceTransientTransactionErrorWithUnknownTransactionCommitResult(exception)) { @@ -146,11 +146,11 @@ public override BsonDocument Execute(IReadBinding binding, OperationContext oper } } - public override async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public override async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { try { - return await base.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + return await base.ExecuteAsync(operationContext, binding).ConfigureAwait(false); } catch (MongoException exception) when (ShouldReplaceTransientTransactionErrorWithUnknownTransactionCommitResult(exception)) { diff --git a/src/MongoDB.Driver/Core/Operations/EstimatedDocumentCountOperation.cs b/src/MongoDB.Driver/Core/Operations/EstimatedDocumentCountOperation.cs index 7c0701af038..eac2d1a32a1 100644 --- a/src/MongoDB.Driver/Core/Operations/EstimatedDocumentCountOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/EstimatedDocumentCountOperation.cs @@ -66,29 +66,29 @@ public bool RetryRequested set => _retryRequested = value; } - public long Execute(IReadBinding binding, OperationContext operationContext) + public long Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { var operation = CreateCountOperation(); - return operation.Execute(context, operationContext); + return operation.Execute(operationContext, context); } } - public async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { var operation = CreateCountOperation(); - return await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/EvalOperation.cs b/src/MongoDB.Driver/Core/Operations/EvalOperation.cs index 9ae4d6721c3..b8bb23cfce5 100644 --- a/src/MongoDB.Driver/Core/Operations/EvalOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/EvalOperation.cs @@ -87,19 +87,19 @@ public BsonDocument CreateCommand() }; } - public BsonValue Execute(IWriteBinding binding, OperationContext operationContext) + public BsonValue Execute(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = operation.Execute(binding, operationContext); + var result = operation.Execute(operationContext, binding); return result["retval"]; } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); var operation = CreateOperation(); - var result = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); return result["retval"]; } diff --git a/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs b/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs index 7c36451db12..d32198f81af 100644 --- a/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/FindAndModifyOperationBase.cs @@ -84,39 +84,39 @@ public bool RetryRequested set { _retryRequested = value; } } - public TResult Execute(IWriteBinding binding, OperationContext operationContext) + public TResult Execute(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.Execute(this, binding, _retryRequested, operationContext); + return RetryableWriteOperationExecutor.Execute(operationContext, this, binding, _retryRequested); } } - public TResult Execute(RetryableWriteContext context, OperationContext operationContext) + public TResult Execute(OperationContext operationContext, RetryableWriteContext context) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.Execute(this, context, operationContext); + return RetryableWriteOperationExecutor.Execute(operationContext, this, context); } } - public Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.ExecuteAsync(this, binding, _retryRequested, operationContext); + return RetryableWriteOperationExecutor.ExecuteAsync(operationContext, this, binding, _retryRequested); } } - public Task ExecuteAsync(RetryableWriteContext context, OperationContext operationContext) + public Task ExecuteAsync(OperationContext operationContext, RetryableWriteContext context) { using (BeginOperation()) { - return RetryableWriteOperationExecutor.ExecuteAsync(this, context, operationContext); + return RetryableWriteOperationExecutor.ExecuteAsync(operationContext, this, context); } } - public TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, OperationContext operationContext) + public TResult ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { var binding = context.Binding; var channelSource = context.ChannelSource; @@ -125,14 +125,14 @@ public TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, transactionNumber); - using (var rawBsonDocument = operation.Execute(channelBinding, operationContext)) + using (var rawBsonDocument = operation.Execute(operationContext, channelBinding)) { return ProcessCommandResult(channel.ConnectionDescription.ConnectionId, rawBsonDocument); } } } - public async Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, OperationContext operationContext) + public async Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { var binding = context.Binding; var channelSource = context.ChannelSource; @@ -141,7 +141,7 @@ public async Task ExecuteAttemptAsync(RetryableWriteContext context, in using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription, transactionNumber); - using (var rawBsonDocument = await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false)) + using (var rawBsonDocument = await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false)) { return ProcessCommandResult(channel.ConnectionDescription.ConnectionId, rawBsonDocument); } diff --git a/src/MongoDB.Driver/Core/Operations/FindOperation.cs b/src/MongoDB.Driver/Core/Operations/FindOperation.cs index 4302f3b1767..7ebc524b81e 100644 --- a/src/MongoDB.Driver/Core/Operations/FindOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/FindOperation.cs @@ -291,48 +291,48 @@ public BsonDocument CreateCommand(ConnectionDescription connectionDescription, I }; } - public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) + public IAsyncCursor Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, operationContext); + return Execute(operationContext, context); } } - public IAsyncCursor Execute(RetryableReadContext context, OperationContext operationContext) + public IAsyncCursor Execute(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginFind(_batchSize, _limit)) { var operation = CreateOperation(context); - var commandResult = operation.Execute(context, operationContext); + var commandResult = operation.Execute(operationContext, context); return CreateCursor(context.ChannelSource, context.Channel, commandResult); } } - public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, operationContext).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } - public async Task> ExecuteAsync(RetryableReadContext context, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginFind(_batchSize, _limit)) { var operation = CreateOperation(context); - var commandResult = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); + var commandResult = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); return CreateCursor(context.ChannelSource, context.Channel, commandResult); } } diff --git a/src/MongoDB.Driver/Core/Operations/GroupOperation.cs b/src/MongoDB.Driver/Core/Operations/GroupOperation.cs index a54b7e1b51f..4c987e09300 100644 --- a/src/MongoDB.Driver/Core/Operations/GroupOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/GroupOperation.cs @@ -138,7 +138,7 @@ public BsonDocument CreateCommand() }; } - public IEnumerable Execute(IReadBinding binding, OperationContext operationContext) + public IEnumerable Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (var channelSource = binding.GetReadChannelSource(operationContext)) @@ -146,11 +146,11 @@ public IEnumerable Execute(IReadBinding binding, OperationContext opera using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(); - return operation.Execute(channelBinding, operationContext); + return operation.Execute(operationContext, channelBinding); } } - public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (var channelSource = await binding.GetReadChannelSourceAsync(operationContext).ConfigureAwait(false)) @@ -158,7 +158,7 @@ public async Task> ExecuteAsync(IReadBinding binding, Opera using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(); - return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/IOperation.cs b/src/MongoDB.Driver/Core/Operations/IOperation.cs index 8cebc23ff53..1ccd8dcb2ad 100644 --- a/src/MongoDB.Driver/Core/Operations/IOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/IOperation.cs @@ -20,13 +20,13 @@ namespace MongoDB.Driver.Core.Operations { internal interface IReadOperation { - TResult Execute(IReadBinding binding, OperationContext operationContext); - Task ExecuteAsync(IReadBinding binding, OperationContext operationContext); + TResult Execute(OperationContext operationContext, IReadBinding binding); + Task ExecuteAsync(OperationContext operationContext, IReadBinding binding); } internal interface IWriteOperation { - TResult Execute(IWriteBinding binding, OperationContext operationContext); - Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext); + TResult Execute(OperationContext operationContext, IWriteBinding binding); + Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding); } } diff --git a/src/MongoDB.Driver/Core/Operations/IRetryableOperation.cs b/src/MongoDB.Driver/Core/Operations/IRetryableOperation.cs index 0f0a222ea7f..d29a8948477 100644 --- a/src/MongoDB.Driver/Core/Operations/IRetryableOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/IRetryableOperation.cs @@ -19,27 +19,27 @@ namespace MongoDB.Driver.Core.Operations { internal interface IExecutableInRetryableReadContext { - TResult Execute(RetryableReadContext context, OperationContext operationContext); - Task ExecuteAsync(RetryableReadContext context, OperationContext operationContext); + TResult Execute(OperationContext operationContext, RetryableReadContext context); + Task ExecuteAsync(OperationContext operationContext, RetryableReadContext context); } internal interface IExecutableInRetryableWriteContext { - TResult Execute(RetryableWriteContext context, OperationContext operationContext); - Task ExecuteAsync(RetryableWriteContext context, OperationContext operationContext); + TResult Execute(OperationContext operationContext, RetryableWriteContext context); + Task ExecuteAsync(OperationContext operationContext, RetryableWriteContext context); } internal interface IRetryableReadOperation : IExecutableInRetryableReadContext { - TResult ExecuteAttempt(RetryableReadContext context, int attempt, long? transactionNumber, OperationContext operationContext); - Task ExecuteAttemptAsync(RetryableReadContext context, int attempt, long? transactionNumber, OperationContext operationContext); + TResult ExecuteAttempt(OperationContext operationContext, RetryableReadContext context, int attempt, long? transactionNumber); + Task ExecuteAttemptAsync(OperationContext operationContext, RetryableReadContext context, int attempt, long? transactionNumber); } internal interface IRetryableWriteOperation : IExecutableInRetryableWriteContext { WriteConcern WriteConcern { get; } - TResult ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, OperationContext operationContext); - Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, OperationContext operationContext); + TResult ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber); + Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs b/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs index adf8ab855ba..320c1c3ea71 100644 --- a/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListCollectionsOperation.cs @@ -90,52 +90,52 @@ public bool RetryRequested set => _retryRequested = value; } - public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) + public IAsyncCursor Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { - using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, operationContext); + return Execute(operationContext, context); } } } - public IAsyncCursor Execute(RetryableReadContext context, OperationContext operationContext) + public IAsyncCursor Execute(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); using (BeginOperation()) { var operation = CreateOperation(); - var result = operation.Execute(context, operationContext); + var result = operation.Execute(operationContext, context); return CreateCursor(context.ChannelSource, context.Channel, result); } } - public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, operationContext).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } } - public async Task> ExecuteAsync(RetryableReadContext context, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); using (BeginOperation()) { var operation = CreateOperation(); - var result = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); return CreateCursor(context.ChannelSource, context.Channel, result); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs b/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs index a5b6c63c486..e55151e5b5c 100644 --- a/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListDatabasesOperation.cs @@ -86,26 +86,26 @@ public BsonDocument CreateCommand() }; } - public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) + public IAsyncCursor Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var reply = operation.Execute(binding, operationContext); + var reply = operation.Execute(operationContext, binding); return CreateCursor(reply); } } - public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) { var operation = CreateOperation(); - var reply = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + var reply = await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); return CreateCursor(reply); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs b/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs index 23d357d0392..b91633c4716 100644 --- a/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListIndexesOperation.cs @@ -67,27 +67,27 @@ public bool RetryRequested set => _retryRequested = value; } - public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) + public IAsyncCursor Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { var operation = CreateOperation(); - return operation.Execute(context, operationContext); + return operation.Execute(operationContext, context); } } - public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (BeginOperation()) - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { var operation = CreateOperation(); - return await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs index a90021db9fc..290bbbf00e5 100644 --- a/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ListIndexesUsingCommandOperation.cs @@ -69,17 +69,17 @@ public bool RetryRequested set => _retryRequested = value; } - public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) + public IAsyncCursor Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, operationContext); + return Execute(operationContext, context); } } - public IAsyncCursor Execute(RetryableReadContext context, OperationContext operationContext) + public IAsyncCursor Execute(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); @@ -88,7 +88,7 @@ public IAsyncCursor Execute(RetryableReadContext context, Operatio var operation = CreateOperation(); try { - var result = operation.Execute(context, operationContext); + var result = operation.Execute(operationContext, context); return CreateCursor(context.ChannelSource, context.Channel, result); } catch (MongoCommandException ex) when (IsCollectionNotFoundException(ex)) @@ -98,17 +98,17 @@ public IAsyncCursor Execute(RetryableReadContext context, Operatio } } - public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, operationContext).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } - public async Task> ExecuteAsync(RetryableReadContext context, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); @@ -117,7 +117,7 @@ public async Task> ExecuteAsync(RetryableReadContext var operation = CreateOperation(); try { - var result = await operation.ExecuteAsync(context, operationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(operationContext, context).ConfigureAwait(false); return CreateCursor(context.ChannelSource, context.Channel, result); } catch (MongoCommandException ex) when (IsCollectionNotFoundException(ex)) diff --git a/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs b/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs index 29589106fff..a68b2227278 100644 --- a/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/MapReduceOperation.cs @@ -87,7 +87,7 @@ protected override BsonDocument CreateOutputOptions() } /// - public IAsyncCursor Execute(IReadBinding binding, OperationContext operationContext) + public IAsyncCursor Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -96,13 +96,13 @@ public IAsyncCursor Execute(IReadBinding binding, OperationContext oper using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - var result = operation.Execute(channelBinding, operationContext); + var result = operation.Execute(operationContext, channelBinding); return new SingleBatchAsyncCursor(result); } } /// - public async Task> ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task> ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -111,7 +111,7 @@ public async Task> ExecuteAsync(IReadBinding binding, Oper using (var channelBinding = new ChannelReadBinding(channelSource.Server, channel, binding.ReadPreference, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - var result = await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + var result = await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); return new SingleBatchAsyncCursor(result); } } diff --git a/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs index 39973e361d9..99e32b1adcd 100644 --- a/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/MapReduceOutputToCollectionOperation.cs @@ -169,7 +169,7 @@ protected override BsonDocument CreateOutputOptions() } /// - public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -178,12 +178,12 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return operation.Execute(channelBinding, operationContext); + return operation.Execute(operationContext, channelBinding); } } /// - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -192,7 +192,7 @@ public async Task ExecuteAsync(IWriteBinding binding, OperationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/OperationExtensionMethods.cs b/src/MongoDB.Driver/Core/Operations/OperationExtensionMethods.cs index 9368a870b89..fe54eb7d637 100644 --- a/src/MongoDB.Driver/Core/Operations/OperationExtensionMethods.cs +++ b/src/MongoDB.Driver/Core/Operations/OperationExtensionMethods.cs @@ -23,55 +23,55 @@ internal static class OperationExtensionMethods { public static TResult Execute( this IReadOperation operation, + OperationContext operationContext, IChannelSourceHandle channelSource, ReadPreference readPreference, - ICoreSessionHandle session, - OperationContext operationContext) + ICoreSessionHandle session) { Ensure.IsNotNull(operation, nameof(operation)); using (var readBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), readPreference, session.Fork())) { - return operation.Execute(readBinding, operationContext); + return operation.Execute(operationContext, readBinding); } } public static TResult Execute( this IWriteOperation operation, + OperationContext operationContext, IChannelSourceHandle channelSource, - ICoreSessionHandle session, - OperationContext operationContext) + ICoreSessionHandle session) { Ensure.IsNotNull(operation, nameof(operation)); using (var writeBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), ReadPreference.Primary, session.Fork())) { - return operation.Execute(writeBinding, operationContext); + return operation.Execute(operationContext, writeBinding); } } public static async Task ExecuteAsync( this IReadOperation operation, + OperationContext operationContext, IChannelSourceHandle channelSource, ReadPreference readPreference, - ICoreSessionHandle session, - OperationContext operationContext) + ICoreSessionHandle session) { Ensure.IsNotNull(operation, nameof(operation)); using (var readBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), readPreference, session.Fork())) { - return await operation.ExecuteAsync(readBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, readBinding).ConfigureAwait(false); } } public static async Task ExecuteAsync( this IWriteOperation operation, + OperationContext operationContext, IChannelSourceHandle channelSource, - ICoreSessionHandle session, - OperationContext operationContext) + ICoreSessionHandle session) { Ensure.IsNotNull(operation, nameof(operation)); using (var writeBinding = new ChannelSourceReadWriteBinding(channelSource.Fork(), ReadPreference.Primary, session.Fork())) { - return await operation.ExecuteAsync(writeBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, writeBinding).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs index 67e31222fb7..84305df6f25 100644 --- a/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/ReadCommandOperation.cs @@ -42,52 +42,52 @@ public bool RetryRequested set => _retryRequested = value; } - public TCommandResult Execute(IReadBinding binding, OperationContext operationContext) + public TCommandResult Execute(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = RetryableReadContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, operationContext); + return Execute(operationContext, context); } } - public TCommandResult Execute(RetryableReadContext context, OperationContext operationContext) + public TCommandResult Execute(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginOperation()) { - return RetryableReadOperationExecutor.Execute(this, context, operationContext); + return RetryableReadOperationExecutor.Execute(operationContext, this, context); } } - public async Task ExecuteAsync(IReadBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IReadBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); - using (var context = await RetryableReadContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, operationContext).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } - public async Task ExecuteAsync(RetryableReadContext context, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, RetryableReadContext context) { Ensure.IsNotNull(context, nameof(context)); using (EventContext.BeginOperation()) { - return await RetryableReadOperationExecutor.ExecuteAsync(this, context, operationContext).ConfigureAwait(false); + return await RetryableReadOperationExecutor.ExecuteAsync(operationContext, this, context).ConfigureAwait(false); } } - public TCommandResult ExecuteAttempt(RetryableReadContext context, int attempt, long? transactionNumber, OperationContext operationContext) + public TCommandResult ExecuteAttempt(OperationContext operationContext, RetryableReadContext context, int attempt, long? transactionNumber) { return ExecuteProtocol(context.Channel, context.Binding.Session, context.Binding.ReadPreference, operationContext.CancellationToken); } - public Task ExecuteAttemptAsync(RetryableReadContext context, int attempt, long? transactionNumber, OperationContext operationContext) + public Task ExecuteAttemptAsync(OperationContext operationContext, RetryableReadContext context, int attempt, long? transactionNumber) { return ExecuteProtocolAsync(context.Channel, context.Binding.Session, context.Binding.ReadPreference, operationContext.CancellationToken); } diff --git a/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs b/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs index 69677409b5d..aee3f2fed1c 100644 --- a/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/RenameCollectionOperation.cs @@ -82,7 +82,7 @@ public BsonDocument CreateCommand(ICoreSessionHandle session, ConnectionDescript }; } - public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -92,11 +92,11 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return operation.Execute(channelBinding, operationContext); + return operation.Execute(operationContext, channelBinding); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); @@ -106,7 +106,7 @@ public async Task ExecuteAsync(IWriteBinding binding, OperationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(channelBinding.Session, channel.ConnectionDescription); - return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs b/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs index 9921dd38b2f..18d62e4b4a5 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableReadContext.cs @@ -24,7 +24,7 @@ internal sealed class RetryableReadContext : IDisposable { #region static - public static RetryableReadContext Create(IReadBinding binding, bool retryRequested, OperationContext operationContext) + public static RetryableReadContext Create(OperationContext operationContext, IReadBinding binding, bool retryRequested) { var context = new RetryableReadContext(binding, retryRequested); try @@ -45,7 +45,7 @@ public static RetryableReadContext Create(IReadBinding binding, bool retryReques } } - public static async Task CreateAsync(IReadBinding binding, bool retryRequested, OperationContext operationContext) + public static async Task CreateAsync(OperationContext operationContext, IReadBinding binding, bool retryRequested) { var context = new RetryableReadContext(binding, retryRequested); try diff --git a/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs b/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs index 76354e1413d..d628382e264 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableReadOperationExecutor.cs @@ -22,25 +22,25 @@ namespace MongoDB.Driver.Core.Operations internal static class RetryableReadOperationExecutor { // public static methods - public static TResult Execute(IRetryableReadOperation operation, IReadBinding binding, bool retryRequested, OperationContext operationContext) + public static TResult Execute(OperationContext operationContext, IRetryableReadOperation operation, IReadBinding binding, bool retryRequested) { - using (var context = RetryableReadContext.Create(binding, retryRequested, operationContext)) + using (var context = RetryableReadContext.Create(operationContext, binding, retryRequested)) { - return Execute(operation, context, operationContext); + return Execute(operationContext, operation, context); } } - public static TResult Execute(IRetryableReadOperation operation, RetryableReadContext context, OperationContext operationContext) + public static TResult Execute(OperationContext operationContext, IRetryableReadOperation operation, RetryableReadContext context) { if (!ShouldReadBeRetried(context)) { - return operation.ExecuteAttempt(context, attempt: 1, transactionNumber: null, operationContext); + return operation.ExecuteAttempt(operationContext, context, attempt: 1, transactionNumber: null); } Exception originalException; try { - return operation.ExecuteAttempt(context, attempt: 1, transactionNumber: null, operationContext); + return operation.ExecuteAttempt(operationContext, context, attempt: 1, transactionNumber: null); } catch (Exception ex) when (RetryabilityHelper.IsRetryableReadException(ex)) @@ -50,7 +50,7 @@ public static TResult Execute(IRetryableReadOperation operatio try { - context.ReplaceChannelSource(context.Binding.GetReadChannelSource(new[] { context.ChannelSource.ServerDescription }, operationContext)); + context.ReplaceChannelSource(context.Binding.GetReadChannelSource(operationContext, new[] { context.ChannelSource.ServerDescription })); context.ReplaceChannel(context.ChannelSource.GetChannel(operationContext)); } catch @@ -60,7 +60,7 @@ public static TResult Execute(IRetryableReadOperation operatio try { - return operation.ExecuteAttempt(context, attempt: 2, transactionNumber: null, operationContext); + return operation.ExecuteAttempt(operationContext, context, attempt: 2, transactionNumber: null); } catch (Exception ex) when (ShouldThrowOriginalException(ex)) { @@ -68,25 +68,25 @@ public static TResult Execute(IRetryableReadOperation operatio } } - public static async Task ExecuteAsync(IRetryableReadOperation operation, IReadBinding binding, bool retryRequested, OperationContext operationContext) + public static async Task ExecuteAsync(OperationContext operationContext, IRetryableReadOperation operation, IReadBinding binding, bool retryRequested) { - using (var context = await RetryableReadContext.CreateAsync(binding, retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableReadContext.CreateAsync(operationContext, binding, retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(operation, context, operationContext).ConfigureAwait(false); + return await ExecuteAsync(operationContext, operation, context).ConfigureAwait(false); } } - public static async Task ExecuteAsync(IRetryableReadOperation operation, RetryableReadContext context, OperationContext operationContext) + public static async Task ExecuteAsync(OperationContext operationContext, IRetryableReadOperation operation, RetryableReadContext context) { if (!ShouldReadBeRetried(context)) { - return await operation.ExecuteAttemptAsync(context, attempt: 1, transactionNumber: null, operationContext).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(operationContext, context, attempt: 1, transactionNumber: null).ConfigureAwait(false); } Exception originalException; try { - return await operation.ExecuteAttemptAsync(context, attempt: 1, transactionNumber: null, operationContext).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(operationContext, context, attempt: 1, transactionNumber: null).ConfigureAwait(false); } catch (Exception ex) when (RetryabilityHelper.IsRetryableReadException(ex)) { @@ -95,7 +95,7 @@ public static async Task ExecuteAsync(IRetryableReadOperation< try { - context.ReplaceChannelSource(context.Binding.GetReadChannelSource(new[] { context.ChannelSource.ServerDescription }, operationContext)); + context.ReplaceChannelSource(context.Binding.GetReadChannelSource(operationContext, new[] { context.ChannelSource.ServerDescription })); context.ReplaceChannel(context.ChannelSource.GetChannel(operationContext)); } catch @@ -105,7 +105,7 @@ public static async Task ExecuteAsync(IRetryableReadOperation< try { - return await operation.ExecuteAttemptAsync(context, attempt: 2, transactionNumber: null, operationContext).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(operationContext, context, attempt: 2, transactionNumber: null).ConfigureAwait(false); } catch (Exception ex) when (ShouldThrowOriginalException(ex)) { diff --git a/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs b/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs index 5ff3185d9b3..bb3ec94e32d 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableWriteCommandOperationBase.cs @@ -86,33 +86,33 @@ public WriteConcern WriteConcern set { _writeConcern = value; } } - public virtual BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public virtual BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { - using (var context = RetryableWriteContext.Create(binding, _retryRequested, operationContext)) + using (var context = RetryableWriteContext.Create(operationContext, binding, _retryRequested)) { - return Execute(context, operationContext); + return Execute(operationContext, context); } } - public virtual BsonDocument Execute(RetryableWriteContext context, OperationContext operationContext) + public virtual BsonDocument Execute(OperationContext operationContext, RetryableWriteContext context) { - return RetryableWriteOperationExecutor.Execute(this, context, operationContext); + return RetryableWriteOperationExecutor.Execute(operationContext, this, context); } - public virtual async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public virtual async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { - using (var context = await RetryableWriteContext.CreateAsync(binding, _retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(operationContext, binding, _retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(context, operationContext).ConfigureAwait(false); + return await ExecuteAsync(operationContext, context).ConfigureAwait(false); } } - public virtual Task ExecuteAsync(RetryableWriteContext context, OperationContext operationContext) + public virtual Task ExecuteAsync(OperationContext operationContext, RetryableWriteContext context) { - return RetryableWriteOperationExecutor.ExecuteAsync(this, context, operationContext); + return RetryableWriteOperationExecutor.ExecuteAsync(operationContext, this, context); } - public BsonDocument ExecuteAttempt(RetryableWriteContext context, int attempt, long? transactionNumber, OperationContext operationContext) + public BsonDocument ExecuteAttempt(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { var args = GetCommandArgs(context, attempt, transactionNumber); // TODO: CSOT implement timeout in Command Execution @@ -131,7 +131,7 @@ public BsonDocument ExecuteAttempt(RetryableWriteContext context, int attempt, l operationContext.CancellationToken); } - public Task ExecuteAttemptAsync(RetryableWriteContext context, int attempt, long? transactionNumber, OperationContext operationContext) + public Task ExecuteAttemptAsync(OperationContext operationContext, RetryableWriteContext context, int attempt, long? transactionNumber) { var args = GetCommandArgs(context, attempt, transactionNumber); // TODO: CSOT implement timeout in Command Execution diff --git a/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs b/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs index d4b69a5261d..9c15d1e9bfc 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableWriteContext.cs @@ -26,7 +26,7 @@ internal sealed class RetryableWriteContext : IDisposable { #region static - public static RetryableWriteContext Create(IWriteBinding binding, bool retryRequested, OperationContext operationContext) + public static RetryableWriteContext Create(OperationContext operationContext, IWriteBinding binding, bool retryRequested) { var context = new RetryableWriteContext(binding, retryRequested); try @@ -47,7 +47,7 @@ public static RetryableWriteContext Create(IWriteBinding binding, bool retryRequ } } - public static async Task CreateAsync(IWriteBinding binding, bool retryRequested, OperationContext operationContext) + public static async Task CreateAsync(OperationContext operationContext, IWriteBinding binding, bool retryRequested) { var context = new RetryableWriteContext(binding, retryRequested); try diff --git a/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs b/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs index 6f5d01ebfef..f654d614260 100644 --- a/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs +++ b/src/MongoDB.Driver/Core/Operations/RetryableWriteOperationExecutor.cs @@ -24,26 +24,26 @@ namespace MongoDB.Driver.Core.Operations internal static class RetryableWriteOperationExecutor { // public static methods - public static TResult Execute(IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested, OperationContext operationContext) + public static TResult Execute(OperationContext operationContext, IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested) { - using (var context = RetryableWriteContext.Create(binding, retryRequested, operationContext)) + using (var context = RetryableWriteContext.Create(operationContext, binding, retryRequested)) { - return Execute(operation, context, operationContext); + return Execute(operationContext, operation, context); } } - public static TResult Execute(IRetryableWriteOperation operation, RetryableWriteContext context, OperationContext operationContext) + public static TResult Execute(OperationContext operationContext, IRetryableWriteOperation operation, RetryableWriteContext context) { if (!AreRetriesAllowed(operation, context)) { - return operation.ExecuteAttempt(context, 1, null, operationContext); + return operation.ExecuteAttempt(operationContext, context, 1, null); } var transactionNumber = context.Binding.Session.AdvanceTransactionNumber(); Exception originalException; try { - return operation.ExecuteAttempt(context, 1, transactionNumber, operationContext); + return operation.ExecuteAttempt(operationContext, context, 1, transactionNumber); } catch (Exception ex) when (RetryabilityHelper.IsRetryableWriteException(ex)) { @@ -52,7 +52,7 @@ public static TResult Execute(IRetryableWriteOperation operati try { - context.ReplaceChannelSource(context.Binding.GetWriteChannelSource(new[] { context.ChannelSource.ServerDescription }, operationContext)); + context.ReplaceChannelSource(context.Binding.GetWriteChannelSource(operationContext, new[] { context.ChannelSource.ServerDescription })); context.ReplaceChannel(context.ChannelSource.GetChannel(operationContext)); } catch @@ -67,7 +67,7 @@ public static TResult Execute(IRetryableWriteOperation operati try { - return operation.ExecuteAttempt(context, 2, transactionNumber, operationContext); + return operation.ExecuteAttempt(operationContext, context, 2, transactionNumber); } catch (Exception ex) when (ShouldThrowOriginalException(ex)) { @@ -75,26 +75,26 @@ public static TResult Execute(IRetryableWriteOperation operati } } - public async static Task ExecuteAsync(IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested, OperationContext operationContext) + public async static Task ExecuteAsync(OperationContext operationContext, IRetryableWriteOperation operation, IWriteBinding binding, bool retryRequested) { - using (var context = await RetryableWriteContext.CreateAsync(binding, retryRequested, operationContext).ConfigureAwait(false)) + using (var context = await RetryableWriteContext.CreateAsync(operationContext, binding, retryRequested).ConfigureAwait(false)) { - return await ExecuteAsync(operation, context, operationContext).ConfigureAwait(false); + return await ExecuteAsync(operationContext, operation, context).ConfigureAwait(false); } } - public static async Task ExecuteAsync(IRetryableWriteOperation operation, RetryableWriteContext context, OperationContext operationContext) + public static async Task ExecuteAsync(OperationContext operationContext, IRetryableWriteOperation operation, RetryableWriteContext context) { if (!AreRetriesAllowed(operation, context)) { - return await operation.ExecuteAttemptAsync(context, 1, null, operationContext).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(operationContext, context, 1, null).ConfigureAwait(false); } var transactionNumber = context.Binding.Session.AdvanceTransactionNumber(); Exception originalException; try { - return await operation.ExecuteAttemptAsync(context, 1, transactionNumber, operationContext).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(operationContext, context, 1, transactionNumber).ConfigureAwait(false); } catch (Exception ex) when (RetryabilityHelper.IsRetryableWriteException(ex)) { @@ -103,7 +103,7 @@ public static async Task ExecuteAsync(IRetryableWriteOperation try { - context.ReplaceChannelSource(await context.Binding.GetWriteChannelSourceAsync(new[] { context.ChannelSource.ServerDescription }, operationContext).ConfigureAwait(false)); + context.ReplaceChannelSource(await context.Binding.GetWriteChannelSourceAsync(operationContext, new[] { context.ChannelSource.ServerDescription }).ConfigureAwait(false)); context.ReplaceChannel(await context.ChannelSource.GetChannelAsync(operationContext).ConfigureAwait(false)); } catch @@ -118,7 +118,7 @@ public static async Task ExecuteAsync(IRetryableWriteOperation try { - return await operation.ExecuteAttemptAsync(context, 2, transactionNumber, operationContext).ConfigureAwait(false); + return await operation.ExecuteAttemptAsync(operationContext, context, 2, transactionNumber).ConfigureAwait(false); } catch (Exception ex) when (ShouldThrowOriginalException(ex)) { diff --git a/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs b/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs index ef06bd5d506..09496dd9d3b 100644 --- a/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/UpdateSearchIndexOperation.cs @@ -43,7 +43,7 @@ public UpdateSearchIndexOperation( _messageEncoderSettings = Ensure.IsNotNull(messageEncoderSettings, nameof(messageEncoderSettings)); } - public BsonDocument Execute(IWriteBinding binding, OperationContext operationContext) + public BsonDocument Execute(OperationContext operationContext, IWriteBinding binding) { using (EventContext.BeginOperation("updateSearchIndex")) using (var channelSource = binding.GetWriteChannelSource(operationContext)) @@ -51,11 +51,11 @@ public BsonDocument Execute(IWriteBinding binding, OperationContext operationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return operation.Execute(channelBinding, operationContext); + return operation.Execute(operationContext, channelBinding); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { using (EventContext.BeginOperation("updateSearchIndex")) using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) @@ -63,7 +63,7 @@ public async Task ExecuteAsync(IWriteBinding binding, OperationCon using (var channelBinding = new ChannelReadWriteBinding(channelSource.Server, channel, binding.Session.Fork())) { var operation = CreateOperation(); - return await operation.ExecuteAsync(channelBinding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, channelBinding).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs b/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs index a6cfaa792f0..033db2d0eae 100644 --- a/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs +++ b/src/MongoDB.Driver/Core/Operations/WriteCommandOperation.cs @@ -38,25 +38,25 @@ public ReadPreference ReadPreference set => _readPreference = Ensure.IsNotNull(value, nameof(value)); } - public TCommandResult Execute(IWriteBinding binding, OperationContext operationContext) + public TCommandResult Execute(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation()) using (var channelSource = binding.GetWriteChannelSource(operationContext)) { - return ExecuteProtocol(channelSource, binding.Session, _readPreference, operationContext); + return ExecuteProtocol(operationContext, channelSource, binding.Session, _readPreference); } } - public async Task ExecuteAsync(IWriteBinding binding, OperationContext operationContext) + public async Task ExecuteAsync(OperationContext operationContext, IWriteBinding binding) { Ensure.IsNotNull(binding, nameof(binding)); using (EventContext.BeginOperation()) using (var channelSource = await binding.GetWriteChannelSourceAsync(operationContext).ConfigureAwait(false)) { - return await ExecuteProtocolAsync(channelSource, binding.Session, _readPreference, operationContext).ConfigureAwait(false); + return await ExecuteProtocolAsync(operationContext, channelSource, binding.Session, _readPreference).ConfigureAwait(false); } } } diff --git a/src/MongoDB.Driver/GridFS/GridFSBucket.cs b/src/MongoDB.Driver/GridFS/GridFSBucket.cs index bb0cff5c5ce..7bd029044b8 100644 --- a/src/MongoDB.Driver/GridFS/GridFSBucket.cs +++ b/src/MongoDB.Driver/GridFS/GridFSBucket.cs @@ -83,15 +83,15 @@ public ImmutableGridFSBucketOptions Options public void Delete(TFileId id, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull((object)id, nameof(id)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (var binding = GetSingleServerReadWriteBinding(operationContext)) { var filesCollectionDeleteOperation = CreateDeleteFileOperation(id); - var filesCollectionDeleteResult = filesCollectionDeleteOperation.Execute(binding, operationContext); + var filesCollectionDeleteResult = filesCollectionDeleteOperation.Execute(operationContext, binding); var chunksDeleteOperation = CreateDeleteChunksOperation(id); - chunksDeleteOperation.Execute(binding, operationContext); + chunksDeleteOperation.Execute(operationContext, binding); if (filesCollectionDeleteResult.DeletedCount == 0) { @@ -104,15 +104,15 @@ public ImmutableGridFSBucketOptions Options public async Task DeleteAsync(TFileId id, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull((object)id, nameof(id)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) { var filesCollectionDeleteOperation = CreateDeleteFileOperation(id); - var filesCollectionDeleteResult = await filesCollectionDeleteOperation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + var filesCollectionDeleteResult = await filesCollectionDeleteOperation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); var chunksDeleteOperation = CreateDeleteChunksOperation(id); - await chunksDeleteOperation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + await chunksDeleteOperation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); if (filesCollectionDeleteResult.DeletedCount == 0) { @@ -125,12 +125,12 @@ public ImmutableGridFSBucketOptions Options public byte[] DownloadAsBytes(TFileId id, GridFSDownloadOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull((object)id, nameof(id)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfo(binding, id, operationContext); + var fileInfo = GetFileInfo(operationContext, binding, id); return DownloadAsBytesHelper(binding, fileInfo, options, cancellationToken); } } @@ -139,12 +139,12 @@ public ImmutableGridFSBucketOptions Options public async Task DownloadAsBytesAsync(TFileId id, GridFSDownloadOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull((object)id, nameof(id)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoAsync(binding, id, operationContext).ConfigureAwait(false); + var fileInfo = await GetFileInfoAsync(operationContext, binding, id).ConfigureAwait(false); return await DownloadAsBytesHelperAsync(binding, fileInfo, options, cancellationToken).ConfigureAwait(false); } } @@ -153,13 +153,13 @@ public ImmutableGridFSBucketOptions Options public byte[] DownloadAsBytesByName(string filename, GridFSDownloadByNameOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filename, nameof(filename)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfoByName(binding, filename, options.Revision, operationContext); + var fileInfo = GetFileInfoByName(operationContext, binding, filename, options.Revision); return DownloadAsBytesHelper(binding, fileInfo, options, cancellationToken); } } @@ -168,13 +168,13 @@ public ImmutableGridFSBucketOptions Options public async Task DownloadAsBytesByNameAsync(string filename, GridFSDownloadByNameOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filename, nameof(filename)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, operationContext).ConfigureAwait(false); + var fileInfo = await GetFileInfoByNameAsync(operationContext, binding, filename, options.Revision).ConfigureAwait(false); return await DownloadAsBytesHelperAsync(binding, fileInfo, options, cancellationToken).ConfigureAwait(false); } } @@ -184,12 +184,12 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(destination, nameof(destination)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfo(binding, id, operationContext); + var fileInfo = GetFileInfo(operationContext, binding, id); DownloadToStreamHelper(binding, fileInfo, destination, options, cancellationToken); } } @@ -199,12 +199,12 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(destination, nameof(destination)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoAsync(binding, id, operationContext).ConfigureAwait(false); + var fileInfo = await GetFileInfoAsync(operationContext, binding, id).ConfigureAwait(false); await DownloadToStreamHelperAsync(binding, fileInfo, destination, options, cancellationToken).ConfigureAwait(false); } } @@ -214,13 +214,13 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(destination, nameof(destination)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfoByName(binding, filename, options.Revision, operationContext); + var fileInfo = GetFileInfoByName(operationContext, binding, filename, options.Revision); DownloadToStreamHelper(binding, fileInfo, destination, options, cancellationToken); } } @@ -230,13 +230,13 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(destination, nameof(destination)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, operationContext).ConfigureAwait(false); + var fileInfo = await GetFileInfoByNameAsync(operationContext, binding, filename, options.Revision).ConfigureAwait(false); await DownloadToStreamHelperAsync(binding, fileInfo, destination, options, cancellationToken).ConfigureAwait(false); } } @@ -244,7 +244,7 @@ public ImmutableGridFSBucketOptions Options /// public void Drop(CancellationToken cancellationToken = default(CancellationToken)) { - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); var filesCollectionNamespace = this.GetFilesCollectionNamespace(); var chunksCollectionNamespace = this.GetChunksCollectionNamespace(); @@ -253,17 +253,17 @@ public ImmutableGridFSBucketOptions Options using (var binding = GetSingleServerReadWriteBinding(operationContext)) { var filesCollectionDropOperation = CreateDropCollectionOperation(filesCollectionNamespace, messageEncoderSettings); - filesCollectionDropOperation.Execute(binding, operationContext); + filesCollectionDropOperation.Execute(operationContext, binding); var chunksCollectionDropOperation = CreateDropCollectionOperation(chunksCollectionNamespace, messageEncoderSettings); - chunksCollectionDropOperation.Execute(binding, operationContext); + chunksCollectionDropOperation.Execute(operationContext, binding); } } /// public async Task DropAsync(CancellationToken cancellationToken = default(CancellationToken)) { - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); var filesCollectionNamespace = this.GetFilesCollectionNamespace(); var chunksCollectionNamespace = this.GetChunksCollectionNamespace(); @@ -272,10 +272,10 @@ public ImmutableGridFSBucketOptions Options using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) { var filesCollectionDropOperation = CreateDropCollectionOperation(filesCollectionNamespace, messageEncoderSettings); - await filesCollectionDropOperation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + await filesCollectionDropOperation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); var chunksCollectionDropOperation = CreateDropCollectionOperation(chunksCollectionNamespace, messageEncoderSettings); - await chunksCollectionDropOperation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + await chunksCollectionDropOperation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); } } @@ -283,7 +283,7 @@ public ImmutableGridFSBucketOptions Options public IAsyncCursor> Find(FilterDefinition> filter, GridFSFindOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filter, nameof(filter)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSFindOptions(); @@ -291,7 +291,7 @@ public ImmutableGridFSBucketOptions Options var operation = CreateFindOperation(filter, options, translationOptions); using (var binding = GetSingleServerReadBinding(operationContext)) { - return operation.Execute(binding, operationContext); + return operation.Execute(operationContext, binding); } } @@ -299,7 +299,7 @@ public ImmutableGridFSBucketOptions Options public async Task>> FindAsync(FilterDefinition> filter, GridFSFindOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filter, nameof(filter)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSFindOptions(); @@ -307,7 +307,7 @@ public ImmutableGridFSBucketOptions Options var operation = CreateFindOperation(filter, options, translationOptions); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - return await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); } } @@ -315,12 +315,12 @@ public ImmutableGridFSBucketOptions Options public GridFSDownloadStream OpenDownloadStream(TFileId id, GridFSDownloadOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull((object)id, nameof(id)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfo(binding, id, operationContext); + var fileInfo = GetFileInfo(operationContext, binding, id); return CreateDownloadStream(binding.Fork(), fileInfo, options, cancellationToken); } } @@ -329,12 +329,12 @@ public ImmutableGridFSBucketOptions Options public async Task> OpenDownloadStreamAsync(TFileId id, GridFSDownloadOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull((object)id, nameof(id)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadOptions(); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoAsync(binding, id, operationContext).ConfigureAwait(false); + var fileInfo = await GetFileInfoAsync(operationContext, binding, id).ConfigureAwait(false); return CreateDownloadStream(binding.Fork(), fileInfo, options, cancellationToken); } } @@ -343,13 +343,13 @@ public ImmutableGridFSBucketOptions Options public GridFSDownloadStream OpenDownloadStreamByName(string filename, GridFSDownloadByNameOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filename, nameof(filename)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); using (var binding = GetSingleServerReadBinding(operationContext)) { - var fileInfo = GetFileInfoByName(binding, filename, options.Revision, operationContext); + var fileInfo = GetFileInfoByName(operationContext, binding, filename, options.Revision); return CreateDownloadStream(binding.Fork(), fileInfo, options); } } @@ -358,13 +358,13 @@ public ImmutableGridFSBucketOptions Options public async Task> OpenDownloadStreamByNameAsync(string filename, GridFSDownloadByNameOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { Ensure.IsNotNull(filename, nameof(filename)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSDownloadByNameOptions(); using (var binding = await GetSingleServerReadBindingAsync(operationContext).ConfigureAwait(false)) { - var fileInfo = await GetFileInfoByNameAsync(binding, filename, options.Revision, operationContext).ConfigureAwait(false); + var fileInfo = await GetFileInfoByNameAsync(operationContext, binding, filename, options.Revision).ConfigureAwait(false); return CreateDownloadStream(binding.Fork(), fileInfo, options); } } @@ -374,13 +374,13 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(filename, nameof(filename)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); using (var binding = GetSingleServerReadWriteBinding(operationContext)) { - EnsureIndexes(binding, operationContext); + EnsureIndexes(operationContext, binding); return CreateUploadStream(binding, id, filename, options); } } @@ -390,13 +390,13 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(filename, nameof(filename)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) { - await EnsureIndexesAsync(binding, operationContext).ConfigureAwait(false); + await EnsureIndexesAsync(operationContext, binding).ConfigureAwait(false); return CreateUploadStream(binding, id, filename, options); } } @@ -406,12 +406,12 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(newFilename, nameof(newFilename)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); var renameOperation = CreateRenameOperation(id, newFilename); using (var binding = GetSingleServerReadWriteBinding(operationContext)) { - var result = renameOperation.Execute(binding, operationContext); + var result = renameOperation.Execute(operationContext, binding); if (result.IsModifiedCountAvailable && result.ModifiedCount == 0) { @@ -425,12 +425,12 @@ public ImmutableGridFSBucketOptions Options { Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(newFilename, nameof(newFilename)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); var renameOperation = CreateRenameOperation(id, newFilename); using (var binding = await GetSingleServerReadWriteBindingAsync(operationContext).ConfigureAwait(false)) { - var result = await renameOperation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + var result = await renameOperation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); if (result.IsModifiedCountAvailable && result.ModifiedCount == 0) { @@ -445,7 +445,7 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(source, nameof(source)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); @@ -461,7 +461,7 @@ public ImmutableGridFSBucketOptions Options Ensure.IsNotNull((object)id, nameof(id)); Ensure.IsNotNull(filename, nameof(filename)); Ensure.IsNotNull(source, nameof(source)); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); options = options ?? new GridFSUploadOptions(); @@ -570,28 +570,28 @@ private bool ChunksCollectionIndexesExist(List indexes) return IndexExists(indexes, key); } - private bool ChunksCollectionIndexesExist(IReadBindingHandle binding, OperationContext operationContext) + private bool ChunksCollectionIndexesExist(OperationContext operationContext, IReadBindingHandle binding) { - var indexes = ListIndexes(binding, this.GetChunksCollectionNamespace(), operationContext); + var indexes = ListIndexes(operationContext, binding, this.GetChunksCollectionNamespace()); return ChunksCollectionIndexesExist(indexes); } - private async Task ChunksCollectionIndexesExistAsync(IReadBindingHandle binding, OperationContext operationContext) + private async Task ChunksCollectionIndexesExistAsync(OperationContext operationContext, IReadBindingHandle binding) { - var indexes = await ListIndexesAsync(binding, this.GetChunksCollectionNamespace(), operationContext).ConfigureAwait(false); + var indexes = await ListIndexesAsync(operationContext, binding, this.GetChunksCollectionNamespace()).ConfigureAwait(false); return ChunksCollectionIndexesExist(indexes); } - private void CreateChunksCollectionIndexes(IReadWriteBindingHandle binding, OperationContext operationContext) + private void CreateChunksCollectionIndexes(OperationContext operationContext, IReadWriteBindingHandle binding) { var operation = CreateCreateChunksCollectionIndexesOperation(); - operation.Execute(binding, operationContext); + operation.Execute(operationContext, binding); } - private async Task CreateChunksCollectionIndexesAsync(IReadWriteBindingHandle binding, OperationContext operationContext) + private async Task CreateChunksCollectionIndexesAsync(OperationContext operationContext, IReadWriteBindingHandle binding) { var operation = CreateCreateChunksCollectionIndexesOperation(); - await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); } internal CreateIndexesOperation CreateCreateChunksCollectionIndexesOperation() @@ -656,16 +656,16 @@ private BulkMixedWriteOperation CreateDeleteFileOperation(TFileId id) this.GetMessageEncoderSettings()); } - private void CreateFilesCollectionIndexes(IReadWriteBindingHandle binding, OperationContext operationContext) + private void CreateFilesCollectionIndexes(OperationContext operationContext, IReadWriteBindingHandle binding) { var operation = CreateCreateFilesCollectionIndexesOperation(); - operation.Execute(binding, operationContext); + operation.Execute(operationContext, binding); } - private async Task CreateFilesCollectionIndexesAsync(IReadWriteBindingHandle binding, OperationContext operationContext) + private async Task CreateFilesCollectionIndexesAsync(OperationContext operationContext, IReadWriteBindingHandle binding) { var operation = CreateCreateFilesCollectionIndexesOperation(); - await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); } private FindOperation> CreateFindOperation( @@ -858,23 +858,23 @@ private GridFSUploadStream CreateUploadStream(IReadWriteBindingHandle b } } - private void EnsureIndexes(IReadWriteBindingHandle binding, OperationContext operationContext) + private void EnsureIndexes(OperationContext operationContext, IReadWriteBindingHandle binding) { _ensureIndexesSemaphore.Wait(operationContext.RemainingTimeout, operationContext.CancellationToken); try { if (!_ensureIndexesDone) { - var isFilesCollectionEmpty = IsFilesCollectionEmpty(binding, operationContext); + var isFilesCollectionEmpty = IsFilesCollectionEmpty(operationContext, binding); if (isFilesCollectionEmpty) { - if (!FilesCollectionIndexesExist(binding, operationContext)) + if (!FilesCollectionIndexesExist(operationContext, binding)) { - CreateFilesCollectionIndexes(binding, operationContext); + CreateFilesCollectionIndexes(operationContext, binding); } - if (!ChunksCollectionIndexesExist(binding, operationContext)) + if (!ChunksCollectionIndexesExist(operationContext, binding)) { - CreateChunksCollectionIndexes(binding, operationContext); + CreateChunksCollectionIndexes(operationContext, binding); } } @@ -887,23 +887,23 @@ private void EnsureIndexes(IReadWriteBindingHandle binding, OperationContext ope } } - private async Task EnsureIndexesAsync(IReadWriteBindingHandle binding, OperationContext operationContext) + private async Task EnsureIndexesAsync(OperationContext operationContext, IReadWriteBindingHandle binding) { await _ensureIndexesSemaphore.WaitAsync(operationContext.RemainingTimeout, operationContext.CancellationToken).ConfigureAwait(false); try { if (!_ensureIndexesDone) { - var isFilesCollectionEmpty = await IsFilesCollectionEmptyAsync(binding, operationContext).ConfigureAwait(false); + var isFilesCollectionEmpty = await IsFilesCollectionEmptyAsync(operationContext, binding).ConfigureAwait(false); if (isFilesCollectionEmpty) { - if (!(await FilesCollectionIndexesExistAsync(binding, operationContext).ConfigureAwait(false))) + if (!(await FilesCollectionIndexesExistAsync(operationContext, binding).ConfigureAwait(false))) { - await CreateFilesCollectionIndexesAsync(binding, operationContext).ConfigureAwait(false); + await CreateFilesCollectionIndexesAsync(operationContext, binding).ConfigureAwait(false); } - if (!(await ChunksCollectionIndexesExistAsync(binding, operationContext).ConfigureAwait(false))) + if (!(await ChunksCollectionIndexesExistAsync(operationContext, binding).ConfigureAwait(false))) { - await CreateChunksCollectionIndexesAsync(binding, operationContext).ConfigureAwait(false); + await CreateChunksCollectionIndexesAsync(operationContext, binding).ConfigureAwait(false); } } @@ -922,22 +922,22 @@ private bool FilesCollectionIndexesExist(List indexes) return IndexExists(indexes, key); } - private bool FilesCollectionIndexesExist(IReadBindingHandle binding, OperationContext operationContext) + private bool FilesCollectionIndexesExist(OperationContext operationContext, IReadBindingHandle binding) { - var indexes = ListIndexes(binding, this.GetFilesCollectionNamespace(), operationContext); + var indexes = ListIndexes(operationContext, binding, this.GetFilesCollectionNamespace()); return FilesCollectionIndexesExist(indexes); } - private async Task FilesCollectionIndexesExistAsync(IReadBindingHandle binding, OperationContext operationContext) + private async Task FilesCollectionIndexesExistAsync(OperationContext operationContext, IReadBindingHandle binding) { - var indexes = await ListIndexesAsync(binding, this.GetFilesCollectionNamespace(), operationContext).ConfigureAwait(false); + var indexes = await ListIndexesAsync(operationContext, binding, this.GetFilesCollectionNamespace()).ConfigureAwait(false); return FilesCollectionIndexesExist(indexes); } - private GridFSFileInfo GetFileInfo(IReadBindingHandle binding, TFileId id, OperationContext operationContext) + private GridFSFileInfo GetFileInfo(OperationContext operationContext, IReadBindingHandle binding, TFileId id) { var operation = CreateGetFileInfoOperation(id); - using (var cursor = operation.Execute(binding, operationContext)) + using (var cursor = operation.Execute(operationContext, binding)) { // TODO: CSOT add a way to propagate cancellationContext into cursor methods. var fileInfo = cursor.FirstOrDefault(operationContext.CancellationToken); @@ -949,10 +949,10 @@ private GridFSFileInfo GetFileInfo(IReadBindingHandle binding, TFileId } } - private async Task> GetFileInfoAsync(IReadBindingHandle binding, TFileId id, OperationContext operationContext) + private async Task> GetFileInfoAsync(OperationContext operationContext, IReadBindingHandle binding, TFileId id) { var operation = CreateGetFileInfoOperation(id); - using (var cursor = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false)) { // TODO: CSOT add a way to propagate cancellationContext into cursor methods. var fileInfo = await cursor.FirstOrDefaultAsync(operationContext.CancellationToken).ConfigureAwait(false); @@ -964,10 +964,10 @@ private async Task> GetFileInfoAsync(IReadBindingHandle } } - private GridFSFileInfo GetFileInfoByName(IReadBindingHandle binding, string filename, int revision, OperationContext operationContext) + private GridFSFileInfo GetFileInfoByName(OperationContext operationContext, IReadBindingHandle binding, string filename, int revision) { var operation = CreateGetFileInfoByNameOperation(filename, revision); - using (var cursor = operation.Execute(binding, operationContext)) + using (var cursor = operation.Execute(operationContext, binding)) { // TODO: CSOT add a way to propagate cancellationContext into cursor methods. var fileInfo = cursor.FirstOrDefault(operationContext.CancellationToken); @@ -979,10 +979,10 @@ private GridFSFileInfo GetFileInfoByName(IReadBindingHandle binding, st } } - private async Task> GetFileInfoByNameAsync(IReadBindingHandle binding, string filename, int revision, OperationContext operationContext) + private async Task> GetFileInfoByNameAsync(OperationContext operationContext, IReadBindingHandle binding, string filename, int revision) { var operation = CreateGetFileInfoByNameOperation(filename, revision); - using (var cursor = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false)) { // TODO: CSOT add a way to propagate cancellationContext into cursor methods. var fileInfo = await cursor.FirstOrDefaultAsync(operationContext.CancellationToken).ConfigureAwait(false); @@ -1003,7 +1003,7 @@ private IReadBindingHandle GetSingleServerReadBinding(OperationContext operation { var readPreference = _options.ReadPreference ?? _database.Settings.ReadPreference; var selector = new ReadPreferenceServerSelector(readPreference); - var server = _cluster.SelectServer(selector, operationContext); + var server = _cluster.SelectServer(operationContext, selector); var binding = new SingleServerReadBinding(server, readPreference, NoCoreSession.NewHandle()); return new ReadBindingHandle(binding); } @@ -1012,7 +1012,7 @@ private async Task GetSingleServerReadBindingAsync(Operation { var readPreference = _options.ReadPreference ?? _database.Settings.ReadPreference; var selector = new ReadPreferenceServerSelector(readPreference); - var server = await _cluster.SelectServerAsync(selector, operationContext).ConfigureAwait(false); + var server = await _cluster.SelectServerAsync(operationContext, selector).ConfigureAwait(false); var binding = new SingleServerReadBinding(server, readPreference, NoCoreSession.NewHandle()); return new ReadBindingHandle(binding); } @@ -1020,7 +1020,7 @@ private async Task GetSingleServerReadBindingAsync(Operation private IReadWriteBindingHandle GetSingleServerReadWriteBinding(OperationContext operationContext) { var selector = WritableServerSelector.Instance; - var server = _cluster.SelectServer(selector, operationContext); + var server = _cluster.SelectServer(operationContext, selector); var binding = new SingleServerReadWriteBinding(server, NoCoreSession.NewHandle()); return new ReadWriteBindingHandle(binding); } @@ -1028,7 +1028,7 @@ private IReadWriteBindingHandle GetSingleServerReadWriteBinding(OperationContext private async Task GetSingleServerReadWriteBindingAsync(OperationContext operationContext) { var selector = WritableServerSelector.Instance; - var server = await _cluster.SelectServerAsync(selector, operationContext).ConfigureAwait(false); + var server = await _cluster.SelectServerAsync(operationContext, selector).ConfigureAwait(false); var binding = new SingleServerReadWriteBinding(server, NoCoreSession.NewHandle()); return new ReadWriteBindingHandle(binding); } @@ -1045,10 +1045,10 @@ private bool IndexExists(List indexes, BsonDocument key) return false; } - private bool IsFilesCollectionEmpty(IReadWriteBindingHandle binding, OperationContext operationContext) + private bool IsFilesCollectionEmpty(OperationContext operationContext, IReadWriteBindingHandle binding) { var operation = CreateIsFilesCollectionEmptyOperation(); - using (var cursor = operation.Execute(binding, operationContext)) + using (var cursor = operation.Execute(operationContext, binding)) { // TODO: CSOT add a way to propagate cancellationContext into cursor methods. var firstOrDefault = cursor.FirstOrDefault(operationContext.CancellationToken); @@ -1056,10 +1056,10 @@ private bool IsFilesCollectionEmpty(IReadWriteBindingHandle binding, OperationCo } } - private async Task IsFilesCollectionEmptyAsync(IReadWriteBindingHandle binding, OperationContext operationContext) + private async Task IsFilesCollectionEmptyAsync(OperationContext operationContext, IReadWriteBindingHandle binding) { var operation = CreateIsFilesCollectionEmptyOperation(); - using (var cursor = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false)) { // TODO: CSOT add a way to propagate cancellationContext into cursor methods. var firstOrDefault = await cursor.FirstOrDefaultAsync(operationContext.CancellationToken).ConfigureAwait(false); @@ -1067,16 +1067,16 @@ private async Task IsFilesCollectionEmptyAsync(IReadWriteBindingHandle bin } } - private List ListIndexes(IReadBinding binding, CollectionNamespace collectionNamespace, OperationContext operationContext) + private List ListIndexes(OperationContext operationContext, IReadBinding binding, CollectionNamespace collectionNamespace) { var operation = CreateListIndexesOperation(collectionNamespace); - return operation.Execute(binding, operationContext).ToList(); + return operation.Execute(operationContext, binding).ToList(); } - private async Task> ListIndexesAsync(IReadBinding binding, CollectionNamespace collectionNamespace, OperationContext operationContext) + private async Task> ListIndexesAsync(OperationContext operationContext, IReadBinding binding, CollectionNamespace collectionNamespace) { var operation = CreateListIndexesOperation(collectionNamespace); - var cursor = await operation.ExecuteAsync(binding, operationContext).ConfigureAwait(false); + var cursor = await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); return await cursor.ToListAsync(operationContext.CancellationToken).ConfigureAwait(false); } } diff --git a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs index a73ab856d25..23f5e48f877 100644 --- a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs +++ b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyDownloadStream.cs @@ -196,18 +196,18 @@ private FindOperation CreateFirstBatchOperation() private void GetFirstBatch(CancellationToken cancellationToken) { var operation = CreateFirstBatchOperation(); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); - _cursor = operation.Execute(Binding, operationContext); + _cursor = operation.Execute(operationContext, Binding); GetNextBatch(cancellationToken); } private async Task GetFirstBatchAsync(CancellationToken cancellationToken) { var operation = CreateFirstBatchOperation(); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); - _cursor = await operation.ExecuteAsync(Binding, operationContext).ConfigureAwait(false); + _cursor = await operation.ExecuteAsync(operationContext, Binding).ConfigureAwait(false); await GetNextBatchAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs index 92f08860940..f77fc81f56f 100644 --- a/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs +++ b/src/MongoDB.Driver/GridFS/GridFSForwardOnlyUploadStream.cs @@ -122,9 +122,9 @@ public override long Position _aborted = true; var operation = CreateAbortOperation(); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); - operation.Execute(_binding, operationContext); + operation.Execute(operationContext, _binding); } public override async Task AbortAsync(CancellationToken cancellationToken = default(CancellationToken)) @@ -137,9 +137,9 @@ public override long Position _aborted = true; var operation = CreateAbortOperation(); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); - await operation.ExecuteAsync(_binding, operationContext).ConfigureAwait(false); + await operation.ExecuteAsync(operationContext, _binding).ConfigureAwait(false); } public override void Close(CancellationToken cancellationToken) diff --git a/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs b/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs index fd0786d8f80..843412df7ef 100644 --- a/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs +++ b/src/MongoDB.Driver/GridFS/GridFSSeekableDownloadStream.cs @@ -172,9 +172,9 @@ private FindOperation CreateGetChunkOperation(long n) private void GetChunk(long n, CancellationToken cancellationToken) { var operation = CreateGetChunkOperation(n); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); - using (var cursor = operation.Execute(Binding, operationContext)) + using (var cursor = operation.Execute(operationContext, Binding)) { var documents = cursor.ToList(); _chunk = GetChunkHelper(n, documents); @@ -185,9 +185,9 @@ private void GetChunk(long n, CancellationToken cancellationToken) private async Task GetChunkAsync(long n, CancellationToken cancellationToken) { var operation = CreateGetChunkOperation(n); - // TODO: CSOT implement proper way to obtain the operationCancellationContext + // TODO: CSOT implement proper way to obtain the operationContext var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); - using (var cursor = await operation.ExecuteAsync(Binding, operationContext).ConfigureAwait(false)) + using (var cursor = await operation.ExecuteAsync(operationContext, Binding).ConfigureAwait(false)) { var documents = await cursor.ToListAsync().ConfigureAwait(false); _chunk = GetChunkHelper(n, documents); diff --git a/src/MongoDB.Driver/OperationExecutor.cs b/src/MongoDB.Driver/OperationExecutor.cs index 6ebdd6ca885..b9049b648d8 100644 --- a/src/MongoDB.Driver/OperationExecutor.cs +++ b/src/MongoDB.Driver/OperationExecutor.cs @@ -53,7 +53,7 @@ public TResult ExecuteReadOperation( var cancellationContext = options.CreateCancellationContext(cancellationToken); var readPreference = options.GetEffectiveReadPreference(session); using var binding = CreateReadBinding(session, readPreference, allowChannelPinning); - return operation.Execute(binding, cancellationContext); + return operation.Execute(cancellationContext, binding); } public async Task ExecuteReadOperationAsync( @@ -71,7 +71,7 @@ public async Task ExecuteReadOperationAsync( var cancellationContext = options.CreateCancellationContext(cancellationToken); var readPreference = options.GetEffectiveReadPreference(session); using var binding = CreateReadBinding(session, readPreference, allowChannelPinning); - return await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(cancellationContext, binding).ConfigureAwait(false); } public TResult ExecuteWriteOperation( @@ -88,7 +88,7 @@ public TResult ExecuteWriteOperation( var cancellationContext = options.CreateCancellationContext(cancellationToken); using var binding = CreateReadWriteBinding(session, allowChannelPinning); - return operation.Execute(binding, cancellationContext); + return operation.Execute(cancellationContext, binding); } public async Task ExecuteWriteOperationAsync( @@ -105,7 +105,7 @@ public async Task ExecuteWriteOperationAsync( var cancellationContext = options.CreateCancellationContext(cancellationToken); using var binding = CreateReadWriteBinding(session, allowChannelPinning); - return await operation.ExecuteAsync(binding, cancellationContext).ConfigureAwait(false); + return await operation.ExecuteAsync(cancellationContext, binding).ConfigureAwait(false); } public IClientSessionHandle StartImplicitSession() diff --git a/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs b/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs index f0b57b50756..aae52d93b19 100644 --- a/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs +++ b/tests/MongoDB.Driver.TestHelpers/Core/CoreTestConfiguration.cs @@ -314,7 +314,7 @@ private static int GetMaxWireVersion() { var command = new BsonDocument("hello", 1); var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var response = operation.Execute(binding, OperationContext.NoTimeout); + var response = operation.Execute(OperationContext.NoTimeout, binding); return response["maxWireVersion"].AsInt32; } } @@ -326,7 +326,7 @@ private static SemanticVersion GetServerVersion() { var command = new BsonDocument("buildinfo", 1); var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var response = operation.Execute(binding, OperationContext.NoTimeout); + var response = operation.Execute(OperationContext.NoTimeout, binding); return SemanticVersion.Parse(response["version"].AsString); } } @@ -338,7 +338,7 @@ public static BsonDocument GetServerParameters() { var command = new BsonDocument("getParameter", new BsonString("*")); var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var serverParameters = operation.Execute(binding, OperationContext.NoTimeout); + var serverParameters = operation.Execute(OperationContext.NoTimeout, binding); return serverParameters; } @@ -404,7 +404,7 @@ private static void DropDatabase() using (var session = StartSession()) using (var binding = CreateReadWriteBinding(session)) { - operation.Execute(binding, OperationContext.NoTimeout); + operation.Execute(OperationContext.NoTimeout, binding); } } @@ -415,7 +415,7 @@ private static IEnumerable FindDocuments(IClusterInternal cluster, { var operation = new FindOperation(collectionNamespace, BsonDocumentSerializer.Instance, __messageEncoderSettings); - return operation.Execute(binding, OperationContext.NoTimeout).ToList(); + return operation.Execute(OperationContext.NoTimeout, binding).ToList(); } } @@ -495,7 +495,7 @@ string GetStorageEngineForCluster(IClusterInternal cluster) { var operation = new ReadCommandOperation(DatabaseNamespace.Admin, command, BsonDocumentSerializer.Instance, __messageEncoderSettings); - var response = operation.Execute(binding, OperationContext.NoTimeout); + var response = operation.Execute(OperationContext.NoTimeout, binding); if (response.TryGetValue("storageEngine", out var storageEngine) && storageEngine.AsBsonDocument.TryGetValue("name", out var name)) { return name.AsString; diff --git a/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs b/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs index 17b8060310f..0122eb8447b 100644 --- a/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs +++ b/tests/MongoDB.Driver.TestHelpers/Core/FailPoint.cs @@ -88,7 +88,7 @@ public static FailPoint ConfigureAlwaysOn(IClusterInternal cluster, ICoreSession private static IServer GetWriteableServer(IClusterInternal cluster) { var selector = WritableServerSelector.Instance; - return cluster.SelectServer(selector, OperationContext.NoTimeout); + return cluster.SelectServer(OperationContext.NoTimeout, selector); } private static void MakeFailPointApplicationNameTestableIfConfigured(BsonDocument command, bool async) @@ -186,7 +186,7 @@ private void ExecuteCommand(BsonDocument command, bool waitForConnected) BsonDocumentSerializer.Instance, new MessageEncoderSettings()); - operation.Execute(_binding, OperationContext.NoTimeout); + operation.Execute(OperationContext.NoTimeout, _binding); } } } diff --git a/tests/MongoDB.Driver.Tests/AuthenticationTests.cs b/tests/MongoDB.Driver.Tests/AuthenticationTests.cs index 3b866b4c14e..0ad423e16eb 100644 --- a/tests/MongoDB.Driver.Tests/AuthenticationTests.cs +++ b/tests/MongoDB.Driver.Tests/AuthenticationTests.cs @@ -338,7 +338,7 @@ private void AssertAuthenticationSucceeds( speculativeAuthenticatationShouldSucceedIfPossible) { var serverSelector = new ReadPreferenceServerSelector(settings.ReadPreference); - var server = client.GetClusterInternal().SelectServer(serverSelector, OperationContext.NoTimeout); + var server = client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, serverSelector); var channel = server.GetChannel(OperationContext.NoTimeout); var helloResult = channel.ConnectionDescription.HelloResult; helloResult.SpeculativeAuthenticate.Should().NotBeNull(); diff --git a/tests/MongoDB.Driver.Tests/ClusterTests.cs b/tests/MongoDB.Driver.Tests/ClusterTests.cs index b13bdf52297..b6d2d8021ff 100644 --- a/tests/MongoDB.Driver.Tests/ClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/ClusterTests.cs @@ -87,8 +87,8 @@ public void SelectServer_loadbalancing_prose_test([Values(false, true)] bool asy var eventCapturer = CreateEventCapturer(); using (var client = CreateMongoClient(eventCapturer, applicationName)) { - var slowServer = client.GetClusterInternal().SelectServer(WritableServerSelector.Instance, default); - var fastServer = client.GetClusterInternal().SelectServer(new DelegateServerSelector((_, servers) => servers.Where(s => s.ServerId != slowServer.ServerId)), default); + var slowServer = client.GetClusterInternal().SelectServer(default, WritableServerSelector.Instance); + var fastServer = client.GetClusterInternal().SelectServer(default, new DelegateServerSelector((_, servers) => servers.Where(s => s.ServerId != slowServer.ServerId))); using var failPoint = FailPoint.Configure(slowServer, NoCoreSession.NewHandle(), failCommand, async); diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs index 82d016cd151..c3486f158e5 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/ReadPreferenceBindingTests.cs @@ -111,19 +111,19 @@ public async Task GetReadChannelSource_should_use_a_read_preference_server_selec if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), It.IsAny()), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), It.IsAny()), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); subject.GetReadChannelSource(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.IsAny(), It.IsAny()), Times.Once); + _mockCluster.Verify(c => c.SelectServer(It.IsAny(), It.IsAny()), Times.Once); } } @@ -135,8 +135,8 @@ public async Task GetReadChannelSource_should_fork_the_session( var mockSession = new Mock(); var subject = new ReadPreferenceBinding(_mockCluster.Object, ReadPreference.Primary, mockSession.Object); var selectedServer = new Mock().Object; - _mockCluster.Setup(m => m.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); - _mockCluster.Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(m => m.SelectServer(It.IsAny(), It.IsAny())).Returns(selectedServer); + _mockCluster.Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(selectedServer)); var forkedSession = new Mock().Object; mockSession.Setup(m => m.Fork()).Returns(forkedSession); diff --git a/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs b/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs index a65dd2f43e6..f16dc755894 100644 --- a/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Bindings/WritableServerBindingTests.cs @@ -115,19 +115,19 @@ public async Task GetReadChannelSource_should_use_a_writable_server_selector_to_ if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), OperationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny())).Returns(Task.FromResult(selectedServer)); await subject.GetReadChannelSourceAsync(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), OperationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny()), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), OperationContext.NoTimeout)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny())).Returns(selectedServer); subject.GetReadChannelSource(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.IsAny(), OperationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny()), Times.Once); } } @@ -171,19 +171,19 @@ public async Task GetWriteChannelSourceAsync_should_use_a_writable_server_select if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), OperationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny())).Returns(Task.FromResult(selectedServer)); await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServerAsync(It.IsAny(), OperationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny()), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), OperationContext.NoTimeout)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny())).Returns(selectedServer); subject.GetWriteChannelSource(OperationContext.NoTimeout); - _mockCluster.Verify(c => c.SelectServer(It.IsAny(), OperationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny()), Times.Once); } } @@ -212,19 +212,19 @@ public async Task GetWriteChannelSource_should_use_a_composite_server_selector_t if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), OperationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(OperationContext.NoTimeout, It.Is(cp => cp.ToString().Contains("PriorityServerSelector")))).Returns(Task.FromResult(selectedServer)); - await subject.GetWriteChannelSourceAsync(deprioritizedServers, OperationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout, deprioritizedServers); - _mockCluster.Verify(c => c.SelectServerAsync(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), OperationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.Is(cp => cp.ToString().Contains("PriorityServerSelector"))), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.Is(cp => cp.ToString().Contains("PriorityServerSelector")), OperationContext.NoTimeout)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.Is(cp => cp.ToString().Contains("PriorityServerSelector")))).Returns(selectedServer); - subject.GetWriteChannelSource(deprioritizedServers, OperationContext.NoTimeout); + subject.GetWriteChannelSource(OperationContext.NoTimeout, deprioritizedServers); - _mockCluster.Verify(c => c.SelectServer(It.Is(c => c.ToString().Contains("PriorityServerSelector")), OperationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.Is(c => c.ToString().Contains("PriorityServerSelector"))), Times.Once); } } @@ -256,19 +256,19 @@ public async Task GetWriteChannelSource_with_mayUseSecondary_should_pass_mayUseS if (async) { - _mockCluster.Setup(c => c.SelectServerAsync(It.IsAny(), OperationContext.NoTimeout)).Returns(Task.FromResult(selectedServer)); + _mockCluster.Setup(c => c.SelectServerAsync(OperationContext.NoTimeout, It.IsAny())).Returns(Task.FromResult(selectedServer)); - await subject.GetWriteChannelSourceAsync(mayUseSecondary, OperationContext.NoTimeout); + await subject.GetWriteChannelSourceAsync(OperationContext.NoTimeout, mayUseSecondary); - _mockCluster.Verify(c => c.SelectServerAsync(It.Is(s => s.MayUseSecondary == mayUseSecondary), OperationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServerAsync(OperationContext.NoTimeout, It.Is(s => s.MayUseSecondary == mayUseSecondary)), Times.Once); } else { - _mockCluster.Setup(c => c.SelectServer(It.IsAny(), OperationContext.NoTimeout)).Returns(selectedServer); + _mockCluster.Setup(c => c.SelectServer(OperationContext.NoTimeout, It.IsAny())).Returns(selectedServer); - subject.GetWriteChannelSource(mayUseSecondary, OperationContext.NoTimeout); + subject.GetWriteChannelSource(OperationContext.NoTimeout, mayUseSecondary); - _mockCluster.Verify(c => c.SelectServer(It.Is(s => s.MayUseSecondary == mayUseSecondary), OperationContext.NoTimeout), Times.Once); + _mockCluster.Verify(c => c.SelectServer(OperationContext.NoTimeout, It.Is(s => s.MayUseSecondary == mayUseSecondary)), Times.Once); } } diff --git a/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs b/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs index 26f042869e2..7a3244b229d 100644 --- a/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Clusters/ClusterTests.cs @@ -128,8 +128,8 @@ public async Task SelectServer_should_throw_if_not_initialized( var subject = CreateSubject(); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(selector, OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, selector)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); exception.Should().BeOfType(); } @@ -145,8 +145,8 @@ public async Task SelectServer_should_throw_if_disposed( subject.Dispose(); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(selector, OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, selector)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); exception.Should().BeOfType(); } @@ -161,8 +161,8 @@ public async Task SelectServer_should_throw_if_serverSelector_is_null( subject.Initialize(); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(null, OperationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(null, OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, null)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, null)); exception.Should().BeOfType(); } @@ -183,8 +183,8 @@ public async Task SelectServer_should_return_a_server_if_one_matches( var selector = new DelegateServerSelector((c, s) => s); var result = async ? - await subject.SelectServerAsync(selector, OperationContext.NoTimeout) : - subject.SelectServer(selector, OperationContext.NoTimeout); + await subject.SelectServerAsync(OperationContext.NoTimeout, selector) : + subject.SelectServer(OperationContext.NoTimeout, selector); result.Should().NotBeNull(); @@ -213,8 +213,8 @@ public async Task SelectServer_should_return_second_server_if_first_cannot_be_fo var selector = new DelegateServerSelector((c, s) => s); var result = async ? - await subject.SelectServerAsync(selector, OperationContext.NoTimeout) : - subject.SelectServer(selector, OperationContext.NoTimeout); + await subject.SelectServerAsync(OperationContext.NoTimeout, selector) : + subject.SelectServer(OperationContext.NoTimeout, selector); result.Should().NotBeNull(); @@ -241,8 +241,8 @@ public async Task SelectServer_should_throw_if_no_servers_match( var selector = new DelegateServerSelector((c, s) => Enumerable.Empty()); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(selector, OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, selector)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); exception.Should().BeOfType(); @@ -269,8 +269,8 @@ public async Task SelectServer_should_throw_if_the_matched_server_cannot_be_foun var selector = new DelegateServerSelector((c, s) => s); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(selector, OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, selector)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); exception.Should().BeOfType(); @@ -297,8 +297,8 @@ public async Task SelectServer_should_throw_if_any_servers_are_incompatible(int var selector = new DelegateServerSelector((c, s) => s); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(selector, OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, selector)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); exception.Should().BeOfType(); @@ -338,8 +338,8 @@ public async Task SelectServer_should_keep_trying_to_match_by_waiting_on_cluster var selector = new DelegateServerSelector((c, s) => s); var result = async ? - await subject.SelectServerAsync(selector, OperationContext.NoTimeout) : - subject.SelectServer(selector, OperationContext.NoTimeout); + await subject.SelectServerAsync(OperationContext.NoTimeout, selector) : + subject.SelectServer(OperationContext.NoTimeout, selector); result.Should().NotBeNull(); @@ -377,8 +377,8 @@ public async Task SelectServer_should_ignore_deprioritized_servers_if_cluster_is _capturedEvents.Clear(); var result = async ? - await subject.SelectServerAsync(selector, OperationContext.NoTimeout) : - subject.SelectServer(selector, OperationContext.NoTimeout); + await subject.SelectServerAsync(OperationContext.NoTimeout, selector) : + subject.SelectServer(OperationContext.NoTimeout, selector); result.Should().NotBeNull(); @@ -411,8 +411,8 @@ public async Task SelectServer_should_return_deprioritized_servers_if_no_other_s _capturedEvents.Clear(); var result = async ? - await subject.SelectServerAsync(selector, OperationContext.NoTimeout) : - subject.SelectServer(selector, OperationContext.NoTimeout); + await subject.SelectServerAsync(OperationContext.NoTimeout, selector) : + subject.SelectServer(OperationContext.NoTimeout, selector); result.Should().NotBeNull(); @@ -492,8 +492,8 @@ public async Task SelectServer_should_apply_both_pre_and_post_server_selectors( _capturedEvents.Clear(); var result = async ? - await subject.SelectServerAsync(middleSelector, OperationContext.NoTimeout) : - subject.SelectServer(middleSelector, OperationContext.NoTimeout); + await subject.SelectServerAsync(OperationContext.NoTimeout, middleSelector) : + subject.SelectServer(OperationContext.NoTimeout, middleSelector); ((DnsEndPoint)result.EndPoint).Port.Should().Be(27020); _capturedEvents.Next().Should().BeOfType(); @@ -527,8 +527,8 @@ public async Task SelectServer_should_call_custom_selector( { var selector = new DelegateServerSelector((c, s) => s); var selectedServer = async ? - await subject.SelectServerAsync(selector, OperationContext.NoTimeout): - subject.SelectServer(selector, OperationContext.NoTimeout); + await subject.SelectServerAsync(OperationContext.NoTimeout, selector): + subject.SelectServer(OperationContext.NoTimeout, selector); var selectedServerPort = ((DnsEndPoint)selectedServer.EndPoint).Port; selectedServerPort.Should().Be(27020); @@ -539,8 +539,8 @@ await subject.SelectServerAsync(selector, OperationContext.NoTimeout): { var selector = new DelegateServerSelector((c, s) => new ServerDescription[0]); var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(selector, OperationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(selector, OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, selector)) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, selector)); exception.Should().BeOfType(); _capturedEvents.Next().Should().BeOfType(); diff --git a/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs b/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs index 27e7537fe85..6d9bcb3dae6 100644 --- a/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs @@ -328,8 +328,8 @@ public async Task SelectServer_should_return_expected_server( PublishDescription(_endPoint); var result = async ? - await subject.SelectServerAsync(Mock.Of(), OperationContext.NoTimeout) : - subject.SelectServer(Mock.Of(), OperationContext.NoTimeout); + await subject.SelectServerAsync(OperationContext.NoTimeout, Mock.Of()) : + subject.SelectServer(OperationContext.NoTimeout, Mock.Of()); result.EndPoint.Should().Be(_endPoint); } @@ -356,8 +356,8 @@ public async Task SelectServer_should_throw_server_selection_timeout_if_server_h } var exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(Mock.Of(), OperationContext.NoTimeout)) : - Record.Exception(() => subject.SelectServer(Mock.Of(), OperationContext.NoTimeout)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(OperationContext.NoTimeout, Mock.Of())) : + Record.Exception(() => subject.SelectServer(OperationContext.NoTimeout, Mock.Of())); var ex = exception.Should().BeOfType().Subject; ex.Message.Should().StartWith($"A timeout occurred after {serverSelectionTimeout.TotalMilliseconds}ms selecting a server. Client view of cluster state is "); @@ -389,8 +389,8 @@ public async Task SelectServer_should_be_cancelled_by_cancellationToken( { var cancellationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationTokenSource.Token); exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(Mock.Of(), cancellationContext)) : - Record.Exception(() => subject.SelectServer(Mock.Of(), cancellationContext)); + await Record.ExceptionAsync(() => subject.SelectServerAsync(cancellationContext, Mock.Of())) : + Record.Exception(() => subject.SelectServer(cancellationContext, Mock.Of())); } exception.Should().BeOfType(); diff --git a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs index ea31f3779d9..70ff0840d24 100644 --- a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3173Tests.cs @@ -75,7 +75,7 @@ public void Ensure_command_network_error_before_handshake_is_correctly_handled([ // The next hello or legacy hello response will be delayed because the waiting in the mock.Callbacks cluster.Initialize(); - var selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint1), OperationContext.NoTimeout); + var selectedServer = cluster.SelectServer(OperationContext.NoTimeout, CreateWritableServerAndEndPointSelector(__endPoint1)); initialSelectedEndpoint = selectedServer.EndPoint; initialSelectedEndpoint.Should().Be(__endPoint1); @@ -107,7 +107,7 @@ public void Ensure_command_network_error_before_handshake_is_correctly_handled([ } // ensure that a new server can be selected - selectedServer = cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); + selectedServer = cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); // ensure that the selected server is not the same as the initial selectedServer.EndPoint.Should().Be(__endPoint2); diff --git a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs index 552e46170c4..a3c5488e56f 100644 --- a/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Jira/CSharp3302Tests.cs @@ -96,7 +96,7 @@ public async Task RapidHeartbeatTimerCallback_should_ignore_reentrant_calls() cluster.Initialize(); // Trigger Cluster._rapidHeartbeatTimer - _ = cluster.SelectServerAsync(CreateWritableServerAndEndPointSelector(__endPoint1), OperationContext.NoTimeout); + _ = cluster.SelectServerAsync(OperationContext.NoTimeout, CreateWritableServerAndEndPointSelector(__endPoint1)); // Wait for all heartbeats to complete await Task.WhenAny(allHeartbeatsReceived.Task, Task.Delay(1000)); @@ -142,13 +142,13 @@ public async Task Ensure_no_deadlock_after_primary_update() server.DescriptionChanged += ProcessServerDescriptionChanged; } - var selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint1), OperationContext.NoTimeout); + var selectedServer = cluster.SelectServer(OperationContext.NoTimeout, CreateWritableServerAndEndPointSelector(__endPoint1)); initialSelectedEndpoint = selectedServer.EndPoint; initialSelectedEndpoint.Should().Be(__endPoint1); // Change primary currentPrimaries.Add(__serverId2); - selectedServer = cluster.SelectServer(CreateWritableServerAndEndPointSelector(__endPoint2), OperationContext.NoTimeout); + selectedServer = cluster.SelectServer(OperationContext.NoTimeout, CreateWritableServerAndEndPointSelector(__endPoint2)); selectedServer.EndPoint.Should().Be(__endPoint2); // Ensure stalling happened diff --git a/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntergationTests.cs b/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntergationTests.cs index 2c5dbba625f..a433e87fa5e 100644 --- a/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntergationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/LoadBalancingIntergationTests.cs @@ -614,11 +614,11 @@ private BulkWriteOperationResult CreateAndRunBulkOperation(RetryableWriteContext if (async) { - return bulkInsertOperation.ExecuteAsync(context, OperationContext.NoTimeout).GetAwaiter().GetResult(); + return bulkInsertOperation.ExecuteAsync(OperationContext.NoTimeout, context).GetAwaiter().GetResult(); } else { - return bulkInsertOperation.Execute(context, OperationContext.NoTimeout); + return bulkInsertOperation.Execute(OperationContext.NoTimeout, context); } } @@ -634,19 +634,19 @@ private IAsyncCursor CreateAndRunFindOperation(RetryableReadContex if (async) { - return findOperation.ExecuteAsync(context, OperationContext.NoTimeout).GetAwaiter().GetResult(); + return findOperation.ExecuteAsync(OperationContext.NoTimeout, context).GetAwaiter().GetResult(); } else { - return findOperation.Execute(context, OperationContext.NoTimeout); + return findOperation.Execute(OperationContext.NoTimeout, context); } } private RetryableReadContext CreateRetryableReadContext(IReadBindingHandle readBindingHandle, bool async) { return async - ? RetryableReadContext.CreateAsync(readBindingHandle, retryRequested: false, OperationContext.NoTimeout).GetAwaiter().GetResult() - : RetryableReadContext.Create(readBindingHandle, retryRequested: false, OperationContext.NoTimeout); + ? RetryableReadContext.CreateAsync(OperationContext.NoTimeout, readBindingHandle, retryRequested: false).GetAwaiter().GetResult() + : RetryableReadContext.Create(OperationContext.NoTimeout, readBindingHandle, retryRequested: false); } private DisposableBindingBundle CreateReadBindingsAndRetryableReadContext(IClusterInternal cluster, ICoreSessionHandle sessionHandle, bool async) @@ -662,8 +662,8 @@ private DisposableBindingBundle Create private RetryableWriteContext CreateRetryableWriteContext(IReadWriteBindingHandle readWriteBindingHandle, bool async) { return async - ? RetryableWriteContext.CreateAsync(readWriteBindingHandle, retryRequested: false, OperationContext.NoTimeout).GetAwaiter().GetResult() - : RetryableWriteContext.Create(readWriteBindingHandle, retryRequested: false, OperationContext.NoTimeout); + ? RetryableWriteContext.CreateAsync(OperationContext.NoTimeout, readWriteBindingHandle, retryRequested: false).GetAwaiter().GetResult() + : RetryableWriteContext.Create(OperationContext.NoTimeout, readWriteBindingHandle, retryRequested: false); } private DisposableBindingBundle CreateReadWriteBindingsAndRetryableWriteContext(IClusterInternal cluster, ICoreSessionHandle sessionHandle, bool async) diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs index ff500312db1..4e11447d94c 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/ChangeStreamCursorTests.cs @@ -450,25 +450,25 @@ public void MoveNext_should_call_Resume_after_resumable_exception( if (async) { mockCursor.Setup(c => c.MoveNextAsync(It.IsAny())).Returns(CreateFaultedTask(resumableException)); - mockOperation.Setup(o => o.ResumeAsync(mockBinding.Object, It.IsAny())).Returns(Task.FromResult(mockResumedCursor.Object)); + mockOperation.Setup(o => o.ResumeAsync(It.IsAny(), mockBinding.Object)).Returns(Task.FromResult(mockResumedCursor.Object)); mockResumedCursor.Setup(c => c.MoveNextAsync(It.IsAny())).Returns(Task.FromResult(expectedResult)); result = subject.MoveNextAsync(It.IsAny()).GetAwaiter().GetResult(); mockCursor.Verify(c => c.MoveNextAsync(It.IsAny()), Times.Once); - mockOperation.Verify(o => o.ResumeAsync(mockBinding.Object, It.IsAny()), Times.Once); + mockOperation.Verify(o => o.ResumeAsync(It.IsAny(), mockBinding.Object), Times.Once); mockResumedCursor.Verify(c => c.MoveNextAsync(It.IsAny()), Times.Once); } else { mockCursor.Setup(c => c.MoveNext(It.IsAny())).Throws(resumableException); - mockOperation.Setup(o => o.Resume(mockBinding.Object, It.IsAny())).Returns(mockResumedCursor.Object); + mockOperation.Setup(o => o.Resume(It.IsAny(), mockBinding.Object)).Returns(mockResumedCursor.Object); mockResumedCursor.Setup(c => c.MoveNext(It.IsAny())).Returns(expectedResult); result = subject.MoveNext(It.IsAny()); mockCursor.Verify(c => c.MoveNext(It.IsAny()), Times.Exactly(2)); - mockOperation.Verify(o => o.Resume(mockBinding.Object, It.IsAny()), Times.Once); + mockOperation.Verify(o => o.Resume(It.IsAny(), mockBinding.Object), Times.Once); mockResumedCursor.Verify(c => c.MoveNext(It.IsAny()), Times.Once); } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs index 8b73a49ed7d..3dcc8a36cfc 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CompositeWriteOperationTests.cs @@ -69,8 +69,8 @@ public async Task Enumerating_operations_should_be_stopped_when_error([Values(fa var subject = new CompositeWriteOperation((healthyOperation1.Object, IsMainOperation: false), (faultyOperation2.Object, IsMainOperation: false), (healthyOperation3.Object, IsMainOperation: true)); var resultedException = async - ? await Record.ExceptionAsync(() => subject.ExecuteAsync(Mock.Of(), OperationContext.NoTimeout)) - : Record.Exception(() => subject.Execute(Mock.Of(), OperationContext.NoTimeout)); + ? await Record.ExceptionAsync(() => subject.ExecuteAsync(OperationContext.NoTimeout, Mock.Of())) + : Record.Exception(() => subject.Execute(OperationContext.NoTimeout, Mock.Of())); resultedException.Should().Be(testException); @@ -92,8 +92,8 @@ public void Enumerating_operations_should_return_result_of_main_operation([Value var subject = new CompositeWriteOperation((operation1.Object, IsMainOperation: false), (operation2.Object, IsMainOperation: true), (operation3.Object, IsMainOperation: false)); var result = async - ? subject.ExecuteAsync(Mock.Of(), OperationContext.NoTimeout).GetAwaiter().GetResult() - : subject.Execute(Mock.Of(), OperationContext.NoTimeout); + ? subject.ExecuteAsync(OperationContext.NoTimeout, Mock.Of()).GetAwaiter().GetResult() + : subject.Execute(OperationContext.NoTimeout, Mock.Of()); result.Should().Be(operation2Result); @@ -107,10 +107,10 @@ private Mock> CreateFaultyOperation(Exception test { var mockedOperation = new Mock>(); mockedOperation - .Setup(c => c.Execute(It.IsAny(), It.IsAny())) + .Setup(c => c.Execute(It.IsAny(), It.IsAny())) .Throws(testException); mockedOperation - .Setup(c => c.ExecuteAsync(It.IsAny(), It.IsAny())) + .Setup(c => c.ExecuteAsync(It.IsAny(), It.IsAny())) .Throws(testException); return mockedOperation; } @@ -119,10 +119,10 @@ private Mock> CreateHealthyOperation(BsonDocument { var mockedOperation = new Mock>(); mockedOperation - .Setup(c => c.Execute(It.IsAny(), It.IsAny())) + .Setup(c => c.Execute(It.IsAny(), It.IsAny())) .Returns(response); mockedOperation - .Setup(c => c.ExecuteAsync(It.IsAny(), It.IsAny())) + .Setup(c => c.ExecuteAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(response); return mockedOperation; } @@ -131,11 +131,11 @@ private void VeryfyOperation(Mock> mockedOperation { if (async) { - mockedOperation.Verify(c => c.ExecuteAsync(It.IsAny(), It.IsAny()), hasBeenCalled ? Times.Once : Times.Never); + mockedOperation.Verify(c => c.ExecuteAsync(It.IsAny(), It.IsAny()), hasBeenCalled ? Times.Once : Times.Never); } else { - mockedOperation.Verify(c => c.Execute(It.IsAny(), It.IsAny()), hasBeenCalled ? Times.Once : Times.Never); + mockedOperation.Verify(c => c.Execute(It.IsAny(), It.IsAny()), hasBeenCalled ? Times.Once : Times.Never); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs index 191ab5e3fd1..37bb5aaf6e0 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CreateCollectionOperationTests.cs @@ -1031,11 +1031,11 @@ private BsonDocument ExecuteOperation(CreateCollectionOperation subject, IWriteB { if (async) { - return subject.ExecuteAsync(binding, OperationContext.NoTimeout).GetAwaiter().GetResult(); + return subject.ExecuteAsync(OperationContext.NoTimeout, binding).GetAwaiter().GetResult(); } else { - return subject.Execute(binding, OperationContext.NoTimeout); + return subject.Execute(OperationContext.NoTimeout, binding); } } @@ -1045,7 +1045,7 @@ private BsonDocument GetCollectionInfo(IReadBinding binding) { Filter = new BsonDocument("name", _collectionNamespace.CollectionName) }; - return listCollectionsOperation.Execute(binding, OperationContext.NoTimeout).Single(); + return listCollectionsOperation.Execute(OperationContext.NoTimeout, binding).Single(); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs index a30edfcc563..e6edf861ed2 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/CreateViewOperationTests.cs @@ -331,7 +331,7 @@ private BsonDocument GetViewInfo(IReadBinding binding, string viewName) { Filter = new BsonDocument("name", viewName) }; - return listCollectionsOperation.Execute(binding, OperationContext.NoTimeout).Single(); + return listCollectionsOperation.Execute(OperationContext.NoTimeout, binding).Single(); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/EvalOperationTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/EvalOperationTests.cs index 6ae0637b1ef..b01a431d766 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/EvalOperationTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/EvalOperationTests.cs @@ -304,11 +304,11 @@ private BsonValue ExecuteOperation(EvalOperation operation, IWriteBinding bindin { if (async) { - return operation.ExecuteAsync(binding, OperationContext.NoTimeout).GetAwaiter().GetResult(); + return operation.ExecuteAsync(OperationContext.NoTimeout, binding).GetAwaiter().GetResult(); } else { - return operation.Execute(binding, OperationContext.NoTimeout); + return operation.Execute(OperationContext.NoTimeout, binding); } } } diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs b/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs index 467575a7b67..e42b9a5a05a 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/OperationTestBase.cs @@ -142,7 +142,7 @@ private protected TResult ExecuteOperation(IReadOperation oper using (var binding = CreateReadBinding()) using (var bindingHandle = new ReadBindingHandle(binding)) { - return operation.Execute(bindingHandle, OperationContext.NoTimeout); + return operation.Execute(OperationContext.NoTimeout, bindingHandle); } } @@ -164,8 +164,8 @@ private protected async Task ExecuteOperationAsync(IReadOperat using (var bindingHandle = new ReadBindingHandle(binding)) { return async ? - await operation.ExecuteAsync(bindingHandle, OperationContext.NoTimeout) : - operation.Execute(bindingHandle, OperationContext.NoTimeout); + await operation.ExecuteAsync(OperationContext.NoTimeout, bindingHandle) : + operation.Execute(OperationContext.NoTimeout, bindingHandle); } } @@ -173,11 +173,11 @@ private protected TResult ExecuteOperation(IReadOperation oper { if (async) { - return operation.ExecuteAsync(binding, OperationContext.NoTimeout).GetAwaiter().GetResult(); + return operation.ExecuteAsync(OperationContext.NoTimeout, binding).GetAwaiter().GetResult(); } else { - return operation.Execute(binding, OperationContext.NoTimeout); + return operation.Execute(OperationContext.NoTimeout, binding); } } @@ -195,7 +195,7 @@ private protected TResult ExecuteOperationSync(IWriteOperation using (var binding = CreateReadWriteBinding(useImplicitSession)) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { - return operation.Execute(bindingHandle, OperationContext.NoTimeout); + return operation.Execute(OperationContext.NoTimeout, bindingHandle); } } @@ -215,11 +215,11 @@ private protected TResult ExecuteOperation(IWriteOperation ope { if (async) { - return operation.ExecuteAsync(binding, OperationContext.NoTimeout).GetAwaiter().GetResult(); + return operation.ExecuteAsync(OperationContext.NoTimeout, binding).GetAwaiter().GetResult(); } else { - return operation.Execute(binding, OperationContext.NoTimeout); + return operation.Execute(OperationContext.NoTimeout, binding); } } @@ -234,7 +234,7 @@ private protected async Task ExecuteOperationAsync(IReadOperat private protected async Task ExecuteOperationAsync(IReadOperation operation, IReadBinding binding) { - return await operation.ExecuteAsync(binding, OperationContext.NoTimeout); + return await operation.ExecuteAsync(OperationContext.NoTimeout, binding); } private protected async Task ExecuteOperationAsync(IWriteOperation operation, bool useImplicitSession = false) @@ -242,7 +242,7 @@ private protected async Task ExecuteOperationAsync(IWriteOpera using (var binding = CreateReadWriteBinding(useImplicitSession)) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { - return await operation.ExecuteAsync(bindingHandle, OperationContext.NoTimeout); + return await operation.ExecuteAsync(OperationContext.NoTimeout, bindingHandle); } } @@ -253,23 +253,23 @@ private protected async Task ExecuteOperationAsync(IWriteOpera { if (async) { - return await operation.ExecuteAsync(bindingHandle, OperationContext.NoTimeout); + return await operation.ExecuteAsync(OperationContext.NoTimeout, bindingHandle); } else { - return operation.Execute(bindingHandle, OperationContext.NoTimeout); + return operation.Execute(OperationContext.NoTimeout, bindingHandle); } } } private protected TResult ExecuteOperation(IWriteOperation operation, IWriteBinding binding, bool async) => async ? - operation.ExecuteAsync(binding, OperationContext.NoTimeout).GetAwaiter().GetResult() : - operation.Execute(binding, OperationContext.NoTimeout); + operation.ExecuteAsync(OperationContext.NoTimeout, binding).GetAwaiter().GetResult() : + operation.Execute(OperationContext.NoTimeout, binding); private protected async Task ExecuteOperationAsync(IWriteOperation operation, IWriteBinding binding) { - return await operation.ExecuteAsync(binding, OperationContext.NoTimeout); + return await operation.ExecuteAsync(OperationContext.NoTimeout, binding); } private protected void CreateIndexes(params CreateIndexRequest[] requests) @@ -513,8 +513,8 @@ private protected void VerifySessionIdWasNotSentIfUnacknowledgedWrite( bool useImplicitSession) { VerifySessionIdSending( - (binding, cancellationToken) => operation.ExecuteAsync(binding, cancellationToken), - (binding, cancellationToken) => operation.Execute(binding, cancellationToken), + (binding, cancellationToken) => operation.ExecuteAsync(cancellationToken, binding), + (binding, cancellationToken) => operation.Execute(cancellationToken, binding), AssertSessionIdWasNotSentIfUnacknowledgedWrite, commandName, async, @@ -524,8 +524,8 @@ private protected void VerifySessionIdWasNotSentIfUnacknowledgedWrite( private protected void VerifySessionIdWasSentWhenSupported(IReadOperation operation, string commandName, bool async) { VerifySessionIdSending( - (binding, cancellationToken) => operation.ExecuteAsync(binding, cancellationToken), - (binding, cancellationToken) => operation.Execute(binding, cancellationToken), + (binding, cancellationToken) => operation.ExecuteAsync(cancellationToken, binding), + (binding, cancellationToken) => operation.Execute(cancellationToken, binding), AssertSessionIdWasSentWhenSupported, commandName, async); @@ -534,8 +534,8 @@ private protected void VerifySessionIdWasSentWhenSupported(IReadOperati private protected void VerifySessionIdWasSentWhenSupported(IWriteOperation operation, string commandName, bool async) { VerifySessionIdSending( - (binding, cancellationToken) => operation.ExecuteAsync(binding, cancellationToken), - (binding, cancellationToken) => operation.Execute(binding, cancellationToken), + (binding, cancellationToken) => operation.ExecuteAsync(cancellationToken, binding), + (binding, cancellationToken) => operation.Execute(cancellationToken, binding), AssertSessionIdWasSentWhenSupported, commandName, async); diff --git a/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs b/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs index f4ab46bce2e..471c4a0a931 100644 --- a/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Operations/RetryableWriteOperationExecutorTests.cs @@ -142,7 +142,7 @@ private ConnectionDescription CreateConnectionDescription(bool withLogicalSessio private RetryableWriteContext CreateContext(bool retryRequested, bool areRetryableWritesSupported, bool hasSessionId, bool isInTransaction) { var binding = CreateBinding(areRetryableWritesSupported, hasSessionId, isInTransaction); - return RetryableWriteContext.Create(binding, retryRequested, OperationContext.NoTimeout); + return RetryableWriteContext.Create(OperationContext.NoTimeout, binding, retryRequested); } private IRetryableWriteOperation CreateOperation(bool withWriteConcern, bool isAcknowledged) diff --git a/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs b/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs index 6f2778d71f4..cd564ab9773 100644 --- a/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Servers/ServerTests.cs @@ -853,7 +853,7 @@ public void Command_should_send_the_greater_of_the_session_and_cluster_cluster_t using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer))) using (var session = cluster.StartSession()) { - var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); + var server = (Server)cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); using (var channel = server.GetChannel(OperationContext.NoTimeout)) { session.AdvanceClusterTime(sessionClusterTime); @@ -900,7 +900,7 @@ public void Command_should_update_the_session_and_cluster_cluster_times() using (var cluster = CoreTestConfiguration.CreateCluster(b => b.Subscribe(eventCapturer))) using (var session = cluster.StartSession()) { - var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); + var server = (Server)cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); using (var channel = server.GetChannel(OperationContext.NoTimeout)) { var command = BsonDocument.Parse("{ ping : 1 }"); @@ -943,7 +943,7 @@ public async Task Command_should_use_serverApi([Values(false, true)] bool async) using (var cluster = CoreTestConfiguration.CreateCluster(builder)) using (var session = cluster.StartSession()) { - var server = (Server)cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); + var server = (Server)cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); using (var channel = server.GetChannel(OperationContext.NoTimeout)) { var command = BsonDocument.Parse("{ ping : 1 }"); diff --git a/tests/MongoDB.Driver.Tests/Encryption/ClientEncryptionTests.cs b/tests/MongoDB.Driver.Tests/Encryption/ClientEncryptionTests.cs index f541233952f..fb09f34e818 100644 --- a/tests/MongoDB.Driver.Tests/Encryption/ClientEncryptionTests.cs +++ b/tests/MongoDB.Driver.Tests/Encryption/ClientEncryptionTests.cs @@ -141,10 +141,10 @@ public async Task CreateEncryptedCollection_should_handle_generated_key_when_sec mockServer.Setup(s => s.GetChannelAsync(It.IsAny())).ReturnsAsync(channel); mockCluster - .Setup(m => m.SelectServer(It.IsAny(), It.IsAny())) + .Setup(m => m.SelectServer(It.IsAny(), It.IsAny())) .Returns(mockServer.Object); mockCluster - .Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())) + .Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(mockServer.Object); var database = Mock.Of(d => @@ -230,10 +230,10 @@ public async Task CreateEncryptedCollection_should_handle_various_encryptedField mockServer.Setup(s => s.GetChannelAsync(It.IsAny())).ReturnsAsync(channel); mockCluster - .Setup(m => m.SelectServer(It.IsAny(), It.IsAny())) + .Setup(m => m.SelectServer(It.IsAny(), It.IsAny())) .Returns(mockServer.Object); mockCluster - .Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())) + .Setup(m => m.SelectServerAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(mockServer.Object); var database = Mock.Of(d => diff --git a/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenConfigureFailPointTest.cs b/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenConfigureFailPointTest.cs index 72bf46cafc2..389449d592d 100644 --- a/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenConfigureFailPointTest.cs +++ b/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenConfigureFailPointTest.cs @@ -52,7 +52,7 @@ protected virtual IServer GetFailPointServer() } var cluster = TestRunner.FailPointCluster; - return cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); + return cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); } protected async virtual Task GetFailPointServerAsync() @@ -63,7 +63,7 @@ protected async virtual Task GetFailPointServerAsync() } var cluster = TestRunner.FailPointCluster; - return await cluster.SelectServerAsync(WritableServerSelector.Instance, OperationContext.NoTimeout).ConfigureAwait(false); + return await cluster.SelectServerAsync(OperationContext.NoTimeout, WritableServerSelector.Instance).ConfigureAwait(false); } protected override void SetArgument(string name, BsonValue value) diff --git a/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenTargetedFailPointTest.cs b/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenTargetedFailPointTest.cs index 5e91ce740e6..8a34e83638d 100644 --- a/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenTargetedFailPointTest.cs +++ b/tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenTargetedFailPointTest.cs @@ -33,14 +33,14 @@ protected override IServer GetFailPointServer() { var pinnedServerEndpoint = GetPinnedServerEndpointAndAssertNotNull(); var pinnedServerSelector = CreateServerSelector(pinnedServerEndpoint); - return TestRunner.FailPointCluster.SelectServer(pinnedServerSelector, OperationContext.NoTimeout); + return TestRunner.FailPointCluster.SelectServer(OperationContext.NoTimeout, pinnedServerSelector); } protected async override Task GetFailPointServerAsync() { var pinnedServerEndpoint = GetPinnedServerEndpointAndAssertNotNull(); var pinnedServerSelector = CreateServerSelector(pinnedServerEndpoint); - return await TestRunner.FailPointCluster.SelectServerAsync(pinnedServerSelector, OperationContext.NoTimeout).ConfigureAwait(false); + return await TestRunner.FailPointCluster.SelectServerAsync(OperationContext.NoTimeout, pinnedServerSelector).ConfigureAwait(false); } // private methods diff --git a/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs b/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs index 84cc0e77e89..8ad80cafbca 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/Runner/MongoClientJsonDrivenTestRunnerBase.cs @@ -456,11 +456,11 @@ private protected FailPoint ConfigureFailPoint(BsonDocument test, IMongoClient c var serverAddress = EndPointHelper.Parse(settings.Server.ToString()); var selector = new EndPointServerSelector(serverAddress); - _failPointServer = cluster.SelectServer(selector, OperationContext.NoTimeout); + _failPointServer = cluster.SelectServer(OperationContext.NoTimeout, selector); } else { - _failPointServer = cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); + _failPointServer = cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); } var session = NoCoreSession.NewHandle(); diff --git a/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs index dc2dae7dc0a..73c1076d90d 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/client-side-encryption/prose-tests/ClientEncryptionProseTests.cs @@ -3245,7 +3245,7 @@ private void DropCollection(CollectionNamespace collectionNamespace, BsonDocumen using (var binding = new WritableServerBinding(_cluster, session.Fork())) using (var bindingHandle = new ReadWriteBindingHandle(binding)) { - operation.Execute(bindingHandle, OperationContext.NoTimeout); + operation.Execute(OperationContext.NoTimeout, bindingHandle); } } diff --git a/tests/MongoDB.Driver.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs b/tests/MongoDB.Driver.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs index 17a2ef3d736..cad223d7c2d 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/connection-monitoring-and-pooling/ConnectionMonitoringAndPoolingTestRunner.cs @@ -671,7 +671,7 @@ private void ParseSettings( connectionIdLocalValueProvider: connectionIdProvider)) .Subscribe(eventCapturer)); - var server = cluster.SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); + var server = cluster.SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); connectionPool = server._connectionPool(); if (test.TryGetValue(Schema.Intergration.failPoint, out var failPointDocument)) @@ -729,7 +729,7 @@ o is ServerHeartbeatSucceededEvent || eventCapturer.WaitForOrThrowIfTimeout(events => events.Any(e => e is ConnectionPoolClearedEvent), TimeSpan.FromMilliseconds(500)); } - var failPointServer = CoreTestConfiguration.Cluster.SelectServer(new EndPointServerSelector(server.EndPoint), OperationContext.NoTimeout); + var failPointServer = CoreTestConfiguration.Cluster.SelectServer(OperationContext.NoTimeout, new EndPointServerSelector(server.EndPoint)); failPoint = FailPoint.Configure(failPointServer, NoCoreSession.NewHandle(), failPointDocument.AsBsonDocument, withAsync: async); if (resetPool) diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsProseTests.cs index 3dba3140de5..e95cf102944 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-reads/RetryableReadsProseTests.cs @@ -79,7 +79,7 @@ public async Task PoolClearedError_read_retryablity_test([Values(true, false)] b .Capture() .CaptureCommandEvents("find"); - var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(failPointSelector, OperationContext.NoTimeout); + var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, failPointSelector); using var failPoint = FailPoint.Configure(failpointServer, NoCoreSession.NewHandle(), failPointCommand); using var client = CreateClient(settings, eventCapturer, heartbeatInterval); @@ -146,8 +146,8 @@ public void Sharded_cluster_retryable_reads_are_retried_on_different_mongos_if_a }, useMultipleShardRouters: true); - var failPointServer1 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationContext.NoTimeout); - var failPointServer2 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint), OperationContext.NoTimeout); + var failPointServer1 = client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint)); + var failPointServer2 = client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint)); using var failPoint1 = FailPoint.Configure(failPointServer1, NoCoreSession.NewHandle(), failPointCommand); using var failPoint2 = FailPoint.Configure(failPointServer2, NoCoreSession.NewHandle(), failPointCommand); @@ -196,7 +196,7 @@ public void Sharded_cluster_retryable_reads_are_retried_on_same_mongos_if_no_oth }, useMultipleShardRouters: false); - var failPointServer = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationContext.NoTimeout); + var failPointServer = client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint)); using var failPoint = FailPoint.Configure(failPointServer, NoCoreSession.NewHandle(), failPointCommand); diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/PoolClearRetryability.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/PoolClearRetryability.cs index c06bb59f57d..78949576f42 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/PoolClearRetryability.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/PoolClearRetryability.cs @@ -82,7 +82,7 @@ public async Task PoolClearedError_write_retryablity_test([Values(false, true)] .Capture() .CaptureCommandEvents("insert"); - var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(failPointSelector, OperationContext.NoTimeout); + var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, failPointSelector); using var failPoint = FailPoint.Configure(failpointServer, NoCoreSession.NewHandle(), failPointCommand); using var client = CreateClient(settings, eventCapturer, heartbeatInterval); diff --git a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/RetryWriteOnOtherMongos.cs b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/RetryWriteOnOtherMongos.cs index bd3d834cb37..c7424f38880 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/RetryWriteOnOtherMongos.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/retryable-writes/prose-tests/RetryWriteOnOtherMongos.cs @@ -61,8 +61,8 @@ public void Sharded_cluster_retryable_writes_are_retried_on_different_mongos_if_ }, useMultipleShardRouters: true); - var failPointServer1 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationContext.NoTimeout); - var failPointServer2 = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint), OperationContext.NoTimeout); + var failPointServer1 = client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint)); + var failPointServer2 = client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, new EndPointServerSelector(client.Cluster.Description.Servers[1].EndPoint)); using var failPoint1 = FailPoint.Configure(failPointServer1, NoCoreSession.NewHandle(), failPointCommand); using var failPoint2 = FailPoint.Configure(failPointServer2, NoCoreSession.NewHandle(), failPointCommand); @@ -112,7 +112,7 @@ public void Sharded_cluster_retryable_writes_are_retried_on_same_mongo_if_no_oth }, useMultipleShardRouters: false); - var failPointServer = client.GetClusterInternal().SelectServer(new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint), OperationContext.NoTimeout); + var failPointServer = client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, new EndPointServerSelector(client.Cluster.Description.Servers[0].EndPoint)); using var failPoint = FailPoint.Configure(failPointServer, NoCoreSession.NewHandle(), failPointCommand); diff --git a/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringProseTests.cs b/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringProseTests.cs index 6ce8ddd9a6b..4d61e9c7b60 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringProseTests.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/server-discovery-and-monitoring/ServerDiscoveryAndMonitoringProseTests.cs @@ -165,7 +165,7 @@ public void Monitor_sleep_at_least_minHeartbeatFrequencyMS_between_checks() settings.ApplicationName = appName; settings.ServerSelectionTimeout = TimeSpan.FromSeconds(5); - var server = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(new EndPointServerSelector(new DnsEndPoint(serverAddress.Host, serverAddress.Port)), OperationContext.NoTimeout); + var server = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, new EndPointServerSelector(new DnsEndPoint(serverAddress.Host, serverAddress.Port))); using var failPoint = FailPoint.Configure(server, NoCoreSession.NewHandle(), failPointCommand); using var client = DriverTestConfiguration.CreateMongoClient(settings); @@ -220,7 +220,7 @@ public void RoundTimeTrip_test() { // Note that the Server Description Equality rule means that ServerDescriptionChangedEvents will not be published. // So we use reflection to obtain the latest RTT instead. - var server = client.GetClusterInternal().SelectServer(WritableServerSelector.Instance, OperationContext.NoTimeout); + var server = client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); var roundTripTimeMonitor = server._monitor()._roundTripTimeMonitor(); var expectedRoundTripTime = TimeSpan.FromMilliseconds(250); var timeout = TimeSpan.FromSeconds(30); // should not be reached without a driver bug @@ -273,7 +273,7 @@ public void ConnectionPool_cleared_on_failed_hello() eventsWaitTimeout); eventCapturer.Clear(); - var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(new EndPointServerSelector(new DnsEndPoint(serverAddress.Host, serverAddress.Port)), OperationContext.NoTimeout); + var failpointServer = DriverTestConfiguration.Client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, new EndPointServerSelector(new DnsEndPoint(serverAddress.Host, serverAddress.Port))); using var failPoint = FailPoint.Configure(failpointServer, NoCoreSession.NewHandle(), failPointCommand); eventCapturer.WaitForEventOrThrowIfTimeout(eventsWaitTimeout); diff --git a/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs b/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs index e8e394e3aba..a61e7d6658a 100644 --- a/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs +++ b/tests/MongoDB.Driver.Tests/Specifications/server-selection/InWindowTestRunner.cs @@ -82,8 +82,8 @@ public void RunTestDefinition(JsonDrivenTestCase testCase) for (int i = 0; i < testData.iterations; i++) { var selectedServer = testData.async - ? cluster.SelectServerAsync(readPreferenceSelector, OperationContext.NoTimeout).GetAwaiter().GetResult() - : cluster.SelectServer(readPreferenceSelector, OperationContext.NoTimeout); + ? cluster.SelectServerAsync(OperationContext.NoTimeout, readPreferenceSelector).GetAwaiter().GetResult() + : cluster.SelectServer(OperationContext.NoTimeout, readPreferenceSelector); selectionHistogram[selectedServer.ServerId]++; } diff --git a/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedTargetedFailPointOperation.cs b/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedTargetedFailPointOperation.cs index ba65dd7fc59..97463a719b0 100644 --- a/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedTargetedFailPointOperation.cs +++ b/tests/MongoDB.Driver.Tests/UnifiedTestOperations/UnifiedTargetedFailPointOperation.cs @@ -52,7 +52,7 @@ public void Execute() _entityMap.RegisterForDispose(client); var cluster = client.GetClusterInternal(); - var server = cluster.SelectServer(new EndPointServerSelector(pinnedServer), OperationContext.NoTimeout); + var server = cluster.SelectServer(OperationContext.NoTimeout, new EndPointServerSelector(pinnedServer)); var session = NoCoreSession.NewHandle(); From 102c9452821b3f9d69ef1e705ed993fc4bdeb1ba Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Tue, 10 Jun 2025 17:06:00 -0700 Subject: [PATCH 07/13] PR --- src/MongoDB.Driver/Core/Clusters/Cluster.cs | 7 +- .../Core/Clusters/LoadBalancedCluster.cs | 9 +- .../ExclusiveConnectionPool.Helpers.cs | 92 +++++++++++-------- src/MongoDB.Driver/OperationContext.cs | 47 +++++----- src/MongoDB.Driver/OperationExecutor.cs | 8 +- src/MongoDB.Driver/OperationOptionsBase.cs | 2 +- .../OperationContextTests.cs | 36 ++++---- 7 files changed, 111 insertions(+), 90 deletions(-) diff --git a/src/MongoDB.Driver/Core/Clusters/Cluster.cs b/src/MongoDB.Driver/Core/Clusters/Cluster.cs index 00bda54accf..fbf9cfe7ac5 100644 --- a/src/MongoDB.Driver/Core/Clusters/Cluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/Cluster.cs @@ -15,6 +15,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; @@ -369,6 +370,7 @@ private class SelectServerHelper : IDisposable private bool _serverSelectionWaitQueueEntered; private readonly IServerSelector _selector; private readonly OperationsCountServerSelector _operationCountServerSelector; + private readonly Stopwatch _stopwatch; public SelectServerHelper(Cluster cluster, IServerSelector selector) { @@ -377,6 +379,7 @@ public SelectServerHelper(Cluster cluster, IServerSelector selector) _connectedServerDescriptions = new List(_connectedServers.Count); _operationCountServerSelector = new OperationsCountServerSelector(_connectedServers); + _stopwatch = Stopwatch.StartNew(); _selector = DecorateSelector(selector); } @@ -461,11 +464,13 @@ public IServer SelectServer(OperationContext operationContext) if (selectedServer != null) { + _stopwatch.Stop(); + _cluster._serverSelectionEventLogger.LogAndPublish(new ClusterSelectedServerEvent( _description, _selector, selectedServer.Description, - operationContext.Elapsed, + _stopwatch.Elapsed, EventContext.OperationId, EventContext.OperationName)); } diff --git a/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs b/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs index 75367a9dbf2..c77d2d45241 100644 --- a/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs +++ b/src/MongoDB.Driver/Core/Clusters/LoadBalancedCluster.cs @@ -184,6 +184,7 @@ public IServer SelectServer(OperationContext operationContext, IServerSelector s null, EventContext.OperationName)); + var stopwatch = Stopwatch.StartNew(); try { serverSelectionOperationContext.WaitTask(_serverReadyTaskCompletionSource.Task); @@ -195,11 +196,13 @@ public IServer SelectServer(OperationContext operationContext, IServerSelector s if (_server != null) { + stopwatch.Stop(); + _serverSelectionEventLogger.LogAndPublish(new ClusterSelectedServerEvent( _description, selector, _server.Description, - serverSelectionOperationContext.Elapsed, + stopwatch.Elapsed, null, EventContext.OperationName)); } @@ -222,6 +225,7 @@ public async Task SelectServerAsync(OperationContext operationContext, null, EventContext.OperationName)); + var stopwatch = Stopwatch.StartNew(); try { await serverSelectionOperationContext.WaitTaskAsync(_serverReadyTaskCompletionSource.Task).ConfigureAwait(false); @@ -233,11 +237,12 @@ public async Task SelectServerAsync(OperationContext operationContext, if (_server != null) { + stopwatch.Stop(); _serverSelectionEventLogger.LogAndPublish(new ClusterSelectedServerEvent( _description, selector, _server.Description, - serverSelectionOperationContext.Elapsed, + stopwatch.Elapsed, null, EventContext.OperationName)); } diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs index 1aa39584175..f2fdefb67ad 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs @@ -178,58 +178,72 @@ public AcquireConnectionHelper(ExclusiveConnectionPool pool) public IConnectionHandle AcquireConnection(OperationContext operationContext) { + var stopwatch = new Stopwatch(); try { - StartCheckingOut(); + StartCheckingOut(stopwatch); _poolQueueWaitResult = _pool._maxConnectionsQueue.WaitSignaled(operationContext.RemainingTimeout, operationContext.CancellationToken); if (_poolQueueWaitResult == SemaphoreSlimSignalable.SemaphoreWaitResult.Entered) { PooledConnection pooledConnection; - EnsureTimeout(operationContext); + if (operationContext.IsTimedOut()) + { + stopwatch.Stop(); + throw _pool.CreateTimeoutException(stopwatch.Elapsed, $"Timed out waiting for a connection after {stopwatch.Elapsed.TotalMilliseconds}ms."); + } using (var connectionCreator = new ConnectionCreator(_pool)) { pooledConnection = connectionCreator.CreateOpenedOrReuse(operationContext); } - return EndCheckingOut(operationContext, pooledConnection); + return EndCheckingOut(stopwatch, pooledConnection); } - throw CreateException(operationContext); + stopwatch.Stop(); + throw CreateException(stopwatch.Elapsed); } catch (Exception ex) { - HandleException(ex, operationContext.Elapsed); + stopwatch.Stop(); + HandleException(ex, stopwatch.Elapsed); throw; } } public async Task AcquireConnectionAsync(OperationContext operationContext) { + var stopwatch = new Stopwatch(); try { - StartCheckingOut(); + StartCheckingOut(stopwatch); _poolQueueWaitResult = await _pool._maxConnectionsQueue.WaitSignaledAsync(operationContext.RemainingTimeout, operationContext.CancellationToken).ConfigureAwait(false); if (_poolQueueWaitResult == SemaphoreSlimSignalable.SemaphoreWaitResult.Entered) { PooledConnection pooledConnection; - EnsureTimeout(operationContext); + if (operationContext.IsTimedOut()) + { + stopwatch.Stop(); + throw _pool.CreateTimeoutException(stopwatch.Elapsed, $"Timed out waiting for a connection after {stopwatch.Elapsed.TotalMilliseconds}ms."); + } using (var connectionCreator = new ConnectionCreator(_pool)) { pooledConnection = await connectionCreator.CreateOpenedOrReuseAsync(operationContext).ConfigureAwait(false); } - return EndCheckingOut(operationContext, pooledConnection); + return EndCheckingOut(stopwatch, pooledConnection); } - throw CreateException(operationContext); + stopwatch.Stop(); + throw CreateException(stopwatch.Elapsed); } catch (Exception ex) { - HandleException(ex, operationContext.Elapsed); + stopwatch.Stop(); + HandleException(ex, stopwatch.Elapsed); throw; } } @@ -273,20 +287,21 @@ private void AcquireWaitQueueSlot() _enteredWaitQueue = true; } - private void StartCheckingOut() + private void StartCheckingOut(Stopwatch stopwatch) { _pool._eventLogger.LogAndPublish(new ConnectionPoolCheckingOutConnectionEvent(_pool._serverId, EventContext.OperationId)); - _pool._poolState.ThrowIfNotReady(); + stopwatch.Start(); + _pool._poolState.ThrowIfNotReady(); AcquireWaitQueueSlot(); } - private IConnectionHandle EndCheckingOut(OperationContext operationContext, PooledConnection pooledConnection) + private IConnectionHandle EndCheckingOut(Stopwatch stopwatch, PooledConnection pooledConnection) { var reference = new ReferenceCounted(pooledConnection, _pool.ReleaseConnection); var connectionHandle = new AcquiredConnection(_pool, reference); - _pool._eventLogger.LogAndPublish(new ConnectionPoolCheckedOutConnectionEvent(connectionHandle.ConnectionId, operationContext.Elapsed, EventContext.OperationId)); + _pool._eventLogger.LogAndPublish(new ConnectionPoolCheckedOutConnectionEvent(connectionHandle.ConnectionId, stopwatch.Elapsed, EventContext.OperationId)); // no need to release the semaphore _poolQueueWaitResult = SemaphoreSlimSignalable.SemaphoreWaitResult.None; @@ -294,21 +309,13 @@ private IConnectionHandle EndCheckingOut(OperationContext operationContext, Pool return connectionHandle; } - private void EnsureTimeout(OperationContext operationContext) - { - if (operationContext.IsTimedOut(out var elapsed)) - { - throw _pool.CreateTimeoutException(elapsed, $"Timed out waiting for a connection after {elapsed.TotalMilliseconds}ms."); - } - } - - private Exception CreateException(OperationContext operationContext) => + private Exception CreateException(TimeSpan elapsed) => _poolQueueWaitResult switch { SemaphoreSlimSignalable.SemaphoreWaitResult.Signaled => MongoConnectionPoolPausedException.ForConnectionPool(_pool._endPoint), SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => - _pool.CreateTimeoutException(operationContext.Elapsed, $"Timed out waiting for a connection after {operationContext.Elapsed.TotalMilliseconds}ms."), + _pool.CreateTimeoutException(elapsed, $"Timed out waiting for a connection after {elapsed.TotalMilliseconds}ms."), // should not be reached _ => new InvalidOperationException($"Invalid {_poolQueueWaitResult}.") }; @@ -848,12 +855,14 @@ public PooledConnection CreateOpened(OperationContext operationContext) { try { + var stopwatch = Stopwatch.StartNew(); _connectingWaitStatus = _pool._maxConnectingQueue.Wait(operationContext.RemainingTimeout, operationContext.CancellationToken); + stopwatch.Stop(); _pool._poolState.ThrowIfNotReady(); if (_connectingWaitStatus == SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut) { - _pool.CreateTimeoutException(operationContext.Elapsed, $"Timed out waiting for in connecting queue after {operationContext.Elapsed.TotalMilliseconds}ms."); + _pool.CreateTimeoutException(stopwatch.Elapsed, $"Timed out waiting for in connecting queue after {stopwatch.ElapsedMilliseconds}ms."); } return CreateOpenedInternal(operationContext); @@ -870,6 +879,7 @@ public PooledConnection CreateOpenedOrReuse(OperationContext operationContext) try { var connection = _pool._connectionHolder.Acquire(); + var stopwatch = Stopwatch.StartNew(); while (connection == null) { @@ -885,13 +895,13 @@ public PooledConnection CreateOpenedOrReuse(OperationContext operationContext) { SemaphoreSlimSignalable.SemaphoreWaitResult.Signaled => _pool._connectionHolder.Acquire(), SemaphoreSlimSignalable.SemaphoreWaitResult.Entered => CreateOpenedInternal(operationContext), - SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(operationContext.Elapsed), + SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(stopwatch.Elapsed), _ => throw new InvalidOperationException($"Invalid wait result {_connectingWaitStatus}") }; - if (connection == null && operationContext.IsTimedOut(out var elapsed)) + if (connection == null && operationContext.IsTimedOut()) { - throw CreateTimeoutException(elapsed); + throw CreateTimeoutException(stopwatch.Elapsed); } } @@ -909,6 +919,7 @@ public async Task CreateOpenedOrReuseAsync(OperationContext op try { var connection = _pool._connectionHolder.Acquire(); + var stopwatch = Stopwatch.StartNew(); while (connection == null) { @@ -924,13 +935,13 @@ public async Task CreateOpenedOrReuseAsync(OperationContext op { SemaphoreSlimSignalable.SemaphoreWaitResult.Signaled => _pool._connectionHolder.Acquire(), SemaphoreSlimSignalable.SemaphoreWaitResult.Entered => await CreateOpenedInternalAsync(operationContext).ConfigureAwait(false), - SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(operationContext.Elapsed), + SemaphoreSlimSignalable.SemaphoreWaitResult.TimedOut => throw CreateTimeoutException(stopwatch.Elapsed), _ => throw new InvalidOperationException($"Invalid wait result {_connectingWaitStatus}") }; - if (connection == null && operationContext.IsTimedOut(out var elapsed)) + if (connection == null && operationContext.IsTimedOut()) { - throw CreateTimeoutException(elapsed); + throw CreateTimeoutException(stopwatch.Elapsed); } } @@ -960,44 +971,47 @@ public void Dispose() // private methods private PooledConnection CreateOpenedInternal(OperationContext operationContext) { - StartCreating(operationContext); + var stopwatch = StartCreating(operationContext); // TODO: CSOT add support of CSOT timeout in connection open code too. _connection.Open(operationContext.CancellationToken); - FinishCreating(operationContext, _connection.Description); + FinishCreating(_connection.Description, stopwatch); return _connection; } private async Task CreateOpenedInternalAsync(OperationContext operationContext) { - StartCreating(operationContext); + var stopwatch = StartCreating(operationContext); // TODO: CSOT add support of CSOT timeout in connection open code too. await _connection.OpenAsync(operationContext.CancellationToken).ConfigureAwait(false); - FinishCreating(operationContext, _connection.Description); + FinishCreating(_connection.Description, stopwatch); return _connection; } - private void StartCreating(OperationContext operationContext) + private Stopwatch StartCreating(OperationContext operationContext) { _pool._eventLogger.LogAndPublish(new ConnectionPoolAddingConnectionEvent(_pool._serverId, EventContext.OperationId)); operationContext.CancellationToken.ThrowIfCancellationRequested(); - if (operationContext.IsTimedOut(out _)) + if (operationContext.IsTimedOut()) { throw new TimeoutException(); } + var stopwatch = Stopwatch.StartNew(); _connection = _pool.CreateNewConnection(); + return stopwatch; } - private void FinishCreating(OperationContext operationContext, ConnectionDescription description) + private void FinishCreating(ConnectionDescription description, Stopwatch stopwatch) { - _pool._eventLogger.LogAndPublish(new ConnectionPoolAddedConnectionEvent(_connection.ConnectionId, operationContext.Elapsed, EventContext.OperationId)); + stopwatch.Stop(); + _pool._eventLogger.LogAndPublish(new ConnectionPoolAddedConnectionEvent(_connection.ConnectionId, stopwatch.Elapsed, EventContext.OperationId)); // Only if reached this stage, connection should not be disposed _disposeConnection = false; diff --git a/src/MongoDB.Driver/OperationContext.cs b/src/MongoDB.Driver/OperationContext.cs index ddfff2e42f9..47e16b63b23 100644 --- a/src/MongoDB.Driver/OperationContext.cs +++ b/src/MongoDB.Driver/OperationContext.cs @@ -42,10 +42,6 @@ internal OperationContext(Stopwatch stopwatch, TimeSpan timeout, CancellationTok public CancellationToken CancellationToken { get; } - public TimeSpan Elapsed => Stopwatch.Elapsed; - - public TimeSpan Timeout { get; } - public OperationContext ParentContext { get; private init; } public TimeSpan RemainingTimeout @@ -57,15 +53,16 @@ public TimeSpan RemainingTimeout return System.Threading.Timeout.InfiniteTimeSpan; } - return Timeout - Elapsed; + return Timeout - Stopwatch.Elapsed; } } private Stopwatch Stopwatch { get; } - public bool IsTimedOut(out TimeSpan elapsed) + private TimeSpan Timeout { get; } + + public bool IsTimedOut() { - elapsed = Elapsed; var remainingTimeout = RemainingTimeout; if (remainingTimeout == System.Threading.Timeout.InfiniteTimeSpan) { @@ -75,24 +72,6 @@ public bool IsTimedOut(out TimeSpan elapsed) return remainingTimeout < TimeSpan.Zero; } - public OperationContext WithTimeout(TimeSpan timeout) - { - var remainingTimeout = RemainingTimeout; - if (timeout == System.Threading.Timeout.InfiniteTimeSpan) - { - timeout = remainingTimeout; - } - else if (remainingTimeout != System.Threading.Timeout.InfiniteTimeSpan && remainingTimeout < timeout) - { - timeout = remainingTimeout; - } - - return new OperationContext(timeout, CancellationToken) - { - ParentContext = this - }; - } - public void WaitTask(Task task) { if (task.IsCompleted) @@ -150,6 +129,24 @@ public async Task WaitTaskAsync(Task task) throw; } } + + public OperationContext WithTimeout(TimeSpan timeout) + { + var remainingTimeout = RemainingTimeout; + if (timeout == System.Threading.Timeout.InfiniteTimeSpan) + { + timeout = remainingTimeout; + } + else if (remainingTimeout != System.Threading.Timeout.InfiniteTimeSpan && remainingTimeout < timeout) + { + timeout = remainingTimeout; + } + + return new OperationContext(timeout, CancellationToken) + { + ParentContext = this + }; + } } } diff --git a/src/MongoDB.Driver/OperationExecutor.cs b/src/MongoDB.Driver/OperationExecutor.cs index b9049b648d8..d4194cf9097 100644 --- a/src/MongoDB.Driver/OperationExecutor.cs +++ b/src/MongoDB.Driver/OperationExecutor.cs @@ -50,7 +50,7 @@ public TResult ExecuteReadOperation( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); - var cancellationContext = options.CreateCancellationContext(cancellationToken); + var cancellationContext = options.ToOperationContext(cancellationToken); var readPreference = options.GetEffectiveReadPreference(session); using var binding = CreateReadBinding(session, readPreference, allowChannelPinning); return operation.Execute(cancellationContext, binding); @@ -68,7 +68,7 @@ public async Task ExecuteReadOperationAsync( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); - var cancellationContext = options.CreateCancellationContext(cancellationToken); + var cancellationContext = options.ToOperationContext(cancellationToken); var readPreference = options.GetEffectiveReadPreference(session); using var binding = CreateReadBinding(session, readPreference, allowChannelPinning); return await operation.ExecuteAsync(cancellationContext, binding).ConfigureAwait(false); @@ -86,7 +86,7 @@ public TResult ExecuteWriteOperation( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); - var cancellationContext = options.CreateCancellationContext(cancellationToken); + var cancellationContext = options.ToOperationContext(cancellationToken); using var binding = CreateReadWriteBinding(session, allowChannelPinning); return operation.Execute(cancellationContext, binding); } @@ -103,7 +103,7 @@ public async Task ExecuteWriteOperationAsync( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); - var cancellationContext = options.CreateCancellationContext(cancellationToken); + var cancellationContext = options.ToOperationContext(cancellationToken); using var binding = CreateReadWriteBinding(session, allowChannelPinning); return await operation.ExecuteAsync(cancellationContext, binding).ConfigureAwait(false); } diff --git a/src/MongoDB.Driver/OperationOptionsBase.cs b/src/MongoDB.Driver/OperationOptionsBase.cs index 17f17ef4b81..5f564ca1b27 100644 --- a/src/MongoDB.Driver/OperationOptionsBase.cs +++ b/src/MongoDB.Driver/OperationOptionsBase.cs @@ -20,7 +20,7 @@ namespace MongoDB.Driver { internal abstract record OperationOptionsBase(TimeSpan Timeout) { - public OperationContext CreateCancellationContext(CancellationToken cancellationToken) + public OperationContext ToOperationContext(CancellationToken cancellationToken) => new (Timeout, cancellationToken); } } diff --git a/tests/MongoDB.Driver.Tests/OperationContextTests.cs b/tests/MongoDB.Driver.Tests/OperationContextTests.cs index 061288fab75..ef90b72cbcd 100644 --- a/tests/MongoDB.Driver.Tests/OperationContextTests.cs +++ b/tests/MongoDB.Driver.Tests/OperationContextTests.cs @@ -16,6 +16,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Reflection; using System.Threading; using System.Threading.Tasks; using FluentAssertions; @@ -30,28 +31,18 @@ public class OperationContextTests public void Constructor_should_initialize_properties() { var timeout = TimeSpan.FromSeconds(42); + var stopwatch = new Stopwatch(); using var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; - var operationContext = new OperationContext(timeout, cancellationToken); + var operationContext = new OperationContext(stopwatch, timeout, cancellationToken); - operationContext.Timeout.Should().Be(timeout); + operationContext._timeout().Should().Be(timeout); + operationContext.RemainingTimeout.Should().Be(timeout); operationContext.CancellationToken.Should().Be(cancellationToken); operationContext.ParentContext.Should().BeNull(); } - [Fact] - public void Elapsed_should_return_elapsed_time() - { - var stopwatch = Stopwatch.StartNew(); - Thread.Sleep(10); - stopwatch.Stop(); - - var operationContext = new OperationContext(stopwatch, TimeSpan.Zero, CancellationToken.None); - - operationContext.Elapsed.Should().Be(stopwatch.Elapsed); - } - [Fact] public void RemainingTimeout_should_calculate() { @@ -78,7 +69,7 @@ public void RemainingTimeout_should_return_infinite_for_infinite_timeout() } [Fact] - public void RenainingTimeout_could_be_negative() + public void RemainingTimeout_could_be_negative() { var timeout = TimeSpan.FromMilliseconds(5); var stopwatch = Stopwatch.StartNew(); @@ -99,10 +90,9 @@ public void IsTimedOut_should_return_expected_result(bool expected, TimeSpan tim stopwatch.Stop(); var operationContext = new OperationContext(stopwatch, timeout, CancellationToken.None); - var result = operationContext.IsTimedOut(out var elapsed); + var result = operationContext.IsTimedOut(); result.Should().Be(expected); - elapsed.Should().Be(stopwatch.Elapsed); } public static IEnumerable IsTimedOut_test_cases = @@ -119,7 +109,7 @@ public void WithTimeout_should_calculate_proper_timeout(TimeSpan expected, TimeS var operationContext = new OperationContext(new Stopwatch(), originalTimeout, CancellationToken.None); var resultContext = operationContext.WithTimeout(newTimeout); - resultContext.Timeout.Should().Be(expected); + resultContext._timeout().Should().Be(expected); } public static IEnumerable WithTimeout_test_cases = @@ -241,5 +231,15 @@ await Record.ExceptionAsync(() => operationContext.WaitTaskAsync(task)) : exception.Should().BeNull(); } } + + internal static class OperationContextReflector + { + private static readonly PropertyInfo __timeoutMemberInfo = typeof(OperationContext).GetProperty("Timeout", BindingFlags.Instance | BindingFlags.NonPublic); + + public static TimeSpan _timeout(this OperationContext context) + { + return (TimeSpan)__timeoutMemberInfo.GetValue(context); + } + } } From 4d6d939bfe254ad4f50f6fd928b84926404745d5 Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Tue, 10 Jun 2025 17:15:47 -0700 Subject: [PATCH 08/13] pr --- .../Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs index f2fdefb67ad..be174043572 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs @@ -190,7 +190,7 @@ public IConnectionHandle AcquireConnection(OperationContext operationContext) if (operationContext.IsTimedOut()) { stopwatch.Stop(); - throw _pool.CreateTimeoutException(stopwatch.Elapsed, $"Timed out waiting for a connection after {stopwatch.Elapsed.TotalMilliseconds}ms."); + throw _pool.CreateTimeoutException(stopwatch.Elapsed, $"Timed out waiting for a connection after {stopwatch.ElapsedMilliseconds}ms."); } using (var connectionCreator = new ConnectionCreator(_pool)) From 3a05fa621c56968c851225de4be869d5a5e4f574 Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Wed, 11 Jun 2025 11:31:27 -0700 Subject: [PATCH 09/13] pr --- src/MongoDB.Driver/OperationExecutor.cs | 16 ++++++++-------- .../Core/Clusters/LoadBalancedClusterTests.cs | 6 +++--- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/MongoDB.Driver/OperationExecutor.cs b/src/MongoDB.Driver/OperationExecutor.cs index d4194cf9097..7025097de70 100644 --- a/src/MongoDB.Driver/OperationExecutor.cs +++ b/src/MongoDB.Driver/OperationExecutor.cs @@ -50,10 +50,10 @@ public TResult ExecuteReadOperation( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); - var cancellationContext = options.ToOperationContext(cancellationToken); + var operationContext = options.ToOperationContext(cancellationToken); var readPreference = options.GetEffectiveReadPreference(session); using var binding = CreateReadBinding(session, readPreference, allowChannelPinning); - return operation.Execute(cancellationContext, binding); + return operation.Execute(operationContext, binding); } public async Task ExecuteReadOperationAsync( @@ -68,10 +68,10 @@ public async Task ExecuteReadOperationAsync( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); - var cancellationContext = options.ToOperationContext(cancellationToken); + var operationContext = options.ToOperationContext(cancellationToken); var readPreference = options.GetEffectiveReadPreference(session); using var binding = CreateReadBinding(session, readPreference, allowChannelPinning); - return await operation.ExecuteAsync(cancellationContext, binding).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); } public TResult ExecuteWriteOperation( @@ -86,9 +86,9 @@ public TResult ExecuteWriteOperation( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); - var cancellationContext = options.ToOperationContext(cancellationToken); + var operationContext = options.ToOperationContext(cancellationToken); using var binding = CreateReadWriteBinding(session, allowChannelPinning); - return operation.Execute(cancellationContext, binding); + return operation.Execute(operationContext, binding); } public async Task ExecuteWriteOperationAsync( @@ -103,9 +103,9 @@ public async Task ExecuteWriteOperationAsync( Ensure.IsNotNull(session, nameof(session)); ThrowIfDisposed(); - var cancellationContext = options.ToOperationContext(cancellationToken); + var operationContext = options.ToOperationContext(cancellationToken); using var binding = CreateReadWriteBinding(session, allowChannelPinning); - return await operation.ExecuteAsync(cancellationContext, binding).ConfigureAwait(false); + return await operation.ExecuteAsync(operationContext, binding).ConfigureAwait(false); } public IClientSessionHandle StartImplicitSession() diff --git a/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs b/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs index 6d9bcb3dae6..2c14c12f751 100644 --- a/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/Core/Clusters/LoadBalancedClusterTests.cs @@ -387,10 +387,10 @@ public async Task SelectServer_should_be_cancelled_by_cancellationToken( Exception exception; using (var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(100))) { - var cancellationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationTokenSource.Token); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationTokenSource.Token); exception = async ? - await Record.ExceptionAsync(() => subject.SelectServerAsync(cancellationContext, Mock.Of())) : - Record.Exception(() => subject.SelectServer(cancellationContext, Mock.Of())); + await Record.ExceptionAsync(() => subject.SelectServerAsync(operationContext, Mock.Of())) : + Record.Exception(() => subject.SelectServer(operationContext, Mock.Of())); } exception.Should().BeOfType(); From a09bf9567d4491ce1fc9dae850c60f6302688d1d Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Wed, 11 Jun 2025 12:26:44 -0700 Subject: [PATCH 10/13] PR --- .../ExclusiveConnectionPool.Helpers.cs | 33 ++++++------- .../Core/ConnectionPools/MaintenanceHelper.cs | 4 +- src/MongoDB.Driver/OperationContext.cs | 11 ++++- tests/MongoDB.Driver.Tests/ClusterTests.cs | 4 +- .../OperationContextTests.cs | 48 ++++++++++++++----- 5 files changed, 64 insertions(+), 36 deletions(-) diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs index be174043572..a7f933a6fa2 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs @@ -187,18 +187,14 @@ public IConnectionHandle AcquireConnection(OperationContext operationContext) if (_poolQueueWaitResult == SemaphoreSlimSignalable.SemaphoreWaitResult.Entered) { PooledConnection pooledConnection; - if (operationContext.IsTimedOut()) - { - stopwatch.Stop(); - throw _pool.CreateTimeoutException(stopwatch.Elapsed, $"Timed out waiting for a connection after {stopwatch.ElapsedMilliseconds}ms."); - } + EnsureTimeout(operationContext, stopwatch); using (var connectionCreator = new ConnectionCreator(_pool)) { pooledConnection = connectionCreator.CreateOpenedOrReuse(operationContext); } - return EndCheckingOut(stopwatch, pooledConnection); + return EndCheckingOut(pooledConnection, stopwatch); } stopwatch.Stop(); @@ -223,18 +219,14 @@ public async Task AcquireConnectionAsync(OperationContext ope if (_poolQueueWaitResult == SemaphoreSlimSignalable.SemaphoreWaitResult.Entered) { PooledConnection pooledConnection; - if (operationContext.IsTimedOut()) - { - stopwatch.Stop(); - throw _pool.CreateTimeoutException(stopwatch.Elapsed, $"Timed out waiting for a connection after {stopwatch.Elapsed.TotalMilliseconds}ms."); - } + EnsureTimeout(operationContext, stopwatch); using (var connectionCreator = new ConnectionCreator(_pool)) { pooledConnection = await connectionCreator.CreateOpenedOrReuseAsync(operationContext).ConfigureAwait(false); } - return EndCheckingOut(stopwatch, pooledConnection); + return EndCheckingOut(pooledConnection, stopwatch); } stopwatch.Stop(); @@ -287,6 +279,15 @@ private void AcquireWaitQueueSlot() _enteredWaitQueue = true; } + private void EnsureTimeout(OperationContext operationContext, Stopwatch stopwatch) + { + if (operationContext.IsTimedOut()) + { + stopwatch.Stop(); + throw _pool.CreateTimeoutException(stopwatch.Elapsed, $"Timed out waiting for a connection after {stopwatch.ElapsedMilliseconds}ms."); + } + } + private void StartCheckingOut(Stopwatch stopwatch) { _pool._eventLogger.LogAndPublish(new ConnectionPoolCheckingOutConnectionEvent(_pool._serverId, EventContext.OperationId)); @@ -296,7 +297,7 @@ private void StartCheckingOut(Stopwatch stopwatch) AcquireWaitQueueSlot(); } - private IConnectionHandle EndCheckingOut(Stopwatch stopwatch, PooledConnection pooledConnection) + private IConnectionHandle EndCheckingOut(PooledConnection pooledConnection, Stopwatch stopwatch) { var reference = new ReferenceCounted(pooledConnection, _pool.ReleaseConnection); var connectionHandle = new AcquiredConnection(_pool, reference); @@ -997,11 +998,7 @@ private Stopwatch StartCreating(OperationContext operationContext) { _pool._eventLogger.LogAndPublish(new ConnectionPoolAddingConnectionEvent(_pool._serverId, EventContext.OperationId)); - operationContext.CancellationToken.ThrowIfCancellationRequested(); - if (operationContext.IsTimedOut()) - { - throw new TimeoutException(); - } + operationContext.ThrowIfTimedOutOrCanceled(); var stopwatch = Stopwatch.StartNew(); _connection = _pool.CreateNewConnection(); diff --git a/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs b/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs index 78ac0a55931..65ac64c2694 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs @@ -113,12 +113,12 @@ private void RunMaintenance(MaintenanceExecutingContext maintenanceExecutingCont private void EnsureMinSize(CancellationToken cancellationToken) { + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); while (_connectionPool.CreatedCount < _connectionPool.Settings.MinConnections && !cancellationToken.IsCancellationRequested) { using (var poolAwaiter = _connectionPool.CreateMaxConnectionsAwaiter()) { - var operationContext = new OperationContext(TimeSpan.FromMilliseconds(20), cancellationToken); - var entered = poolAwaiter.WaitSignaled(operationContext.RemainingTimeout, operationContext.CancellationToken); + var entered = poolAwaiter.WaitSignaled(TimeSpan.FromMilliseconds(20), operationContext.CancellationToken); if (!entered) { return; diff --git a/src/MongoDB.Driver/OperationContext.cs b/src/MongoDB.Driver/OperationContext.cs index 47e16b63b23..d9c25405e24 100644 --- a/src/MongoDB.Driver/OperationContext.cs +++ b/src/MongoDB.Driver/OperationContext.cs @@ -59,7 +59,7 @@ public TimeSpan RemainingTimeout private Stopwatch Stopwatch { get; } - private TimeSpan Timeout { get; } + public TimeSpan Timeout { get; } public bool IsTimedOut() { @@ -72,6 +72,15 @@ public bool IsTimedOut() return remainingTimeout < TimeSpan.Zero; } + public void ThrowIfTimedOutOrCanceled() + { + CancellationToken.ThrowIfCancellationRequested(); + if (IsTimedOut()) + { + throw new TimeoutException(); + } + } + public void WaitTask(Task task) { if (task.IsCompleted) diff --git a/tests/MongoDB.Driver.Tests/ClusterTests.cs b/tests/MongoDB.Driver.Tests/ClusterTests.cs index b6d2d8021ff..e1a453acefa 100644 --- a/tests/MongoDB.Driver.Tests/ClusterTests.cs +++ b/tests/MongoDB.Driver.Tests/ClusterTests.cs @@ -87,8 +87,8 @@ public void SelectServer_loadbalancing_prose_test([Values(false, true)] bool asy var eventCapturer = CreateEventCapturer(); using (var client = CreateMongoClient(eventCapturer, applicationName)) { - var slowServer = client.GetClusterInternal().SelectServer(default, WritableServerSelector.Instance); - var fastServer = client.GetClusterInternal().SelectServer(default, new DelegateServerSelector((_, servers) => servers.Where(s => s.ServerId != slowServer.ServerId))); + var slowServer = client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, WritableServerSelector.Instance); + var fastServer = client.GetClusterInternal().SelectServer(OperationContext.NoTimeout, new DelegateServerSelector((_, servers) => servers.Where(s => s.ServerId != slowServer.ServerId))); using var failPoint = FailPoint.Configure(slowServer, NoCoreSession.NewHandle(), failCommand, async); diff --git a/tests/MongoDB.Driver.Tests/OperationContextTests.cs b/tests/MongoDB.Driver.Tests/OperationContextTests.cs index ef90b72cbcd..474fcaf54af 100644 --- a/tests/MongoDB.Driver.Tests/OperationContextTests.cs +++ b/tests/MongoDB.Driver.Tests/OperationContextTests.cs @@ -16,7 +16,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Reflection; using System.Threading; using System.Threading.Tasks; using FluentAssertions; @@ -37,7 +36,7 @@ public void Constructor_should_initialize_properties() var operationContext = new OperationContext(stopwatch, timeout, cancellationToken); - operationContext._timeout().Should().Be(timeout); + operationContext.Timeout.Should().Be(timeout); operationContext.RemainingTimeout.Should().Be(timeout); operationContext.CancellationToken.Should().Be(cancellationToken); operationContext.ParentContext.Should().BeNull(); @@ -102,6 +101,39 @@ public void IsTimedOut_should_return_expected_result(bool expected, TimeSpan tim [true, TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(10)], ]; + [Fact] + public void ThrowIfTimedOutOrCanceled_succeed_if_no_timeout_and_no_cancellation() + { + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, CancellationToken.None); + + var exception = Record.Exception(() => operationContext.ThrowIfTimedOutOrCanceled()); + + exception.Should().BeNull(); + } + + [Fact] + public void ThrowIfTimedOutOrCanceled_throws_on_timeout() + { + var operationContext = new OperationContext(TimeSpan.FromMilliseconds(10), CancellationToken.None); + Thread.Sleep(20); + + var exception = Record.Exception(() => operationContext.ThrowIfTimedOutOrCanceled()); + + exception.Should().BeOfType(); + } + + [Fact] + public void ThrowIfTimedOutOrCanceled_throws_on_cancellation() + { + using var cancellationSource = new CancellationTokenSource(); + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationSource.Token); + cancellationSource.Cancel(); + + var exception = Record.Exception(() => operationContext.ThrowIfTimedOutOrCanceled()); + + exception.Should().BeOfType(); + } + [Theory] [MemberData(nameof(WithTimeout_test_cases))] public void WithTimeout_should_calculate_proper_timeout(TimeSpan expected, TimeSpan originalTimeout, TimeSpan newTimeout) @@ -109,7 +141,7 @@ public void WithTimeout_should_calculate_proper_timeout(TimeSpan expected, TimeS var operationContext = new OperationContext(new Stopwatch(), originalTimeout, CancellationToken.None); var resultContext = operationContext.WithTimeout(newTimeout); - resultContext._timeout().Should().Be(expected); + resultContext.Timeout.Should().Be(expected); } public static IEnumerable WithTimeout_test_cases = @@ -231,15 +263,5 @@ await Record.ExceptionAsync(() => operationContext.WaitTaskAsync(task)) : exception.Should().BeNull(); } } - - internal static class OperationContextReflector - { - private static readonly PropertyInfo __timeoutMemberInfo = typeof(OperationContext).GetProperty("Timeout", BindingFlags.Instance | BindingFlags.NonPublic); - - public static TimeSpan _timeout(this OperationContext context) - { - return (TimeSpan)__timeoutMemberInfo.GetValue(context); - } - } } From 26872055230478f23431b0a39ba8bcf002f4d315 Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Wed, 11 Jun 2025 14:27:48 -0700 Subject: [PATCH 11/13] pr --- .../ExclusiveConnectionPool.Helpers.cs | 6 +- .../OperationContextTests.cs | 62 ++++++++++++------- 2 files changed, 41 insertions(+), 27 deletions(-) diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs index a7f933a6fa2..42495935df2 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs @@ -187,7 +187,7 @@ public IConnectionHandle AcquireConnection(OperationContext operationContext) if (_poolQueueWaitResult == SemaphoreSlimSignalable.SemaphoreWaitResult.Entered) { PooledConnection pooledConnection; - EnsureTimeout(operationContext, stopwatch); + ThrowIfTimedOut(operationContext, stopwatch); using (var connectionCreator = new ConnectionCreator(_pool)) { @@ -219,7 +219,7 @@ public async Task AcquireConnectionAsync(OperationContext ope if (_poolQueueWaitResult == SemaphoreSlimSignalable.SemaphoreWaitResult.Entered) { PooledConnection pooledConnection; - EnsureTimeout(operationContext, stopwatch); + ThrowIfTimedOut(operationContext, stopwatch); using (var connectionCreator = new ConnectionCreator(_pool)) { @@ -279,7 +279,7 @@ private void AcquireWaitQueueSlot() _enteredWaitQueue = true; } - private void EnsureTimeout(OperationContext operationContext, Stopwatch stopwatch) + private void ThrowIfTimedOut(OperationContext operationContext, Stopwatch stopwatch) { if (operationContext.IsTimedOut()) { diff --git a/tests/MongoDB.Driver.Tests/OperationContextTests.cs b/tests/MongoDB.Driver.Tests/OperationContextTests.cs index 474fcaf54af..9b253837d8a 100644 --- a/tests/MongoDB.Driver.Tests/OperationContextTests.cs +++ b/tests/MongoDB.Driver.Tests/OperationContextTests.cs @@ -102,7 +102,7 @@ public void IsTimedOut_should_return_expected_result(bool expected, TimeSpan tim ]; [Fact] - public void ThrowIfTimedOutOrCanceled_succeed_if_no_timeout_and_no_cancellation() + public void ThrowIfTimedOutOrCanceled_should_not_throw_if_no_timeout_and_no_cancellation() { var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, CancellationToken.None); @@ -134,32 +134,17 @@ public void ThrowIfTimedOutOrCanceled_throws_on_cancellation() exception.Should().BeOfType(); } - [Theory] - [MemberData(nameof(WithTimeout_test_cases))] - public void WithTimeout_should_calculate_proper_timeout(TimeSpan expected, TimeSpan originalTimeout, TimeSpan newTimeout) - { - var operationContext = new OperationContext(new Stopwatch(), originalTimeout, CancellationToken.None); - var resultContext = operationContext.WithTimeout(newTimeout); - - resultContext.Timeout.Should().Be(expected); - } - - public static IEnumerable WithTimeout_test_cases = - [ - [Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan], - [TimeSpan.FromMilliseconds(5), Timeout.InfiniteTimeSpan, TimeSpan.FromMilliseconds(5)], - [TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(5), Timeout.InfiniteTimeSpan], - [TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(10)], - [TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(5)], - ]; - [Fact] - public void WithTimeout_should_set_ParentContext() + public void ThrowIfTimedOutOrCanceled_throws_CancelledException_when_timedout_and_cancelled() { - var operationContext = new OperationContext(new Stopwatch(), Timeout.InfiniteTimeSpan, CancellationToken.None); - var resultContext = operationContext.WithTimeout(TimeSpan.FromSeconds(10)); + using var cancellationSource = new CancellationTokenSource(); + var operationContext = new OperationContext(TimeSpan.FromMilliseconds(10), cancellationSource.Token); + Thread.Sleep(20); + cancellationSource.Cancel(); - resultContext.ParentContext.Should().Be(operationContext); + var exception = Record.Exception(() => operationContext.ThrowIfTimedOutOrCanceled()); + + exception.Should().BeOfType(); } [Theory] @@ -262,6 +247,35 @@ await Record.ExceptionAsync(() => operationContext.WaitTaskAsync(task)) : exception.Should().BeNull(); } + + + [Theory] + [MemberData(nameof(WithTimeout_test_cases))] + public void WithTimeout_should_calculate_proper_timeout(TimeSpan expected, TimeSpan originalTimeout, TimeSpan newTimeout) + { + var operationContext = new OperationContext(new Stopwatch(), originalTimeout, CancellationToken.None); + var resultContext = operationContext.WithTimeout(newTimeout); + + resultContext.Timeout.Should().Be(expected); + } + + public static IEnumerable WithTimeout_test_cases = + [ + [Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan], + [TimeSpan.FromMilliseconds(5), Timeout.InfiniteTimeSpan, TimeSpan.FromMilliseconds(5)], + [TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(5), Timeout.InfiniteTimeSpan], + [TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(10)], + [TimeSpan.FromMilliseconds(5), TimeSpan.FromMilliseconds(10), TimeSpan.FromMilliseconds(5)], + ]; + + [Fact] + public void WithTimeout_should_set_ParentContext() + { + var operationContext = new OperationContext(new Stopwatch(), Timeout.InfiniteTimeSpan, CancellationToken.None); + var resultContext = operationContext.WithTimeout(TimeSpan.FromSeconds(10)); + + resultContext.ParentContext.Should().Be(operationContext); + } } } From 27d728c11af5437d2f59e71fa7e9135a16d24282 Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Wed, 11 Jun 2025 15:50:02 -0700 Subject: [PATCH 12/13] PR --- .../ConnectionPools/ExclusiveConnectionPool.Helpers.cs | 5 +++-- .../Core/ConnectionPools/MaintenanceHelper.cs | 7 ++++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs index 42495935df2..7eb3e317db4 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs @@ -852,12 +852,12 @@ public ConnectionCreator(ExclusiveConnectionPool pool) _disposeConnection = true; } - public PooledConnection CreateOpened(OperationContext operationContext) + public PooledConnection CreateOpened(TimeSpan maxConnectingQueueTimeout, CancellationToken cancellationToken) { try { var stopwatch = Stopwatch.StartNew(); - _connectingWaitStatus = _pool._maxConnectingQueue.Wait(operationContext.RemainingTimeout, operationContext.CancellationToken); + _connectingWaitStatus = _pool._maxConnectingQueue.Wait(maxConnectingQueueTimeout, cancellationToken); stopwatch.Stop(); _pool._poolState.ThrowIfNotReady(); @@ -866,6 +866,7 @@ public PooledConnection CreateOpened(OperationContext operationContext) _pool.CreateTimeoutException(stopwatch.Elapsed, $"Timed out waiting for in connecting queue after {stopwatch.ElapsedMilliseconds}ms."); } + var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); return CreateOpenedInternal(operationContext); } catch (Exception ex) diff --git a/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs b/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs index 65ac64c2694..568ed1933c3 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/MaintenanceHelper.cs @@ -113,12 +113,13 @@ private void RunMaintenance(MaintenanceExecutingContext maintenanceExecutingCont private void EnsureMinSize(CancellationToken cancellationToken) { - var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); + var minTimeout = TimeSpan.FromMilliseconds(20); + while (_connectionPool.CreatedCount < _connectionPool.Settings.MinConnections && !cancellationToken.IsCancellationRequested) { using (var poolAwaiter = _connectionPool.CreateMaxConnectionsAwaiter()) { - var entered = poolAwaiter.WaitSignaled(TimeSpan.FromMilliseconds(20), operationContext.CancellationToken); + var entered = poolAwaiter.WaitSignaled(minTimeout, cancellationToken); if (!entered) { return; @@ -126,7 +127,7 @@ private void EnsureMinSize(CancellationToken cancellationToken) using (var connectionCreator = new ConnectionCreator(_connectionPool)) { - var connection = connectionCreator.CreateOpened(operationContext); + var connection = connectionCreator.CreateOpened(minTimeout, cancellationToken); _connectionPool.ConnectionHolder.Return(connection); } } From 7dba679b615bfc166e592ee11a89039f5d29892d Mon Sep 17 00:00:00 2001 From: Oleksandr Poliakov Date: Wed, 11 Jun 2025 21:24:23 -0700 Subject: [PATCH 13/13] pr --- .../Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs index 7eb3e317db4..b4adb83a8db 100644 --- a/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs +++ b/src/MongoDB.Driver/Core/ConnectionPools/ExclusiveConnectionPool.Helpers.cs @@ -866,8 +866,7 @@ public PooledConnection CreateOpened(TimeSpan maxConnectingQueueTimeout, Cancell _pool.CreateTimeoutException(stopwatch.Elapsed, $"Timed out waiting for in connecting queue after {stopwatch.ElapsedMilliseconds}ms."); } - var operationContext = new OperationContext(Timeout.InfiniteTimeSpan, cancellationToken); - return CreateOpenedInternal(operationContext); + return CreateOpenedInternal(new(Timeout.InfiniteTimeSpan, cancellationToken)); } catch (Exception ex) {